Day 26: TogetherJS–Let’s Code Together - Archived

Today for my 30 day challenge, I decided to learn a cool new JavaScript library from Mozilla called TogetherJS. A few months ago, I wrote an online Java editor for the latest version of Java i.e. version 8. Today, we will learn how to add collaborative features to the TryJava 8 application using TogetherJS.

TogetherJS logo

What is TogetherJS?

TogetherJS is an open source HTML5 based JavaScript library that allows realtime collaboration between users. It adds the same kind of tools that you see in Google Drive to any web application. It also enables text and audio chat between two or more people via WebRTC. Using TogetherJS two or more people can interact on the same page, seeing each other’s cursors, edits, and browsing a site together. It works with the latest versions of Firefox, Chrome , and Safari.

TogetherJS Demo

To showcase TogetherJS, I updated my TryJava8 application to add collaboration. The app is running on OpenShift http://tryjava-t20.rhcloud.com/.

To see application in action, open two browsers. I am using Chrome and Safari.

TogetherJS logo

Next, click on Start TogetherJS button to start a new TogetherJS session. User will get a confirmation dialog, asking him to confirm that he is ready to start the new session.

TogetherJS logo

Before clicking on I’m Ready, user can change his/her name and picture. I used my real name and picture. Then, press I’m Ready.

TogetherJS logo

User will be given a link that he/she can share with other users.

TogetherJS logo

In the second browser, I will open the invitation link. Second user will also get a confirmation dialog asking him/her to join the session.

TogetherJS logo

On joining the session, second user can see any action first users perform on his/her screen.

TogetherJS logo

The second user write a simple Hello World Java program. First user in realtime will also see the code without performing any action.

TogetherJS logo

First user opens the chat box and sends a message to second user.

TogetherJS logo

Second user receives the message.

TogetherJS logo

The first user fixes the semicolon error and second users get the changes in realtime.

TogetherJS logo

The first users run the program and ends the TogetherJS session.

TogetherJS logo

Github Repository

The code for today’s demo application is available on github: day26-togetherjs-demo.

Prerequisite

We will use Harp as a static web server. Harp requires NodeJS and the NPM package manager which comes by default with node.js installations. You can download the latest version of NodeJS from official website. Once you have node.js and NPM installed, we will use the NPM system to install Harp.

$ npm install -g harp

Developing TogetherJS Application

Create a new directory at any convenient directory on your file system.

$ mkdir day26demo
$ cd day26demo
$ touch index.html

The commands shown above will create a day26demo directory on the local machine and then create an empty index.html file.

Copy the following code and paste it in the index.html source file

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Run Java 8 in Cloud">
<meta name="author" content="Shekhar Gulati">
<title>TryJava8 | Run Java 8 in Cloud | Powered by OpenShift</title>
 
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.19.0/codemirror.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.19.0/codemirror.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.19.0/addon/edit/matchbrackets.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.19.0/mode/clike/clike.js"></script>
<style>
.CodeMirror {
    border: 2px inset #dee;
}
body{
    padding-top: 80px;
}
</style>
 
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
</head>
 
<body>
    <nav class="navbar navbar-default navbar-inverse navbar-fixed-top" role="navigation">
 
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="/">TryJava</a>
  </div>
 
 
  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
      <li class="active"><a href="/">Home</a></li>
    </ul>
   </div>
</nav>
 
    <div class="jumbotron container">
        <h1>TryJava8 -- Free , Online Java 8 Code Editor</h1>
        <p>Write your Java 8 code online anywhere , anytime...</p>
 
      </div>
 
    <div class="container">
 
        <div class="row">
            <div class="col-md-7">
                <h2>Run your Java 8 Code</h2>
                <form id="codeForm">
                    <div class="control-group">
                        <div class="controls">
                            <textarea id="code" name="code"
                                placeholder="Write your Java8 Code"></textarea>
                        </div>
                    </div>
                    <div class="control-group">
                        <div class="controls">
                            <button type="submit" class="btn btn-success">Run Code</button>
                        </div>
                    </div>
                </form>
 
            </div>
 
 
            <div id="outputBox" class="col-md-4 col-md-offset-1">
 
                <div id="resultRow" class="row">
                    <h2>Program Output</h2>
                    <div id="result" class="col-md-4"></div>
                </div>
 
            </div>
 
        </div>
 
        <hr>
 
        <footer id="footer">
            <p>&copy; Shekhar Gulati 2013</p>
 
            <p>
                Made with love by <a href="https://twitter.com/shekhargulati/"
                    target="_blank">Shekhar Gulati</a>. Contact him at <a
                    href="mailto:shekhargulati84@gmail.com">shekhargulati84@gmail.com</a>.
            </p>
            <p>
                <a href="https://www.openshift.com/" target="_blank"><img
                    alt="Powered by OpenShift"
                    src="https://www.openshift.com/sites/default/files/images/powered-transparent-black.png"></a>
            </p>
 
        </footer>
 
    </div>
 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
            lineNumbers : true,
            matchBrackets : true,
            mode : "text/x-java"
        });
    </script>
 
 
</body>
</html>

The html file shown above imports all the scripts and css files from cdnjs. We have used Twitter Bootstrap 3 for styling, jQuery, and CodeMirror for rendering a code editor.

Run the Java Program

Now we add the code which will make the POST call using jQuery to execute the Java code. Add the following to end of index.html before </body>.

<script type="text/javascript">
        $("#codeForm").submit(
            function(event) {
                event.preventDefault();
                $("#status").empty();
                $("#result").empty();
                var code = $('textarea').val();
                if (!code) {
                    alert("Please write some code");
                    return;
                }
                var data = {code : code};
                var url = "http://tryjava-t20.rhcloud.com/api/snippets";
                $.ajax( url,
                        {
                            data : JSON.stringify(data),
                            crossDomain : true,
                            contentType : 'application/json',
                            type : 'POST',
                            async : true,
                            success : function(result) {
                                $("#resultRow").show();
                                if (result.compilerOutput != 0) {
                                    $("#result").append("<p class='text-error'>"+ result.result + "</p>");
                                } else if (result.verdict === "FAILURE") {
                                    $("#result").append("<p class='text-error'>"+ result.result+ "</p>");
                                } else {
                                    $("#result").append("<p class='text-success'>"+ result.result+ "</p>");
                                }
                            },
                            error : function() {
                                alert("Something wrong happened on the server");
                            }
                        });
            });
    </script>

Enable Collaboration

Now we will enable collaboration using TogetherJS. First add the TogetherJS javascript library to index.html.

<script src="//togetherjs.com/togetherjs-min.js"></script>

Now add a button next to Run Code button which will enable collaboration.

<button class="btn btn-info" onclick="TogetherJS(this); return false;">Start TogetherJS</button>

Now reload the browser and you will see Start TogetherJS button. On button click, TogetherJS(this) call initiates the library, displaying an opt-in dialog, and then users can see where other users place their cursor, click, change form fields, and modify page contents.

TogetherJS sessions are connected to the domain you start them on (specifically the origin). So if part of your site is on another domain, people won‘t be able to talk across those domains. Even a page that is on https when another is on http will cause the session to be lost.

Want To Host Your Own TryJava Application

Yes, you can deploy your own personal TryJava application in cloud. The code for backend and front-end is open source.

Before we deploy the application to OpenShift, we’ll have to do few setup tasks :

  1. Sign up for an OpenShift Account. It is completely free, and Red Hat gives every user three free Gears on which to run your applications. At the time of this writing, the combined resources allocated for each user is 1.5 GB of memory and 3 GB of disk space.

  2. Install the rhc client tool on the machine. The rhc is a ruby gem so you need to have ruby 1.8.7 or above on your machine. To install rhc, just typesudo gem install rhc
    If you already have one, make sure it is the latest one. To update the rhc, execute the command shown below.sudo gem update rhc
    For additional assistance setting up the rhc command-line tool, see the following page: https://openshift.redhat.com/community/developers/rhc-client-tools-install

  3. Setup the OpenShift account using rhc setup command. This command will help us create a namespace and upload your ssh keys to OpenShift server.

After setup, we can create a new OpenShift application by running the following command.

$ rhc create-app tryjava diy mongodb-2 --from-code https://github.com/shekhargulati/tryjava.git

It will do all the stuff from creating an application, to setting up public DNS, to creating private git repository, and then finally deploying the application using code from my Github repository. The app is running here http://tryjava-t20.rhcloud.com//

That’s it for today. Keep giving feedback.

Next Steps

Categories
Node.js
Tags
, ,
Comments are closed.