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 :)

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 ...

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:

Thursday Dec 04, 2008

Playing with Alice and PhET

These days, my son is playing with these (apart from usual game sites):
Alice is a 3D programming environment. He likes it as much as he likes Scratch.
Interactive simulation tool for physical phenomena from University of Colorado. He kept trying to soft land "on the moon" :-) I guess Chandrayaan I has impressed him a lot!

What is the common between Alice and PhET apart from being great education tools? It is Java! With the advent of JavaFX, we can expect that such fantastic rich GUI applications will be written in JavaFX.

Friday Aug 08, 2008

Scriptifying BTrace?

One of the issues reported with BTrace is that the trace authors have to write "verbose" code [some people say Java is "verbose"!]. In BTrace, we have to repeat the same set of imports, annotations in every btrace file and all methods have to be "public static void" and so on. Instead of inventing a new scripting language, I've added a simple C preprocessor like step in BTrace compilation. This preprocessor is based on the one in the GlueGen project. Thanks to Ken Russell for this code and for reviewing my changes specific to BTrace project. The preprocessor solution does not rule out a scripting solution in future :-) If you have nice ideas or would like contribute in this area, you are always welcome! But, I think preprocessor solution is simple and will be useful to some.

Simple Example:


To run this sample, the following command can be used:

   btrace -I . <pid-of-the-traced-process>

Without the -I option in command line, BTrace skips the preprocessor step.

Friday Jul 25, 2008

Playing with JSqueak

Squeak is a open source implementation of Smalltalk. What is JSqueak? JSqueak is a Squeak interpreter written in Java. You can download JSqueak source code and play with it. I did the following:
  • Expanded the downloaded under a directory, say c:\\JSqueak.
  • cd c:\\JSqueak
  • javac -d . \*.java
  • copy mini.image.gz JSqueak
  • java JSqueak.Main
Even if you are not going to learn Smalltalk (why?), you can have the fun of reading Smalltalk VM implemented in Java. If you are lazy and don't want to compile, you can run directly by JNLP link from Inside the Squeak environment, I wrote the legendary "Hello World" :-) This is how it looks...

Friday Jul 18, 2008

BTrace and JMX

You can dyanamically attach BTrace to a Java process to inject trace code into it. BTrace client classescollect the trace output via a socket -- these client classes are used by BTrace command line client as well as VisualVM plugin for BTrace. How about attaching a JMX client to collect BTrace's trace data? Yes, it is possible to access a BTrace class's static fields as attributes of a MBean with this RFE.

There are two MBean samples in the BTrace repository. I attached both BTrace samples to a "Java2D demo" process. And then I attached VisualVM to view the Mbean registered by these BTrace samples:

  1. - this sample instruments java.lang.Thread.start() method to update a counter field. This counter field is accessible by JMX clients.

  2. - this sample collects histogram of java.awt.Component objects created by an application and exposes the histogram (map) as MBean attribute.

Monday Jun 16, 2008

BTrace in the real world

In the last few weeks, I came to know about two cases of real world use of BTrace.
  1. Glencross, Christian M (his blog?) wrote about attempting to write a script to track SQL statements executed by a Java application (private email). Thanks to him for permitting me to blog about his BTrace script. I've made few formatting changes to fit his code in this blog and added few explanatory comments (staring with "VERBOSE:").
    import static com.sun.btrace.BTraceUtils.\*;
    import java.sql.Statement;
    import java.util.Map;
    import java.util.concurrent.atomic.AtomicLong;
    import com.sun.btrace.\*;
    import com.sun.btrace.annotations.\*;
     \* BTrace script to print timings for all executed JDBC statements on an event.
     \* <p>
     \* @author Chris Glencross
    public class JdbcQueries {
        private static Map preparedStatementDescriptions = newWeakMap();
        private static Map statementDurations = newHashMap();
        // VERBOSE: @TLS makes the field "thread local" -- sort of like using java.lang.ThreadLocal
        private static String preparingStatement;
        private static long timeStampNanos;
        private static String executingStatement;
         \* If "--stack" is passed on command line, print the Java stack trace of the JDBC statement.
         \* VERBOSE: Command line arguments to BTrace are accessed as $(N) where N is the command line arg position.
         \* Otherwise we print the SQL.
        private static boolean useStackTrace = $(2) != null && strcmp("--stack", $(2)) == 0;
        // The first couple of probes capture whenever prepared statement and callable statements are
        // instantiated, in order to let us track what SQL they contain.
         \* Capture SQL used to create prepared statements.
         \* VERBOSE: +foo in clazz means foo and it's subtypes. Note the use of regular expression
         \* for method names. With that BTrace matches all methods starting with "prepare". The
         \* type "AnyType" matches any Java type.
         \* @param args - the list of method parameters. args[1] is the SQL.
        @OnMethod(clazz = "+java.sql.Connection", method = "/prepare.\*/")
        public static void onPrepare(AnyType[] args) {
            preparingStatement = useStackTrace ? jstackStr() : str(args[1]);
         \* Cache SQL associated with a prepared statement.
         \* VERBOSE: By default, @OnMethod matches method entry points. Modifying with @Location 
         \* annotation to match the method return points.
         \* @param arg - the return value from the prepareXxx() method.
        @OnMethod(clazz = "+java.sql.Connection", method = "/prepare.\*/", location = @Location(Kind.RETURN))
        public static void onPrepareReturn(AnyType arg) {
            if (preparingStatement != null) {
                print("P"); // Debug Prepared
                Statement preparedStatement = (Statement) arg;
                put(preparedStatementDescriptions, preparedStatement, preparingStatement);
                preparingStatement = null;
        // The next couple of probes intercept the execution of a statement. If it execute with no-args,
        // then it must be a prepared statement or callable statement. Get the SQL from the probes up above.
        // Otherwise the SQL is in the first argument.
        @OnMethod(clazz = "+java.sql.Statement", method = "/execute.\*/")
        public static void onExecute(AnyType[] args) {
            timeStampNanos = timeNanos();
            if (args.length == 1) {
                // No SQL argument; lookup the SQL from the prepared statement
                Statement currentStatement = (Statement) args[0]; // this
                executingStatement = get(preparedStatementDescriptions, currentStatement);
            } else {
                // Direct SQL in the first argument
                executingStatement = useStackTrace ? jstackStr() : str(args[1]);
        @OnMethod(clazz = "+java.sql.Statement", method = "/execute.\*/", location = @Location(Kind.RETURN))
        public static void onExecuteReturn() {
            if (executingStatement == null) {
            print("X"); // Debug Executed
            long durationMicros = (timeNanos() - timeStampNanos) / 1000;
            AtomicLong ai = get(statementDurations, executingStatement);
            if (ai == null) {
                ai = newAtomicLong(durationMicros);
                put(statementDurations, executingStatement, ai);
            } else {
                addAndGet(ai, durationMicros);
            executingStatement = null;
        // VERBOSE: @OnEvent probe fires whenever BTrace client sends "event" command.
        // The command line BTrace client sends BTrace events when user pressed Ctrl-C 
        // (more precisely, on receiving SIGINT signal)
        public static void onEvent() {
            printNumberMap("JDBC statement executions / microseconds:", statementDurations);

    And he has expressed few wish lists for BTrace based on his experience with DTrace. We plan to investigate those items in near future.

  2. Binod P.G exchanged private e-mails about BTrace usage to track down a memory leak. Subsequently, he has blogged about the same.

Friday May 09, 2008

Thursday May 8, JavaOne

Here are the few highlights from the talks that I attended today:

TS-5428 Java Technology Meets the Real World: Intelligence Everywhere.

This talk is about pervasive computing (a.k.a ubiquitous computing) with products from Sentilla. There was an interesting demo about humidity sensor detecting changes and sending a message to a host. The "motes" run CLDC 1.1 VM (+ proprietary profile for motes). These motes have ports for sensors and actuators and some built-in sensor. There were many interesting suggestions for embedded programming for such small devices (don't allocate in inner loops and there by leading to to GC kick-in, avoid too many static fields, avoid threads whenever possible and so on).

TS-7575 Using Java Technology-Based Class Loaders to design and implementing a Java platform, Micro Edition

The basic idea is to run JavaME applications (developed for different configurations/profiles/subsets of optional packages) on top of JavaSE. The extended JavaSE classes and packages not available in specific profile or optional package set [implemented by a specific phone] should not be made available to JavaME apps targeted. i.e., only the classes available to a specific phone model should be available. If the JavaME app tries to access any other class, it should receive ClassNotFoundException. The speakers explained how to achieve such "containers" by class loader based isolation. The problem is that they seem to solve only the class access. What about extended methods and fields? For example, platform core classes on JavaSE have superset of methods [more methods on the same class available on JavaME - eg. java.util.Hashtable has more methods on JavaSE). The application classes have to bytecode analyzed and instrumented to take care of field/method accces. It seems that their current product that does not address this yet.

PAN-5542 Developing Semantic Web Applications on the Java Platform.

The discussion started with some nice demos. There was a demo with AllegroGraph RDF store, Twine, a demo with using GRDDL and getting RDF triples by a proxy server. i.e., a proxy serves does the GRDDL transformations to get RDF triples from sites [which could be stored/analyzed with RDF stores subsequently] and a demo with FOAF files. Interesting take aways from the discussion include:

  • We don't have to wait for SEMANTIC WEB with full fledged reasoners and so on. Instead, add little semantic bits to existing web (say using RDFa, GRDDL etc.) in your current web projects/pages.
  • There are many Java tools. There is need to standard Java APIs for triple store access etc. Right now, we have to write for Jena, Sesame etc. It was also felt that APIs will need to wait for more usage scenarios.
  • There are tools to expose your existing databases as virtual RDF stores -- for example: D2RQ. Probably, most of the RDF triples could come from existing data.
  • Privacy, security of the information is very important. Work needs to be done in this area.
  • Natural language processing and getting triples out of it is very hard. You may want to refer to systems like DBpedia.

Thursday May 08, 2008

Wednesday May 7, JavaOne

Today Bill, Chihiro, Jaya and I talked on Blu-ray. The talk was centered around the open source project @ - a library and a set of tools to build Blu-ray discs. If you haven't checked out code/docs, you may want to checkout and play with the code. All you need is a laptop with blu-ray drive and a BD-RE disc. Optionally, for added fun you may want to have a hardware bluray player such as PS3 -- so that you can see the output on your TV rather than on a laptop. Other than the session, we also had a very informal BOF on blu-ray, OCAP etc. during the evening. It is good to meet experts in respective technologies in one place!

Other than the the blu-ray stuff, I did attend other talks/BOF. Just after Blu-ray session, I attended "TS-6000 Improving Application Performance with Monitoring and Profiling Tools" talk. This talk was about OS specific tools, JDK tools and third-party tools for profiling and monitoring. Gregg Sporar and Jaroslav Bachorik (NetBeans Profiler team) presented very well. There were many interesting questions/discussions as well. If you haven't done so already, you may want to download VisualVM. If you want bit more fun doing monitoring/profiling, you may want to check out the sources from and build it yourself. You can build BTrace VisualVM plugin using the command:

    c:\\visualvm\\plugins>ant build

assuming you have checked out VisualVM sources under "c:\\visualvm". If you have already checked out BTrace sources under some other directory, say "c:\\btrace", you can use

    c:\\visualvm\\plugins>ant -Dbtrace.home=c:\\btrace build

To run VisualVM with all the plugins that you built, you can use the following command:

    c:\\visualvm\\plugins>ant -Dbtrace.home=c:\\btrace run

Please let us know what features you'd like to see with BTrace and/or BTrace VisualVM plugin.

I attended and liked the "Class Loader Rearchitected (BOF-6180)" BOF. If you have ever written class loaders, chances are that you have faced mysterious deadlocks or ClassCastException that said "ClassCastException: Foo cannot be cast to Foo" or having to decide between overriding loadClass and findclass, you probably should have attended this talk and gave your opinions/suggestions/ideas :-) If I understood properly, I think there was a suggestion to add class loader info. to the ClassCastException (something like class-loader-class-name@identity-HashCode style string?) so that one can quickly see it is a class loader issue. Also, there were many questions on loading classes from jar files. Looks like there will be changes to class loader API and class loading in VM for JDK 7.

Wednesday May 07, 2008

Tuesday May 6, JavaOne

In today's sessions that I attended I liked the following:

JRuby: Why, What, How... Do It Now

This talk is a good introduction to (J)Ruby the language and important applications of (J)Ruby. And many pointers to related (J)Ruby sessions. Nice summary!

JavaScript programming language: The Language Everybody Loves to Hate

great talk by Roberto Chinnici. Nice summary of functional and prototype-based object orientation aspects of JavaScript. You can easily impress your friends will some neat snippets of JavaScript :-) You may want to continue the fun by reading Doug Crockford's pages, if you have not do already!

At 7.30 PM, we (I and Kannan) talked about BTrace. There were many interesting questions/discussions -- both during and after the BOF! Today (Wed May 7) will be a Blu-ray day -- it starts with TS-5449 Java Technology for Blu-ray and TV: Creating your own Blu-ray Java Discs session. It is about the open source project @ Meet you all there!

Wednesday Apr 30, 2008

JVM Languages @ JavaOne 2008

In JavaOne 2008, there are many intesting sessions on "other" JVM languages covering both dynamically typed languages (JavaScript, Groovy, JRuby) and statically typed languages (JavaFX, Scala). As usual, there are many sessions covering application aspects -- like using scripting on Glassfish, Grials (Groovy), Rails (JRuby) and so on. But, my interest is mostly on the programming language aspects and JVM implementation issues. Here is a table of sessions covering those:

Session ID

Session Title

Session Type

Speakers and Company

Speakers and Company

Venue - Room


Overview of the JavaFX™ Script Programming Language

Technical Session

Christopher Oliver, Sun Microsystems, Inc.

May 06
10:50 - 11:50

Moscone Center -
Gateway 104


JRuby: Why, What, How...Do It Now

Technical Session

Thomas Enebo, Sun Microsystems, Inc. ; Charles Nutter, Sun Microsystems, Inc.

May 06
10:50 - 11:50

Moscone Center -
Esplanade 307-310


A JavaFX™ Script Programming Language Tutorial

Technical Session

James Weaver, LAT

May 06
12:10 - 13:10

Moscone Center -
Esplanade 305


JavaScript™ Programming Language: The Language Everybody Loves to Hate

Technical Session

Roberto Chinnici, Sun Microsystems, Inc.

May 06
15:20 - 16:20

Moscone Center -
Esplanade 307-310


The Script Bowl: A Rapid-Fire Comparison of Scripting Languages

Panel Session

Guillaume Laforge, G2One, Inc.; Charles Nutter, Sun Microsystems, Inc. ; Jorge Ortiz, Stanford; Raghavan Srinivas, Sun Microsystems, Inc.; Frank Wierzbicki, Sun Microsystems

May 07
09:30 - 10:30

Moscone Center -
Gateway 104


Groovy, the Red Pill: Metaprogramming--How to Blow the Mind of Developers on the Java™ Platform

Technical Session

Scott Davis, Davisworld Consulting, Inc.

May 07
09:30 - 10:30

Moscone Center -
North Mtg-121/122/124/125


Programming with Functional Objects in Scala

Technical Session

Martin Odersky, EPFL

May 08
13:30 - 14:30

Moscone Center -
Gateway 104


Writing Your Own JSR-Compliant, Domain-Specific Scripting Language

Technical Session

John Colosi, VeriSign, Inc.; David Smith, VeriSign Inc.

May 08
13:30 - 14:30

Moscone Center -
Esplanade 301


Comparing JRuby and Groovy

Technical Session

Neal Ford, ThoughtWorks Inc.

May 09
13:30 - 14:30

Moscone Center -
Esplanade 303


Jython - Implementing Dynamic Language Features for the Java™ Platform Ecosystem

Technical Session

Jim Baker, Zyasoft; Tobias Ivarsson, Neo Technology

May 09
14:50 - 15:50

Moscone Center -
Esplanade 305




« October 2015

No bookmarks in folder


No bookmarks in folder


No bookmarks in folder