Tech Manthan

January 2, 2008

Scripting In Java Platform

Filed under: Java Manthan — ”દીપ” @ 11:37 am

Happy New Year to All 

One key feature of Java 6.0 is change in (Java Specification Request (JSR) 223), helps developers to integrate Java technology and scripting languages by defining a standard framework and application programming interface (API) to do the following:

  1.     Access and control Java technology-based objects from a scripting environment 
  2.     Create web content with scripting languages
  3.     Embed scripting environments within Java technology-based applications

This article focuses on the specification’s third goal and will show you how to use an embedded scripting environment from a Java platform application. A demo application called ScriptCalc will provide a working example of how to extend your applications with user-defined scripts in the JavaScript programming language.

Basic Reasons to Use a Scripting Language

Most scripting languages are dynamically typed. You can usually create new variables without predetermining the variable type, and you can reuse variables to store values of different types. Also, scripting languages tend to perform many type conversions automatically, for example, converting the number 10 to the text “10″ as necessary. Although some scripting languages are compiled, most languages are interpreted. Script environments generally perform the script compilation and execution within the same process. Usually, these environments also parse and compile scripts into intermediate code when they are first executed.These qualities of scripting languages help you write applications faster, execute commands repeatedly, and tie together components from different technologies.

Combining scripting languages with the Java platform provides developers an opportunity to leverage the abilities of both environments. You can continue to use scripting languages for all the reasons you already have, and you can use the powerful Java class library to extend the abilities of those languages. If you are a Java language programmer, you now have the ability to ship applications that your customers can significantly and dynamically customize. The synergy between the Java platform and scripting languages produces an environment in which developers and end users can collaborate to create more useful, dynamic applications.

JSR 223 Implementation

Version 6 of the Java Platform, Standard Edition (Java SE), does not mandate any particular script engine, but it does include the Mozilla Rhino engine for the JavaScript programming language. The Java SE 6 platform implements the java.script APIs, which allow you to use script engines that comply with JSR 223.  

Ways to Use the Scripting API

 The scripting API is in the javax.script package available in the Java SE 6 platform. The API is still relatively small, composed of six interfaces and six classes, as Table 1 indicates.

Table 1: Interfaces and Classes in the Java SE 6 Platform

Interface Class
Bindings AbstractScriptEngine
Compilable CompiledScript
Invocable ScriptEngineManager
ScriptContext SimpleBindings
ScriptEngine SimpleScriptContext
ScriptEngineFactory ScriptException

 Your starting point should be the ScriptEngineManager class. A ScriptEngineManager object can tell you what script engines are available to the Java Runtime Environment (JRE). It can also provide ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use this API is to do the following: 

  1. Create a ScriptEngineManager object.
  2. Retrieve a ScriptEngine object from the manager.
  3. Evaluate a script using the ScriptEngine object.

That sounds easy enough, but what does the code look like? Above Example  performs all three steps, printing Hello, world! to the console.

Create a ScriptEngine object using the engine name.

  ScriptEngineManager mgr = new ScriptEngineManager();

  ScriptEngine jsEngine = mgr.getEngineByName(“JavaScript”); 

  try {   

          jsEngine.eval(“print(‘Hello, world!’)”); 

  } catch (ScriptException ex) { ex.printStackTrace();  }   

Below code shows how to evaluate a file that the customer has supplied. The file name is /scripts/F1.js, and it is located under the application directory.

 The eval method can read script files.

  ScriptEngineManager engineMgr = new ScriptEngineManager();

  ScriptEngine engine = engineMgr.getEngineByName(“ECMAScript”); 

  InputStream is =       this.getClass().getResourceAsStream(“/scripts/F1.js”); 

  try {    Reader reader = new InputStreamReader(is);   

 engine.eval(reader); 

 } catch (ScriptException ex) {    ex.printStackTrace();  }

 How to Invoke a Script Procedure 

Running entire scripts is useful, but you may want to invoke only specific script procedures. Some script engines implement the Invocable interface. If an engine implements this interface, you can call or invoke specific methods or functions that the engine has already evaluated. Script engines are not required to support the Invocable interface. However, the Rhino JavaScript technology implementation in the Java SE 6 platform does. If your script contains a function called sayHello, you could invoke it repeatedly by casting your ScriptEngine object to an Invocable object and by calling its invokeFunction method. Alternatively, if your script defines objects, you can call object methods using the invokeMethod method. Code Example 7 demonstrates how to use this interface. You can use the Invocable interface to call specific methods in a script.

  jsEngine.eval(“function sayHello() {” +           println(‘Hello, world!’);” +                “}”); 

  Invocable invocableEngine = (Invocable) jsEngine; 

  invocableEngine.invokeFunction(“sayHello”);

 Be aware that invokeMethod and invokeFunction methods can throw several exceptions, so you must be prepared to catch ScriptException, NoSuchMethodException, and perhaps even NullPointerException exceptions.

More Information : http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/ 

May 14, 2007

JAVA DESING PATTERNS – I

Filed under: Java Manthan — ”દીપ” @ 10:26 am

JAVA DESIGN PATTERN (PART-I)

By Deepak Parmar

“Pattern” as the name suggests, means series of events occurring in a definite order. The patterns can be found in Java and J2ee technologies also. Many a times, we find that there is a particular way of tackling a problem. This way is easy and has been used many times successfully by a number of people earlier also. This method becomes a pattern.

Patterns Defined: The patterns can be defined in many ways. You can find the definitions of patterns in many good books.

“Design patterns are recurring solutions to design problems.”

Patterns: According to commonly known practices, there are 23 design patterns in Java. These patterns are grouped under three heads:

1. Creational Patterns

2. Structural Patterns

3. Behavioral Patterns

Creational Patterns – Factory Pattern

Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.Let’s take an example to understand this pattern.

Example: Let’s suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. <Name> and if the sex is Female (F), it displays message saying Hello Ms <Name>.The skeleton of the code can be given here.

public class Person {
// name string
public String name;
// gender : M or F
private String gender;
public String getName() {
return name;
}public String getGender() {
return gender;
}
}// End of class

This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen.

public class Male extends Person {
public Male(String fullName) {
System.out.println(“Hello Mr. “+fullName);
}
}// End of class

Also, the class Female

public class Female extends Person {
public Female(String fullNname) {
System.out.println(“Hello Ms. “+fullNname);
}
}// End of class

Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided.

public class SalutationFactory {
public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson(args[0], args[1]);
}
public Person getPerson(String name, String gender) {
if (gender.equals(“M”))
return new Male(name);
else if(gender.equals(“F”))
return new Female(name);
else
return null;
}
}// End of class

This class accepts two arguments from the system at runtime and prints the names. Running the program:After compiling and running the code on my computer with the arguments Prashant and M:java Prashant MThe result returned is: “Hello Mr. Prashant”.

When to use a Factory Pattern?

1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.

April 30, 2007

Hibernate – An Object Relational Mapping (ORM) solution

Filed under: Java Manthan — sandipdavda @ 12:02 pm

Hibernate

By Anju Ravindran

Hibernate is an object-relational mapping (ORM) solution for the Java language. It is free as open source software that is distributed under the GNU Lesser General Public License. It provides an easy to use framework for mapping an object-oriented domain model to a traditional relational database. The purpose of Hibernate is to relieve the developer from a significant amount of common data persistence-related programming tasks. Hibernate adapts to the developer’s development process, whether starting from scratch or from a legacy database. The main disadvantages of java CMP entity beans include:

  • CMP entity beans are slow
  • They must reside inside some Application Server
  • They require special method names.
  • They are not serializable

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernate generates the SQL calls and relieves the developer from manual result set handling and object conversion, keeping the application portable to all SQL databases. Hibernate provides transparent persistence for “Plain Old Java Objects”; the only strict requirement for a persistent class is a no-argument constructor, not compulsorily public. Hibernate is typically used both in standalone Java applications and in Java EE applications using servlets or EJB session beans.


Hibernate Core for Java key features:

  • Natural programming model – Hibernate supports natural OO idiom; inheritance, polymorphism, composition and the Java collections framework

  • Support for fine-grained object models – a rich variety of mappings for collections and dependent objects

  • No build-time byte code enhancement – there’s no extra code generation or bytecode processing steps in your build procedure

  • Extreme scalability – Hibernate is extremely performant, has a dual-layer cache architecture, and may be used in a cluster

  • The query options – Hibernate addresses both sides of the problem; not only how to get objects into the database, but also how to get them out again

  • Support for “conversations” – Hibernate supports both long-lived persistence contexts, detach/reattach of objects, and takes care of optimistic locking automatically

  • Free/open source – Hibernate is licensed under the LGPL (Lesser GNU Public License)

  • EJB 3.0 – Hibernate implements the Java Persistence management API and object/relational mapping options, two members of the Hibernate team are active in the expert group

JAVAP – Hidden Fact Behind Java Programs

Filed under: Java Manthan — sandipdavda @ 5:01 am

JAVAP – Do u know this?  

By: Sandip Davda

When compiling programs in Java, it is well known that the code is not compiled to machine code. Programs in Java are compiled to into an intermediate bytecode format that is executed by a Java Virtual Machine. Most developers although have never seen byte code. (nor have many ever wanted to see it!) One way to view the byte code is to compile your class and then open the .class file in a hex editor and translate the bytecodes by referring to the virtual machine specification. A much easier way is to utilize the command-line utility javap. The Java SDK from Sun includes the javap disassembler, that will convert the byte codes into human-readable mnemonics.

public class JavapDemoApplication {    
 public static void main(String[] args) {       
  System.out.println("javap Demo Application");    
 } }

Using the ‘-c’ option, you can get a bytecode listing from javap as follows:

 


% javac JavapDemoApplication.java
% javap -c JavapDemoApplication
 Compiled from JavapDemoApplication.java
public class JavapDemoApplication
 extends java.lang.Object
{     public JavapDemoApplication();
     public static void main(java.lang.String[]);
}
 Method JavapDemoApplication()
   0 aload_0 1 invokespecial #1 <Method java.lang.Object()>
   4 return  Method void main(java.lang.String[])
   0 getstatic #2 <Field java.io.PrintStream out>
   3 ldc #3 <String "javap Demo Application">
   5 invokevirtual #4 <Method void println(java.lang.String)>
   8 return


To gain a better understanding of byte code, lets start with the first instruction in the main method:

  0 getstatic #2 <Field java.io.PrintStream out>

The initial integer is the offset of the instruction in the method. So the first instruction begins with a ‘0′. The mnemonic for the instruction follows the offset. In this example, the ‘getstatic‘ instruction pushes a static field onto a data structure called the operand stack. Later instructions can reference the field in this data structure. Following the getstatic instruction is the field to be pushed. In this case the field to be pushed is “#2 <Field java.io.PrintStream out>.” If you examined the bytecode directly, you would see that the field information is not embedded directly in the instruction. Instead, like all constants used by a Java class, the field information is stored in a shared pool. Storing field information in a constant pool reduces the size of the bytecode instructions. This is because the instructions only have to store the integer index into the constant pool instead of the entire constant. In this example, the field information is at location #2 in the constant pool. The order of items in the constant pool is compiler dependent, so you might see a number other than ‘#2.’After analyzing the first instruction, it’s easy to guess the meaning of the other instructions. The ‘ldc(load constant) instruction pushes the constant “javap Demo Application” onto the operand stack. The ‘invokevirtual‘ invokes the println method, which pops its two arguments from the operand stack. Don’t forget that an instance method such as println has two arguments: the obvious string argument, plus the implicit ‘this’ reference 

Blog at WordPress.com.