Java - Java Programing -Java Web Hosting

Blog About Java Programing and Java Technologies

CHAPTER 9 SCRIPTING AND JSR 223 175

Filed under: Java 6 Platform — webmaster @ 1:22 am

CHAPTER 9 SCRIPTING AND JSR 223 177 The Compilable Interface Typically, scripting languages are interpreted. What this means is that each time the scripting source is read, it is evaluated before executing. To optimize execution time, you can compile some of that source such that future executions are faster. That is where the Compilable interface comes into play. If a specific scripting engine also implements Compilable, then you can precompile scripts before execution. The compilation process involves the compile() method of Compilable, and returns a CompiledScript upon success. As shown in Listing 9-4, execution of the compiled script is now done with the eval() method of CompiledScript, instead of the ScriptEngine. Listing 9-4. Working with Compilable Scripts import javax.script.*; import java.io.*; public class CompileTest { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); engine.put(”counter”, 0); if (engine instanceof Compilable) { Compilable compEngine = (Compilable)engine; try { CompiledScript script = compEngine.compile( “function count() { ” + ” counter = counter +1; ” + ” return counter; ” + “}; count();”); Console console = System.console(); console.printf(”Counter: %s%n”, script.eval()); console.printf(”Counter: %s%n”, script.eval()); console.printf(”Counter: %s%n”, script.eval()); } catch (ScriptException e) { System.err.println(e); } } else { System.err.println(”Engine can’t compile code”); } } }

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

CHAPTER 9 SCRIPTING AND JSR 223 175

Filed under: Java 6 Platform — webmaster @ 1:22 am

CHAPTER 9 SCRIPTING AND JSR 223 175 “var date = new Date();” + “date.getHours();”); String msg; if (hour < 10) { msg = "Good morning"; } else if (hour < 16) { msg = "Good afternoon"; } else if (hour < 20) { msg = "Good evening"; } else { msg = "Good night"; } Console console = System.console(); console.printf("Hour %s: %s%n", hour, msg); } catch (ScriptException e) { System.err.println(e); } } } Depending upon the current time of day, you ll get different results. > java RunJavaScript Hour 8.0: Good morning The last thing to really demonstrate in the API here is Bindings. First off is the primary reason to use Bindings: they offer the means of passing Java objects into the scripting world. While you can certainly get the Bindings object for a ScriptEngine and work with it as a Map, the ScriptEngine interface has get() and put() methods that work directly with the bindings of the engine. The FlipBindings class in Listing 9-3 shows the indirect use of the Bindings class. The program accepts a single command-line argument, which is passed into the JavaScript engine via a binding. In turn, the JavaScript reverses the string and passes the results out as a different binding. The reversed string is then displayed to the user. Listing 9-3. Reversing a String Through ScriptEngine Bindings import javax.script.*; import java.io.*;

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

172 CHAPTER 9 SCRIPTING AND JSR 223

Filed under: Java 6 Platform — webmaster @ 7:38 pm

CHAPTER 9 SCRIPTING AND JSR 223 173 factory.getLanguageVersion(), factory.getExtensions(), factory.getMimeTypes(), factory.getNames()); ScriptEngine engine = factory.getScriptEngine(); } } } Running the program demonstrates that the only installed engine is version 1.6, release 2, of the Mozilla Rhino engine. > java ListEngines Name: Mozilla Rhino Version: 1.6 release 2 Language name: ECMAScript Language version: 1.6 Extensions: [js] Mime types: [application/javascript, application/ecmascript, text/javascript, text/ecmascript] Names: [js, rhino, JavaScript, javascript, ECMAScript, ecmascript] The last line represents the different names that can be used to locate this engine from the manager. While getting the scripting engine from the factory that was acquired from the scripting manager certainly works, you don t need to go through that level of indirection. Instead, you can ask the manager directly for the engine associated with a particular extension, mime type, or name, as follows: ScriptEngine engine1 = manager.getEngineByExtension(”js”); ScriptEngine engine2 = manager.getEngineByMimeType(”text/javascript”); ScriptEngine engine3 = manager.getEngineByName(”javascript”); The getEngineByXXX() methods are not static methods of ScriptEngineManager, so you have to create an instance first; but if you know you want to evaluate a JavaScript expression, just ask for the JavaScript engine, and then use the returned engine to evaluate the expression. Note There are two constructors for ScriptEngineManager, with a class loader passed into one, allowing you to provide multiple contexts for where to locate additional engines.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

172 CHAPTER 9 SCRIPTING AND JSR 223

Filed under: Java 6 Platform — webmaster @ 7:38 pm

174 CHAPTER 9 SCRIPTING AND JSR 223 To have a scripting engine evaluate an expression, you would use one of the six versions of its eval() method, all of which can throw a ScriptException if there are errors in the script: public Object eval(String script) public Object eval(Reader reader) public Object eval(String script, ScriptContext context) public Object eval(Reader reader, ScriptContext context) public Object eval(String script, Bindings bindings) public Object eval(Reader reader, Bindings bindings) The script to evaluate can either be in the form of a String object or come from a Reader stream. The ScriptContext allows you to specify the scope of any Bindings objects, as well as get input, output, and error streams. There are two predefined context scopes: ScriptContext.GLOBAL_SCOPE and ScriptContext.ENGINE_SCOPE. The Bindings objects are just a mapping from a String name to a Java instance, with global scope meaning that names are shared across all engines. Tip To set the default context for an engine, for when a ScriptContext isn t passed into eval(), call the setContext() method of ScriptEngine. Listing 9-2 demonstrates the evaluation of a simple JavaScript expression from a string. It gets the current hour and displays an appropriate message. The JavaScript code itself is in bold. Listing 9-2. Evaluating JavaScript import javax.script.*; import java.io.*; public class RunJavaScript { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); try { Double hour = (Double)engine.eval(

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

172 CHAPTER 9 SCRIPTING AND JSR 223

Filed under: Java 6 Platform — webmaster @ 7:38 pm

172 CHAPTER 9 SCRIPTING AND JSR 223 the framework is there for tighter enterprise integration; it is just that Mustang only requires Mustang to run its classes, not some enterprise edition of the Java platform. At least with Mustang, you won t find any servlet objects related to JSR 223. Scripting Engines The scripting package added with Mustang is rather small, at least from the public API perspective: six interfaces, five classes, and an exception. Looking behind the scenes, though, there are many nonpublic elements involved. For instance, the embedded Rhino JavaScript engine has over 140 classes you just never see them or know that you re working with them, thanks to those six interfaces that are defined in the javax.script package. What you ll learn here is how to use the interfaces, not how to create your own engine. The main class of the javax.script package is called ScriptEngineManager. The class provides a discovery mechanism to the installed ScriptEngineFactory objects, which in turn provide access to an actual ScriptEngine. Listing 9-1 demonstrates this relationship from ScriptEngineManager to ScriptEngineFactory to ScriptEngine, displaying information about each factory found. Nothing is actually done with the engine just yet. Listing 9-1. Listing Available Scripting Engine Factories import javax.script.*; import java.io.*; import java.util.*; public class ListEngines { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); List factories = manager.getEngineFactories(); for (ScriptEngineFactory factory: factories) { Console console = System.console(); console.printf(”Name: %s%n” + “Version: %s%n” + “Language name: %s%n” + “Language version: %s%n” + “Extensions: %s%n” + “Mime types: %s%n” + “Names: %s%n”, factory.getEngineName(), factory.getEngineVersion(), factory.getLanguageName(),

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

168 CHAPTER 8 THE JAVA COMPILER API

Filed under: Java 6 Platform — webmaster @ 1:42 pm

Scripting and JSR 223 CHAPTER 9 What can it be now? When I first heard about scripting support in Java 6, I understood it to mean that the Mozilla Rhino JavaScript interpreter would be embedded in the platform. Using a JEditorPane, you would be able to not only show HTML in the component, but also have it execute the JavaScript on the web pages your users visit, allowing the component to be more like a full-fledged browser than just an HTML viewer for help text. But, that isn t where the scripting support in Mustang went. Instead, while Rhino is present, JSR 223 adds to Mustang a common interface to integrate any scripting language (like PHP or Ruby not just JavaScript), a framework for those scripting languages to access the Java platform, and a command-line scripting shell program, jrunscript. Before looking at the different elements offered by JSR 223, take a look at Table 9-1, which shows the relatively small size of the javax.script package, which provides the public APIs to the new scripting support library. Table 9-1. javax.script.* Package Sizes Package Version Interfaces Classes Throwable Total script 6.06 50+1 12 While I haven t been involved with JSR 223 since its beginning in 2003, I ve gathered that the JSR originated from a desire for a language for scripting web servlets with something comparable to the Bean Scripting Framework (or BSF for short). Yes, BSF is an Apache project (see http://jakarta.apache.org/bsf). BSF offered (offers?) a tag library for JavaServer Pages (JSP), allowing you to write web pages in languages other than the Java programming language. A package named something like javax.script.http would integrate with your servlets for execution on your web servers, with the script results passed back to the browser. At least for Mustang, what seems to have morphed out of the deal is something more appropriate for the standard edition of Java than for the enterprise edition. So, instead of a new javax.script.http package, you get just javax.script with no real direct web hooks, yet. And as best as can be found, it has little to no direct servlet or JSP relationship. Surely

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services


Blog About Java Programing and Java Technologies

168 CHAPTER 8 THE JAVA COMPILER API

Filed under: Java 6 Platform — webmaster @ 1:42 pm

CHAPTER 8 THE JAVA COMPILER API 169 Summary The Java Compiler API isn t needed by everyone. In fact, it isn t needed by most people. It s great for those creating tools like editors, or something like JSP engines, which require real-time compilation. Thanks to JSR 199, you can do this with Java 6. Chapter 9 moves on to JSR 223, which incorporates even more new features into Mustang. This JSR defines a framework for combining the scripting world with the Java world, enabling scripting languages to interact with full-fledged Java objects in a standard way. No longer will you have to explore any vendor-specific options, thanks to the new javax.script and javax.script.http packages.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

168 CHAPTER 8 THE JAVA COMPILER API

Filed under: Java 6 Platform — webmaster @ 1:42 pm

168 CHAPTER 8 THE JAVA COMPILER API System.err.println(”Invocation target: ” + e); } } } } Listing 8-8. The JavaSourceFromString Class Definition import javax.tools.*; import java.net.*; public class JavaSourceFromString extends SimpleJavaFileObject { final String code; JavaSourceFromString(String name, String code) { super(URI.create( “string:///” + name.replace(’.',’/') + Kind.SOURCE.extension), Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } Running the CompileSource program generates the following output: > java CompileSource Success: true —–Output—- Hello, World —–Output—-

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

Blog About Java Programing and Java Technologies

CHAPTER 8 THE JAVA COMPILER API 165

Filed under: Java 6 Platform — webmaster @ 8:07 am

CHAPTER 8 THE JAVA COMPILER API 167 out.println(” }”); out.println(”}”); out.close(); JavaFileObject file = new JavaSourceFromString(”HelloWorld”, writer.toString()); // Compile class Iterable compilationUnits = Arrays.asList(file); CompilationTask task = compiler.getTask( null, null, diagnostics, null, null, compilationUnits); task.run(); boolean success = task.getResult(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) System.console().printf( “Code: %s%n” + “Kind: %s%n” + “Position: %s%n” + “Start Position: %s%n” + “End Position: %s%n” + “Source: %s%n” + “Message: %s%n”, diagnostic.getCode(), diagnostic.getKind(), diagnostic.getPosition(), diagnostic.getStartPosition(), diagnostic.getEndPosition(), diagnostic.getSource(), diagnostic.getMessage(null)); System.out.println(”Success: ” + success); // Invoke new class if (success) { try { System.out.println(”—–Output—–”); Class.forName(”HelloWorld”).getDeclaredMethod(”main”, new Class[] {String[].class}).invoke(null, new Object[] {null}); System.out.println(”—–Output—–”); } catch (ClassNotFoundException e) { System.err.println(”Class not found: ” + e); } catch (NoSuchMethodException e) { System.err.println(”No such method: ” + e); } catch (IllegalAccessException e) { System.err.println(”Illegal access: ” + e); } catch (InvocationTargetException e) {

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services

Blog About Java Programing and Java Technologies

CHAPTER 8 THE JAVA COMPILER API 165

Filed under: Java 6 Platform — webmaster @ 8:07 am

CHAPTER 8 THE JAVA COMPILER API 165 “Source: %s%n” + “Message: %s%n”, diagnostic.getCode(), diagnostic.getKind(), diagnostic.getPosition(), diagnostic.getStartPosition(), diagnostic.getEndPosition(), diagnostic.getSource(), diagnostic.getMessage(null)); fileManager.close(); System.out.println(”Success: ” + success); } } After compiling SecondCompile, running the program will generate .class files for the Bar and Baz classes in the classes subdirectory. It will also display information from the Diagnostic of the warning messages, as shown here: > java SecondCompile Code: compiler.note.deprecated.filename Kind: NOTE Position: -1 Start Position: -1 End Position: -1 Source: null Message: Note: Bar.java uses or overrides a deprecated API. Code: compiler.note.deprecated.recompile Kind: NOTE Position: -1 Start Position: -1 End Position: -1 Source: null Message: Note: Recompile with -Xlint:deprecation for details. Code: compiler.note.unchecked.filename Kind: NOTE Position: -1 Start Position: -1 End Position: -1 Source: null Message: Note: Bar.java uses unchecked or unsafe operations. Code: compiler.note.unchecked.recompile Kind: NOTE Position: -1 Start Position: -1 End Position: -1

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services

« Previous PageNext Page »

Powered by Java Web Hosting

Windows 7 Требует Драйвер Dvd Драйвера Для Веб Камеры Lenovo руководство по массажу скачать Asrock N68 S Драйвера Скачать руководство по эксплуатации уаз патриот Asus A8j Драйвера руководство по ремонту ваз 21120 руководство по ремонту daf Acer Aspire 5315 Драйвера Скачать понятие и характеристика стилей руководства Sb Audigy Драйвер востание под руководством степана разина Logitech Quickcam V Um14 Драйвер Lenovo 3000 G430 Скачать Драйвера Cmi8738 Pci Sx Драйвер Скачать Драйвера Asus T101mt руководство по эксплуатации киа церато Defender Km 2080b Драйвер руководство по ремонту тойота авенсис Скачать Драйвер Hp Photosmart C6283 руководство по эксплуатации nokia 8800 Dv Драйвера Ethernet 10 100 Драйвер Драйвера Asus F5rseries педагогическое руководство коллективом руководство пользователя тойота приус Genius Colorpage Hr6x Slim Драйвер Драйвер Lg K1 руководство по эксплуатации ваз2121 Sony Ericsson Z520 Драйвера руководство по эксплуатации ваз 2170 руководство astra h Samsung R525 Драйвера Xp Avertv 203 Драйвер Скачать руководство пользователя видеорегистратор требования к руководству по качеству Epson Epl 6200l Драйвер руководство по качеству строительной организации citroen c3 руководство по ремонту Драйвер Acer Для Сетевого Адаптера руководство toyota windom руководство по ремонту калина калина Скачать Драйвер Epson Stylus Cx4100 Logitech C300 Драйвера руководство по эксплуатации ваз 21074 Toshiba Satellite P10 Драйвера руководство по эксплуатации нокиа n8 руководство по ремонту bmw e34 Canon 4300 Драйвер спин практическое руководство Canyon Cnp Wcam320 Драйвера Скачать руководство по ремонту ford explorer Emachines G630g Драйвера руководство mazda 323 f Epson Stylus C86 Драйвера формы руководства руководство по эксплуатации опель антара Видео Драйвер Geforce руководство по эксплуатации mazda premacy wingroad руководство по эксплуатации скачать Драйвер Ep 8kmm3i руководство по ремонту funcargo скачать openoffice calc руководство