JavaBeat
calling cards | international calling cards | phone card
Search JavaBeat

JAVABEAT
home
articles
tips
QnA
Books
forums
ARTICLE TOPICS
All Articles
Java 5.0
Java 6.0
EJB 3.0
JCA
Struts
JSF
Spring
Groovy
JBoss Seam
Hibernate
Eclipse
JavaFx
Google Guice
J2ME
GWT
WebServices
AJAX
ARCHIVE
2007 | 12 11 10 09 08 07 06 05 04 03
2008 | 07 06 05 04 03 02 01
CERTIFICATION KITS
350 SCJP 1.5 Mock Exams
400 SCJP 1.6 Mock Exams
300 SCWCD 5.0 Mock Exams
300 SCBCD 5.0 Mock Exams
Enter email address:

Latest JavaBeat Articles Delivered by FeedBurner
OUR NETWORK
javabeat
planetoss
Favorites
Java Jobs eCommerce software Get Ubuntu 8.04 Get FireFox 3.0  

Pages : 1 2 3

Introduction to Java 6.0 New Features, Part–I

Author : Raja
Date : Wed Jun 6th, 2007
Topic : java6  
Enter email address:

Latest JavaBeat Articles Delivered

4) Scripting Language for the Java Platform

4.1) Introduction

Java 6 provides the Common Scripting Language Framework for integrating various Scripting Languages into the Java Platform. Most of the popular Scripting Languages like Java Script, PHP Script, Bean Shell Script and PNuts Script etc., can be seamlessly integrated with the Java Platform. Support for Intercommunication between Scripting Languages and Java Programs is possible now because of this. It means that Scripting Language Code can access the Set of Java Libraries and Java Programs can directly embed Scripting Code. Java Applications can also have options for Compiling and Executing Scripts which will lead to good performance, provided the Scripting Engine supports this feature. Let us have a high-level overview of this JSR before going in detail.

Following sections provide the two core components of the Scripting engine namely,

  • Language Bindings
  • The Scripting API

4.2) Language Bindings

The Language Bindings provides mechanisms for establishing communications between the Java Code and the Script Code. More specifically, it deals with how actually a Java Object creating by a Script Code is stored and maintained by the Scripting Engine, how the Script Arguments are converted back and forth, how the Calls that are made to the Java Methods from within the Scripting Code got translated and how the return values from the Java Code are made available to the Scripting code. To illustrate on this further, consider the JavaScript Code,

					
var aJavaString = new String("A Test String");
					

This piece of code essentially creates a new Java String object and assigns it to a JavaScript object called aJavaString which is of var type. As soon as the Rhino Script Engine (which is the Scripting Engine name for JavaScript) parses this Script Code, it has to create a new instance of String object and should store it somewhere. The place where Java Objects and Script objects are stored are referred to as Bindings in Java Scripting Terminology. Here, aJavaString acts as a Proxy Object for the real java.lang.String object.

Again consider the following code,

					
var aJavaString = new java.lang.String('A Test String');
var length = aJavaString.substring(7, 13);
					

So many Micro-Level Tasks are involved if we analyse the above piece of code carefully. They are listed as follows,

  1. Script Arguments are Converted to Java Arguments
  2. Java Method to be invoked is identified
  3. Logic is performed on the invoked Java Method
  4. Return Values, if any, are sent back to the Scripting Code

The first line indicates that a new instance of java.lang.String object is created and it is stored in a Java Script object called aJavaString. Here aJavaString acts as a Proxy Object for the original java.lang.String object. After that we can see that the arguments 7 and 13 are passed from the Script Code to the method String.substring(int,int). The Engine will now convert the arguments that are to be sent to the Java method by using the Default Script-Java Mappings which is very specific to every Script Engine. After that, the Scripting Engine must ensure the availability of the method String.substring(int,int) at the run-time by abundantly depending on the Java Reflection API. Now the method is invoked and the logic gets executed. The return values are then converted using the Java-Script Mappings as defined by the Script Engine and will get populated in the length JavaScript object.

4.3) Scripting API

This API allows Java Programs to take the full advantage of Directing Embedding Scripting Code into the Applications. It also provides a framework wherein New Scripting Engines can be easily plugged-in. The entire API is available in the javax.script package.

ScriptEngineManager class provides mechanisms for Searching and Adding Scripting Engines into the Java Platform. Convenient methods are available for Discovering Existing Scripting Engines. For example, the following code will iterate and will list down all the Script Engines that are available in the Java 6 Distribution.

					
List<ScriptEngineFactory> allFactories = ScriptEngineManager.getEngineFactories();

for(ScriptEngineFactory engineFactory : allFactories){
    System.out.println("Engine Name" + engineFactory.getEngineName());
}
					

The ScriptEngineFactory is the Factory Class for creating ScriptEngine objects. As such, two different ways are there to get instances of ScriptEngine classes. One way is to call the method ScriptEngineFactory.getScriptEngine(). The other direct way is to depend on the ScriptEngineManager itself to call getEngineByName().

					
// First Way
ScriptEngineFactory rhinoFactory = getScriptEngineFactory();
ScriptEngine rhinoEngine = rhinoFactory.getScriptEngine();

// Second Way
String name  = "javascript";
ScriptEngine rhinoEngine = ScriptEngineManager.getEngineByName(engineName);
					

Execution of scripts can be done by calling the ScriptEngine.eval(String) method.

Bindings as represented by javax.script.Bindings, provide key/name information to ScriptEngines. Two types of Binding Scopes are available, one is the Global Scope and the other is the Engine Scope. By default, the ScriptEngineManager manages some set of Default bindings, which can be obtained by making a call to ScriptManager.getBindings(). The Bindings that are obtained in this manner (i.e from ScriptEngineManager) are called Global Bindings. Following is the code to get a reference to the Global-Bindings object and to populate it with application-specific values.

					
Bindings globalBindings = scriptEngineManager.getBindings();
globalBindings.put("key1", "value1");
globalBindings.put("key2", "value2");
					

It is also possible to customize the Binding information on Engine-by-Engine basis. For example, to obtain Bindings that is very specific to a particular Engine, a call to ScriptEngine.getBindings() can be made. These Bindings that are obtained in this way are called Engine Bindings.

4.4) Sample Code

This following Sample Application demonstrates how to directly embed Scripting Code in Java Applications. Argument passing between the Java Code and the Script Code are illustrated in this Sample.

					
package test;

import javax.script.*;

public class ScriptTest{

    public static void main(String[] args){

        try{
            // Create an instance of the Scripting manager.
            ScriptEngineManager manager = new ScriptEngineManager();

            // Get the reference to the rhino scripting engine.
            ScriptEngine rhinoEngine = manager.getEngineByName("javascript");

            // Get the Binding object for this Engine.
            Bindings bindings =	rhinoEngine.getBindings(ScriptContext.ENGINE_SCOPE);

            // Put the input value to the Binding.
            bindings.put("strValue", "A Test String");

            // Populate the script code to be executed.
            StringBuilder scriptCode = new StringBuilder();
            scriptCode.append("var javaString = new java.lang.String(strValue);");
            scriptCode.append("var result = javaString.length();");

            // Evaluate the Script code.
            rhinoEngine.eval(scriptCode.toString());

            // Take the output value from the script, i.e from the Bindings.
            int strLength = (Integer)bindings.get("result");

            System.out.println("Length is " + strLength);
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }
}
					

In the above code, a new instance of ScriptEngineManager is created in the very first line. Then, the Scripting Engine that comes shipped with the Mustang, (i.e, Rhino Java Script Engine) is obtained by calling ScriptEngineManager.getEngineByName("javascript"). Arguments are passed from and to the Java Code with the help of Bindings. The input string to be processed is added to the Bindings with the call to Bindings.put("strValue", "A Test String"). Notice how the input string is populated within the script code at run-time, var javaString = new java.lang.String(strValue). It means that at run-time the Script code becomes var javaString = new java.lang.String('A Test String'). Then the script is executed by calling the ScriptEngine.eval(String) method. The output which is the length of the input string is now in the Script variable called result. And as mentioned previously, since all the Script and the Java Objects will be maintained and controlled by the Bindings, it is possible to get the value of the Script object result directly by calling Bindings.get("result").

Pages : 1 2 3
 

Favorites
AffiliatedAds.com
Buy movies
Access Control
Busby seo challenge contest
Sohbet
Chat
Webmaster Hosting Forum
Java Jobs
MyVideoLib
India News
Internet Advances
Sohbet
chat
Latest QnA
SCJD Tips
When we start a thread by applying start() method on it ,how does it knows that to execute run()method?
About Wrapper class in Java
How to configure weblogic 7.0 in MyEclipse?
Static Block and Static Initializer in Java

JavaBeat Website (2004-2008), India
javabeat | about us | planetoss
Copyright (2004 - 2008), JavaBeat