terça-feira, 15 de abril de 2014

Writing JavaFX apps using Javascript with the Java 8 Nashorn engine

Java 8 was just a great release! We already talked about Lambdas and created JavaFX 8 apps on this blog. Bruno Borges created a fx2048, a JavaFX version of the famous 2048 game, which shows Lambdas and the Stream library usage.

Today I'll rewrite the Sentiments App view in Javascript using the new JS engine named Nashorn, one of the exciting Java 8 new features.

Loading the Script


We load a file with the view contents, but before doing this, we add the main Stage so it can be referenced from the javascript file. That's enough for the Java part!

package org.jugvale.sentiments.view;

import javafx.application.Application;
import javafx.stage.Stage;
import javax.script.*;
import java.io.FileReader;

public class AppJS extends Application{

        private final String SCRIPT = getClass().getResource("/sentimentsView.js").getPath();

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

        @Override
        public void start(Stage stage){
                try{
                        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
                        engine.put("stage", stage);
                        engine.eval(new FileReader(SCRIPT));
                }catch(Exception e){ 
                        e.printStackTrace();
                }   
        }   
 }



Notice in my case I'm calling the script from my Java code, but it's possible to use jjs to invoke scripts and build JavaFX apps.

Writing Javascript

After this, we can already start writing Javascritp code and leave Java behind for a moment. The core of the application (the service and model classes)  is written in Java and we can refer to it in our JS.

The good parts

The best thing about JS I can highlight is that we don't need to use get/set methods anymore! Nashorn threat Java beans properties (those accessed by get and set methods) as an object property and behind the scenes it will invoke the get/set methods!
We also take full advantage of the scripting language: don't need to use semiclon, easier to declare variables, more clar
I liked the fact that I don't need to recompile the class to update the view. If I modify the script and re-run the java part, the view will be updated!

The bad parts

I didn't like how to handle the imports. It seems that I have to either declare the type or write the FQN of a class to instantiate it.
I also prefer Java and FXML over writing the view in pure javascript. Remember you can script on FXML as well!

Code and running

Here's the final script for the Sentiments App view:

// Imports
var Scene = Java.type('javafx.scene.Scene')
var VBox = Java.type('javafx.scene.layout.VBox')
var Label = Java.type('javafx.scene.control.Label')
var TextField = Java.type('javafx.scene.control.TextField')
var PieChart = Java.type('javafx.scene.chart.PieChart')
var TableView  = Java.type('javafx.scene.control.TableView')
var TableColumn  = Java.type('javafx.scene.control.TableColumn')
var PropertyValueFactory  = Java.type('javafx.scene.control.cell.PropertyValueFactory')
var SearchService  = Java.type('org.jugvale.sentiments.service.SearchService')
var TextSentimentService  = Java.type('org.jugvale.sentiments.service.TextSentimentService')
var TableView  = Java.type('javafx.scene.control.TableView')
var FXCollections = Java.type('javafx.collections.FXCollections')

// variable declaration
var root = new VBox(10)
var txtQuery = new TextField()
var table = new TableView()
var chart = new PieChart()
var textSentimentService = new TextSentimentService()
var searchService = new SearchService()

// main block
root.children.addAll(txtQuery, chart, table)
stage.scene = new Scene(root)
stage.title = "Sentiments"
stage.width = 400
stage.height = 550
stage.show()
initializeApp()
// functions 
function initializeApp(){
 txtQuery.promptText = "Enter your query for text and press enter"
 chart.title = "Sentiments for \"" + txtQuery.getText() +"\""
 txtQuery.onAction = queryAction
 addTableColumns()
 queryAction(null)
}
function queryAction(e){
 var textSentiments = getTextSentiments(txtQuery.getText());
 fillTable(textSentiments);
 fillChart(textSentiments);
}
function fillTable(textSentiments){
 table.items = FXCollections.observableList(textSentiments)
}
function fillChart(textSentiments){
 var polarity0Count = textSentiments.stream().filter(function (s) s.getPolarity() == 0).count();
 var polarity2Count = textSentiments.stream().filter(function(s)  s.getPolarity() == 2).count();
 var polarity4Count = textSentiments.stream().filter(function(s)  s.getPolarity() == 4).count();
 chart.data = 
  FXCollections.observableArrayList(
   new PieChart.Data(":(", polarity0Count),
   new PieChart.Data(":|", polarity2Count),
   new PieChart.Data(":)", polarity4Count)
 )
}
function getTextSentiments(q){
 return textSentimentService.getSentiments(query(q)).textSentiments
}
function addTableColumns(){
 var textCol = new TableColumn("Text")
 var polarityCol = new TableColumn("Polarity")
 textCol.cellValueFactory = new PropertyValueFactory("text")
 textCol.minWidth = 200
 polarityCol.cellValueFactory = new PropertyValueFactory("polarity")
 polarityCol.minWidth = 80
 polarityCol.resizable = false
 table.columns.setAll(textCol, polarityCol)
}
function query(q){
 if(!q || q.trim().isEmpty()){
  return java.util.Arrays.asList("obama is awesome", "obama sucks", "obama eats potato");
 }else{
  return  searchService.search(q, SearchService.Provider.TWITTER);
 }
}


The full code is on github and you can build it by simply typing the following maven instruction on command line (remember to have maven and JAVA_HOME pointing to your Java 8 installation root directory):

$ mvn package exec:java -Dexec.mainClass="org.jugvale.sentiments.view.AppJS" -DskipTests

Conclusion

Using Javascript from Java is easy and with the new JS engine we have increased the performance due the Invoke Dynamic feature.
Using JS can be a good advantage for a team who has JS programmers and needs to build a desktop app, so we can use their full potential on Javascript and take all advantages and libraries from Java.

Nenhum comentário:

Postar um comentário