SlideShare a Scribd company logo
Java Scripting:
One VM, Many Languages


Sang Shin
sang.shin@sun.com
javapassion.com
Sun Microsystems, Inc.
Agenda
•   Quick overview
•   Scripting API
•   Java SE 6 Scripting Support
•   Demo
•   Future Directions
•   Resources
Quick Overview
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
Different Languages, different jobs
• Perl
  > Text processing, report generation
• Bash, sh, ksh
  > job control
• Ruby
  > Web based applications
Java Programming Language
and Ruby Compared
public class Filter {
  public static void main(String[] args) {
    List list = new java.util.ArrayList();
    list.add(“Tim"); list.add(“Ike"); list.add(“Tina");
    Filter filter = new Filter();
    for (String item : filter.filterLongerThan(list, 3)) {
      System.out.println( item );
    }
  }
  public List filterLongerThan(List list, int length) {
    List result = new ArrayList();
    for (String item : list) {
      if (item.length() >= length) { result.add( item ); }
    }
    return result;
  }
}
Java Programming Language
and Ruby Compared
Ruby!

list = [‘Tim’, ‘Ike’, ‘Tina’]
list.select {|n| n.length > 3}.each {|n| puts n}

=> ‘Tina’
Scripting Over
Java Platform
Why Scripting Languages & Java
together?
• Combining scripting languages with the Java
  platform provides developers and end-users an
  opportunity to leverage the abilities of both
  environments
• Use scripting languages for quick and easy
  development & testing for certain parts of your
  applications
• Use Java programming language and platform for
  what it is known for
  > Scalable and highly performing business logics
Why Scripting Languages & Java
together?
• Allows end-users to customize the applications
  further
Java Platform Supports Scripting
Languages Well!
• Java Language != Java Platform
  >   Java 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
The Virtual Machine




 and more...


Development    The Virtual Machine   Devices
And Announced Recently

                 • Ruby Support from Sun
                   > JRuby @ Sun
                   > Building full Ruby and
                      Rails Support right in
                      the Virtual Machine
                   > A new team
                 • NetBeans Tools
                   > Ruby and Rails
                   > JavaScript Support
Client Scripting Scenarios
• Class files written in other languages
  >   Groovy
  >   Jython Compiler
  >   Kawa Scheme
  >   JRuby
• Java applications execute script programs
  > Stand-alone interpreter
  > Macro interpreters
  > Web Scripting
• In both cases, programs use Java Objects/Libraries
Scripting Scenarios


                                            Java Libraries
 VIRTUAL         VIRTUAL                                        VIRTUAL MACHINE
 MACHINE         MACHINE      JAVA VIRTUAL MACHINE




   Native Scripting           Java Virtual Machine                    Web
 The Community does Both...    Living the Java Lifestyle...      Leverage the VM
       (port and run)                                           (multiple languages)

                                    = You do          = We do
Scripting Framework
& API over Java Platform
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
•   Available for Java 5.0
Scripting API

 •   ScriptEngine
 •   ScriptContext, Bindings
 •   ScriptEngineFactory
 •   ScriptEngineManager
Interfaces

 • 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
ScriptEngine API
• ScriptEngine (Interface)
 >   eval()
 >   put()
 >   get()
 >   getBindings()/setBindings()
 >   createBindings()
 >   getContext()/setContext()
 >   getFactory()
• AbstractScriptEngine
 > Standard implementation of several eval() methods
ScriptEngineManager
• Provides the ScriptEngine discovery mechanism
  >   getEngineByName()
  >   getEngineByExtension()
  >   getEngineByMimeType()
  >   getEngineFactories()
• Developers can add script engines to a JRE
  > with the JAR Service Provider specification
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())");
    }
Example - “eval” script file

 // Create script engine manager
 ScriptEngineManager manager = new ScriptEngineManager();


 // Create JavaScript engine
 ScriptEngine engine = manager.getEngineByExtension(“js”);


 // Evaluate a file (or any java.io.Reader)
 engine.eval(new FileReader(“test.js”));
Example – Invoking functions

 // JavaScript code in a String
 String script = "function hello(name) { print('Hello, ' + name); }";


 // Evaluate script
 engine.eval(script);


 // JavaScript engine implements Invocable interface
 Invocable inv = (Invocable) engine;


 // Invoke a global function called “hello”
 inv.invoke("hello", new Object[] {"Scripting!!"} );
Mapping script variables to
application objects
ScriptContext and Bindings
(interface)
 •   ScriptContext—Script’s view of host application
 •   ScriptContext contains one or more Bindings
 •   Bindings is subtype of Map<String, Object>
 •   Scope is a set of named attributes
 •   Engine Scope Bindings
     > Script variables → application objects
 • Global Scope Bindings
     > Variables shared across engines
 • Writers for stdout, stderr
 • Reader for stdin
ScriptContext and Bindings (cont.)
• Exposes readers/writers for script engines to use for
  input and output
  >   setBindings()/getBindings()
  >   setAttributes()/getAttribute()
  >   setWriter()/getWriter()
  >   setReader()/getReader()
• SimpleScriptContext
Example – Script variables
 // Create script engine manager
 ScriptEngineManager manager = new ScriptEngineManager();


 // Create JavaScript engine
 ScriptEngine engine = manager.getEngineByName(“JavaScript”);
 File f = new File(“test.txt”);


 // Expose File object as variable to script
 engine.put(“file”, f);


 // Evaluate a script string wherein the “file” variable is accessed, and a
 // method is called upon it
 engine.eval(“print(file.getAbsolutePath())”);
ScriptEngineFactory (interface)
• Describe and instantiate script engines
  > 1-1 with ScriptEngines
• Factory method—getScriptEngine
• Metadata methods
  > Script file extensions, mimetypes
  > Implementation-specific behavior (threading)
• Script generation methods
  > Generate method call
  > Generate “print” call
ScriptEngineFactory (cont.)
• Each script engine has a ScriptEngineFactory
  >   getEngineName()
  >   getEngineVersion()
  >   getExtensions()
  >   getMimeTypes()
  >   getLanguageName()
  >   getProgram()
  >   getScriptEngine()
Other Scripting Classes
• CompiledScript
 > Compiled version of script
 > No requirement for reparsing
 > Associated with a script engine
• ScriptException
 > All checked exceptions must be wrapped in this type
 > Records line number, column number, filename
• Bindings/SimpleBindings
 > Mapping of key/value pairs, all strings
Java SE 6 Scripting
Support
Javascript Engine
• Based on Mozilla Rhino 1.6v2
• Features omitted for security/footprint reasons
  > Optimizer (script-to-bytecode compiler – only interpreter
    support)
  > E4X (XML language support) – depends on xmlbeans.jar
  > Rhino command line tools (shell, debugger etc.)
• Security Tweaks
Scripting Tools / Samples
• Tools
  > <JDK>/bin directory
  > jrunscript
      > Interactive command-line interpreter.
  > jhat
      > Processes heap analysis tool output
  > jconsole scripting plugin
• Samples
  > Script notepad
     > Swing application mostly implemented in Javascript
     > Fancy Javascript programming.
Demo
Programmable Calculator
●   From “Scripting for the Java Platform” by John
    O'Connor
    http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/
●   100% Java Swing application
●   Customizable using end-users' scripts
●   Uses Java SE Javascript engine
●   Enhanced to use any JSR 223 Engine
Demo: Scripting over Java SE
• Build and run ScriptPad sample app from JDK 6
  samples
  > You can build and run as NetBeans project
• Executing JavaScript code
• Invoking Java methods from JavaScript code
Scripting on the
Server side
Scripting in Java EE
• Web-tier is a natural place for scripting
  > tends to have high rate of change
• JSP is already very script-like
  > allow mixing of Java language and tags on HTML page
• Project Phobos supports JavaScript
  > as server-side web page scripting language
  > as lightweight way of implementing servlets
  > see phobos.dev.java.net
Sample JRuby Script
$response.setStatus(200)
$response.setContentType("text/html")
writer = $response.getWriter()
writer.println("<html><head><title>Hello</title></hea
  d><body>Hello from JRuby!</body></html>")
writer.flush()
Application Layout
/application            /static
   /controller             /dojo
       test.js                    dojo.js
   /module                 /css
       application.js             main.css
   /script                 faq.html
       index.js            release_notes.html
       hello.rb
   /template            /environment
   /view                   development.js
       layout.ejs          startup-glassfish.js
       test.ejs
Future Direction
Language JSRs
• invokedynamic Bytecode – JSR 292
  > http://www.jcp.org/en/jsr/detail?id=292
  > Used for better compilation of dynamically-typed scripts
• Groovy – JSR 241
  > http://groovy.codehaus.org/
• BeanShell – JSR 272
  > http://www.beanshell.org
JSR 292 – invokedynamic bytecode
• To enable the compilation of dynamically typed
  languages such as Groovy, Jruby, Jython to JVM
  bytecodes, a new bytecode called invokedynamic
  is being proposed as part of JSR 292
• The invokedynamic will not require target class
  name, and the method signature.
• It will search the specified method on the target
  object based on the method name
  > JSR will specify how to handle method overloading in
    such scenario
  > JSR will specify how to handle failures
JSR 292 – invokedynamic bytecode
• There are 4 JVM bytecodes to call methods:
  > invokeinterface - used to call an interface method on an
    object
  > invokestatic - used to call a static method of a class
  > invokevirtual - used to call a overridable method
  > invokespecial - used to call
     > constructors
     > private instance methods
     > super class methods (super.foo() calls in the source)
JSR 292 – invokedynamic bytecode
• All these instructions require the specification of
  > target class (or interface for invokeinterface) name
  > the name of the method (or <init> for constructors)
  > the signature of the method.
JSR 292 – invokedynamic bytecode
Impact on Groovy
• Groovy today supports a flexible method
  dispatching mechanism
 class Main {                                         class Person {
   public static void main(String[] args) {
     // see Person class below..                       public void work() {
     Person p = new Person();                            System.out.println("Okay, I'll work tomorrow!");
     System.out.println("Starting...");                }

     // call methods that are defined in Person class public void greet() {
     p.work();                                          System.out.println("Hello, World!");
     p.greet();                                       }

     // call methods that are not defined in Person    public Object invokeMethod(String name,
                                                       Object args) {
     // or it's superclass
                                                         System.out.println("Why are you calling " +
     p.surfTheNet();                                     name + "?"); }}
     p.writeBlog(); }}
Server-side scripting – Phobos
• http://phobos.dev.java.net
• Borrows from Ruby on Rails
  > Speed of development
  > Well-organized application structure
• Access to enterprise Java
• Javascript libraries
• Support for other technologies
  > AJAX
  > RSS / Atom
Resources
Resources - scripting.dev.java.net
• BSD License
• Scripting Engines
  > jruby, groovy, beanshell, jacl, jaskell, java,
    jawk,jelly,jexl,jruby,javascript,jython,ognl,pnuts,scheme,sl
    eep,xpath,xslt
• Applications
  > NetBeans Scripting module
• Also see coyote.dev.java.net
  > NetBeans Scripting IDE
  > Jython, groovy support
Resources - references
• JSR-223
  > http://jcp.org/en/jsr/detail?id=223
• A. Sundararajan's Blog
  > http://blogs.sun.com/sundararajan
• Roberto Chinnici's Blog (serverside scripting)
  > http://weblogs.java.net/blog/robc/
• JavaScript Developer Connection
  > http://java.sun.com/javascript
Java Scripting:
One VM, Many Languages


Sang Shin
sang.shin@sun.com
javapassion.com
Sun Microsystems, Inc.

More Related Content

What's hot (19)

15 darwino script & command line
15   darwino script & command line15   darwino script & command line
15 darwino script & command line
darwinodb
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentation
Mahnoor Hashmi
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
Kevin Webber
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
Omar Bashir
 
Java compilation
Java compilationJava compilation
Java compilation
Mike Kucera
 
Vert.x - Tehran JUG meeting Aug-2014 - Saeed Zarinfam
Vert.x - Tehran JUG meeting Aug-2014 - Saeed ZarinfamVert.x - Tehran JUG meeting Aug-2014 - Saeed Zarinfam
Vert.x - Tehran JUG meeting Aug-2014 - Saeed Zarinfam
Saeed Zarinfam
 
Introduction to Play Framework
Introduction to Play FrameworkIntroduction to Play Framework
Introduction to Play Framework
Warren Zhou
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Play framework
Play frameworkPlay framework
Play framework
sambaochung
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
team11vgnt
 
What is-java
What is-javaWhat is-java
What is-java
Shahid Rasheed
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
Teng Shiu Huang
 
Wt unit 4
Wt unit 4Wt unit 4
Wt unit 4
team11vgnt
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
Core web application development
Core web application developmentCore web application development
Core web application development
Bahaa Farouk
 
Java introduction with JVM architecture
Java introduction with JVM architectureJava introduction with JVM architecture
Java introduction with JVM architecture
atozknowledge .com
 
How to dockerize rails application compose and rails tutorial
How to dockerize rails application compose and rails tutorialHow to dockerize rails application compose and rails tutorial
How to dockerize rails application compose and rails tutorial
Katy Slemon
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
Cognizant
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
Rajiv Gupta
 
15 darwino script & command line
15   darwino script & command line15   darwino script & command line
15 darwino script & command line
darwinodb
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentation
Mahnoor Hashmi
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
Kevin Webber
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
Omar Bashir
 
Java compilation
Java compilationJava compilation
Java compilation
Mike Kucera
 
Vert.x - Tehran JUG meeting Aug-2014 - Saeed Zarinfam
Vert.x - Tehran JUG meeting Aug-2014 - Saeed ZarinfamVert.x - Tehran JUG meeting Aug-2014 - Saeed Zarinfam
Vert.x - Tehran JUG meeting Aug-2014 - Saeed Zarinfam
Saeed Zarinfam
 
Introduction to Play Framework
Introduction to Play FrameworkIntroduction to Play Framework
Introduction to Play Framework
Warren Zhou
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
Teng Shiu Huang
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
Core web application development
Core web application developmentCore web application development
Core web application development
Bahaa Farouk
 
Java introduction with JVM architecture
Java introduction with JVM architectureJava introduction with JVM architecture
Java introduction with JVM architecture
atozknowledge .com
 
How to dockerize rails application compose and rails tutorial
How to dockerize rails application compose and rails tutorialHow to dockerize rails application compose and rails tutorial
How to dockerize rails application compose and rails tutorial
Katy Slemon
 

Similar to Java ScriptingJava Scripting: One VM, Many Languages (20)

JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVMJavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVM
PaulThwaite
 
Venkat Subramaniam Blending Java With Dynamic Languages
Venkat Subramaniam Blending Java With Dynamic LanguagesVenkat Subramaniam Blending Java With Dynamic Languages
Venkat Subramaniam Blending Java With Dynamic Languages
deimos
 
Nashorn
NashornNashorn
Nashorn
Rory Preddy
 
Java: Rumours of my demise are greatly exaggerated
Java: Rumours of my demise are greatly exaggeratedJava: Rumours of my demise are greatly exaggerated
Java: Rumours of my demise are greatly exaggerated
Steve Dalton
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRuby
Brian Sam-Bodden
 
Ola Bini Evolving The Java Platform
Ola Bini Evolving The Java PlatformOla Bini Evolving The Java Platform
Ola Bini Evolving The Java Platform
deimos
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
Tugdual Grall
 
sl slides-unit-1.pptx
sl slides-unit-1.pptxsl slides-unit-1.pptx
sl slides-unit-1.pptx
SRAVANTHISALLARAM1
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajja
Priti Srinivas Sajja
 
Why Java
Why JavaWhy Java
Why Java
Kiki Ahmadi
 
Introduction to programming world
Introduction to programming worldIntroduction to programming world
Introduction to programming world
Jaskaran Singh
 
1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming
amitraj53904
 
java intro.pptx
java intro.pptxjava intro.pptx
java intro.pptx
MangaiyarkarasiDurai
 
Scripting In Java
Scripting In JavaScripting In Java
Scripting In Java
Lars Gregori
 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
jaxLondonConference
 
A Quick Tour of JVM Languages
A Quick Tour of JVM LanguagesA Quick Tour of JVM Languages
A Quick Tour of JVM Languages
Stefane Fermigier
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
day
 
MWLUG - Universal Java
MWLUG  -  Universal JavaMWLUG  -  Universal Java
MWLUG - Universal Java
Philippe Riand
 
Javanotes ww8
Javanotes ww8Javanotes ww8
Javanotes ww8
kumar467
 
Java notes
Java notesJava notes
Java notes
Chaitanya Rajkumar Limmala
 
JavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVMJavaOne 2012 CON3978 Scripting Languages on the JVM
JavaOne 2012 CON3978 Scripting Languages on the JVM
PaulThwaite
 
Venkat Subramaniam Blending Java With Dynamic Languages
Venkat Subramaniam Blending Java With Dynamic LanguagesVenkat Subramaniam Blending Java With Dynamic Languages
Venkat Subramaniam Blending Java With Dynamic Languages
deimos
 
Java: Rumours of my demise are greatly exaggerated
Java: Rumours of my demise are greatly exaggeratedJava: Rumours of my demise are greatly exaggerated
Java: Rumours of my demise are greatly exaggerated
Steve Dalton
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRuby
Brian Sam-Bodden
 
Ola Bini Evolving The Java Platform
Ola Bini Evolving The Java PlatformOla Bini Evolving The Java Platform
Ola Bini Evolving The Java Platform
deimos
 
Scripting Oracle Develop 2007
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
Tugdual Grall
 
Introduction to java by priti sajja
Introduction to java by priti sajjaIntroduction to java by priti sajja
Introduction to java by priti sajja
Priti Srinivas Sajja
 
Introduction to programming world
Introduction to programming worldIntroduction to programming world
Introduction to programming world
Jaskaran Singh
 
1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming
amitraj53904
 
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)Real-world polyglot programming on the JVM  - Ben Summers (ONEIS)
Real-world polyglot programming on the JVM - Ben Summers (ONEIS)
jaxLondonConference
 
A Quick Tour of JVM Languages
A Quick Tour of JVM LanguagesA Quick Tour of JVM Languages
A Quick Tour of JVM Languages
Stefane Fermigier
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
day
 
MWLUG - Universal Java
MWLUG  -  Universal JavaMWLUG  -  Universal Java
MWLUG - Universal Java
Philippe Riand
 
Javanotes ww8
Javanotes ww8Javanotes ww8
Javanotes ww8
kumar467
 
Ad

More from elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
elliando dias
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
elliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
elliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
elliando dias
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
elliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
elliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
elliando dias
 
Ragel talk
Ragel talkRagel talk
Ragel talk
elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
elliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
elliando dias
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
elliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
elliando dias
 
Rango
RangoRango
Rango
elliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
elliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
elliando dias
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
elliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
elliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
elliando dias
 
Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
elliando dias
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
elliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
elliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
elliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
elliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
elliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
elliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
elliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
elliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
elliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
elliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
elliando dias
 
Ad

Recently uploaded (20)

The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 

Java ScriptingJava Scripting: One VM, Many Languages

  • 1. Java Scripting: One VM, Many Languages Sang Shin [email protected] javapassion.com Sun Microsystems, Inc.
  • 2. Agenda • Quick overview • Scripting API • Java SE 6 Scripting Support • Demo • Future Directions • Resources
  • 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. Different Languages, different jobs • Perl > Text processing, report generation • Bash, sh, ksh > job control • Ruby > Web based applications
  • 6. Java Programming Language and Ruby Compared public class Filter { public static void main(String[] args) { List list = new java.util.ArrayList(); list.add(“Tim"); list.add(“Ike"); list.add(“Tina"); Filter filter = new Filter(); for (String item : filter.filterLongerThan(list, 3)) { System.out.println( item ); } } public List filterLongerThan(List list, int length) { List result = new ArrayList(); for (String item : list) { if (item.length() >= length) { result.add( item ); } } return result; } }
  • 7. Java Programming Language and Ruby Compared Ruby! list = [‘Tim’, ‘Ike’, ‘Tina’] list.select {|n| n.length > 3}.each {|n| puts n} => ‘Tina’
  • 9. Why Scripting Languages & Java together? • Combining scripting languages with the Java platform provides developers and end-users an opportunity to leverage the abilities of both environments • Use scripting languages for quick and easy development & testing for certain parts of your applications • Use Java programming language and platform for what it is known for > Scalable and highly performing business logics
  • 10. Why Scripting Languages & Java together? • Allows end-users to customize the applications further
  • 11. Java Platform Supports Scripting Languages Well! • Java Language != Java Platform > Java 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
  • 12. The Virtual Machine and more... Development The Virtual Machine Devices
  • 13. And Announced Recently • Ruby Support from Sun > JRuby @ Sun > Building full Ruby and Rails Support right in the Virtual Machine > A new team • NetBeans Tools > Ruby and Rails > JavaScript Support
  • 14. Client Scripting Scenarios • Class files written in other languages > Groovy > Jython Compiler > Kawa Scheme > JRuby • Java applications execute script programs > Stand-alone interpreter > Macro interpreters > Web Scripting • In both cases, programs use Java Objects/Libraries
  • 15. Scripting Scenarios Java Libraries VIRTUAL VIRTUAL VIRTUAL MACHINE MACHINE MACHINE JAVA VIRTUAL MACHINE Native Scripting Java Virtual Machine Web The Community does Both... Living the Java Lifestyle... Leverage the VM (port and run) (multiple languages) = You do = We do
  • 16. Scripting Framework & API over Java Platform
  • 17. 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 • Available for Java 5.0
  • 18. Scripting API • ScriptEngine • ScriptContext, Bindings • ScriptEngineFactory • ScriptEngineManager
  • 19. Interfaces • 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
  • 20. ScriptEngine API • ScriptEngine (Interface) > eval() > put() > get() > getBindings()/setBindings() > createBindings() > getContext()/setContext() > getFactory() • AbstractScriptEngine > Standard implementation of several eval() methods
  • 21. ScriptEngineManager • Provides the ScriptEngine discovery mechanism > getEngineByName() > getEngineByExtension() > getEngineByMimeType() > getEngineFactories() • Developers can add script engines to a JRE > with the JAR Service Provider specification
  • 22. 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())"); }
  • 23. Example - “eval” script file // Create script engine manager ScriptEngineManager manager = new ScriptEngineManager(); // Create JavaScript engine ScriptEngine engine = manager.getEngineByExtension(“js”); // Evaluate a file (or any java.io.Reader) engine.eval(new FileReader(“test.js”));
  • 24. Example – Invoking functions // JavaScript code in a String String script = "function hello(name) { print('Hello, ' + name); }"; // Evaluate script engine.eval(script); // JavaScript engine implements Invocable interface Invocable inv = (Invocable) engine; // Invoke a global function called “hello” inv.invoke("hello", new Object[] {"Scripting!!"} );
  • 25. Mapping script variables to application objects
  • 26. ScriptContext and Bindings (interface) • ScriptContext—Script’s view of host application • ScriptContext contains one or more Bindings • Bindings is subtype of Map<String, Object> • Scope is a set of named attributes • Engine Scope Bindings > Script variables → application objects • Global Scope Bindings > Variables shared across engines • Writers for stdout, stderr • Reader for stdin
  • 27. ScriptContext and Bindings (cont.) • Exposes readers/writers for script engines to use for input and output > setBindings()/getBindings() > setAttributes()/getAttribute() > setWriter()/getWriter() > setReader()/getReader() • SimpleScriptContext
  • 28. Example – Script variables // Create script engine manager ScriptEngineManager manager = new ScriptEngineManager(); // Create JavaScript engine ScriptEngine engine = manager.getEngineByName(“JavaScript”); File f = new File(“test.txt”); // Expose File object as variable to script engine.put(“file”, f); // Evaluate a script string wherein the “file” variable is accessed, and a // method is called upon it engine.eval(“print(file.getAbsolutePath())”);
  • 29. ScriptEngineFactory (interface) • Describe and instantiate script engines > 1-1 with ScriptEngines • Factory method—getScriptEngine • Metadata methods > Script file extensions, mimetypes > Implementation-specific behavior (threading) • Script generation methods > Generate method call > Generate “print” call
  • 30. ScriptEngineFactory (cont.) • Each script engine has a ScriptEngineFactory > getEngineName() > getEngineVersion() > getExtensions() > getMimeTypes() > getLanguageName() > getProgram() > getScriptEngine()
  • 31. Other Scripting Classes • CompiledScript > Compiled version of script > No requirement for reparsing > Associated with a script engine • ScriptException > All checked exceptions must be wrapped in this type > Records line number, column number, filename • Bindings/SimpleBindings > Mapping of key/value pairs, all strings
  • 32. Java SE 6 Scripting Support
  • 33. Javascript Engine • Based on Mozilla Rhino 1.6v2 • Features omitted for security/footprint reasons > Optimizer (script-to-bytecode compiler – only interpreter support) > E4X (XML language support) – depends on xmlbeans.jar > Rhino command line tools (shell, debugger etc.) • Security Tweaks
  • 34. Scripting Tools / Samples • Tools > <JDK>/bin directory > jrunscript > Interactive command-line interpreter. > jhat > Processes heap analysis tool output > jconsole scripting plugin • Samples > Script notepad > Swing application mostly implemented in Javascript > Fancy Javascript programming.
  • 35. Demo
  • 36. Programmable Calculator ● From “Scripting for the Java Platform” by John O'Connor http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/ ● 100% Java Swing application ● Customizable using end-users' scripts ● Uses Java SE Javascript engine ● Enhanced to use any JSR 223 Engine
  • 37. Demo: Scripting over Java SE • Build and run ScriptPad sample app from JDK 6 samples > You can build and run as NetBeans project • Executing JavaScript code • Invoking Java methods from JavaScript code
  • 39. Scripting in Java EE • Web-tier is a natural place for scripting > tends to have high rate of change • JSP is already very script-like > allow mixing of Java language and tags on HTML page • Project Phobos supports JavaScript > as server-side web page scripting language > as lightweight way of implementing servlets > see phobos.dev.java.net
  • 40. Sample JRuby Script $response.setStatus(200) $response.setContentType("text/html") writer = $response.getWriter() writer.println("<html><head><title>Hello</title></hea d><body>Hello from JRuby!</body></html>") writer.flush()
  • 41. Application Layout /application /static /controller /dojo test.js dojo.js /module /css application.js main.css /script faq.html index.js release_notes.html hello.rb /template /environment /view development.js layout.ejs startup-glassfish.js test.ejs
  • 43. Language JSRs • invokedynamic Bytecode – JSR 292 > http://www.jcp.org/en/jsr/detail?id=292 > Used for better compilation of dynamically-typed scripts • Groovy – JSR 241 > http://groovy.codehaus.org/ • BeanShell – JSR 272 > http://www.beanshell.org
  • 44. JSR 292 – invokedynamic bytecode • To enable the compilation of dynamically typed languages such as Groovy, Jruby, Jython to JVM bytecodes, a new bytecode called invokedynamic is being proposed as part of JSR 292 • The invokedynamic will not require target class name, and the method signature. • It will search the specified method on the target object based on the method name > JSR will specify how to handle method overloading in such scenario > JSR will specify how to handle failures
  • 45. JSR 292 – invokedynamic bytecode • There are 4 JVM bytecodes to call methods: > invokeinterface - used to call an interface method on an object > invokestatic - used to call a static method of a class > invokevirtual - used to call a overridable method > invokespecial - used to call > constructors > private instance methods > super class methods (super.foo() calls in the source)
  • 46. JSR 292 – invokedynamic bytecode • All these instructions require the specification of > target class (or interface for invokeinterface) name > the name of the method (or <init> for constructors) > the signature of the method.
  • 47. JSR 292 – invokedynamic bytecode Impact on Groovy • Groovy today supports a flexible method dispatching mechanism class Main { class Person { public static void main(String[] args) { // see Person class below.. public void work() { Person p = new Person(); System.out.println("Okay, I'll work tomorrow!"); System.out.println("Starting..."); } // call methods that are defined in Person class public void greet() { p.work(); System.out.println("Hello, World!"); p.greet(); } // call methods that are not defined in Person public Object invokeMethod(String name, Object args) { // or it's superclass System.out.println("Why are you calling " + p.surfTheNet(); name + "?"); }} p.writeBlog(); }}
  • 48. Server-side scripting – Phobos • http://phobos.dev.java.net • Borrows from Ruby on Rails > Speed of development > Well-organized application structure • Access to enterprise Java • Javascript libraries • Support for other technologies > AJAX > RSS / Atom
  • 50. Resources - scripting.dev.java.net • BSD License • Scripting Engines > jruby, groovy, beanshell, jacl, jaskell, java, jawk,jelly,jexl,jruby,javascript,jython,ognl,pnuts,scheme,sl eep,xpath,xslt • Applications > NetBeans Scripting module • Also see coyote.dev.java.net > NetBeans Scripting IDE > Jython, groovy support
  • 51. Resources - references • JSR-223 > http://jcp.org/en/jsr/detail?id=223 • A. Sundararajan's Blog > http://blogs.sun.com/sundararajan • Roberto Chinnici's Blog (serverside scripting) > http://weblogs.java.net/blog/robc/ • JavaScript Developer Connection > http://java.sun.com/javascript
  • 52. Java Scripting: One VM, Many Languages Sang Shin [email protected] javapassion.com Sun Microsystems, Inc.