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!
JavaFX compiler has a built-in script shell - Per Bothner has implemented a read-eval-print loop facility for JavaFX. The script shell class is com.sun.tools.javafx.script.ScriptShell.
Note:This is in the openjfx-compiler repository and not in the JavaFX 1.0 binary.
A sample JavaFX session is as follows:
$ java -cp dist/lib/shared/javafxc.jar com.sun.tools.javafx.script.ScriptShell
/*fx1*/ "hello"
hello
/*fx2*/ 2 + 4
6
/*fx3*/ function greet (name) { println("Hello, {name}") }
/*fx4*/ greet("Sundar")
Hello, Sundar
/*fx5*/ var s = [ "Sunday", "Monday", "Tuesday" ]
[ Sunday, Monday, Tuesday ]
/*fx6*/ for (i in s) println(i)
Sunday
Monday
Tuesday
/*fx7*/ class Person { public var name: String; }
/*fx8*/ var p = Person { name: "Sundar" }
fx7$Person@13fba1
/*fx9*/ p.name
Sundar
/*fx10*/ import javax.swing.*;
/*fx11*/ var f = new JFrame("hello");
fx11:1: cannot find symbol
symbol : class JFrame
location: class fx11
/*fx12*/
/*fx13*/ var f = new javax.swing.JFrame("hello")
javax.swing.JFrame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=hello,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
/*fx14*/ f.setSize(300, 300)
/*fx15*/ f.setVisible(true)
While there is a generic shell called "jrunscript" for languages that implement jsr-223, it does not work very well for statically typed languages (which can be said about jsr-223 itself). But, the above mentioned JavaFX script shell is independent of jsr-223 interface.
Besides, jrunscript crashes for JavaFX!
$ jrunscript -cp dist/lib/shared/javafxc.jar -l javafx
fx> "hello"
Exception in thread "main" java.lang.NoSuchMethodError: com.sun.tools.javac.main.RecognizedOptions.getJavacFileManagerOptions(Lcom/sun/tools/javac/main/RecognizedOptions$OptionHelper
[Lcom/sun/tools/javac/main/JavacOption$Option;
at com.sun.tools.javac.util.JavacFileManager.(JavacFileManager.java:973)
at com.sun.tools.javafx.api.JavafxcTool.getStandardFileManager(JavafxcTool.java:102)
at com.sun.tools.javafx.script.JavaFXScriptCompiler.(JavaFXScriptCompiler.java:87)
at com.sun.tools.javafx.script.JavaFXScriptContext.(JavaFXScriptContext.java:45)
at com.sun.tools.javafx.script.JavaFXScriptEngineImpl.getJavaFXScriptContext(JavaFXScriptEngineImpl.java:61)
at com.sun.tools.javafx.script.JavaFXScriptEngineImpl.getJavaFXScriptContext(JavaFXScriptEngineImpl.java:55)
at com.sun.tools.javafx.script.JavaFXScriptEngineImpl.parse(JavaFXScriptEngineImpl.java:220)
at com.sun.tools.javafx.script.JavaFXScriptEngineImpl.eval(JavaFXScriptEngineImpl.java:173)
at com.sun.tools.javafx.script.JavaFXScriptEngineImpl.eval(JavaFXScriptEngineImpl.java:164)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
at com.sun.tools.script.shell.Main.evaluateString(Main.java:280)
at com.sun.tools.script.shell.Main.processSource(Main.java:249)
at com.sun.tools.script.shell.Main.access$100(Main.java:19)
at com.sun.tools.script.shell.Main$1.run(Main.java:165)
at com.sun.tools.script.shell.Main.main(Main.java:30)
This is because JavaFX compiler code depends on modified javac classes. The code for jrunscript lives in tools.jar along with the unmodified javac classes! These unmodified javac classes are loaded which results in exception from javafxc code! We have to use the bootstrap path workaround as shown below:
$ jrunscript -J-Xbootclasspath/p:./dist/lib/shared/javafxc.jar -l javafx
fx> 233 + 334
567
fx> for (i in [0..4]) println(i)
0
1
2
3
4
fx>
But, now we have a much better ScriptShell for JavaFX
We don't need to resort to this hack...
There is an unsupported (read - can be removed in future without notice!) command line option with JavaFX compiler. If you run javafxc as
javafxc -XDdumpjava Test.fx
the compiler generates intermediate Java code for your JavaFX program in "./dumpjava" directory (compiler expects you to create ./dumpjava directory before invoking javafxc). This is meant to be a debugging option for JavaFX compiler developers. But, you can look at generated Java code to see what happens behind the scenes - much like C++ programmers used to look at intermediate C code and/or preprocessed code.
I missed attending and speaking at Sun Tech Days at Hyderabad due to a personal reason
In fact, I prepared slides for a talk titled "JavaFX for Java, JavaScript programmers". This is much like my earlier language comparison blog entries such as Java, JavaScript and Jython, Java, Groovy and JRuby etc. The idea is to learn a language by language comparison - and not to conclude "better"/"worse" language and so on. So, no politics please
Although I could not attend Sun Tech Days, I am posting the slides here :
slides in a .pdf file
I wanted to install Ubuntu on my PlayStation 3.
The installation was smooth except for one small issue - the installation seemed to hang in "Select and install software" step. After 6% the progress bar did not increase at all! Fortunately, this seems to be a known issue with text mode installer. Please refer to Ubuntu 8.10 release notes and bug 290234. I pressed Alt-F4 and Alt-F1 to toggle between logging console and main screen to check the progress. Eventually, the installation completed! While installing I configured network as well -- i.e., giving WEP password etc. -- not sure if this is mandatory, but in my case I have wireless connectivity and so I supplied the configuration values for the same.
sudo boot-game-os
[Settings] -> [System Settings] -> [Default System] -> [Other OS]
I work on JavaFX compiler these days. The command line (debugging) option that I often use is -doe ("dump on error"). This option prints stack trace of the compiler when error message is printed. NOTE: This is an internal option and can be removed any time without notice! But, it is useful for debugging. This option works for javac as well as javafxc. When I misspelled "class" as "clas" and run compiler with -doe option, I got the stack trace below:
$ javac -doe t.java
t.java:1: class, interface, or enum expected
clas t {}
^
java.lang.RuntimeException
at com.sun.tools.javac.util.Log.writeDiagnostic(Log.java:565)
at com.sun.tools.javac.util.Log.report(Log.java:523)
at com.sun.tools.javac.util.Log.error(Log.java:404)
at com.sun.tools.javac.parser.Parser.reportSyntaxError(Parser.java:282)
at com.sun.tools.javac.parser.Parser.syntaxError(Parser.java:267)
at com.sun.tools.javac.parser.Parser.classOrInterfaceOrEnumDeclaration(Parser.java:2206)
at com.sun.tools.javac.parser.Parser.typeDeclaration(Parser.java:2180)
at com.sun.tools.javac.parser.Parser.compilationUnit(Parser.java:2126)
at com.sun.tools.javac.main.JavaCompiler.parse(JavaCompiler.java:509)
at com.sun.tools.javac.main.JavaCompiler.parse(JavaCompiler.java:550)
at com.sun.tools.javac.main.JavaCompiler.parseFiles(JavaCompiler.java:801)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:727)
at com.sun.tools.javac.main.Main.compile(Main.java:353)
at com.sun.tools.javac.main.Main.compile(Main.java:279)
at com.sun.tools.javac.main.Main.compile(Main.java:270)
at com.sun.tools.javac.Main.compile(Main.java:69)
at com.sun.tools.javac.Main.main(Main.java:54)
1 error
I bought a laptop from ELCOT for my sons. It came with SUSE Linux Enterprise Desktop 10 SP2. Kids wanted to see how it is like playing games in the "old" days. Nothing better than seeing and really playing! And so VirtualBox
Also, having access to more than one OS without having to partition does not hurt -- even for a kid's laptop! We can run OLPC, OpenSolaris, Puppy Linux, or anything else!
These days, my son is playing with these (apart from usual game sites):
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.
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:
btracedefs.h
ThreadBean.java
To run this sample, the following command can be used:
btrace -I . <pid-of-the-traced-process> ThreadBean.java
Without the -I option in command line, BTrace skips the preprocessor step.
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:
This is how it looks...
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:
I work from home in Chennai, India. There is maintenance power shutdown in my part of the city today [from 9.00 AM to 5.00 PM). I'm writing this blog from a Sun office in Apeejay Business Centre, Chennai. It is nice to be in an office after quite some time - at least as a change! But, I think I'd rather prefer to avoid travel, preparation to go office etc. every day
If you have used DTrace, chances are that you have used aggregations. For performance issues, aggregated data is often more useful than individual data points. With BTrace, aggregating data is bit painful (you have to manage using Maps explicitly). It would be nice to have DTrace-style aggregation functions such as sum, max, min and so on. Glencross, Christian M (cited in my previous entry) has contributed code changes, doc and a sample for easy-to-use aggregation facility for BTrace. Please refer to the sample code (JdbcQueries.java) that demonstrates aggregations.
Now something unrelated to aggregations, but related to BTrace : I came to know about another use-case of BTrace. See also http://blog.igorminar.com/2008/06/btrace-dtrace-for-java.html
In the last few weeks, I came to know about two cases of real world use of BTrace.
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
*/
@BTrace
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
@TLS
private static String preparingStatement;
@TLS
private static long timeStampNanos;
@TLS
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) {
return;
}
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)
@OnEvent
public static void onEvent() {
println("---------------------------------------------");
printNumberMap("JDBC statement executions / microseconds:", statementDurations);
println("---------------------------------------------");
}
}
And he has expressed few wish lists for BTrace based on his experience with DTrace. We plan to investigate those items in near future.
I received emails asking for BTrace BOF (JavaOne-2008) slides. Better late than never... I've uploaded PDF of the slides. The BOF was mostly around demos -- slides do not contain much. But, slides have few pointers that may be useful.