Partying with IntelliJ IDEA Dart, Java, WebSocket and Glassfish

Recently I wrote a blog showing how to use the WebSocket protocol to push the data from a Java server to a JavaScript client. This time I’ll keep the same code on the server, but the client will be written in Dart. For this example I was using GlassFish 4.1 server, and IntelliJ IDEA 14.1 with installed Dart plugin. I also have Dart 1.9.1 SDK. My goal was to create one Web application deployable module that would contain both Java and Dart code.

I’ll be brief assuming the the reader has some familiarity with IntelliJ IDEA IDE and the structure of Dart projects. Repeating the same exercise in Eclipse IDE should be a trivial task too.

By the time I was creating this app, I already had an IntelliJ IDEA project with multiple Dart modules. So I wanted to add a new Java module with Dart support to the same project. If you prefer creating a new IDEA project from scratch, instead of creating a new module create a new project. Here’s how I did it:

1. Create a new GlassFish configuration (IDEA menu Run | Edit Configurations) pointing at the existing GlassFish installation.

2. Create a new module of type Java Enterprise selecting GlassFish as an application server Web Application and WebSocket as additional libraries. IDEA will create a project with directories src and web (the latter will contain the WEB-INF dir). I called my module GlassfishWebsocketDart. IDEA will also generate index.jsp, which you can delete.

GlassFish_Idea

3. Go to the Project Structure (Cmd ; ) and add GlassFish, GlassFIsh WebSocket, and Dart SDK as dependencies to the module GlassfishWebsocketDart.

4. Create (or copy from an existing Dart module) the files pubspec.yaml and pubspeck.lock into the root dir of your module.

5. Create index.html and main.dart in the web dir. The file index.html can look like this:

 
<!DOCTYPE html>
<html><head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="scaffolded-by" content="https://github.com/google/stagehand">
    <title>hello</title>

</head>

<body>

  <div id="output">dart uber</div>

  <script type="application/dart" src="main.dart"></script>
  <script data-pub-inline src="packages/browser/dart.js"></script>
</body></html>

My file main.dart looks as follows:

import 'dart:html';

main() {

  var output = querySelector('#output');

  WebSocket ws = new WebSocket('ws://localhost:8080/GlassfishWebsocketDart_war_exploded/clock');

  ws.onOpen.listen((event){
    output.text = &amp;amp;quot;Connected&amp;amp;quot;;
  });

  ws.onMessage.listen((event){
    output.text = event.data;
  });
}

6. Open main.dart in the editor and IDEA will show the option Enable Dart support – click on it.

7. Right-click on the pubspec.yaml and run pub build (select the debug mode). It’ll create the folder build with files and dart packages required for deployment.

build

8. Copy all the files from the build/web dir into the web dir located in the root of your module.

9. In the src directory create the following file WebSocketClock.java

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@ServerEndpoint("/clock")
public class WebSocketClock {

    static ScheduledExecutorService timer =
            Executors.newSingleThreadScheduledExecutor();

    private static Set<Session> allSessions;

    DateTimeFormatter timeFormatter =
            DateTimeFormatter.ofPattern("HH:mm:ss");
    @OnOpen
    public void showTime(Session session){
        allSessions = session.getOpenSessions();

        // start the scheduler on the very first connection
        // to call sendTimeToAll every second
        if (allSessions.size()==1){
            timer.scheduleAtFixedRate(
                    () -> sendTimeToAll(session),0,1,TimeUnit.SECONDS);
        }
    }

    private void sendTimeToAll(Session session){
        allSessions = session.getOpenSessions();
        for (Session sess: allSessions){
            try{
                sess.getBasicRemote().sendText("Local time: " +
                        LocalTime.now().format(timeFormatter));
            } catch (IOException ioe) {
                System.out.println(ioe.getMessage());
            }
        }
    }
}

10. IDEA can deploy Java web apps in the exploded mode (default) or as an WAR archive. Open the GlassFish configuration (menu Run | Edit), and it should look like this:

gf_exploded

11. Run your GlassFish and you should see the server pushing the local time every second. The Chromium browser runs the client’s code in its Dart VM, which properly runs WebSocket client communicating with the Java server.

chromium

You may ask, “Will this app work in other browsers that don’t have (and will never have) Dart VM?”. Good question. Theoretically the last two lines in our index.html file should check the presence of Dart VM and replace the references to main.dart with a reference to the JavaScript main.dart.js that was generated by the pub build process.

  <script type="application/dart" src="main.dart"></script>
  <script data-pub-inline src="packages/browser/dart.js"></script>

In practice this may not happen, and you’d get a 404 on “missing” dart.js. Now you have two choices:

a) Manually replace the above two lines with this one:

 <script src="main.dart.js"></script>

b) Add a dependency to your project to use the transformer dart_to_js_script_rewriter to do this replacement automatically. Your modified pubspec.yaml should look like this:

name: 'glassfish_websocket_dart'
version: 0.0.1
description: >
  A web app that illustrates dart, websocket, and glassfish.
environment:
  sdk: '>=1.0.0 <2.0.0'
dependencies:
  browser: any
  dart_to_js_script_rewriter: any
transformers:
  - dart_to_js_script_rewriter

Now run the pub get and pub build and only the JavaScript version will be used. This should be done only if you decide to deploy my useful application in production.

The other improvement that can be done are to create a deployment artifact that builds a WAR file that will include the content from the Dart build folder as well as compiled Java classes. And those who already cut the IDE umbilical cord should automate build and deployment with gradle and gulp.

In April, I’ll be making the presentation “Dart for Java developers” twice. On April 14 I’ll do it online at the New York Dart Users Group, and on April 23 I’ll do a live presentation for the New York Java SIG.

Update for MAC OS users: After upgrading to 10.10.3 GlassFish doesn’t start unless you change the startup line to
/Users/yfain11/glassfish4/glassfish/bin/asadmin start-domain –verbose

Why You Should Start Developing With Google Dart

In the summer of 2013 I wrote a blog “How Serious is Google About Dart“. It’s January of 2015, and I’d like to give you an update from the trenches. Our team has developed and deployed in prod a beta version of the application that helps consumers with finding and rating insurance agents and getting quotes online. The front end of EasyInsure is written in Dart language.

Before introducing the Dart ecosystem, I’d like to give you a little background about our prior experience in developing Web applications (I work for Farata Systems).

On the server side we always use Java and have no plans to switch to any other technology. After spending many years developing the front end with Adobe Flex framework and ActionScript programming language we got spoiled by this super-productive environment. After the mankind led by Apple killed Flash Player, we started to look for an alternative.

Back in 2005 we’ve abandoned JavaScript, but decided to give it another chance. Things were a little better this time. JavaScript has better IDEs and browser-based tools for developers. The number of JavaScript frameworks and libraries went down from two hundred to a couple of dozens, which is a good thing.

Still, the productivity of our developers dropped substantially in JavaScript comparing to what we’ve seen with Flex. I can’t give you exact numbers, but it looks like developing in Flex is at least three times faster than with any JavaScript framework we tried (ExtJS,AngularJS, and lots of small libraries). When I say JavaScript, I mean its version based on the ECMAScript 5 specification.

In 2013 we got familiar with the Google Dart language. The syntax of the language was pretty appealing and easy to understand. It felt like Java, but a little more modern. Dart is optionally-typed language. You can run the compiled Dart code in DartVM, but no browser except Dartium support it, and it’ll remain this way. Generating JavaScript from the Dart code is a realistic way of delivering Dart applications for any browser today.

But any language without the proper tooling is doomed, and this is what makes Dart stand out. Here’s the list of tools available for Dart Developers:

1. The IDEs: Dart Editor from Google and WebStorm from JetBrains. We use Dart Editor because it’s smarter than WebStorm today.
2. dart2js is a Dart-to-JavaScript compiler and a tree-shaker, which removes the unused code from the third-party libraries used in the application.
3. pub is a dependency management, development server and build tool.
4. gulp is a task manager. It’s an analog of Grunt or Gradle. We use gulp to prepare optimized ready-to-deploy application from the code produced by the pub build. In particular, we do the gzip compression there.
5. Dartium is a Web Browser for developers. Google Chrome is based on the open source project called Chromium, and Dartium is Chromium with built-in DartVM. We use it for launching and debugging applications.
6. Dump-Info Visualizer – allows to inspect the generated JavaScript. It gives a very convenient breakdown by the application’s JavaScript code so we can analyze file sizes and identify the scripts to be optimized.
7. Observatory is Dart profiler (we haven’t used it yet).
8. AngularDart framework. It’s a port of a popular JavaScript framework AngularJS.

The above list is pretty impressive, isn’t it? As Google Dart evangelists say, “Batteries included”.

Developing JavaScript applications in Dart is definitely more productive. I do recommend you to start learning Dart and develop the front end of your Web applications in this developer-friendly environment. Having said that, I’d like to warn you that there are no jobs on dice.com that require programmers with Dart skills. Oops… Moreover, three years from now your Dart skills may be in even lesser demand in the enterprise world. Oops…

After these two oopses half of the readers may lose interest to Dart, because it doesn’t meet their career objectives. For those of you who continue reading I’ll explain why IMHO you still should learn and use Dart today. Because the final release of ECMAScript 6 (ES6) is around the corner. Because this spec already gave birth to JavaScript 6 (it’s a boy)!

By the way, do you know why there is no enterprise jobs that require Dart skills? Because enterprise architects will fight hard against any language that runs in a browser unless it’s called JavaScript. Back in 2007 Adobe sales force did a great job by pushing Flex framework into enterprises. Enterprise architects were fighting hard against Flex then, and they will do the same with Dart. But Google is not Adobe. They won’t fight for Dart in enterprises.

But promoting Dart in your organization can be easy. Just explain your enterprise architects that programming in Dart is just a smart way of preparing the enterprise to embrace the bright JavaScript 6 future with classes,modules, promise, fast image rendering, et al. The code that you’ll be writing in Dart during the next 12-18 months will need to be converted into EcmaScript 6 as soon as several major Web browsers will start supporting it.

The syntax of Dart and ES6 are literally the same. Google invested time and resources in creation of IDE for Dart, and now they’re working on the IDE for ES6. Even manual refactoring of the code from Dart to ES6 shouldn’t be a major project, but I’m sure this process will be automated soon.

As a matter of fact, some browsers already started supporting ES6. See for yourself:

dartblog

I’d like to draw your attention to the greenest column on the right side. Yes, it’s the successor of the today’s funniest browser known as IE! Microsoft calls it Spartan, and promises that Spartan will be a lightweight browser that feels like Chrome or Firefox. You just can’t go wrong with such a name.

Spartan already supports ES6. Courageous early adopters can start developing code in ES6 now, than compile the code down to ES5 with Traceur compiler and deploy it in any today’s browser. But if you want to work in a tools-rich environment just develop your single-page applications in Dart and AngularDart. Give the ES6 some time to mature. The work on ES7 is being done too, and it looks very interesting and promising.

I’ve created a New York City Dart Meetup with a hope to get some Manhattan-based firm to host our meetings in the future. Meanwhile we’ll run our meetings online so you’re welcome to join no matter where you are located. Go Dart if you need to deliver today!

Finally, a language without protected variables

When I started to learn the soon-to-be-released programming language Dart, it was a love from first sight. I like Java, and Dart is like Java, but a little better. I’m planning to write a series of blogs about Dart, but I couldn’t resist writing about the missing protected keyword.

The thing is that I firmly believe that having protected data access is pretty annoying, and on multiple ocassions it was forcing me to write convoluted code just to access protected variables from a non-descendant class. Seven years ago I published a post “Who needs protected variables” at JavaLobby.

A year later I had to fight with protected variables in ActionScript – here’s why.

Now, I’m happy to report that Dart language specification has only private and public data access. Just like I always wanted! This is what the spec states:
Dart supports two levels of privacy: public and private. A declaration is private if its name begins with an underscore (the _ character) otherwise it is public.” Just like that. No keywords to remember.

I like Dart and suggest Java, C#, and ActionScript developers to learn it. You’ll find yourself at home. The JavaScript folks should learn it too.

How serious is Google about Dart?

Developing applications in JavaScript is not overly productive. You can use CoffeeScript or TypeScript to write code that will be converted into JavaScript for deployment. We are also closely watching the progress with Google’s new programming language called Dart.

It’s a compiled language with an elegant and terse syntax, which is easy to understand to anyone who knows Java or C#. Although compiled version of the Dart code requires Dartium VM, which is currently available only in the Chromium browser, Google created dart2js compiler that turns your application code into JavaScript in seconds, so it can run in all Web browsers today. Google also offers Dart Editor – an IDE with debugger and autocomplete. You can event debug the Dart code in Dart Editor while running generated JavaScript in the browser.

Dart’s VM can communicate with JavaScript’s VM, so if you have a portion of your application written in JavaScript, it can peacefully coexist with the Dart code. You can literally have two buttons on the Web page: one written in JavaScript and the other in Dart.

W3C published a document called “Introduction to Web Components”, which among other things defines recommendations on how to create custom HTML components. Existing implementation of Web UI package includes a number of UI components and defining a new custom HTML element can be done in a declarative way. The following code sample I borrowed from the Dart Web site:

html

This code extends the Web UI element `div` and includes a template, which uses binding – the value of the variable count is bound to HTML span, so as soon as counter’s value increases, the Web page immediately reflects its new value. I remember those powerful curly braces from programming with Flex framework. The Web UI package will be replaced soon with the Polymer Stack built on top of Web components. In 2014, the popularity of Dart should increase if Google will remain committed to this project. Will it?

Yesterday, we had a meeting at Farata Systems discussing the possibility of developing new functionality to our insurance stack in Dart. During the meeting one person said that about 15% of our users are still working with older browsers and we don’t want to lose them if Dart-generated JavaScript won’t work in Internet Explorer 7 or 8. I immediately answered that this wouldn’t be an issue, because several years ago Google created a smart way to automatically download Chrome’s JavaScript VM if the application runs inside IE. The name of this smart solution is Google Frame.

The meeting went on, and I decided to see what’s happening with this really useful plugin for IE. A quick googling for Google Frame revealed the page that started with a message “We’re winding down Chrome Frame, and plan to cease support and updates in January 2014”. WAT? Google did it again. Remember Google Reader? Forget it. Millions of people were using it and now it’s discontinued. “All subscription data will be permanently, and irrevocably deleted”. Google became bored with this toy too.

Unless Google will seriously reconsider their policies of decommissioning software, Dart won’t fly in the enterprise world. I hope Google will provide some iron clad guarantees that their Dart project will be around for the next 5 years. If this will happen, I’m all for it, and will prepare a new proposal to O’Reilly Media for a book titled “Enterprise Web Development with Dart”, where Farata’s engineers will share their experience in developing enterprise-grade applications with this promising language.