Universal Translator for your Tweets

I thought this was going to be easy… SO much for preconceptions. Today, I’m going to give you the code to create a twitter translation App using, HTML, CSS, JavaScript and Java, the Twitter API and the Google Translate API. In a future tutorial I will demonstrate cross domain Ajax to get this Application to work totally on the client side but in the mean time you will need to have a Java enabled server to execute the server-side JSP that requests the API for twitter.

As you type your tweet the the JavaScript will analyze your keystrokes and check for when a space is entered assuming you are done typing a word, at this point the text is passed to Google for translation. When your done typing hit tweet and it’s off to twitter with your tweet.

This is what your app will look like when it’s finished:

translateApp

Source

The Folder structure you will need is similar to all other projects. You can download the source folder for this project and open it in NetBeans to get a better idea of how the end result will look. There are no special libraries you need to get this going just java.io.* and java.net.* .

This is the HTML you will need, (/index.html):

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="Stylesheet" media="screen" href="assets/css/style.css" >
        <title>Twitter Universal Translate</title>
    </head>
    <body>
        <div id="content">
            <div class="head">Twitter Multilanguage</div>

            <form>
                <label class="textlabel" for="username">Username</label>
                <input class="textinput" type="text" id="username" name="username" value="">

                <label class="textlabel" for="password">Password</label>
                <input class="textinput" type="password" id="password" name="password" value="">

                <label class="textlabel" for="lang">Translate To</label>
                <select class="select" id="lang" name="lang" onclick="translateTwo()" >
                    <option value="en">English</option>
                    <option value="fr">French</option>
                    <option value="it">Italian</option>
                    <option value="de">German</option>
                </select>

                <label class="textlabel" for="textarea">Tweet</label>
                <textarea id="textarea" class="textarea" name="textarea" cols="5" rows="5" onblur="translateTwo()" onkeydown="translate(event)"></textarea>

                <input class="textinput" type="button" value="Tweet" onclick="callLoad()"/>
            </form>
            <div class="infobar">“Translate your tweet into a chosen language as you type.”</div>
            <span id="status"></span>
        </div>

        <script type="text/javascript" src="http://www.google.com/jsapi"></script>
        <script type="text/javascript" src="assets/js/jscript.js"></script>
    </body>
</html>

This is the CSS you will need, (/assets/css/style.css):

* {
    margin: 0;
    padding: 0;
}

/*///////////////////////////////////////////////////*/

#content{
    color:#333;
    width:350px;
    margin:100px auto;
    border:15px inset #66ffff;
    padding:10px;
    font-family:sans-serif;
    -moz-border-radius:10px;
}

.textlabel,textinput{
    display:block;
}

.textlabel{
    font-weight:bold;
}

.textlabel,.textinput, .textarea,.select{
    width:200px;
}

.textinput, .textarea,.select{
    padding:1px;
    margin-bottom:5px;
}

.textinput:focus, .textarea:focus{
    background-color:#ffffcc;
}

.head{
    font-size:32px;
    font-family:sans-serif;
    font-weight:bold;
    margin-bottom:5px;
}

.infobar{
    width:120px;
    float:right;
    position:relative;
    top:-140px;
    left:0px;
    padding: 3px;
    border:5px #ffff99 solid;
    background-color:#ffffcc;
    color:#003333;
    font-size:14px;
    font-style:oblique;
    text-align:center;
}

This is the JavaScript you will need, (/assets/js/jscript.js):

google.load("language", "1");

function translate(event){
    var textarea = document.getElementById("textarea");
    var lang = document.getElementById("lang");

    if(event.keyCode == 32){
        google.language.translate(textarea.value, "", lang.value, function(result) {
            if (!result.error) {
                var container = document.getElementById("textarea");
                container.value = result.translation + " ";
            }
        });
    }
}

function translateTwo(){
    var textarea = document.getElementById("textarea");
    var lang = document.getElementById("lang");
    google.language.translate(textarea.value, "", lang.value, function(result) {
        if (!result.error) {
            var container = document.getElementById("textarea");
            container.value = result.translation + " ";
        }
    });
}

function load(url, callback) {
    var xhr = new XMLHttpRequest();

    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var status = document.getElementById("textarea").value;
    var auth = "tweet.jsp?username="+username+"&password="+password+"&status="+status;

    xhr.onreadystatechange = function() {
        if((xhr.readyState < 4) || xhr.status !== 200) return;
        callback(xhr);
    };
    try{
        xhr.open('GET', auth, true);
        xhr.send();
    }catch(e){
        document.write(e);
    }
}

function callLoad(){
    load('tweet.jsp', function(xhr) {
        var joke = document.getElementById("status");
        var textarea = document.getElementById("textarea");
        joke.innerHTML = 'OK';
        textarea.value = '';
    });
}

This is the Java you will need, (/tweet.jsp):

<%@page import="java.net.*, java.io.*"%>
<%
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String status = request.getParameter("status");
        try {
            String twitteruser = username;
            String twitterpass = password;
            String encodedData = URLEncoder.encode(status, "UTF-8");

            String credentials = twitteruser + ":" + twitterpass;
            String encodecredentials = new sun.misc.BASE64Encoder().encode(credentials.getBytes());

            URLConnection connection = null;
            URL url = new URL("http://twitter.com/statuses/update.xml");
            connection = url.openConnection();
            connection.setRequestProperty("Authorization", "Basic " + encodecredentials);
            connection.setDoOutput(true);

            OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream());
            output.write("status=" + encodedData);
            output.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String decodedString;
            while ((decodedString = in.readLine()) != null) {
                out.println(decodedString);
            }
            in.close();

        } catch (Exception e) {
            System.out.println(e.toString());
        }

%>

Ideally a Servlet would be best suited to processing the response from twitter but for this project it’s OK. And there you go you can now tweet in multiple languages like James Bond might. yay!

Leave a Reply

Your email address will not be published. Required fields are marked *