SlideShare una empresa de Scribd logo
1 de 52
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

15 darwino script & command line
15   darwino script & command line15   darwino script & command line
15 darwino script & command linedarwinodb
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentationMahnoor Hashmi
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin 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 RuntimeOmar Bashir
 
Java compilation
Java compilationJava compilation
Java compilationMike 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 ZarinfamSaeed Zarinfam
 
Introduction to Play Framework
Introduction to Play FrameworkIntroduction to Play Framework
Introduction to Play FrameworkWarren Zhou
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersTeng 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 Coursepeter_marklund
 
Core web application development
Core web application developmentCore web application development
Core web application developmentBahaa Farouk
 
Java introduction with JVM architecture
Java introduction with JVM architectureJava introduction with JVM architecture
Java introduction with JVM architectureatozknowledge .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 tutorialKaty Slemon
 

La actualidad más candente (19)

15 darwino script & command line
15   darwino script & command line15   darwino script & command line
15 darwino script & command line
 
Java byte code presentation
Java byte code presentationJava byte code presentation
Java byte code presentation
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 
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
 
Java compilation
Java compilationJava compilation
Java compilation
 
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
 
Introduction to Play Framework
Introduction to Play FrameworkIntroduction to Play Framework
Introduction to Play Framework
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Play framework
Play frameworkPlay framework
Play framework
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
What is-java
What is-javaWhat is-java
What is-java
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
 
Wt unit 4
Wt unit 4Wt unit 4
Wt unit 4
 
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
 
Core web application development
Core web application developmentCore web application development
Core web application development
 
Java introduction with JVM architecture
Java introduction with JVM architectureJava introduction with JVM architecture
Java introduction with JVM architecture
 
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
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 

Similar a Java ScriptingJava Scripting: One VM, Many Languages

Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016johannes_fiala
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundryrajdeep
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3day
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationStuart (Pid) Williams
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentationdhananajay95
 
SubScript: A Process Algebra extension progress and perspectives
SubScript: A Process Algebra extension progress and perspectivesSubScript: A Process Algebra extension progress and perspectives
SubScript: A Process Algebra extension progress and perspectivesAnatolii Kmetiuk
 
javascript 1
javascript 1javascript 1
javascript 1osman do
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 

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

Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
 
Play Support in Cloud Foundry
Play Support in Cloud FoundryPlay Support in Cloud Foundry
Play Support in Cloud Foundry
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
Bn1005 demo ppt core java
Bn1005 demo ppt core javaBn1005 demo ppt core java
Bn1005 demo ppt core java
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
 
Java1
Java1Java1
Java1
 
Java1
Java1Java1
Java1
 
SubScript: A Process Algebra extension progress and perspectives
SubScript: A Process Algebra extension progress and perspectivesSubScript: A Process Algebra extension progress and perspectives
SubScript: A Process Algebra extension progress and perspectives
 
Curso de Programación Java Básico
Curso de Programación Java BásicoCurso de Programación Java Básico
Curso de Programación Java Básico
 
intoduction to java
intoduction to javaintoduction to java
intoduction to java
 
javascript 1
javascript 1javascript 1
javascript 1
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 

Más de elliando dias

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slideselliando 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 ClojureScriptelliando dias
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structureselliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de containerelliando 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 Agilityelliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Librarieselliando 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 Webelliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduinoelliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorceryelliando 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 Designelliando dias
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makeselliando 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 Facebookelliando 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 Studyelliando dias
 

Más de elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
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
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
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
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
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!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
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
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
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
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
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
 

Último

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

Java ScriptingJava Scripting: One VM, Many Languages

  • 1. Java Scripting: One VM, Many Languages Sang Shin sang.shin@sun.com 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 sang.shin@sun.com javapassion.com Sun Microsystems, Inc.