Pushing data to multiple WebSocket clients from a Java server

Finished writing the WebSocket chapter for the second edition of my Java 24 Hour Trainer. In this blog I’ll show you one of the code samples from lesson 28.

Pretty often you need to write a program that publishes the same message to all connected clients. For example, multiple clients of the online auctions have to be notified when a new bid is placed on the product. Another example is when a new stock price quote need to be pushed from the server to all connected clients. With websockets it’s a pretty easy task.

I’ll show you a basic example when a WebSocket endpoint pushes the server’s time to all connected clients. If you can publish the server’s time to all connected clients, you can publish any application-specific data.

The following endpoint WebSocketClock schedules the task that gets and formats the server’s time every second and publishes the time to all connected clients. I schedule this timer once when the first client connects to our endpoint. The method sendTimeToAll() finds all connected clients by invoking getOpenSessions() on the Session object. Then on each session it calls getBasicRemote().sendText().

@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());         
          }   
     }   
  }
}

The Web client is pretty simple. On the page load the JavaScript code connects to the WebSocket endpoint on the server. The callback onMessage() is invoked when the message (current time) arrives. In this callback I update the content of the span HTML element with the current time. Since my Java code will send the message every second, the span content updates with this frequency. No page refreshes, no heavy HTTP headers, no AJAX long polling hacks either.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
  <span id="messageGoesHere"></span>
  
  <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/Lesson28/clock"); 
       
    ws.onmessage = function(event) {
      var mySpan = document.getElementById("messageGoesHere");
      mySpan.innerHTML=event.data; 
    };
    
    ws.onerror = function(event){
        console.log("Error ", event)
    }  
</script>
</body>
</html>

The next screenshot shows how Eclipse internal browser, Chrome, and Firefox display the current time published by my WebSocket endpoint.

f28_6

Three Web clients get current time published by a WebSocket endpoint every second.

Iterating through all open sessions works fine if the number of connected clients is small. But if you have hundreds of clients, consider grouping the Session objects into separate collections in @OnOpen message handler, and sending messages to each group in parallel from multiple threads. Important: by default, a Java EE server creates a new instance of the server endpoint class for each client’s connection, so if you’ll be creating your own session collections they must be static:

 
private static Set<Session> sessionsChunk1 = Collections.synchronizedSet(new HashSet<>());
private static Set<Session> sessionsChunk2 = Collections.synchronizedSet(new HashSet<>());
Advertisement

Submitted a proposal to IoT track at Cloud Expo New York

In June a large expo and a conference Cloud Computing comes back Javits Center in Manhattan. This year it includes a new track Internet of Things, which promises to be “The Next Big Thing”. In our company we have enough of early adopters of anything related to software development, and we’d like to present what we can do in this field. Here’s the proposal I just submitted to the IoT Expo:

ABSTRACT

Case Study. IoT In The Field Force Automation

From software development perspective IoT is about programming “things”, about connecting them with each other or integrating them with existing applications. This case study will show you how small IoT-enabled devices from multiple manufacturers can be integrated into workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.

BIO

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion. He leads Princeton Java Users Group. Two of Yakov’s books will go in print this year: “Enterprise Web Development” (O’Reilly) and “Java For Kids” (No Starch Press).

Keeping my fingers crossed…

Java Swing Has to be Deprecated

Every time I start teaching my new Java class I’m looking at the Swing units in the manual asking myself, “Why my students need to know Swing framework?” Well, I need to teach them how to program GUI, event listeners, asynchronous worker threads and event loop that are pretty much the same in every programming language that deals with UI. My students create applets and test them in appletviewer, then they are going through hard times trying to run them in Web browsers… In the end, I tell them that they won’t be going doing Swing programming in the real world projects. I also tell them that if Amazon.com would decide to re-write their UI in Java they’d be out of business in no time.

If not with Swing framework, how should my Java students learn GUI programming? There is another Oracle product called JavaFX. It’s a better looking wrapper for Swing. It still runs on JVM, so Amazon would go out of business as quickly as with Swing, but at least with a better looking UI.

Java developers look down at the HTML/JavaScript crowd. Yes, programming in JavaScript is not as productive as in Java, but HTML5 applications usually look nice. HTML5 developers know that having a Web designer producing professionally looking CSS is a must. Whereas Swing components are ugly by default. They are so last century.

Recently I was attending a presentation on a particular Eclipse plugin that could produce Web reports. The speaker was using Twitter API to demonstrate how easy it was to generate a report finding tweets based on a certain hashtag. Tada….Report is generated, the Web browser opens the report’s URL and pops up the modal dialog asking to enter the search parameter. What an ugly dialog box that was! Eclipse grey style, 90% of its real estate was empty with an input field on top prompting to enter the parameter’s value. No one in the audience (all Java developers) seemed to care. They are all used to ugly GUI in enterprise applications. OK, this product was using RCP UI components, but the Swing ones are definitely not better.

The sooner Swing is deprecated the better. Even if JavaFX has no future in the Web or mobile applications, it has to become a mandatory replacement for Swing. Just because it promotes a better looking UI. Just because it promotes better taste among Java developers, who live in two different realities: the ugly depressive GUI at work and the eye candy world of iOS or Android applications. Let’s make a first step toward merging these worlds by killing Java Swing framework.

How we write a book for O’Reilly

In the past, to write a book the writer would need a quill pen. After a while, Microsoft Word replaced the goose feather. Today, any Word processor is not good enough. You need to have tools to generate the book content in various formats to be read on various devices. Things get complicated if you have more than one writer working on the book. Now you need a distributed version control system.

We’ve recorded a Webcast showing how we write a technical book for O’Reilly Media. This Webcast is not about the book itself, but rather about the process of writing the book and the software tools we use for it.

The recording is available here. This is an interactive recording – you can switch it to the full screen mode.

HTML5, PowerPoint, and the Real World

If you are going to attend any HTML5 conference, most likely you’ll see some of the speakers using Web browsers for presentation slides. The audience likes it cause it’s cool. A month ago one of our software engineers presented this way at the conference for Web developers.

There is an extra benefit in using such html-based slides especially when your presentation is about Web applications. Just think about it, when the time comes for a demo, you are not leaving the Web browser – the next “slide” has the URL of your demo right in the address bar of your browser and you do the demo right there. Hit the right arrow, and the demo turns into a slide again. Isn’t it cool? Yes it’s cool, but not practical.

Because everything else in not as cool and requires a lot of work comparing to Microsoft’s PowerPoint or Apple’s Keynote. Say, you want to add an image to the slide, make it smaller, and move it to the top right corner of the slide. In Powerpoint your hand just does it automatically. In HTML slides it’s a project. How about font manipulations? In Powerpoint you don’t even think about it – you just do it. In HTML slides it’s a project.

Animations? Which one you want? Just pick one from a dozen that are readily available in PowerPoint. You want the image to fly from the top, bounce a couple of times and settle in the middle? Takes 10 seconds to pick the image, 20 seconds for testing, and another 5 second to remove this flashy-bouncy-flying effect cause it would make your audience dizzy. I’m sure this will be easy in the HTML6 era, but the HTML5 tooling is not there yet.

How about embedding media into slides? OK, ok, you got the message.

Next week I’ll need to find some time to migrate that HTML presentation into the tried and true PowerPoint slide deck. Yes, I’ll be switching from PowerPoint to the Web Browser when the time will come for the demo. This is a drawback. But every other aspect of making a presentation in PowerPoint or Keynote is superior to HTML.

I’m observing the same situation in the enterprise world, where some IT managers are diving into new HTML5 project without thinking about the consequences. If you guys want to be cool, just dive right into the cold water.

If you want to develop an application that will contain 100% of the required functionality – wait a couple of years for HTML5 tooling to mature. But if you want to be cool now, eliminate half of the required functionality and do your 100-screen enterprise Web application in HTML5.

Today, at the meeting with a prospective client I said that if you decide to implement the same functionality in HTML5 vs. a mature platform with a compiled language and predictable VM, multiply the development time by two. Now I’m thinking I was wrong. The time should be tripled.

The Cover and the Epilogue of the Upcoming Book

Our publisher sent us for approval the image of a cover of the upcoming book on Web development. We were told that the name of the bird is Roseate Spoonbill. Why they decided that Roseate Spoonbill should be associated Web development will remain a mystery. I guess, since the beak of this birdy is pointing at the word “Web”, the customer of the book store should think to himself, “Hmm, I have no idea what kind of bird this is and I don’t know how to develop for the Web. Let me buy this book!” In the unlikely event that you’re also not overly familiar with Roseate Spoonbill, please refer to THE SOURCE.

cover

But this cover pales in comparison with the book epilogue. This book is about HTML5, and one would expect some drum roll and fanfares praising HTML5. Here’s what the current version of the book epilogue reads:


Epilogue

Even though this book is about HTML5, the authors would rather work with compiled languages that produce applications to run in virtual machines. Such software platforms are more productive for development and more predictable for deployment. While writing this book we were often arguing about pros and cons of switching to HTML5, and so far we are concerned that the HTML/JavaScript/CSS platform is not ready for developing of the enterprise applications just yet. We live in the era when amateurs feel comfortable creating Web sites and that JavaScript provides flexibility and customization the Access and Excel provided in the old good PC times.

Till this day Microsoft Excel is the most popular application among business users in the enterprises. They start the application locally, it has a local storage that enables work in the occasionally-connected scenarios. Both the data and the code are physically located close to the user’s heart. Microsoft Excel allows the users to have her own little pieces of data and amateurish-but-working-code (a.k.a. formulas) very close and personal. Right on the desktop. No need to ask these IT prima donnas for favors. No dependencies on the connectivity or some mysterious servers being slow or down. The most advanced business users even learn how to operate MS Access database to further lessen the dependency on IT.

But there is only so much you can do with primitive tools. Visual Basic was “JavaScript” of the nineties – it had similar problems, but nevertheless had huge followings. Now the same people are doing JavaScript. If we don’t break this cycle by adopting a common to all browsers VM, we are doomed for going through the generation after generation of underpowered crap. We wrote this book to help people with understanding of what HTML5 applications are about. But make no mistakes – the world of HTML5 is not a peachy place in the future preached by educated and compassionate scientists, but rather a nasty past that is catching up bringing the mob with it.

Most likely the publisher won’t let this epilogue to finish the book, and this blog will remain the only place this text will be published. Amen, bro!

Starting XAMPP Apache from Aptana IDE

In the first five chapters of the upcoming book on Web development we use Aptana IDE. It’s free, easy to use, has a simple internal Web server, and is Eclipse based. All this makes it a perfect IDE for teaching Web development with HTML and JavaScript. While working on a jQuery.ajax() code sample for the upcoming book, I wanted to show how to make an AJAX POST request to the server side script with the manual form serialization. Since knowledge of Java is not a requirement for reading this book, I found myself in an unfamiliar territory of using PHP.

Disclamer: I’m not a PHP developer, and have no intention to become one.

I just needed a simple script that would echo the data it received. Writing such a script is not a rocket science, but now I need a Web server that would support PHP, which means pretty much any server other than the toy one that comes with Aptana.

xampp_UI

OK, I’ve installed the XAMPP package that includes Apache Web Server and supports PHP. It comes with a nice little UI with the buttons to start stuff. It’s shown on the right and can turn on/off Apache, MySQL, and FTP with a click of a button, which is perfect solution for everyone, but me. Remember, I want to do it from Aptana, and not from and external UI panel. But first things first, let me check that my PHP script even works under Apache.

This part went through fine. I created an Aptana project right under the document root of Apache, which is the htdocs folder, put there helloworld.php, html, JavaScript – he whole shebang. Then I opened the Web browser, paster the URL there, and it worked like a charm – I’m da man!

But the fact that I had to leave Aptana bothered me and I decided to configure an external Web server in this IDE. I did similar thing in Eclipse and Apache Tomcat a million times, but this is different – I needed to start a prepackaged Apache Web server from XAMPP.

First, I learned how to do this from a command line in the Terminal Window (I use MAC OS):

To start apache do this: sudo /Applications/XAMPP/xamppfiles/xampp startapache

To stop apache do that: sudo /Applications/XAMPP/xamppfiles/xampp stopapache

But I knew it wouldn’t be that easy to do from the IDE, casu when I do stuff as a sudo user, I get a command line prompt to enter the admin’s password. OK, let’s try and see what happens. Right-click on the Aptana’s project, then Run Configurations, then the link Configure next to the “Use selected server”. Then I’ve entered everything about my Apache Web server:

ApacheServer_Aptana

Aptana has created the Servers view with this server entry, but when I tried to start the server by clicking on the green play button it gave me this error: “no tty present and no askpass program specified”. I knew it! Aptana doesn’t know where to ask for the sudo’s password!

How can I turn this stupid password off? Google helped – there is a system file /etc/sudoers that has to be edited to allow certain users to sudo without being bothered with the password. Can’t edit it – not enough permissions. That’s an easy one. The unix command chmod works fie on Mac. Being a lazy person I did sudo chmod 777 sudoers. It did the job, but it was a mistake – stay tuned. Opened the file, figured out that I need to uncomment one line and specify my ID with the NOPASSWD option.

OK, but the warning in this file reads “# This file MUST be edited with the ‘visudo’ command as root. Failure to use ‘visudo’ may result in syntax or file permission errors that prevent sudo from running.” Uuuh, getting dangerous, nice! I still remember a couple of vi commands – did the editing in the Terminal window, saved the file… and got the error message that the “/etc/sudoers is mode 0777, should be 0440 “. Man, that was my laziness with chmod 777. Let me change it to 440. Not that easy now! It doesn’t allo me to change the permissions back. Am I screwed or what? Did a backup to my external disk last week – shouldn’t be difficult to recover the original file sudoers.

But let me google first – it helped again – was there a life before Google? Some kind soul suggested to run Disk Utility, which has a button “Repair Disk Permissions”. It repaired a bunch of files including this one keeping my corrections intact.

Voila! Now I can start my Apache Web Server without leaving Aptana IDE by clicking on the Play button in the Servers view! Great! But how to stop it? Eclipse IDE has a red little square next to Play? The right-click menu doesn’t exist in the Servers view in Aptana Studio 3 IDE – I guess their developers are as lazy as I am. I’m not going to continue my research though. Nough! If anyone knows how to stop the server started from Aptana IDE – please do let me know.

HTML5 or Flex Framework

More than a year passed since Adobe decided to stop supporting Flex framework and gave it away to Apache Foundation. This writeup is based on the conversation I had with my colleague Anatole Tartakovsky in January of 2013. In this conversation I’ve been representing the HTML5 community while Anatole fought for Flex framework. I’m trying to find arguments against using FLex framework even though I believe that it remains the best and the most production way for developing Web applications. I’ll be just playing devil’s advocate here. Anatolepoor and ill also believes that Flex is the best framework available today, but in our company we often argue about the tools to use for various projects. We hope that Web developers find this conversation useful and thought provoking.

Yakov. If you read this blog, most likely you know about our company, Farata Systems. Our engineers work on both consulting projects and develop a product for our sister company SuranceBay that creates software for insurance industry. Technology-wise, we have three practices:

1. Rich Internet Applications using Apache Flex and Adobe AIR
2. Web application with HTML/JavaScript/CSS
3. eCommerce applications (we have about 20 Hybris developers)

On the server side we use nothing but Java. We’re hiring people, but noticed that it’s getting a lot more difficult to find experienced Flex developers. Last week we made an offer to a Flex developer, but before accepting it, he asked me to share my opinion about the future of Flex. He knows about our company and is glad that he’ll be joining our team, but at the same time he’s worried that Flex skills won’t be a useful asset on his resume. I can read his mind, “I’ll waste a couple of years doing Flex, but my classmates, colleagues and the rest of the progressive mankind will be studying HTML5. Is it worth it?” I did my job defending Flex, now it’s your turn, Anatole, and I’ll try to prove you wrong.

Anatole. As I just learned, I’ve been working with useless technologies for 30+ years, and every technology I liked is not in use anymore. In my opinion, Flex framework has no future.

Y. What a nice way to defend Flex! Do you want to say that your programmer’s life was wasted?

A. I want to say that it was extremely interesting, but Flex has no future.

Y. Was this by M.Zhvanetsky who said, “Who cares about the soup if so much is going on in the kitchen“?

A. I’d rather say that Flex has no future, but it has the present. HTML5 has the future, but the present is dark and foggy. First, we need to decide if we live in the present or in the future. Second, it’s very difficult to properly guess the technology worth studying and using. Of course, the tools that are popular on the market will win, but they will also lose by attracting legions of low paid developers. Besides, being unproductive these tools won’t allow timely releases of high quality software. This leads to further degrading of software projects and programmers’ pay. There is a high end market, where more expensive and rare tools are being used by well rounded developers. And there is mainstream that uses various versions of HTML, Visual Basic and the like. These tools were never highly productive, but their better competitors could not attract even a one tenth of the developers community. At some point the psychiatric situation on the market causes people to not pay attention to the good tools, but rather go with the flow.

Y. Our company is not a typical one – each of the owners remains highly technical, and we don’t have any political reasons to select or reject any technology. Sure enough, we are very carefully monitoring the latest trends in the industry to be able to offer help in IT consulting. But we are down to earth people who want to deliver our own software as fast as possible without jeopardizing the quality of the product. You may be surprised, but new Flex projects are being started and the Flex-to-Flex redesigns are happening on the Wall Street – we continue getting requests for help. Such projects are typically run by smart and technically savvy managers who are not afraid to voice an opinion that may differ from the general software policy in their organiation. But an average manager does not want to take a risk and use a non-popular technology with a literally non-existent talent pool. Anatole is running the project where all developers know Flex and Java, and he’s not planning to switch to a different set of technologies any time soon. Why do you prefer Flex and AIR.

A. I’m planning to switch and will do so, when I’ll see a better than FLex technology that meets our needs. I agree to switch, but it’s like “Tomorrow I’ll marry the Queen of England. Half of this plan is accomplished – I agree“. The problem is to find a replacement. IMO, technologies like HTML5 will change the style of programming and the resulting product too.

Y. After making such strong statements, you need to say something to improve your credibility. Please tell the audience what did you work on in the beginning of this century.

A. There were no alternatives to HTML/JavaScript before the Flex framework was created. We had DHTML, HttpRequest and XMLHttpRequest, which was later branded as AJAX. The CSS capabilities were limited, but it was not that important because there was only one enterprise browser back then, and styling just worked without the need to worry about the incompatibility issues. We’ve been creating libraries having the functionality similar to ExtJS. They were not as polished, tested, and documented as ExtJS, but productivity-wise they were at least as good as today’s HTML5/JavaScript mainstream libraries. I was leading a team of 5 developers that were working on this library (XMLSP) from 1999 till 2004. But to create a product as good as Flex, the community would need to create 6-7 products that would comprise a platform that would include the following:

– a much more mature JSON that would support the skeleton generation on both sides
– a compiled JavaScript-like programming language (expecting to see it soon)
– an ability for creation of the finite state machine and CSS (give it another 2-3 years to appear)

Unfortunately, during the last seven years Flex didn’t have competitors. HTML is the future, but it’s a remote one. I don’t see it real in the enterprise applications for at least two years, but more likely till 2016.

Y. You’re talking about enterprise Web, not about small Web sites that can be easily developed in HTML5. All evangelists are happy to demo simple applications like Contact List to prove that HTML5 and their JavaScript framework is here to stay and is THE Framework to use. The rookie developers are often impressed by a demo of an HTML5 game moving objects using an HTML SVG element. To get cheap applauses at a Web conference you need to proclaim, “No more plugins like Flash or Silverlight. RIP!”. It’s even more effective than making fun of Internet Explorer.

A. True. If you want to write HTML5 application you need to seriously reevaluate what your application should be able to do. You’ll need to simplify it. A typical enterprise Web application serves the consumers that don’t use it anyway, and it also serves the professional business users that help consumers.

Y. Please don’t just make such ungrounded statements. Explain, what this means.

A. This means that consumers spend very little time using these Web applications – they they don’t use such applications from 9 to 5. These applications are being used on a weekly or monthly basis. The requirements for such applications are a lot simpler than for heavily used applications for professionals. The back office applications must increase productivity of business users and support a lot more functions. If you need to support wide variety of users, you’ll need environments allowing configurable applications that can be compiled and support quick refactoring for the new class of users or when the business requirements change.

Y. I agree that refactoring in Flex is more advanced than in JavaScript, but what are the problems with configurable applications?

A. By configurable applications I mean the ability to quickly customize the application with the same code base to support more complex or more simple interface and security. It’s not so easy to do with JavaScript, because it HTTP requests can be disassembled, you’ll have to deal with security problems, the code becomes more difficult to understand without having the compiler’s support.

Y. As far as I remember, Flash Player was also blamed for security holes, wasn’t it? Besides, since HTML5 is a mainstream, all major browsers treat security issues very seriously and all security holes will be closed a lot faster than any single vendor like Adobe, Microsoft, or Oracle would do.

A. The roots of Adobe’s security holes are in attempts to merge two incompatible security models of Acrobat and Flash Player. Now you can run Flash code inside PDF, which revealed security holes originated in incompatibility of the sandboxes. Most of these holes can be plugged by changing security settings of Acrobat and not by fixing Flash Player’s errors. But overall, Flash Player has less security issues than infamous cross-scripting of Web browsers and the likes. We are able to create secure Flash applications that would certainly had security issues should they be written in HTML5. What I really miss in Flash Player is the ability to integrate with telephony and work with peripherals that exist in natural environments. Unfortunately, Flash Player is not evolving fast enough to support new technologies for input/output and the voice interface. The main problem of Flash Player is that it was literary frozen since 2008. During the last four years Adobe didn’t do much to bring it up to date.

Y. It’s been more than a year since Adobe announced that their main interests for Flash are games and videos. You can’t expect any improvements in Flash for enterprise applications. Don’t forger that Adobe remains the owner of Flash Player, and no matter how great the Apache Flex contributors are, their hands are tied – the runtime is out of their control. I don’t like the way Adobe handled open sourcing of Flex, but they have business to run, and if they make money elsewhere, no one can force them to allocate proper resources to implement Flex and Flash Player improvements. Do you have any reasons to believe that Flex won’t lag more and more behind HTML5 technically?

A. I don’t have any hopes that Flex won’t lag behind. So far Flex and Flash player is still far ahead – we still live in the future comparing to HTML5. Yes, HTML5 has some features that make it appealing for enterprise and mobile development, and it would be great if Flash Player would continue evolving in these directions too. The main reason why Flash Player is dying is that ten years ago Adobe rejected Apple’s requests to create tools for their platform. Adobe considered this platform unproductive, and Apple had to recreate equivalents for all Adobe’s products themselves. After that, Apple stopped allowing Adobe’s products on their market. You can call it politics or personal vendetta, but unfortunately there is nothing you can do about it. Without Apple’s support Adobe’s tools will always have hard times. Will it change in the next couple of years? Not likely, unless the structure of both Adobe and Apple’s management will change.

Y. Based on what I see, Adobe won’t be willing to make steps toward Apple. Adobe prefers selling expensive and profitable software to corporations, and it’s not likely that they’ll return to Web browser’s plugins that are not welcomed by majority of the developers.

A. This is true for the most part. But historically, there were precedents when spin-offs were created to purchase some of the software products from large companies. Adobe is not the first company specializing in milking old cows (making money from old products). I.e they don’t improve some of their products, but purchase established third party companies and invest in cross-integration with their products charging the newly acquired customers for the new functionality. The chances are that non-profitable Flash platform can become a candidate for such a spin-off. Adobe might sell the Flash Player for a small chunk of cash to people who are interested in improving this technology. Unless this happens, Apache Flex is a still baby. I’ve attended several meetings in Apache Flex community, but I’ve yet to see people who can lead this community.

Y. There are lots of excellent Flex software developers in the world who could do it, but they simply can’t afford it. As I said, there is not many companies that can continue using a technology based on its merits. Flex experts need to make a living and feed their families. They can’t spread themselves thin doing both Flex and HTML5. They either work as independent contractors and want to keep their hourly rates high, or work as enterprise employees and don’t want to go against corporate IT policies. Many of them prefer to stay focused on one major technology to keep their skills in demand.

Our company is in minority, but we are not afraid to become known as one of the last Flex shops. We believe in hiring well rounded developers that are open to adding Flex to their skill set understanding that in a couple of years they may need to learn something else. By the way, some of the people are still doing Cobol and dine in Michelin-starred restaurants on a regular basis. The if-statement exists in every programming language. In some cases you’ll need to put a curly brace after if, and in some languages you need to write elseif as one word. Some languages support classical inheritance, and some – prototypal. This doesn’t scare me, but it seems that lots of people are reluctant to accept that learning something new is a way of life of professional software developers.

A. Of course, people have to take care of themselves, but if I were a young software developer, I wouldn’t worry that much about any particular technology. Let’s go back to the year of 2008, when Flash Player’s penetration on desktops was about 99% and no one could even imagine that this bulldozer could be stopped. Adobe offered to use ActionScript 3 as the ECMAScript standard arguing that they have a compiled and extended version of JavaScript, and Flash Player can be used as a virtual machine for the code produced by this language. Web browsers would simply need to recognize in HTML documents, which is an easy part.

Y. In the 90th, some people would even do language=”VBScript” for Visual Basic Script.Today, you don’t even have to specify that your scripting language is JavaScript – it’s a default in all browsers, and the language property is deprecated. Actually, you should be using the type property instead of language, and if it’s missed – JavaScript is assumed.

A. But browsers can support other languages, but there is no standard language. Sooner or later Microsoft and other companies that decided to deny ActionScript as a standard compiled language and solve the problems of performance and refactoring of JavaScript will need to solve these problems. And the future HTML6 or 7 will include a compiled language that will look very much similar to today’s ActionScript. Yes, it may have different keywords, support even more dynamic constructs and do a better job with eval, but the young developers doing ActionScript will be better positioned in three years than those who develop in JavaScript. Most likely, the ActionScript code developed today will be converted one-to-one to this new language of the future.

Y. Did you have a chance to get familiar with the Microsoft’s language TypeScript?

A. I haven’t. But when we were developing our own browser, when JavaScript would pass the first version of p-code we would create and cache automated objects to avoid recompilation of JavaScript.

Y. The syntax of Typescript extends JavaScript, but it supports static types, classes, and modules, and can be compiled into JavaScript, i.e. will require nothing, but JavaScript engine. On the other hand, Google’s Dart expect a browser to have a VM in addition to JavaScript engine.

A. No matter what language will win, the conversion from ActionScript will be mechanical more or less. It all comes down to your way of thinking and to the level of complexity you can afford in a compiled environment vs interpreted one. There is a major difference in approaches to programming in ActionScript
and in JavaScript. After spending some time designing and writing the ActionScript code you fix most of the syntax and refactoring issues during the compilation and linking stages . In JavaScript you can immediately test your code without getting error messages even if your code has the wrong syntax or linking problems. The time that Flex developers spend beatifying the code while writing it, JavaScript developers spend debugging their code in runtime. Programming in dynamic and static languages requires a big cultural shift. Developing complex projects in JavaScript is extremely difficult. If application developers have no prior experience in developing frameworks in JavaScript, they can only deliver Web applications with a set of relatively simple Web pages with limited functionality. Regular programmers who don’t remember what they have written yesterday, will have hard times debugging their own code. I’m not trying to insult people, but unless you can keep in your head all your code, the chances of producing well functioning large JavaScript application are very limited. I recommend to spend the next several years in a comfortable environment waiting till HTML6 or 7 will include a compiled language. In my opinion, when it happens, you’ll need to forget most of what you’ve learned about HTML5.

Y. I don’t agree with you. We didn’t talk about the development for mobile devices. You are talking about programming in a comfortable ActionScript environment, but why not spend a couple of years learning HTML5 methodologies and tools that would allow today’s Web developer digest the Mobile First concept, learn how to properly modularize JavaScript code, which frameworks to use in both desktop and mobile devices, what Responsive Design is about, is it possible to live with one code base for all devices or it’s better go hybrid or even native, and on, and on, and on. This takes a lot of time, and, putting yourself in the shoes of that young developer, spending these couple of years in learning all this new world won’t be a waste of time. By the way, in the book “The Enterprise Web Development” we show how to develop a Web application that will work in all devices from the same code. So I don’t believe that developing in Flex for a couple of years will allow this guy just to change the hat and start writing HTML/XYZScript/CSS code. I’m sure that just working in your team would make him or her a well rounded developer, but it’s not as obvious for other people.

A. If this developer would work in my team since 2006, he’d skip lots of frameworks like Mate or Parsley without losing much. People who say that their frameworks help in programming are the same that were promoting the Axe Soup before. One way or the other – good people is the solution. Frameworks rarely help. Tools do. HTML has a number of tools to test UI on different platforms. Similar tools were created for Flex and cross-platform CSS and skinning. But I don’t believe in miracles. I haven’t seen a single-code-base applications that work well on Android, iPhone, and desktop browsers.

Y. We need to compromise. In Flash Player applications you can choose pixel-perfect design: the user must have a 1024×768 viewport minus chrome and margins – my way or highway. But if you’ll need to make this application work on highly fragmented Android market, on iOS, Blackbery, desktops, and other devices, ask yourself a simple question, “Do we have money to hire two-three teams for developing and supporting several versions of the application for different devices or we’d rather compromise, and push the HTML5-based product out the door?” Money talks in the enterprise unless your project has unlimited budget. But if you’ll agree to compromise and move away from the pixel-perfect world accepting the fact that the Donate button will look a little bit different on different devices, go with the responsive design principles and have one code base. You’ll provide different CSS sections that will automatically apply different layouts based on the screen (a.k.a. viewport) size, but the HTML and JavaScript will be the same. I know, this approach has drawbacks cause some portions of CSS will be loaded for nothing to any particular device, but it can be a practical business solution.

A. People who promote the same design for different platforms usually talk about publishing information and not about interactive applications. If you need to publish the information using different layout managers, responsive design will help. But enterprise applications often have more than one target audiences. Consumers need an easily downloadable application and Web browser works fine here. Mobile applications should be compiled either into the native code or into some byte code that performs close to the native one. But UI must be different based on the available screen real estate and use touch interface.
If you’ll take any framework that works on both desktop and mobile devices you’ll get two sets of controls and the need to maintain two different source code.

Y. Nobody forces you to use any framework – just stick to JavaScript and, maybe, non-intrusive jQuery components and plugins.

A. Without frameworks I’ll have less UI controls to chose from. Frameworks may address the need in controls and convenience of UI.

Y. and browsers incompatibilities

A. Maybe. But when I hear that someone has the same codebase for the desktop browser and other devices, I want to see it and make suer that it doesn’t falls into the publishing realm.

Y. Of course, the Boston Globe site is a classical example of responsive design in publishing. But we can even take an application that we use in our book – Save Sick Child http://enterprisewebbook.com/#_responsive_design_one_site_fits_all. We have five areas (div’s) that include forms (a donation form or an online auction), each form is a separately loadable module, and if on the wide screen we could display three of these div’s horizontally and two underneath, on the narrow screen each of these sections will be scaled down and displayed one under another. And this is not just a publishing application.

A. When I’m porting an application to a tablet 800×600 with UI having large controls and fonts, I need to think about this application as a service to minimize the need of data entry. Don’t forget that half of the screen will be taken by a virtual keyboard, and if you ignore this, the user will have to work with your UI via a keyhole, and even these five separate div’s may not fit. So I’ll need to modify the UI and use the set of controls that will require minimal data entry. I don’t want to give the same UI to the consumers and back-office users.

Y. I keep trying to bring the money into our conversation, but you are avoiding this subject. Sure, it’s better to be healthy and wealthy, than poor and ill. But most of the enterprise projects are poor and ill, i.e. have limited budget and developers are not overqualified. Why a modern enterprise employs many low-qualified people is a subject of different conversation – let’s not go there.

Coming back to my five div’s, we can use CSS to hide what has to be hidden in certain devices, fonts can become larger, and we can use so called fluid grids to have our layout float. It may not be perfect, but it’s a compromise.

A. You can’t turn a truck into a car and then into a bike just using styling. I’m for complete redesign to use the features of a particular platform to its fullest. And the reason why IT has so many low qualified people is because these people allowed non-technical people to lower their qualification. We can help them to improve their qualification.

Y. Most people don’t want it. They live comfortably with what they know.

A. You and I are sitting now in a lobby of a fancy hotel that differs from a motel, right? Why? Because we’ve decided that the service has to be well compensated. And people working in this hotel do their job well. There is always market for the high-end things, which were produced better then others of the same type. If you’ll be producing low quality software, you’ll hate your job, which will shorten your life. Why?

Y. I hear you, but don’t agree with you. It’s great that you and I can afford now (it may change) to work only with interesting projects. But many young programmers have a long way to go before they will establish themselves to pick what they really want to do. Id your message “Just do what you like and the day will come”?

A. If you need to work hard to establish yourself, why doing it where the crowd is? Do it in the unpopular areas.

Y. Most of the people prefer to walk on the paved roads. It’s a reality.

A. Compare software and automotive industries. Some time ago you could have selected any car as long as it was black Ford of a certain model. Then General Motors started mass production of cars where people could select different models of different colors. By dong this they pushed Ford back. The software industry will go through the process of customization. We already reached the point when the software created for a certain enterprise is being replaced by a software-as-a-service (SAAS). The next task is not to create several versions of the same page with CSS, but understand what the user is doing with this page and to make it as convenient for the user as possible. If this will be happening, then software developers will transform into people who belong to service industries.

Y. I may disappoint you, but there were many attempts to cultivate a new creature – a cross of the user experience (UX) specialist and a software developer – it didn’t happen. These are different people with different mindsets.

A. in the end the winning applications will be not the ones that will have nice looking design, but those that will do what the user needs and will do it conveniently.

I have to finish this rather large transcript although our conversation didn’t stop here. Thank you for reading this far. I’m not going to give you a summary with recommendations or predictions of what tool or programming language is the best bet in today’s development of the cross-platform UI. Pick what you like, dig deep, and enjoy your work. It’ll pay off sooner or later.

Four chapters submitted to O’Reilly

We have submitted the drafts of four chapters of the book “Enterprise Web Development: from Desktop to Mobile” to O’Reilly for review and editing. This is a pretty hands-on book as we are developing an application Save Sick Child while explaining various techniques and technologies. The readers will get a new independent working application every time we add a new piece of functionality (e.g. login, donation form, video, Google maps, charts, auction, etc.). These projects will be published on the dedicated Web site savesickchild.org. For example, this is a sample application illustrating modularization of the JavaScript-based UI.

ssc15

The following chapters are submitted to the publisher, but the raw texts are available for you to read now on the github at https://github.com/Farata/EnterpriseWebBook:

Chapter 2. Advanced Intro to JavaScript
Chapter 3. Mocking up Save Sick Child
Chapter 4. Using AJAX and JSON
Chapter 9. Replacing HTTP with WebSockets

Currently we are working on the chapters on responsive design, test-driven development and modularization of the JavaScript applications. We’re making these unpolished chapters available for you to read hoping to get valuable technical feedback from you. Please do let us know if you see some bugs or inefficient solutions in the code samples. We really really appreciate it.