Am I still a Java Developer?

This morning I got the following email from a Java developer: “It seems you are doing less Java and more web development every year.” This got me thinking, and I decided to write this blog.

Am I still a Java developer after 17 years of using this language? I certainly am. But in today’s world using just one programming language is almost impossible unless you’re willing to limit yourself to the server-side development. I’m not saying this is bad – it’s a huge field for never ending self-education and research. Even from the career perspective becoming an expert in a specific Java field can put bread and butter on your table for years to come. For example, Java experts specializing in performance tuning can charge several times more than a typical Java developer. Some people become experts in security or concurrent programming, which allows them to eat an omelet with truffles for breakfast daily.

But 95% of Java developers are doing more or less routine work, and learning other languages and tools can bring some excitement in their lives and make them more competitive in the job market.

While Java is the server-side king, HTML/JavaScript/CSS (a.k.a. HTML5) rule on the client. You can use HTML5 for creating a cross-platform UI for desktop and mobile applications. People use a variety of languages and frameworks to develop Web applications that we use daily. If you already know Java, why not come out of the closet and explore the huge and ever growing HTML5 world?

Traditionally many Java developers look down on JavaScript developers with a false assumption that real development is happening only in Java. I can reveal a secret: this is wrong. JavaScript is as close to the Web what as C language is to the hardware. Just look at this long list of compilers from different languages that generate JavaScript. In our company we use Google Dart as a way to produce JavaScript. Next year we’re planning to switch to programming in the new version of JavaScript (EcmaScript 6 spec will be finalized this summer).

Lots of popular IDEs offer great support for developing and debugging JavaScript. Every Web browser comes with a developer tool allows you to debug JavaScript and monitor everything that goes over the wire during the runtime. The tooling of a modern JavaScript developer has everything that Java developers are accustomed too:

node.js – JS framework plus a runtime for all development tools listed below
npm – node package manager used for installing and managing development tools
bower – package manager for the application dependencies
grunt – a build automation tool
yeoman – a scaffolding tool for generating the initial structure of an application for various frameworks

I teach JavaScript classes for Java developers several times a year. A typical feedback is “I thought JavaScript is a toy, but it’s a serious programming ecosystem worth learning and mastering”. And this is what I do while remaining a Java developer.

Why I Rejected a LinkedIn-Originated Offer of 10 Million Euros

LinkedIn is a popular social network for connecting professionals, and I have an account there. Every day I get an invite to connect with someone. Typically I ignore these invites unless I know the person. But I’ve never received invites to connect from a chair of board of directors of a bank. Till yesterday.  So I’ve accepted the invite.

Then I’ve received an LinkedIn email from this woman stating that she had a business proposition for me, and if I was interested, she was ready to explain. She also provided her email that ended in outlook.com. I checked her LinkedIn profile again. Looked legit. She even had a Twitter account with recent tweets in two languages.

I responded that I was ready to hear about this business proposition. Next day I’ve received a long email from her explaining how she had a private client named Lewis Fain who initially deposited €19M  in their bank and she helped him to grow the wealth to €22M, but unfortunately he died in a car crash. She’s ready to wire transfer me the money, in one condition: we’d split the amount in half so she could improve the wellbeing  of her family. She also asked me not to ruin her career in the bank if I was not interested.

At this point it was clear that it was a new type of a scam that involved creating  fake LinkedIn accounts and impersonating themselves as someone else. Still I decided to continue my treasure hunt and responded to my fake banker asking her to send me any email from her bank email account. She responded again, stating that she understood my concern, but couldn’t use her bank email for such a delicate matter. But to establish trust, she attached a photo of her bank ID.

At this time I had enough of materials for this blog and responded wishing her good luck in finding another heir of poor Lewis Fain. Then I decided to report this scam to LinkedIn. To my surprise this banker was not in my connections list any longer. I searched by her name in LinkedIn, and found the account of that banker, the profile looked different and she didn’t have any connections.So either someone else reported this as a stolen account, or the con artists have removed it programmatically. I’ve reported this account to LinedIn anyway.So beware of LinkedIn initiated scams.

One more warning. Even if this banker would have sent me an email from the account that ended with the bank name, this would not be enough. Being a programmer, I can easily write a program that would send an email with any address in the “Reply To” field. Here’s how a fragment of the Java code to wannabe con artists:

Message emailMessage = new MimeMessage(session);

emailMessage.setFrom(new InternetAddress("MaryLou@thefakebank.com")); 
emailMessage.setRecipients(Message.RecipientType.TO, 
                                 InternetAddress.parse(emailRecipient, false));
emailMessage.setSubject(emailSubject); 
emailMessage.setSentDate(new Date()); 
emailMessage.setText(emailText);  

So if you want to confirm someone’s identity, you need to send an email to the provided email address and receive a response back. Hope this helps.

JavaFX 8: The keyboard events are not being processed if a scene has only shapes

I ran into an interesting problems with JavaFX. When the GUI is done in FXML it seems that if a scene has only shapes (e.g. Rectangle, Circle, etc.) the handler method doesn’t receive keyboard events. And the problem seems to be that there is no way (at least I don’t see it) to give a focus to such a scene. I found a workaround, but I’d appreciate if someone could offer a cleaner solution or confirm that this is a JavaFX bug.

Here’s a code sample that illustrates the problem and the solution:

1. Here is the main application:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

@Override
  public void start(Stage primaryStage) throws Exception{
   Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

   primaryStage.setScene(new Scene(root, 300, 300));
   primaryStage.show();
  }

  public static void main(String[] args) {
     launch(args);
  }
}

2. Here’s the sample.fxml that works, except I don’t need a Button there:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.Group?>

<Group fx:id="theGroup" onKeyPressed="#keyHandler" focusTraversable="true"
       xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
       fx:controller="sample.Controller">
   <children>
       <Button />
       <Rectangle fill="BLUE" height="300.0"  stroke="BLACK"
                              strokeType="INSIDE" width="300.0" />

   </children>
</Group>

3. Here’s the Controller.java:

package sample;

import javafx.fxml.FXML;
import javafx.scene.Group;
import javafx.scene.input.KeyEvent;

public class Controller {

  @FXML Group theGroup;

  public void initialize(){
     theGroup.setFocusTraversable(true); // doesn't have any effect
     theGroup.requestFocus(); // doesn't have any effect
  }

  public void keyHandler(KeyEvent event){
    System.out.println("A Key was pressed");
  }
}

This application works and prints the message “A Key was pressed” as long as I keep the <Button> tag in FXML (it’s not visible on GUI because the Rectangle covers it). This is my workaround to make sure that event handler works and prints the message.  Remove the <Button> tag from FXML, and the application won’t process the keyboard events. The problem seems to be that if the FXML has only shapes, it can’t get the focus. The code in the initialize() method doesn’t help to set the focus on a Group container.If anyone could find an explanation of why this code  doesn’t work without a <Button>, please let me know.

Update: The user jewelsea on Stack Overflow suggested to set the focus after  calling  primaryStage.show(); http://stackoverflow.com/questions/28506855/javafx-8-the-keyboard-events-are-not-being-processed-if-a-scene-has-only-shapes.

This gave me an idea how to do it. I’ve added one line root.requestFocus(); at the end of the start() method. No <Button> is needed in FXML and no initialize() method is needed in the Controller.

 

 

 

Introducing AngularJS to Java Developers

If you want to develop Web applications, you’ll need to learn JavaScript. But writing code in JavaScript (at least in its ECMAScript 5 incarnation) is non-productive. You need to pick up a one of the JavaScript frameworks, because:

  • they make you more productive
  • will deal with cross-browser compatibility and make the application more structured
  • may include reusable components
  • lower the amount of manually written code.

JavaScript market offers multiple frameworks and libraries. While frameworks expect you to programs using well defined ruleswithin a certain code structure, libraries just offer reusable components a la cart.

In turn, frameworks can be categorized as feature complete (rigid app structure, intrusive, rich GUI components, tooling) and lightweight (MVC + Binding + Routing)
.

Ext JS, YUI, and Dojo represent feature-complete frameworks. AngularJS, Backbone.js, and Ember are examples of lightweight frameworks. After years of experimenting with different frameworks and libraries we decided to stick with hugely popular AngularJS by Google.

I work in a Java shop, and one of my responsibilities is to create an conduct trainings (both internal and external). Several years ago I started to work with our engineers on the curriculum introducing AngularJS to an enterprise Java developer.

The learning curve of AngularJS is not too steep for Java developers, who understand the concept of containers, dependency injections, callbacks. They must become proficient with JavaScript with its functions, closures and other good stuff.

But equally important is to be familiar with todays tooling of a productive Web developer. Here’s a short list of tools that JavaScript developers use today:

  • npm – node package manager used for installing and managing development tools
  • yeoman – a scaffolding tool used to generate the initial structure of an application
  • bower – package manager for application dependencies
  • grunt – a build automation tool
  • A JavaScript testing framework

The next decision to make is how to communicate with the Java backend. Forget about JSP, servlets, and JSFs. Preparing HTML in your Java code is out of fashion. A Java server exchanges the JSON-formatted data with a single-page HTML/JavaScript front end, which use either AJAX techniques (old) or WebSocket protocol (new).

On the Java side we like to use such tried and true technologies as RESTful Web service and Java Messaging API.

When we hire a AngularJS/Java developer, we expect him to be familiar with at least 90% of all the above buzzwords. Finding such skilled software engineers may be difficult, so we’ve created a training program to prepare such a person.

By now, we’ve taught and fine-tuned this training class multiple times. The latest online version of this class consists of seven weekly training sessions (3.5 hours each) and seven consultations (from 30 to 60 min each). Programmers learn and gradually apply all of the above tools and techniques while working on the Online Auction application that has the following architecture:

javaauction-1

We have a great feedback from people who have completed this training. But everyone says it’s challenging. And it should be. Back in the nineties a person who knew one of the programming languages plus SQL could relatively easy get a well paid job. Not anymore.

JavaScript for Java/C#/C++ Developers

This year I’m planning to run a one day workshop at a couple of software development conferences and privately for IT shops. The goal is to introduce JavaScript and related technologies to developers that are accustomed to developing in classical object-oriented languages like Java, C++ or C#. Below is the outline of this workshop.

Part 1. JavaScript Building blocks

* Functions, Objects, Prototypal Inheritance,Closures
* Using Chrome Developer Tools
* JavaScript in the Web Browser, DOM, CSS.
* New JavaScript: an overview of selected ECMAScript 6 features.

Part 2. Designing Single-Page Web Applications

* Web app prototyping. Designing a Product page of an online auction using Pure JavaScript and CSS.
* Responsive Web Design. CSS Media Queries. Redesigning the Product page for smart phones and tablets by adding CSS Media Queries. Our Product page will look like this.
* Single-Page Applications. AJAX.
* The Bootstrap framework. Responsive GUI components. Fluid grids. Yet another redesign of the Product page by using responsive Bootstrap components.

Part 3. Productive JavaScript development with Google Dart

* Getting familiar with the Google Dart language. Classes, top-level functions.
* Dart Tooling. Dartium VM. Dart Editor IDE. Dart to JavaScript Compiler. Package manager pub.
* Re-creating the Product page in Dart + Bootstrap. JavaScript generation and deployment.

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

Tic-Tac-Toe in JavaFX

Finished writing the JavaFX chapters for the second edition of my Java 24 Hour Trainer. It included a sample code of the Tic-Tac-Toe game. The front end is done in FXML and the application logic is written in Java.

fig_19_18

Using FXML allows to substantially minimize the amount of Java code. This application has 200 lines of code, namely:

Tic-Tac-Toe.fxml: 45 lines
Main.java: 27 lines
TicTacToeContoller.java: 118 lines
application.css: 12 lines.

The FXML and CSS files can be created and modified by people who do not know Java at all (i.e. graphic designers). I haven’t implemented a couple of menus, which would add a couple of dozens lines to the code base. Pretty concise, isn’t it? The source code of the Tic-Tac-Toe project is available among other code samples at https://github.com/yfain/java24hourtrainer2ndedition. I’ve developed this in Eclipse IDE with the E(fx)clipse plugin that generated an initial project for me. At the time of this writing NetBeans 8 IDE has the best support of JavaFX followed by IntelliJ IDEA 14, and then goes Eclipse with E(fx)clipse plugin.

Have you shortened your talk yet?

Attention span is getting shorter and shorter. At least mine. I can’t do the same thing for 50 minutes straight, can you? Books became thinner. In the past getting a 1500-page book on programming for $40 would be considered a good deal. Now people don’t want to buy books that have more than 500 pages. In my recent book project the publisher decided to not include a 60-page chapter in the printed version, but offered it as a free online bonus chapter. The chapter content was good, but marketers said that thinner books sell better.

IT conferences should follow the same trend. 50-minute presentations are so last century! Some conferences include ignite talks. They last 5-10 minutes, and ideally, the slides should be flipped automatically to force presenters stay focused. This is called Pecha Kucha.

I can share a secret with you: I can deliver a 50-min presentation in 25 min. Or in 15. Or in 5. Just tell me how much time I have, and I’ll remove the irrelevant content. It’s like extracting juice concentrate.

Shorter presentations would require better concentration not only from the speakers, but from the audience as well. There is no time for checking emails, tweets, or reading the news. As a matter of fact, the conference organizers wouldn’t need to pay outrageous amounts of money for providing this flaky Wi-Fi connections for the audience. No time for Internet browsing.

A typical IT conference runs for 3-4 days averaging 7 presentation slots per track daily. What if each presentation would run for half the time – 25 minutes? A rare conference would run for more than two days. This translates into cost savings for both conference organizers and those who pays for a trip to the conference. For those who who are not in the know, I have another secret to share. Remember that airline-quality lunch that you got for free? The conference organizers paid anywhere from $50 to a $100 for each plate.

Can software developers absorb 14 presentations a day? Yes, we can. But realistically, none of the conferences can offer 14 interesting presentation a day. Except one. TED. BTW, I don’t remember ever watching a TED presentation that was longer than 25 minutes, and they were all great!

Can IT conferences follow the leader? Yes they can. Last month I was participating in the HTML5Dev/IOTA conference in San Francisco. Take a look at the schedule. It was based on 20-min slots. But if a speaker wanted to talk for 50, he would get 2 slots + 10 minute break. It worked like charm.

Pretty often attendees find themselves in a wrong auditorium after the first 5 minutes into the talk. Some of them are shy to simply walk out. 50 minutes of their time wasted. If the presentations were shorter, they would have wasted only 20 minutes!

Anyway, this blog is getting too long too, but as someone said, “Sorry, I din’t have time to write you a shorter letter”.

IT book publishers may extinct soon

Not sure how IT book publishers can survive these days. People are intoxicated with free content. During American Civil War soldiers were bringing liquor to the camps by hiding it in their boots (a.k.a. boot-legging). But this is the ancient history of America. With soft media, there is no need to hide anything in the boots. You can find almost any content online for free. I’ll give you one of the examples that directly relates to me.

After spending lots and lots of hours writing the book “Enterprise Web Development”, preparing code samples and going through several rounds of editing, the book is finally in print. Lots of people besides the authors were involved in the process. During the entire process the drafts of the all chapters were available online for free. Thank you O’Reilly Media! The idea was to build a community while the book is being worked on.

Now the book is printed. Booksellers get it from the publisher for about 50% of the list price. The publisher paid the authors an advance, which is ours to keep even if not a single copy of the book is sold. The publisher takes a risk. If the book sells well, the author(s) will get a dollar or two in royalties for each sold copy. We’ll split the royalties for this book (if any) between four coauthors, so it’s clearly a not-for-profit project for us. Now check this out:

freebooks

Two thousands of free downloads just at this pirate site. It’s great for the authors that the book is popular. All authors are working programmers, and our income doesn’t depend on book sales. But this book is a good PR for us and our company (all work for Farata Systems). Read the book, and hire us for your next consulting project! Book writing worked for us really well so far. Our company exists since 2006 and we never had even a single salesman. PR works. It sounds like a paradox, but the more bootlegged copies will be distributed, the better it is for us!

But what about the publishers? How they are supposed to make a living? I simply don’t know. It’s sad to see how the IT sections in the bookstores are shrinking, but this trend will continue.

Programming to Interfaces in Java

Seasoned Java programmers are programming to interfaces. What does it means?

Let’s consider a simple example. Let’s say I’ve declared a variable customers of type ArrayList:

ArrayList<Customer> customers = new ArrayList<>(3);

While this code is correct,  there a better way of declaring the variable customers:

List<Customer> customers = new ArrayList(3);

You can read the first example as follows: “I want to declare a variable customers that will have all access to all API offered by the class ArrayList“. The second version means the following: “I want to declare a variable customers that has a behavior declared in the List interface”. The first example declares a variable of a specific implementation of the List interface – ArrayList. Now rake a look at this code example:

ArrayList<Customer> customers = new ArrayList<>(3);

// The code to populate customers with instances of 
// Customer is omitted for brevity

int totalElem = customers.size();

// Iterate through the list customers and do something with each
// element of this collection

for (int i=0; i<totalElem;i++){
    Customer currentCustomer= customers.get(i);
    System.out.println(currentCustomer);
  }
}

ArrayList implements several interfaces besides List, which means that it has more methods that the List defines.  But if you read the documentation on the List interface, you’ll see that among others it includes the methods as add(), get(), and size() , which are the only ones used with our collection customers. If this is all we need, declaring a variable customers of type List gives us more flexibility. If later we decide to switch to a different implementation of the List (e.g. LinkedList instead of ArrayList ) we won’t need to change the type of the variable customers.

You may say that changing a variable declaration from ArrayList to LinkedList it’s not a big deal – it’s still the same line of code. But it may be a bigger deal if, say you program needs to pass the object referred by customers to another object’s method that also was declared with the argument of type ArrayList:

processCustomers (ArrayList<Customer> customers){

...
}

Now we need to change both the variable and the method argument declarations . In large projects such a refactoring may become a time consuming process.

If you just need a behavior defined in a particular interface (e.g. List), declare the variable of this interface type rather than of a concrete implementation (e.g. ArrayList) of this interface.

P.S. Here’s the Java 8 way of writing the above loop, which is not relevant for the blog subject:

customers.forEach( customer -> System.out.println(customer));