JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Java ScriptEngineFactory Example

April 22, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to get the details of the script engines supported by your JVM. Java supports the different script engines that can be retrieved and used depends upon the client side scripts. Java provides javax.script.ScriptEngineFactory for storing all the script engine details like script engine name, version, default script engine, language, etc. You can use getEngineFactories() method in the javax.script.ScriptEngineManager to get the list of factories and the associated script engines. Lets look at the example. ScriptEngineFactoryExample.java

[code lang=”java”]
package javabeat.net.script;

import java.util.List;

import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

/**
* Java ScriptEngineFactory Details Example
*
* @author Krishna
*
*/
public class ScriptEngineFactoryExample {
public static void main(String[] args){

// Create ScriptEngineManager
ScriptEngineManager engineManager = new ScriptEngineManager();

//Get the ScriptEngineFactory List
List list = engineManager.getEngineFactories();

//Print the supported ScriptEngine Names
System.out.println(list.get(0).getNames());

//Print the supported ScriptEngine MimeTypes
System.out.println(list.get(0).getMimeTypes());

//Print the default script engine
System.out.println(list.get(0).getEngineName());
}
}
[/code]

Output…

[code]
[js, rhino, JavaScript, javascript, ECMAScript, ecmascript]
[application/javascript, application/ecmascript, text/javascript, text/ecmascript]
Mozilla Rhino
[/code]

Filed Under: Java Tagged With: Javax Script

How To Import Java Package Inside JavaScript using ScriptEngine

April 22, 2014 by Krishna Srinivasan Leave a Comment

This example show how to import Java package inside JavaScript. We can import the Java package and use the classes inside the scripts. In this example, I have imported the java.util package and use java.util.Date class to print today’s date. Lets look at the example.

JavaScriptEngineImportPackageExample.java

[code lang=”java”]
package javabeat.net.script;

import java.io.FileNotFoundException;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Java ScriptEngine Import Package Example
*
* @author Krishna
*
*/
public class JavaScriptEngineImportPackageExample {
public static void main(String[] args) throws ScriptException,
FileNotFoundException, NoSuchMethodException {

// Create ScriptEngineManager
ScriptEngineManager engineManager = new ScriptEngineManager();

// Create ScriptEngine
ScriptEngine engine = engineManager.getEngineByName("ECMAScript");

//Import package statement in string buffer
StringBuffer buffer = new StringBuffer();
buffer.append("importPackage(java.util);");
buffer.append("");
buffer.append("var todayDate = new Date();");
buffer.append("println(‘Today Date Is ‘ + todayDate);");

//Execute the script
engine.eval(buffer.toString());

}
}
[/code]

Output…

[code]
Today Date Is Tue Apr 22 2014 15:04:46 GMT+0530 (IST)
[/code]

Filed Under: Java Tagged With: Javax Script

How To Run External JavaScript File using ScriptEngine

April 22, 2014 by Krishna Srinivasan Leave a Comment

This example is to show how to load the script files to ScriptEngine and evaluate it. In our previous example I have explained how to write script in the Java file and use it in the Java method. In real scenario, scripts written in the external files with bunch of code. We have load the file using the File readers.

This example does the following things:

  • Create ScriptEngineManager and ScriptEngine
  • Create external script file named Eval.js
  • Create FileReader for reading the script file
  • Load the script file by passing the FileReader using ScriptEngine.eval() method
  • Invoke the methods

JavaScriptEngineEvalExample.java

[code lang=”java”]
package javabeat.net.script;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Load Script File Example
*
* @author Krishna
*
*/
public class JavaScriptEngineEvalExample {
public static void main(String[] args) throws ScriptException,
FileNotFoundException, NoSuchMethodException {

// Create ScriptEngineManager
ScriptEngineManager engineManager = new ScriptEngineManager();

// Create ScriptEngine
ScriptEngine engine = engineManager.getEngineByName("ECMAScript");

//Create file and reader instance for reading the script file
File file = new File("Eval.js");
Reader reader = new FileReader(file);

//Pass the script file to the engine
engine.eval(reader);
System.out.println("Java Program Output");
//Create invocable instance
Invocable invocable = (Invocable) engine;

//Invoke the methods defined in the script file
invocable.invokeFunction("firstFn", "Eval.js");

}
}
[/code]

Eval.js

[code]
println("Loaded the scripts");
function firstFn(name){
println("This Method written in script file : "+name);
}
[/code]

Output…

[code]
Loaded the scripts
Java Program Output
This Method written in script file : Eval.js
[/code]

Filed Under: Java Tagged With: Javax Script

Invoke Script Function using ScriptEngine

April 22, 2014 by Krishna Srinivasan Leave a Comment

This is an example of invoking a method in the Script using Java. We have to create javax.script.ScriptEngineManager and javax.script.ScriptEngine to invoke the methods. In this example I have created two methods one without parameter and one with two parameters. Once we have created the script engine instances, then we need to get javax.script.Invocable instance which is used for invoking the methods. Method invokeFunction() takes the first parameter as method name and variable arguments as the parameters.

Lets look at the example.

JavaScriptEngineMethodExample.java

[code lang=”java”]
package javabeat.net.script;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Invoke Script Method Example
*
* @author Krishna
*
*/
public class JavaScriptEngineMethodExample {
public static void main(String[] args) throws ScriptException,
NoSuchMethodException {
//Write script with two methods
String str = "function testFn(){" + "println(‘hi’)}"
+ "function add(a,b){print(‘Add Function : ‘);println(a + b)}";

//Create ScriptEngineManager
ScriptEngineManager engineManager = new ScriptEngineManager();

//Create ScriptEngine
ScriptEngine engine = engineManager.getEngineByExtension("js");

//Evaluate script
engine.eval(str);

//Create Invocable instance
Invocable invocable = (Invocable) engine;

//Invoke the methods without parameter
invocable.invokeFunction("testFn");

//Invoke the methods with parameters
invocable.invokeFunction("add", 10, 20);
}
}
[/code]

Output…

[code]
hi
Add Function : 30
[/code]

Filed Under: Java Tagged With: Javax Script

How To Get Java ScriptEngine By MimeType

April 22, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to get the script engine by using the mimetype. This is the first step when you are using the Java script engines for executing the scripts. Before your run the scripts, you must get the javax.script.ScriptEngine instance from javax.script.ScriptEngineManager. The engines are registered using the Names ,Extensions and Mimetype. This example snipped retrieving the script engine by using the mimetype by calling the method getEngineByMimeType().

Lets look at the example.

GetScriptEngineExample.java

[code lang=”java”]
package javabeat.net.script;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Get ScriptEngine By MimeType Example.
*
* @author Krishna
*
*/
public class GetScriptEngineExample {
public static void main(String[] args) throws ScriptException{

// Create ScriptEngine
ScriptEngineManager engineManager = new ScriptEngineManager();

//Get script engine using name
ScriptEngine engine = engineManager.getEngineByMimeType("application/javascript");

//Evaluate simple printing message
engine.eval("println(‘ScriptEngine Loaded using MimeTypes!!’)");
engine.eval("print(‘Welcome To JavaBeat!!!’)");

}
}
[/code]

Output…

[code]
ScriptEngine Loaded using MimeTypes!!
Welcome To JavaBeat!!!
[/code]

Filed Under: Java Tagged With: Javax Script

How To Get Java ScriptEngine By Extension

April 22, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to get the script engine by using the extension. This is the first step when you are using the Java script engines for executing the scripts. Before your run the scripts, you must get the javax.script.ScriptEngine instance from javax.script.ScriptEngineManager. The engines are registered using the Names ,Extensions and Mimetypes. This example snipped retrieving the script engine by using the extension by calling the method getEngineByExtension().

Lets look at the example.

GetScriptEngineExample.java

[code lang=”java”]
package javabeat.net.script;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Get ScriptEngine By Name Example.
*
* @author Krishna
*
*/
public class GetScriptEngineExample {
public static void main(String[] args) throws ScriptException{

// Create ScriptEngine
ScriptEngineManager engineManager = new ScriptEngineManager();

//Get script engine using name
ScriptEngine engine = engineManager.getEngineByExtension("js");

//Evaluate simple printing message
engine.eval("println(‘ScriptEngine Loaded using Extension name!!’)");
engine.eval("print(‘Welcome To JavaBeat!!!’)");

}
}
[/code]

Output…

[code]
ScriptEngine Loaded using Extension name!!
Welcome To JavaBeat!!!
[/code]

Filed Under: Java Tagged With: Javax Script

How To Get Java ScriptEngine By Name

April 22, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to get the script engine by using the name. This is the first step when you are using the Java script engines for executing the scripts. Before you run the scripts, you must get the javax.script.ScriptEngine instance from javax.script.ScriptEngineManager. The engines are registered using the Names ,Extensions and Mimetypes. This example snipped retrieving the script engine by using the name by calling the method getEngineByName().

Lets look at the example.

GetScriptEngineExample.java

[code lang=”java”]
package javabeat.net.script;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Get ScriptEngine By Name Example.
*
* @author Krishna
*
*/
public class GetScriptEngineExample {
public static void main(String[] args) throws ScriptException{

// Create ScriptEngine
ScriptEngineManager engineManager = new ScriptEngineManager();

//Get script engine using name
ScriptEngine engine = engineManager.getEngineByName("JavaScript");

//Evaluate simple printing message
engine.eval("println(‘ScriptEngine Loaded using name!!’)");
engine.eval("print(‘Welcome To JavaBeat!!!’)");

}
}
[/code]

Output…

[code]
ScriptEngine Loaded using name!!
Welcome To JavaBeat!!!
[/code]

Filed Under: Java Tagged With: Javax Script

Java ScriptEngine Example

April 21, 2014 by Krishna Srinivasan Leave a Comment

This example demonstrates how to access the Java object from JavaScript statements. Java support the JavaScript access with the ScriptEngineManager class and ScriptEngine interface. Here you will see how we can execute the JavaScript code using the Java API’s.

  • Create ScriptEngineManager which tracks the states of all the script engines.
  • Create ScriptEngine by using the method getEngineByExtension() define in ScriptEngineManager. Here we pass the parameter “js” to get the JavaScript engine.
  • Add the Java object which is used inside the script
  • Evaluate the JavaScript by using the ScriptEngine.eval() method

Lets look at the example.

ScriptEngineExample.java

[code lang=”java”]
package javabeat.net.script;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
* Invoke Java from JavaScript example.
*
* @author Krishna
*
*/
public class ScriptEngineExample {
public static void main(String[] args) {
// Create Java array with list of cities
String cities[] = { "London", "NewYork", "Sydney", "Bangalore",
"Chennai", "Mumbai" };

// Create script which accessing Java object
String script = "var index; " + "var cities = citiesArray;" + ""
+ "for (index in cities) { " + "println(cities[index]);" + "}";

// Create ScriptEngine
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByExtension("js");

// Add Java object to script engine
engine.put("citiesArray", cities);
try {
// Evaluate script using script engine
engine.eval(script);
} catch (ScriptException exception) {
exception.printStackTrace();
}
}
}
[/code]

Output…

[code]
London
NewYork
Sydney
Bangalore
Chennai
Mumbai
[/code]

javax.script.ScriptException

If you miss any syntax in the script, you would get the following exception.

[code]
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing ( after for (<Unknown source>#1) in <Unknown source> at line number 1
at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source)
at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source)
at javax.script.AbstractScriptEngine.eval(Unknown Source)
at javabeat.net.script.ScriptEngineExample.main(ScriptEngineExample.java:31)
Caused by: sun.org.mozilla.javascript.internal.EvaluatorException: missing ( after for (<Unknown source>#1)
at sun.org.mozilla.javascript.internal.DefaultErrorReporter.runtimeError(Unknown Source)
at sun.org.mozilla.javascript.internal.DefaultErrorReporter.error(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.addError(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.addError(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.reportError(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.reportError(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.reportError(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.forLoop(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.statementHelper(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.statement(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.parse(Unknown Source)
at sun.org.mozilla.javascript.internal.Parser.parse(Unknown Source)
at sun.org.mozilla.javascript.internal.Context.compileImpl(Unknown Source)
at sun.org.mozilla.javascript.internal.Context.compileReader(Unknown Source)
at sun.org.mozilla.javascript.internal.Context.compileReader(Unknown Source)
at sun.org.mozilla.javascript.internal.Context.evaluateReader(Unknown Source)
… 4 more
[/code]

Filed Under: Java Tagged With: Javax Script

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved