ebook img

Java APIs for Nashorn PDF

372 Pages·2014·3.72 MB·English
by  
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Java APIs for Nashorn

® BOOKS FOR PROFESSIONALS BY PROFESSIONALS S h a r a n Scripting in Java RELATED Scripting in Java teaches you how to use the Java Scripting API and JavaScript to execute scripts and take advantage of the features of a scripting language while developing Java applications. The book also covers topics that enable scripting languages to take advantage of Java features and the Java class library, including the new Java Collections and JavaFX 8 APIs. Most of the examples in this book use JavaScript on the Nashorn engine. Author Kishori Sharan will show you scripts in JavaScript to demonstrate its power and use in your Java applications. Some of the examples use the jrunscript and jjs command-line tools. Furthermore, debugging is discussed to equip you for situations when or if you encounter any issues with this kind of Java scripting. After reading and using this book, you will have most of what you need to do scripting in Java. You’ll learn: • How to execute scripts and pass parameters to scripts • What is the Java Scripting API as found in the new Java 8 • How to write scripts in Nashorn and invoke procedures in scripts • How to use compiled scripts and use Java in scripting languages • How to use the new Java APIs, including JavaFX 8 and Collections in Nashorn • How to implement a script engine • How to use the jrunscript and jjs command-line tools Shelve in ISBN 978-1-4842-0714-7 53499 Programming Languages/Java User level: Intermediate SOURCE CODE ONLINE 9781484207147 www.apress.com www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info Contents at a Glance About the Author ���������������������������������������������������������������������������xvii About the Technical Reviewers ������������������������������������������������������xix Acknowledgments ��������������������������������������������������������������������������xxi Introduction ����������������������������������������������������������������������������������xxiii ■ Chapter 1: Getting Started ��������������������������������������������������������������1 ■ Chapter 2: Executing Scripts ��������������������������������������������������������17 ■ Chapter 3: Passing Parameters to Scripts ������������������������������������25 ■ Chapter 4: Writing Scripts in Nashorn ������������������������������������������51 ■ Chapter 5: Procedures and Compiled Scripts �����������������������������175 ■ Chapter 6: Using Java in Scripting Languages ���������������������������191 ■ Chapter 7: Collections ����������������������������������������������������������������211 ■ Chapter 8: Implementing a Script Engine �����������������������������������263 ■ Chapter 9: The jrunscript Command-Line Shell ��������������������������281 ■ Chapter 10: The jjs Command-Line Tool �������������������������������������295 ■ Chapter 11: Using JavaFX in Nashorn ����������������������������������������307 ■ Chapter 12: Java APIs for Nashorn ��������������������������������������������319 ■ Chapter 13: Debugging, Tracing, and Profiling Scripts ���������������343 Index ����������������������������������������������������������������������������������������������355 v www.it-ebooks.info Introduction When I wrote the three volumes of Harnessing Java 7 in 2012, I did not include a chapter on the Java Scripting API because of the limited space that I had for each volume. Note the phrase “Java Scripting,” which uses two separate words: “Java” and “Scripting.” “JavaScript” is the name of a scripting language, which has nothing to do with the Java programming language, whereas the phrase “Java Scripting API” is the Java API that lets Java applications interact with scripting languages. In the first release, I had titled this book Harnessing Scripting in Java, and it covered only the Java Scripting API and Rhino script engine. The release did not cover the JavaScript language. JDK 8 ships with a lightweight high-performance JavaScript engine called Nashorn, which replaces the Rhino engine that shipped with JDK7. This book covers the JavaScript language completely with comprehensive coverage of the Nashorn engine. Learning the Java Scripting API, which was introduced in Java 6, is not essential for all Java developers, although it is important and very useful if you are familiar with scripting languages such as Rhino JavaScript, Groovy, Jython, JRuby, and so on and want to take advantage of those scripting languages in Java applications. I started learning the Java Scripting API by reading some online blogs and articles; they were helpful, but not quite comprehensive in giving me a clear and complete picture of how the Java Scripting API helps Java applications interact with scripting languages. My next step in the learning process was reading the specification for JSR-223, Scripting for the Java Platform Specification, along with the Java API documentation for the javax.script package. Reading the JSR-233 specification gave me a complete picture of the Java Scripting API; however, I was not ready to write this book. I was still missing some pieces of the puzzle. Therefore, I decided to read the source code for the classes in the javax.script package. I also read the source code for some scripting languages. Finally, in the process of learning the API, I developed a simple scripting engine, which I named JKScript. Finally, I read the ECMAScript 5.1 specification to get a complete picture of the JavaScript language itself. The main difficulty that I faced in writing this book was getting the information on the Nashorn engine and its features. A Wiki is maintained at https://wiki.openjdk.java.net/display/Nashorn/Main, which provides information about the Nashorn engine in bits and pieces. Tying them together in this book with cohesive examples was a challenge. It is my sincere hope that readers will enjoy this book and benefit from it. xxiii www.it-ebooks.info ■ IntroduCtIon Structure of the Book This book contains 13 chapters: Each chapter introduces a new topic from the Java Scripting API and the JavaScript language. Each chapter makes use of the material covered in the previous chapters. Chapter 1, Getting Started, introduces you to the Java Scripting API and demonstrates how to write your first Java program to execute a script written in Nashorn. It walks through the steps that are needed to download and install other scripting languages such as Groovy, Jython, and JRuby. Finally, this chapter takes a brief tour of the classes and interfaces contained in the javax.script package, describing their usages and relationship with other classes. Chapter 2, Executing Scripts, shows how to execute a script, which is stored in a file. It also demonstrates how to pass parameters from a Java application to a scripting engine, and vice versa. Chapter 3, Passing Parameter to Scripts, discusses advanced techniques and all the internal setups that are involved in passing parameters between a Java application and a scripting engine. It starts with a detailed description of the terms binding, scope, and script context. Later, it explains in detail with several illustrations how bindings, scope, and script context work together in the Java Scripting API. Each explanation is paired with a snippet of code, a complete program, or both. The chapter ends with a program that shows how to redirect outputs from a script to a file. Chapter 4, Writing Scripts in Nashorn, covers the JavaScript language in great detail as described in the ECMAScript 5.1 specification that is supported by the Nashorn engine. Chapter 5, Procedures and Compiled Scripts, explains how to invoke top-level procedures, functions, and object-level methods written in a scripting language from a Java application. It explains how to compile scripts in intermediate form, if supported by the scripting engine, and execute them repeatedly. Chapter 6, Using Java in Nashorn, explains how to use features and constructs of the Java programming language inside scripting languages. The Java features discussed are importing Java classes, creating Java objects, using Java overloaded methods, implementing Java interfaces, and so on. Chapter 7, Collections, explains untyped and typed arrays in Nashorn. It also explains how to use Java collection classes such as java.util.Set and java.util.Map in Nashorn. Chapter 8, Implementing a Script Engine, discusses the steps needed to implement a new script engine. It explains all classes and interfaces in the Java Scripting API that are involved in creating a new script engine. It walks through the deployment setup that makes a script engine autodiscoverable by a script engine manager. In the process, it creates a simple script engine, which we call JKScript, which is capable of executing an arithmetic expression. Chapter 9, The jrunscript Command-Line Shell, explains how to use the jrunscript command-line shell to execute script using different scripting engines. Chapter 10, The jjs Command-Line Tool, explains how to use the jjs command-line tool to execute Nashorn scripts in different modes. It walks through the syntax and the options for the command-line tool. Several examples are provided to illustrate the usage of the shell. xxiv www.it-ebooks.info ■ IntroduCtIon Chapter 11, Using JavaFX in Nashorn, explains how to write and run JavaFX programs using the jjs command-line tool. Chapter 12, Java APIs for Nashorn, covers the Java classes and interfaces that can be used to work with JavaScript objects in Java programs. Chapter 13, Debugging, Tracing, and Profiling Scripts, explains the debugging support in NetBeans 8.0 for debugging Nashorn scripts. It also explains how to trace and profile Nashorn scripts. Audience This book is designed to be useful for anyone who wants to learn the Java Scripting API in Java and Nashorn JavaScript. A basic knowledge of Java is required to use this book. Although it would be helpful to have a prior knowledge of a scripting language such as Rhino JavaScript, Groovy, JRuby, Jython, and so on, it is not required. Examples contained in this book are written in Nashorn JavaScript. Examples are deliberately kept simple and short so that readers can understand them without any prior experience with a scripting language. If you do not have experience working with a scripting language, you need to read the book chapter-by-chapter sequentially. Source Code and Errata Source code and errata for this book may be downloaded from www.apress.com/source-code. Questions and Comments Please direct all your questions and comments for the author to [email protected]. xxv www.it-ebooks.info Chapter 1 Getting Started In this chapter, you will learn: • What scripting in Java is • How to execute your first script from Java • How to use other scripting languages such as JRuby, Jython from Java • javax.script API • How script engines are discovered and instantiated What Is Scripting in Java? Some believe that the Java Virtual Machine (JVM) can execute programs written only in the Java programming language. However, that is not true. The JVM executes language- neutral bytecode. It can execute programs written in any programming language, if the program can be compiled into Java bytecode. A scripting language is a programming language that provides you with the ability to write scripts that are evaluated (or interpreted) by a runtime environment called a script engine (or an interpreter). A script is a sequence of characters that is written using the syntax of a scripting language and used as the source for a program executed by an interpreter. The interpreter parses the scripts, produces intermediate code, which is an internal representation of the program, and executes the intermediate code. The interpreter stores the variables used in a script in data structures called symbol tables. Typically, unlike in a compiled programming language, the source code (called a script) in a scripting language is not compiled but is interpreted at runtime. However, scripts written in some scripting languages may be compiled into Java bytecode that can be run by the JVM. Java 6 added scripting support to the Java platform that lets a Java application execute scripts written in scripting languages such as Rhino JavaScript, Groovy, Jython, JRuby, Nashorn JavaScript, and so on. Two-way communication is supported. It also lets scripts access Java objects created by the host application. The Java runtime and a scripting language runtime can communicate and make use of each other’s features. Support for scripting languages in Java comes through the Java Scripting API. All classes and interfaces in the Java Scripting API are in the javax.script package. 1 www.it-ebooks.info Chapter 1 ■ GettinG Started Using a scripting language in a Java application provides several advantages: • Most scripting languages are dynamically typed, which makes it simpler to write programs. • They provide a quicker way to develop and test small applications. • Customization by end users is possible. • A scripting language may provide domain-specific features that are not available in Java. Scripting languages have some disadvantages as well. For example, dynamic typing is good to write simpler code; however, it turns into a disadvantage when a type is interpreted incorrectly and you have to spend a lot of time debugging it. Scripting support in Java lets you take advantage of both worlds: it allows you to use the Java programming language for developing statically typed, scalable, and high-performance parts of the application and use a scripting language that fits the domain-specific needs for other parts. I will use the term script engine frequently in this book. A script engine is a software component that executes programs written in a particular scripting language. Typically, but not necessarily, a script engine is an implementation of an interpreter for a scripting language. Interpreters for several scripting languages have been implemented in Java. They expose programming interfaces so a Java program may interact with them. JDK 7 was cobundled with a script engine called Rhino JavaScript. JDK 8 replaced the Rhino JavaScript engine with a lightweight, faster script engine called Nashorn JavaScript. This book discusses Nashorn JavaScript, not Rhino JavaScript. Please visit www.mozilla.org/rhino for more details on Rhino JavaScript documentation. If you want to migrate programs written with Rhino JavaScript to Nashorn, please visit the Rhino Migration Guide at https://wiki.openjdk.java.net/display/Nashorn/Rhino+Migration+Guide. If you are interested in using Rhino JavaScript with JDK 8, visit the page at https://wiki.openjdk.java.net/display/Nashorn/Using+Rhino+JSR-223+engine+with+JDK8. Java includes a command-line shell called jrunscript that can be used to run scripts in an interactive mode or a batch mode. The jrunscript shell is scripting- language-neutral; the default language is Rhino JavaScript in JDK 7 and Nashorn in JDK 8. I will discuss the jrunscript shell in detail in Chapter 9. JDK 8 includes another command-line tool called jjs that invokes the Nashorn engine and offers Nashorn-specific command-line options. If you are using Nashorn, you should use the jjs command-line tool over jrunscript. I will discuss the jjs command-line tool in Chapter 10. Java can execute scripts in any scripting language that provides an implementation for a script engine. For example, Java can execute scripts written in Nashorn JavaScript, Rhino JavaScript, Groovy, Jython, JRuby, and so on. Examples in this book use Nashorn JavaScript language. In this book, the terms “Nashorn,” “Nashorn Engine,” “Nashorn JavaScript,” “Nashorn JavaScript Engine,” “Nashorn Scripting Language,” and “JavaScript” have been used synonymously. 2 www.it-ebooks.info Chapter 1 ■ GettinG Started The Nashorn scripting engine can be invoked in two ways: • By embedding the engine in the JVM • By using the jjs command-line tool In this chapter, I will discuss both ways of using the Nashorn script engine. Executing Your First Script In this section, you will use Nashorn to print a message on the standard output. You will access the Nashorn engine from Java code. The same steps can be used to print a message using any other scripting languages, with one difference: you will need to use the scripting language-specific code to print the message. You need to perform three steps to run a script in Java: • Create a script engine manager. • Get an instance of a script engine from the script engine manager. • Call the eval() method of the script engine to execute a script. A script engine manager is an instance of the ScriptEngineManager class. You can create a script engine, like so: // Create a script engine manager ScriptEngineManager manager = new ScriptEngineManager(); An instance of the ScriptEngine interface represents a script engine in a Java program. The getEngineByName(String engineShortName) method of a ScriptEngineManager is used to get an instance of a script engine. To get an instance of the Nashorn engine, use JavaScript as the short name of the engine as shown: // Get the reference of a Nashorn engine ScriptEngine engine = manager.getEngineByName("JavaScript"); ■ Tip the short name of a script engine is case-sensitive. Sometimes a script engine has multiple short names. nashorn engine has the following short names: nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript. You can use any of the short names of an engine to get its instance using the getEngineByName() method of the ScriptEngineManager class. 3 www.it-ebooks.info Chapter 1 ■ GettinG Started In Nashorn, the print() function prints a message on the standard output and a string literal is a sequence of characters enclosed in single or double quotes. The following snippet of code stores a script in a String object that prints Hello Scripting! on the standard output: // Store a Nashorn script in a string String script = "print('Hello Scripting!')"; If you want to use double quotes to enclose the string literal in Nashorn, the statement will look as shown: // Store a Nashorn script in a string String script = "print(\"Hello Scripting!\")"; To execute the script, you need to pass it to the eval() method of the script engine. A script engine may throw a ScriptException when it runs a script. For this reason, you need to handle this exception when you call the eval() method of the ScriptEngine. The following snippet of code executes the script stored in the script variable: try { engine.eval(script); } catch (ScriptException e) { e.printStackTrace(); } Listing 1-1 contains the complete code for the program to print a message on the standard output. Listing 1-1. Printing a Message on the Standard Output Using Nashorn // HelloScripting.java package com.jdojo.script; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class HelloScripting { public static void main(String[] args) { // Create a script engine manager ScriptEngineManager manager = new ScriptEngineManager(); // Obtain a Nashorn script engine from the manager ScriptEngine engine = manager.getEngineByName("JavaScript"); // Store the script in a String String script = "print('Hello Scripting!')"; 4 www.it-ebooks.info

Description:
When I wrote the three volumes of Harnessing Java 7 in 2012, I did not include a covers the JavaScript language completely with comprehensive coverage of the shows some examples of using the return value of the eval() method for Nashorn. c:\> jjs -scripting heredoc.js -- Kishori Sharan.
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.