Java Scripting: Java FX Script and JRuby Inyoung Cho Java Technology Evangelist Sun Microsystems Inc. 1
Agenda • Java Scripting • Java FX Script > Motivation > What is it? > Examples and Demos > Languge Features, API > Deployment, Performance, Tools • JRuby • Futures • Resources 2
Java Scripting
Why Scripting? • Java Language != Java Platform > > > >
VM runs “language-neutral” bytecode Rich set of Class libraries are “language-neutral” “Write once run anywhere” applies to Platform Leverage programmer skills and advantages of particular languages.
• Time-tested technologies > Open-source projects for various languages > Jakarta BSF
4
Scripting Languages • Typically dynamically typed languages > > > >
No need to define variables before you use them Many type conversions happen automagically Can be good... Can be bad...
• Most scripting languages are interpreted > Perform the script compilation and execution within the
same process
• Very good for fast results for small jobs > Write application faster, execute commands repeatedly 5
The Virtual Machine
Java FX Development
The Virtual Machine
Devices 6
Scripting framework • JSR 223 defines the scripting framework • It supports pluggable framework for third-party script engines > Resembles BSF ActiveX Scripting > “Java application runs script programs” scenario
• javax.script package • Optional javax.script.http package for Web scripting • Part of Java SE 6 umbrella • Available for Java 5.0 7
Scripting API • • • •
ScriptEngine ScriptContext, Bindings ScriptEngineFactory ScriptEngineManager
8
ScriptEngine • ScriptEngine interface—required > Execute scripts—“eval” methods > Map Java objects to script variables (“put” method)
• Invocable interface—optional > Invoke script functions/methods > Implement Java interface using script functions/methods
• Compilable interface—optional > Compile Script to intermediate form > Execute multiple times without recompilation
9
Example – Hello world import javax.script.*; public class Main { public static void main(String[] args) throws ScriptException { // Create a script engine manager ScriptEngineManager factory = new ScriptEngineManager(); // Create JavaScript engine ScriptEngine engine = factory.getEngineByName("JavaScript"); // Add a script variable whose value is a Java Object engine.put(“greeting”, new Exception(“Hello World!”)); // Evaluate JavaScript code from String engine.eval("print(greeting.toString())"); } }
10
Java FX Script
JavaFX Script Motivation
12
Rich Integrated Internet Clients Terminal Client/Server Applications Applications
Client
Web Rich Internet Applications Applications
Integrated Rich Clients
Local Services & Data Richness / Interactivity Client Integration Client / Browser Applicability
Web as a Platform
Server
Complexity Management Security / Reliability Management Consolidation
TIME
13
Market Trends • Personal & mobile computing are blurring > Handsets becoming more advanced > Higher-speed IP Networks
• Ecosystem shifting to “platforms” > full app environment including middleware, user
experience, etc. > Reduce development costs and improves device consistency
• Software stacks largely proprietary > Industry looking for an Open alternative 14
JavaFX Product Family • Announced at JavaONE 2007 • Leverages the Java platform's write-once-runanywhere portability, application security model, ubiquitous distribution and enterprise connectivity • Initially comprised of: JavaFX Script
– Highly productive scripting language for content developers to create rich media and interactive content
JavaFX Mobile
– Mobile software stack available via OEM license to carriers and handset manufacturers seeking a branded relationship with consumers 15
JavaFX: An Architecture that Scales The Big Picture Home Entertainment
JavaFX Mobile
Desktop Interactive Content JavaFX Framework
SVG/MSA
CLDC
PBP
CDC
AGUI
CDC
2D/3D
Content Authoring Tools JavaFX Script
Devices
SE 16
JavaFX Workflow Visual Designer
Content developer
Java FX Mobile App Binary
Pa ck ag ing
JavaFX Mobile
App Binary
Co mp ila tio n
g agin k c Pa
JavaFX TV
ing ag ck Pa
JavaFX Script code
sets al As Visu
Java FX Source Application
Java FX TV
Java FX Desktop App Binary
JavaFX Tools
JavaFX Desktop / Consumer JRE 17
Expanding the Developer Base
Script Developers
JavaFX Script
Java Programing Required
Java Software Developers
Visual Designers
Volume 18
Why yet another scriting language for Java, JavaFX Script?
• Language for Spicying up Java GUI Programing easier • Building and running of media/content- rich Java clients application much easier • More productive by making Swing and Java 2D™ API accessible to a much the script programmer • Simple Accessing of Java Objects • Serve as persistence format for a new class of tools targeted at non programmers like designers and end users 19
The GUI Quagmire • Java Swing and 2D APIs are very powerful and yet > Why does it take a long time to write GUI programs? > How can we avoid the “Ugly Java technology GUI”
stereotype? > Why do Flash programs look different than Java programs? > Why does it seem easier to write web apps than Swing programs? > How can I avoid having an enormous mass of listener patterns? 20
JavaFX Script What is it?
21
What is JavaFX Script? • Formerly known as F3 (Form Follows Function) of Chirstopher Oliver from Sun Microsystems > http://blogs.sun.com/chrisoliver/category/JavaFX
• Java Scripting Language > > > > >
Object-oriented Static typing + type inference Declarative Syntax Automatic Data Binding Mixed functional/procedural evaluation model
• Web sites > http://www.sun.com/javafx > http://openjfx.dev.java.net
22
What is JavaFX Script? • Extensive widget library encompassing Swing components and Java2D objects • Easily create and configure individual components • Work with all major IDEs • Statically typed - retains same code structuring, reuse, and encapsulation features of Java • Capable of supporting GUIs of any size or complexity • Makes it easier to use Swing • Rich Internet Applications (RIA) 23
JavaFX Script – A Simple Comparison In JavaFX Script
In Java Main guitar class
picks.opacity = [0, .01 .. 1 ] dur 1000 linear
In Java (SwingLabs Timing Framework) public void class Guitar { private GuitarPick pick = ...; public Guitar() { pick.setOpacity(.5f); Animator a = PropertySetter.createAnimator( 300, pick, "opacity", .5f, 1.0f); MouseTrigger.addTrigger(pick, a, MouseTriggerEvent.ENTER, true); } }
guitarAnimationThread = new StringOpThread(); ...... ...... if (guitarAnimationThread != null) { guitarAnimationThread.run(); } ......... StringOpThread class ........... public void run() { opacityBegin = 0.01; opacityEnd = 1.0; opacityIncreStep = 0.02; opacitySleep = 2; for(currOpacity = opacityBegin; \ currOpacity < opacityEnd; \ currOpacity+=opacityIncreStep) { setPickOpacity(); repaint(); try { thread.sleep(opacitySleep); } catch (InterruptedException e) { }
24
JavaFX Script Examples and Demos
25
Example : Hello world $ cat hello.fx import java.lang.System; System.out.println("Hello, world"); $ javafx.sh hello.fx compile thread: Thread[AWT-EventQueue-0,6,main] compile 0.01 Hello, world init: 0.036
26
Example : Hello world in Java FX import javafx.ui.*; Frame { title: "Hello World JavaFX" width: 200 height: 50 content: Label { text: "Hello World" } visible: true } 27
Example : Hello world in Swing import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new Jframe("HelloWorld Swing"); final JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } 28
Data Binding in JavaFX • Cause and Effect—Responding to change • The JavaFX bind operator—Allows dynamic content to be expressed declaratively • Dependency-based evaluation of any expression • Automated by the system—Rather than manually wired by the programmer • You just declare dependencies and the JavaFX runtime takes care of performing updates when things change • Eliminates listener patterns
29
Example: Dynamic Behavior class HelloWorldModel { attribute saying: String; } var model = HelloWorldModel { saying: "Hello World" }; var win = Frame { title: bind "{model.saying} JavaFX" width: 200 content: TextField { value: bind model.saying } visible: true }; 30
Example : Using Swing Component import javafx.ui.*; import java.lang.System; import javax.swing.*; import javax.swing.JComponent; class SwingWidget extends Widget { attribute swingComponent: Jcomponent; } operation SwingWidget.createComponent():<<javax.swing.JComponent> { return swingComponent;} Frame { onClose: operation() { System.exit(0); } content: SwingWidget { swingComponent: new JTree()} visible: true title: "WTF, the Widget Test Framework" }
31
Java 2D API • To match the designs of UI designers requires using Java 2D API • But Java 2D API doesn’t have compositional behavior > The barrier to entry for many Java code programmers is too high (i.e., other than Romain Guy) • In addition to Swing Components, JFX includes SVG-like interfaces to Java 2D API as first-class elements which can be composed together into higher-level components • FX allows declarative expression of this composition
32
Demo: Java FX 2D Tutorial
33
Demo: Weather Netbeans Sample
34
Does Flash Look Better? • Actually—they don’t • Java 2D API can do what Flash does—You just have to use it! • Demo StudioMoto: > http://download.java.net/general/openjfx/demos/studiomoto.jnlp
35
JavaFX Sample: Partial Recreation of Motorola's StudioMoto Web Site • download.java.net/general/openjfx/demos/studiomoto.jnlp
36
http://teslamotors.com
37
JavaFX Sample: Partial Recreation of teslamotors Web Site
38
Java FX Script: Language Characteristics and APIs
39
Functions //Functions may contain several variable declarations followed by one return statement function percent(a, b) { var i = a * 100; return i / b; }
40
Operations (Procedures) //Operations may contain more than one statements operation substring(s:String, n:Number) : String { try { return s.substring(n); catch (e : StringOutOfBoundsException) { return “Index out of bounds”; } } 41
Array Definitions • • • •
Enclosed in [ ] Separated by commas Do not nest Use .. to indicate arithmetic range > var oneToTen = [1 .. 10];
• Can contain expressions > var greaterThanFive = oneToTen[. > 5];
• indexof function > list[indexof . > 0]; // all but first element 42
Inserting Into Arrays • insert expr [ as first | as last ] into expr2; • insert expr before expr2; • insert expr after expr2; var x = [1,2]; insert 12 into x; // [1,2,12] insert 10 as first into x; // [10,1,2,12] insert 11 after x[. == 2]; // [10,1,2,11,12]
43
Deleting From Arrays • • • •
delete var; delete expr.attribute; delete variable[predicate]; delete expr.variable[predicate];
var x = [1,2,3,4,5]; delete x[. == 2]; // [1,3,4,5] delete x[. > 3]; // [1,3] delete x; // [] 44
Querying Arrays (List Comprehension) var titleTracks = select indexof track + 1 from album in albums, track in album.tracks where track == album.title; var squares = select n*n from n in [1..10];
45
Formatting • expr format as << directive >> • directive can be: > java.text.DecimalFormat > java.text.SimpleData > java.util.Formatter (always starts with %)
100.896 format as <<%f>> // 100.896000 31.intValue() format as <<%02X>> // 1F
46
Expressions • if, while, try – Same syntax as Java for (i in [0..10]) ... for (i in [0..10] where i%2 == 0) ... for (i in [0..10], j in [0..10]) ...
47
Avoiding the Event Dispatch Thread do { // block of code executes in // separate bg thread - synchronous } do later { // block of code using // java.awt.EventQueue.invokeLater // asynchronous execution in bg thr. } 48
Triggers class X { attribute nums: Number*; } trigger on new X { // Creation trigger insert [1,2] into this.nums; } trigger on insert num into X.nums {//Insert Trigger System.out.println(“{num} added to X”); } trigger on delete num from X.nums {//Delete Trigger System.out.println(“{num} deleted from X”);} trigger on X.nums[oVal] = nVal { System.out.println(“{nVal} replaced {oVal} in X”};} 49
Reflection • As in Java, the .class operator is the key to the reflective world var x = Foo { str: “Hello” }; var c = x.class; var attrs = c.Attributes; var opers = c.Operations; var v = x[attrs[Name=='str']]; var w = opers[Name=='opr'](x, “Hi”); 50
The Bind Operater • The bind operator provide support for incremental evaluation and lazy evaluation • All attributes of JavaFX classes are observable var x1=Foo{a:1, b:2, c:3}; var x2=Foo{ a:x1.a b:bind x1.b, c:bind lazy x1.c };
51
JavaFX Widget Set • Maps to Swing and Java 2D components • Can be used easily in scripts > Define attributes quickly and easily > Code functionality around this
52
JavaFX and Swing Components • Borders and Layout Managers • Menus • Labels • Group Panel, Simple Label, and TextField • Buttons • ListBoxes • SplitPanes
• RadioButton, RadioButtonMenuItem, ToggleButton, and ButtonGroup • ComboBoxes • Trees • Tables • TextComponents • Spinners and Sliders 53
Example Widget Usage Button { row: row column: column2 opaque: false mnemonic: W text: "Width" action: operation() { width = [0..200] dur 1000; } } 54
JavaFX Script: 2D Primitives • Canvas • Shapes > Rect, Circle, Ellipse, Line, Polyline, Polygon, Arc,
CubicCurve, QuadCurve, Star, Text, Path (MoveTo, LineTo, Hline, Vline, CurveTo, QuadTo, ClosePath)
• Painting > Stroke, Fill, Gradient, Pattern
• Transformations > translate, rotate, scale, skew
55
JavaFX Script: 2D Primitives • Group • Swing components > View
• Images > ImageView
• Transparency > opacity
• Filters > Shadow, Blur, Noise, ShapeBurst 56
JavaFX Script: 2D Primitives • MouseEvents > onMouseEntered, etc.
• Area operations > Add, Subtract, Intersect, XOR
• Clipping • User defined graphics objects > CompositeNode
• Animation > The dur (duration) operator
• Shape Morphing 57
Animation: The dur operator • The documentation for the dur operator is sparse and the syntax is still being worked out var x = [0, 0.1 .. 1.0] dur 1000 linear while shouldStop continue if shouldRepeat;
58
JavaFX Script Deployment
59
JavaFX Script Deployment using Java Web Start HTML JRE JNLP File
JavaFX Shell
60
JavaFX Script Deployment • http://blogs.sun.com/chrisoliver/entry/f3_deployment • JavaFX Script Runtime > 1.5 MB jars (700 kb with pack200)
• JavaFX Script Deployment the same as Java > JavaFX Script files are archived in Jar files and loaded
via the Java class loader > Standalone Java Application > Java Web Start > Applet
61
Consumer JRE • Quickstarter: Radically reduce the startup time for Java applications and applets. • Java Kernel: Reduce the time-to-install-and-launch when the user needs to install the JRE in order to run an application. • Deployment Toolkit: Enable easy detection and installation of the JRE. • Installer Improvements: Improve the user experience of installation. • Windows Graphics Performance: Enable default graphics acceleration for simple and advanced 2D rendering. • Nimbus Look & Feel : Release a new cross-platform look & feel based on Synth.
62
Java Plug-In • Today > Robust mechanism to support Java content in the browser > Java <-> JavaScript Communication on all browsers > Access to the DOM
– http://iris.dev.java.net/ : AJAX-like web app built with Java > Easy to deploy 3D content as Applets – JNLPAppletLauncher: http://applet-launcher.dev.java.net
• Tomorrow > Will enable deployment of more sophisticated Applets > Control over heap size and low-level JVM command line
arguments > Unification between Java Web Start and Java Plug-In – Using JNLP as standard deployment mechanism
63
JavaFX Script Performance
64
JavaFX Compiler • • • •
Open Source Compiler Compiles JavaFX directly to bytecode 50x Faster than the interpreter Works will Java objects and APIs
65
Benefits of static-typing • High-quality, compile-time error reporting • High-quality IDE support > Code-completion > Searching > Refactoring • Efficient compilation
66
Bubble Mark looks good! http://metalinkltd.com/?p=139
• JavaFX — 14 fps • Firefox + Silverlight (JavaScript) — 56 fps • Firefox + Flex — 62 fps • Adobe AIR — 62 fps • Firefox + Silverlight (CLR) — 99 202 fps (update: 202 fps after fixing main timer’s latency)
• Download time - size of the deployment unit - The bubblemark JNLP doesn't use pack200 compression so the download of the JavaFX runtime + the app is ~2.1 MB • Performance of the JavaFX interpreter in doing the collision detection - which is currently probably 50-100 times slower than doing it in Java • Lack of caching or hardware acceleration of the vector graphics and gradients that make up the ball 67
JavaFX Script Tools, Future, Resources
68
JavaFXPad
http://download.java.net/general/openjfx/demos/javafxpad.jnlp 69
JavaFX Canvas Tutorial
http://download.java.net/general/openjfx/demos/tutorial.jnlp 70
Netbeans
71
JFX Builder
72
JavaFX Script: Futures • Compiler development is in progress • NetBeans Plugins are updated regularly • JavaFX Hardware Platforms: > Phones (JavaFX Mobile) > Set top boxes
• • • •
3D Scene Graph Media Component Embedded Browser Fast community growth 73
JavaFX Script Community • Open Sourcing in progress > Compiler is in Open Source
• How can you make a difference: > > > >
Register at http://openjfx.dev.java.net Learn, play, ask questions on forum Participate, submit patches or content Educate, drive, inspire
74
Resources http://openjfx.dev.java.net http://openjfx-compiler.dev.java.net http://www.sun.com/javafx https://openjfx.dev.java.net/nonav/api/i ndex.html http://jfx.wikia.com http://evc-cit.info/jfx/makeapi/api/index.html 75
Getting Started
http://developers.sun.com/events/techdays/labs.jsp https://openjfx.dev.java.net/Getting_Started_With_JavaFX.html
76
Historical Information http://blogs.sun.com/chrisoliver http://blogs.sun.com/chrisoliver/entry/more_f3_demos http://blogs.sun.com/chrisoliver/entry/interactive_f3_tutorial http://blogs.sun.com/chrisoliver/resource/swing.html http://blogs.sun.com/rags/F3Pad.jnlp http://java.sun.com/products/javawebstart http://developers.sun.com/events/techdays/labs.jsp
77
Summary • JavaFX script simplifies GUI programming > Let the graphic artists do the hard work
• More coming, watch this space > Better tools (more drag'n'drop) > Ease of deployment > Consumer, modular JRE
78
JRuby
Open source Java implementation of the Ruby language 80
What Is JRuby? • • • • •
Started in 2002 Java platform implementation of Ruby language Open source, many active contributors Aiming for compatibility with current Ruby version Integrates with Java technology > Call to Ruby from Java technology via Java Specification
Request (JSR) 223, BSF, Spring > Use Java class files from Ruby (e.g., Script Java)
• Growing set of external projects based on JRuby > JRuby-extras (GoldSpike, ActiveRecord-JDBC,…) 81
JRuby: Java Technology Integration • Script Java > Power of Java technology with the Syntax of Ruby require 'java' list list list list
= java.util.ArrayList.new << 1 << 3 << 2
list.sort
82
Why JRuby? • JRuby over Ruby > > > > > >
Strong likelihood we will be faster soon Better scalability with native threading Native unicode support Compilation Integration with Java libraries Easier path to getting Ruby in the enterprise
• JRuby over Java technology > Language features – Blocks, modules, metaprogramming, dynamic-typing
> Ruby applications/libraries – Rails, Rspec, Rake, Raven, other R’s
83
What Is Ruby on Rails? A full-stack MVC web development framework Open source (MIT), many contributors Written in Ruby Single-threaded design First released in 2004 by David Heinemeier Hansson • Ruby and Rails book sales are outselling Perl book sales • Shipping with “Leopard” • • • • •
84
Ruby on Rails Precepts • Convention over configuration > Why punish the common cases? > Encourages standard practices > Everything simpler and smaller
• Don’t Repeat Yourself (DRY) > Framework written around minimizing repetition > Repetitive code harmful to adaptability
• Agile development environment > No recompile, deploy, restart cycles > Simple tools to generate code quickly > Testing built into framework
85
Why Ruby on Rails? • Greatly simplified web development > “Less Rails code than Java application configuration” > Instant applications: working code in minutes
• Growing excited community of developers • Makes small apps trivial to create • Ruby is an excellent language
86
Why JRuby on Rails? • Deployment to Java application servers • Java technology production environments pervasive > Easier to switch framework vs. whole architecture > Lower barrier to entry
• Broader, more scalable database support • Integration with Java technology libs, legacy services • No need to leave Java technology servers, libraries, reliability 87
JRuby on Rails: Java EE Platform • Pool database connections • Access any Java Naming and Directory Interface™ (J.N.D.I.) API resource • Access any Java EE platform TLA: > > > > >
Java Persistence API (JPA) Java Management Extensions (JMX™) Enterprise JavaBeans™ (EJB™) Java Message Service (JMS) API SOAP/WSDL/SOA
88
JRuby on Rails: Deployment • Mongrel • Warfile deployment to: > Project GlassFish™ V2 > Servlet-based app server
• Project GlassFish™ V3 • Go to technical keynote at 1:30
89
JRuby on Rails: Futures • Improve Java EE platform support for Rails > Rubify Java EE platform APIs > Create Rails plug-ins to make installable units
• Use Java technology native equivalents > Unicode support > XML support
• Port Ruby native libraries > RMagick
90
More Information • • • • • •
JRuby: www.jruby.org Ruby: www.ruby-lang.org Rails: www.rubyonrails.org NetBeans™ IDE: www.netbeans.org Charles’s blog: www.headius.blogspot.com Tom’s blog: www.bloglines.com/blog/ThomasEEnebo
91
Inyoung Cho Java Technology Evangelist Sun Microsystems Inc. 92