Java Scripting: Java FX Script and JRuby - Inyoung Cho Java Technology Evangelist Sun Microsystems Inc.
←
→
Page content transcription
If your browser does not render page correctly, please read the page content below
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
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
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 Web Rich Internet Integrated Applications Applications Applications Applications Rich Clients Local Services & Data Richness / Interactivity Client 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-run- anywhere 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 Devices Home JavaFX Desktop Content Authoring Tools Entertainment Mobile JavaFX Script Interactive Content JavaFX Framework 2D/3D AGUI PBP SVG/MSA CLDC CDC CDC SE 16
JavaFX Workflow Visual Designer Content developer Java FX Mobile App Binary JavaFX Mobile ing ag ck Java FX TV Pa App Binary JavaFX Script code g Visu ck agin JavaFX TV Pa al As etss n tio Pa ila mp ck ag Co Java FX Source ing Application Java FX Desktop App Binary JavaFX Tools JavaFX Desktop / Consumer JRE 17
Expanding the Developer Base Java Software Developers Programing JavaFX Script Required Java Script Developers Visual Designers Volume 18
What Problem Does JavaFX Script Solve? • Fundamentally: how can we make GUI development more efficient? • GUI development is a collaboration between content designers, graphic artists, and programmers • The main bottleneck in this process appears to be us—the programmers—and not the content designers or graphic artists • But what exactly is making us inefficient? We’ll explore that in subsequent slides 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
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 21
JavaFX Script What is it? 22
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 23
What is JavaFX Script? • Extensive widget library encompassing Swing components and Java2D objects • Makes it easier to use Swing • Easily create and configure individual components • Statically typed - retains same code structuring, reuse, and encapsulation features of Java • Capable of supporting GUIs of any size or complexity • Work with all major IDEs • Rich Internet Applications (RIA) 24
JavaFX Script – A Simple Comparison In JavaFX Script In Java Main guitar class picks.opacity = [0, .01 .. 1 ] dur 1000 linear guitarAnimationThread = new StringOpThread(); ...... ...... if (guitarAnimationThread != null) { guitarAnimationThread.run(); } In Java ......... (SwingLabs Timing Framework) StringOpThread class ........... public void run() { public void class Guitar { opacityBegin = 0.01; private GuitarPick pick = ...; opacityEnd = 1.0; opacityIncreStep = 0.02; public Guitar() { opacitySleep = 2; pick.setOpacity(.5f); Animator a = for(currOpacity = opacityBegin; \ PropertySetter.createAnimator( currOpacity < opacityEnd; \ 300, pick, "opacity", .5f, 1.0f); currOpacity+=opacityIncreStep) { MouseTrigger.addTrigger(pick, a, setPickOpacity(); repaint(); MouseTriggerEvent.ENTER, true); try { } thread.sleep(opacitySleep); } } catch (InterruptedException e) { } 25
JavaFX Script Examples and Demos 26
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 27
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 } 28
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); } 29
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 30
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 }; 31
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():
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 33
Demo: Java FX 2D Tutorial 34
Demo: Weather Netbeans Sample 35
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 36
JavaFX Sample: Partial Recreation of Motorola's StudioMoto Web Site • download.java.net/general/openjfx/demos/studiomoto.jnlp 37
http://teslamotors.com 38
JavaFX Sample: Partial Recreation of teslamotors Web Site 39
Java FX Script: Language Characteristics and APIs 40
Functions //Functions may contain several variable declarations followed by one return statement function percent(a, b) { var i = a * 100; return i / b; } 41
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”; } } 42
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 43
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] 44
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; // [] 45
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]; 46
Formatting • expr format as > • directive can be: > java.text.DecimalFormat > java.text.SimpleData > java.util.Formatter (always starts with %) 100.896 format as // 100.896000 31.intValue() format as // 1F 47
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]) ... 48
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. } 49
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”};} 50
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”); 51
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 }; 52
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 53
JavaFX and Swing Components • Borders and Layout • RadioButton, Managers RadioButtonMenuItem, • Menus ToggleButton, and ButtonGroup • Labels • ComboBoxes • Group Panel, Simple Label, and TextField • Trees • Buttons • Tables • ListBoxes • TextComponents • SplitPanes • Spinners and Sliders 54
Example Widget Usage Button { row: row column: column2 opaque: false mnemonic: W text: "Width" action: operation() { width = [0..200] dur 1000; } } 55
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 56
JavaFX Script: 2D Primitives • Group • Swing components > View • Images > ImageView • Transparency > opacity • Filters > Shadow, Blur, Noise, ShapeBurst 57
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 58
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; 59
JavaFX Script Deployment 60
JavaFX Script Deployment using Java Web Start HTML JRE JNLP JavaFX File Shell 61
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 62
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. 63
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 64
JavaFX Script Performance 65
JavaFX Compiler • Open Source Compiler • Compiles JavaFX directly to bytecode • 50x Faster than the interpreter • Works will Java objects and APIs 66
Benefits of static-typing • High-quality, compile-time error reporting • High-quality IDE support > Code-completion > Searching > Refactoring • Efficient compilation 67
Bubble Mark looks good! http://metalinkltd.com/?p=139 • JavaFX — 14 fps • Download time - size of the deployment unit - The • Firefox + Silverlight bubblemark JNLP doesn't use pack200 compression so the (JavaScript) — 56 fps download of the JavaFX • Firefox + Flex — 62 fps runtime + the app is ~2.1 MB • Performance of the JavaFX • Adobe AIR — 62 fps interpreter in doing the collision detection - which is currently • Firefox + Silverlight probably 50-100 times slower (CLR) — 99 202 fps than doing it in Java (update: 202 fps after • Lack of caching or hardware fixing main timer’s acceleration of the vector graphics and gradients that latency) make up the ball 68
JavaFX Script Tools, Future, Resources 69
JavaFXPad http://download.java.net/general/openjfx/demos/javafxpad.jnlp 70
JavaFX Canvas Tutorial http://download.java.net/general/openjfx/demos/tutorial.jnlp 71
Netbeans 72
JFX Builder 73
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 74
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 75
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 76
Getting Started http://developers.sun.com/events/techdays/labs.jsp https://openjfx.dev.java.net/Getting_Started_With_JavaFX.html 77
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 78
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 79
JRuby
Open source Java implementation of the Ruby language 81
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,…) 82
JRuby: Java Technology Integration • Script Java > Power of Java technology with the Syntax of Ruby require 'java' list = java.util.ArrayList.new list
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 84
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” 85
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 86
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 87
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 88
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 89
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 90
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 91
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 92
Inyoung Cho Java Technology Evangelist Sun Microsystems Inc. 93
You can also read