Saturday Oct 10, 2015

Thursday Oct 08, 2015

Fun with NetLogo using Nashorn JavaScript engine

NetLogo is a multi-agent programmable modeling environment running for the Java platform. In addition to being a GUI program to edit and run NetLogo models, NetLogo supports Controlling API so that NetLogo can be invoked and controlled by a program running on JVM. The "controlling api" supports both GUI and 'headless' mode.

I used Nashorn javascript engine to use NetLogo "controlling API" from a script. I ran the bundled Maxwell's demon model in "headless mode" using the following Nashorn script:

File: nl_maxwell_demon.js

// NetLogo "controlling API" example in Nashorn

// java classes used
var HeadlessWorkspace = org.nlogo.headless.HeadlessWorkspace;
var Thread = java.lang.Thread;

// set the thread context loader for correct working of NetLogo!

Thread.currentThread().contextClassLoader = HeadlessWorkspace.class.classLoader;

// new headless workspace
var ws = HeadlessWorkspace.newInstance();

// change this as per your installation directory!
// My NetLogo installation dir is "C:\Program Files (x86)\NetLogo 5.2.1"

var NL = "C:\\Program Files (x86)\\NetLogo 5.2.1\\"; + "models\\Curricular Models\\GasLab\\GasLab Maxwells Demon.nlogo");

// setup and call "go" (100 iterations)
ws.command("repeat 100 [ go ]");

// print average left and right speeds
print("average speed (left) = " +"avg-speed-left"));
print("average speec (right) = ""avg-speed-right"));

// We're done!

I used the jjs nashorn shell command to run the above script:

$ jjs  -cp "C:\\Program Files (x86)\\NetLogo 5.2.1\\NetLogo.jar" nl_maxwell_demon.js
average speed (left) = 8.712072244000128
average speec (right) = 9.08120463863075

Saturday Oct 03, 2015

Standalone JavaFX FXML app with nashorn scripts for event handling - no java code!

In nashorn openjdk repository, there is a script called "fxmlrunner.js" in the "samples" directory. This script can accept any FXML file as command line argument and "run it". If that FXML file has event handlers written in (nashorn) javascript, then we can have complete runnable application without having to write any Java code!

When I came across this FXML example, I wanted to replace Java event handling + actual calculator implementation with nashorn scripts. The "ported" FMXL+nashorn script app. uses nashorn scripts for action handlers and uses "eval" to implement calculator back-end.

Calculator App in FXML + nashorn scripts

Download these files: Now, you can the app with the following command:

jjs -fx fxmlrunner.js -- calc.fxml

You should see a calculator app window that looks like this:

Wednesday Sep 30, 2015

Playing with Java (java9) REPL - an example that uses nashorn engine in REPL

I love "Exploratory Programming" ( tools. If you've not already played with "Java REPL" project, you may want to do so! Check out Kulla project.

Clone kulla forest @ and build using these commands:
  1. hg clone kulla-dev
  2. cd kulla-dev
  3. sh
  4. sh configure --with-boot-jdk=/path/to/jdk1.8.0
  5. make clean images
  6. make install

Once build finishes, you can use the Java REPL tool "jshell" ( $kulla-dev/build//images/jdk/bin/jshell). I built on Windows. My jshell path is D:\src\kulla-dev\build\windows-x86_64-normal-server-release\images\jdk\bin\jshell.exe.

Now, two lines to print the squares of integers in the range [0, 100):

|  Welcome to JShell -- Version 1.9.0-internal
|  Type /help for help

-> import*

-> IntStream.range(0, 100).map(x->x*x).forEach(System.out::println)

Slightly bigger repl sample that pulls weather data in JSON format, uses Nashorn script engine to parse JSON and print the statistics on it using Streams API.

File: weather.repl

import javax.script.*
import java.util.*

// URL to fetch JSON for weather data for Chennai, India
URL u = new URL(

// read text from URL
String getText(URL u) {
    StringBuilder buf = new StringBuilder();
    try (BufferedReader reader =  new BufferedReader(
        new InputStreamReader(u.openStream()))) {
    } catch (IOException exp) {
    return buf.toString();

// create nashorn engine
ScriptEngine e = new ScriptEngineManager().getEngineByName("js")

// expose weather data JSON as global variable to nashorn engine
e.put("str", getText(u))

// massage JSON using nashorn and get the max. temp values
double[] values = (double[]) e.eval(
    " val.temp.max), Java.type('double[]'))")

// stat on max. temp values

You can evaluate the above source as follows:

jshell  weather.repl
|  Welcome to JShell -- Version 1.9.0-internal
|  Type /help for help
-> DoubleSummaryStatistics{count=7, sum=227.160000, min=30.210000, average=32.451429, max=36.5800

Yep, Chennai is HOT! 32 C average! In Chennai, we have only three seasons - hot, hotter and the hottest :)

Tuesday Sep 22, 2015

Playing with Nerdamer symbolic math JS library with Nashorn jjs

Using third-party JavaScript libraries with nashorn javascript shell. Using Nerdamer Symbolic math library with nashorn.[Read More]

Sunday Dec 13, 2009

Graphs, GXL, dot and Graphviz

Sometimes you may want to quickly generate graphs programmatically and view/analyze those. Examples include, inheritance/type relation diagrams of an object oriented program, function call graphs and any other domain specific graphs (reporting chain of your organization chart for example). I find GXL very useful for this. GXL stands for Graph eXchange Language. It is a simple XML format to specify graphs. A simple graph stating that "JavaFX" language is related to "Java" language is as follows:

File: Test.gxl


<!-- edgemode tells this is directed or undirected graph -->
<graph id="langs" edgemode="directed">

<!-- write your nodes -->
<node id="java"/>
<node id="javafx"/>

<-- now write your edges -->
<edge from="java" to="javafx"/>


You can also add number of "attributes" to nodes and edges - like color of the edge, style of the edge and so on. For example, "red" color can be specified for an edge as follows:

<edge from="java" to="javafx">
  <attr name="color"><string>red</string></attr>

Now that we have written a simple graph with two nodes and a single edge between them, we may want to view it. There are number of tools/libraries to view GXL documents -- I've used Graphviz. Graphviz displays it's own native format called ".dot". Graphviz comes with a set of command line tools. One such tool is "gxl2dot", which as you'd have guessed, can be used to convert a .gxl file to a .dot file.

    gxl2dot Test.gxl >

Once converted the .dot file can be opened in Graphviz GUI and we can export it to .pdf/.jpg/.png and so on. This way you can email the graphs to others and/or publish in your blogs/webpages easily.

The converted .pdf file for the above simple graph is here: test.pdf

I've used GXL graphs in a recent debugging tool related to JavaFX compiler. More on that later...

Wednesday Oct 21, 2009

Look Ma, javac tells me I am overriding static method wrongly!!

// File:

public class SuperClass {
    public static int func() {
        return 0;

// File:

public class SubClass extends SuperClass {
    public static boolean func() {
        return false;

$ javac -fullversion
javac full version "1.6.0_15-b03-226"

javac func() in SubClass cannot override func() in SuperClass; attempting to use incompatible return type
found   : boolean
required: int
    public static boolean func() { 
1 error

The subclass uses a different return type for the same named method with same argument types. So, it is overloading SuperClass.func() and the overloading SubClass.func() differs only in return type. But, I am not sure of the error message....

Thursday Sep 17, 2009

"helloworld" with Maxine JVM on Mac

Last night, I listened to this nice podcast on Maxine JVM from Software Engineering Radio. Maxine is a Java Virtual Machine implemented in the Java programming language.

I wanted to try out Maxine on my MacBook Pro running Mac OS X 10.5.8. I followed these steps to try it out:

  • Get the Maxine sources
        hg clone maxine
  • Setup the environment
        export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home
        export JUNIT4_CP=<full-path-of junit-4.4.jar>
  • Build Maxine
       cd $MAXINE_HOME/bin
       ./max build
       ./max image   
  • Run the "helloworld"
        ./max helloworld

Wow! Maxine VM printed "Hello World!". Now, it is time to explore Maxine's inspector and other cool stuff ...

Wednesday Sep 02, 2009

java.lang.NoClassDefFoundError: com/sun/javafx/runtime/FXBase

I created a simple JavaFX applet and compiled it with "javafxc" and created a jar "HelloApplet.jar". Then, I created a simple HTML file as follows:

<script src=""></script>
               archive: "HelloApplet.jar",
               draggable: true,
               width: 150,
               height: 100,
               code: "hello.HelloApplet",
               name: "HelloApplet"

When viewing the HTML, I did not see the expected applet content in it - just a gray rectangle panel :-( Then, I turned on the "Show Java Console" option. I saw the following exception trace in Java console:

JNLPAppletLauncher: static initializer
Exception in thread "AWT-EventQueue-2" java.lang.NoClassDefFoundError: com/sun/javafx/runtime/FXBase
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(
[.. more stack frames deleted for brevity ..]

Aha! com.sun.javafx.runtime.FXBase is new since JavaFX 1.2. Yes, I had compiled my applet with JavaFX 1.2 (full version "1.2.0_b233"). So, the JavaFX runtime used turned out to be old one! I changed the HTML script URL from to The applet worked as expected :-)

Tuesday Jul 28, 2009

My twitter updates..

In the past, I blogged about Cricket (the sport and not the insect!) in this space. Once angry reader questioned me why I was writing that here. I guess people read my Sun blogs only tech. stuff. That is fine. So, I've revived my twitter login. I'll be posting my one liners (tech as well as non-tech) there. Longer posts on tech. (mostly Java, JavaFX) topics will continue here.

Tuesday Jul 21, 2009

Teaching programming to kids

I've been experimenting/playing with programming tools for kids. I've two kids - 8 and 5 year old.


Great multimedia rich introduction to programming for kids. My son keeps playing with it! If you are after ease-of-use, this is probably the best choice. Available for download on Mac and Windows. If you have Squeak installed, you can get Scratch running on Linux as well (possibly with some audio problems). It is possible to export your Scratch projects as applets from your website

  • Website:
  • Tutorials:
  • Examples/Repository: Register @ to download lots of great samples! You can view scratch programs online if you have Java plugin installed.


EToys is an tool to teach children a multimedia rich authoring environment and visual programming system. If you have OLPC laptop (or emulation environment for OLPC), it comes pre-installed with EToys. Or else you can download EToys for your platform. It is avaliable for Linux, Mac and Windows.


Although StarLogoTNG is described as "tool to create and understand simulations of complex systems", it can be used as a tool to teach programming. It supports 3D and it is cross-platform a (Java) tool.


This is an environment to teach programming in a 3D environment. This is a cross-platform (Java) tool.

Turtle Art

Turtle Art activity is bundled with OLPC. If you don't have OLPC, you can use an emulator environment. For example, you can download VirtualBox and run OLPC inside it following the steps here. I run VirtualBox on Mac, Ubuntu and Windows XP.

Want to work with source code?

So far, we looked at visual programming tools. But, if you think it is better to expose to source code ("they have to look at code at somepoint anyway, let them see syntax errors sooner"), then you may want to try these:


From the site: "Greenfoot as a combination between a framework for creating two-dimensional grid assignments in Java and an integrated development environment (class browser, editor, compiler, execution, etc.) suitable for novice programmers". This is a cross-platform (Java) tool.


With Bots Inc we can learn how to program robots interactively. Language used to program is Smalltalk (BotsInc is built with Squeak). Since BotsInc is a Squeak image, it possible to slowly graduate to full Smalltalk. It is available on all platforms.

Alice 3 Beta

Alice 3 beta is hosted at Alice 3 beta seems to have support to emit NetBeans projects. I've played with Alice 3 Beta - but not yet with NetBeans project support.

Tuesday Jul 14, 2009

BTrace "unsafe" mode

We kept saying BTrace is a safe, dynamic tracing tool for Java. To ensure safety, BTrace does not permit many constructs of Java language and also allows calls only to BTraceUtils class.But, not everyone likes safety -- sometimes developers want "unsafe" facility ("I know what I am doing"-style). We have got comments of this nature about BTrace - for example here and here. We have added "unsafe" mode to BTrace - you can edit "btrace" script to change -Dcom.sun.btrace.unsafe=false to -Dcom.sun.btrace.unsafe=true. In "unsafe" mode BTrace permits all Java constructs and also allows calls to arbitrary code. Like every other unsafe facility in programming, you are on own your own with this facility! You may get weird errors while instrumenting target classes and/or running transformed code. But then you know what you are doing, right?

Monday Jul 13, 2009

javafxdoc-style docs for Java code

You may have browsed JavaFX API docs generated by javafxdoc tool. javafxdoc tool is implemented as a doclet. It is possible to use javafxdoc's doclet to generate API docs for Java code.

Note: The XMLDoclet implemented as part of javafxdoc tool is an implementation detail and not part of official JavaFX/tool API and so please do not depend on this. This is more for fun/learning/personal use!)

I generated javadoc for BTrace source using the following command:

javadoc -docletpath $JAVAFX_HOME/lib/shared/javafxdoc.jar  -doclet -sourcepath .  -subpackages com.sun.btrace

where JAVAFX_HOME is the directory where JavaFX SDK lives.

A screenshot from generated docs:

Monday Jul 06, 2009

BTrace project moved to

We have recently moved BTrace project to If you are interested in BTrace, please continue to use it and help develop it from

Thursday Feb 26, 2009

Prizes for having fun! Hurry....

Do you live in India? What do you want? Sony Ericsson phone or Canon Camera or iPod? If so, have fun writing JavaFX code and win any of these prizes!



« October 2015

No bookmarks in folder


No bookmarks in folder


No bookmarks in folder