Thursday, October 25, 2007

Practical SOA patterns

The SOA patterns I have discussed do not talk about the organization IT policies but the practical SOA patterns:-
1.1 Avoid point to point Web Services:
Problem: Web Service point to point is STILL point to point; doing a bad practice in XML doesn't make it better.

Effect: An organization believes that they are creating next generation loosely coupled architecture just because they are using Web Services. Web Service calls are invoked directly, using a URI which is hard-coded into the WSDL. Having a highly disorganized and interdependent systems model leads to increased cost of change and a high degree of fragility of the enterprise. When one service is changed a number of other services either fail or behave in unpredictable ways. There is a lack of clarity as to how one service depends on another and what the impact of change is across these services. Consumers then start demanding multiple versions of services, and these add further to the spaghetti in the enterprise.

While designing a BPEL process the endpoints of the web service may not be known, there is no simple way to determine the web service endpoint dynamically.

Resolution: The first step is to indirect all of the calls and this can be done in a number of ways; the least invasive is to "proxy" all web-service requests via some form of mediation. So while the host application is still calling webservice.mycompany.com, this is proxied so mediation and routing can be applied if required. The next stage is to understand the different dependencies and identify those which are valid and those which should have been done in a more managed way. A clear governance plan then needs to be created to identify and manage dependencies and versions and to help manage the Web Service infrastructure.

Once this level of management has been created it is time to start considering what the enterprise Service model should be, that requires the creation of the business service architecture and then overtime evolving the current infrastructure to better represent the business that pays for it.
1.2 Use Business Rules to make your process flexible:

Problem: Orchestration Languages provide constructs that break the linear flow of control. These constructs alter the flow of service orchestration based on run time information. These constructs change often.

Effect: In mortgage decisioning a conditional control structure implements the pre-screening step that determines whether the process performs decisioning or generates a rejection letter instead. The conditional verifies eligibility, determining how the orchestration unfolds based on whether the applicant's credit score is above a threshold. In effect, the condition associated with a control structure in the orchestration definition captures a business rule. In case the threshold changes, there is a change in the business process and the process needs to be changed and deployed again.

Resolution: Business rules complement processes. While business processes provide recipes for achieving results, business rules describe the operations, definitions and constraints that apply to an organization in achieving these results. For example a business rule might state that no credit check is required for existing Orchestra Bank customers. A business rules engine integrated with the BPEL manager can be used to solve the problem.

1.3 Use Composite Services to combine multiple services:

Problem: We need to combine the functionality of multiple services and make it available to consumers interested in is as a whole rather than the individual services implementing it.

Effect: Combining existing services could provide significant value over any individual service. In fact the recursive composition is key to the ability of adding value through combining functionality of the existing services. As the number of SOA adopters increases so does the number of choices.

Service consumers require functionality which can be implemented by suitably combining multiple existing services. They do not want to make multiple calls to the individual services and control the invocation flow.

Combining the functionality of existing business services (especially when they are provided by different organizations) requires a certain amount of know how and typically has sensitivities (e.g., the underlying services may change or different providers for these services can be selected). Exposing this knowledge to the service consumer introduces coupling.

Following mergers and acquisitions or through agreements with multiple partners several business services with similar functionality can be available to the enterprise (similarly to the credit check service from the context). These services can be distinguished by their interfaces and SLAs. The availability of multiple choices places the onus of selecting one service to the consumers, thus introducing coupling.

Solution: Expose the services involved in satisfying required functionality and their coordination as a separate service.
I was already using quite a few of these patterns but found them documented in Antipatterns and Orchestration patterns.

Wednesday, September 26, 2007

Java Annotations

I was preparing a talk on annotations in java and ended up learning a few cool stuff.

I believe the utility of annotations would be the freedom from implementing interfaces like the JUnit test case and the EJB 3.0.

New and innovative uses for annotations are also likely to come up.

Annotations is cool if used intelligently. Now if a developer wants to use a annotations to save configuration values I ask can you blame annotations.

The problem lies sometimes in the fuzziness of what is configuration values. Say in hibernate in by bean I hard code my table name, is my table name configuration. I believe not, but in some cases it could be true. I haven't seen table names being different in production environment and development but using annotations makes it less flexible.

Sun could have made the creation of annotations more 'Java like' @interface to define an annotation and the definition of the default values....

The annotation processing tool is also very interesting. The tool ties us with the Sun jdk and probably would evolve as a part of standard SDK distribution.

Presentation is available at : http://sashwat.gupta.googlepages.com/Annotations.pdf
Example code is available at : http://sashwat.gupta.googlepages.com/annotation.zip

Wednesday, July 4, 2007

ClassCastException

When do we get a ClassCastException?

The java documentation of ClassCastException states:-

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x);


The statement seems to be a very simple, but not when different class loaders are involved. Another scenario when this exception occurs is when the class accesses an object of the same class loaded by another class loader hierarchy.

I was determined to write a simple code to simulate the exception.

So I wrote two classes to be loaded by different classloaders.

package classldr;

public class Tree {

private String name = "sash";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

//------ different file ----------//
package classldr;

public class Person{

public void doIT(Object t)
{
//try to create the typecast exception here!!
System.out.println("Tree planted : " + ((Tree)t).getName());
}
}



I would try to load these classes using different classloaders and simulate the error.

So I created instances of URLClassLoader and did the same. I had to make sure that the class creating the class loaders could not access these classes, as it was the parent of the URLClassLoader and would have actually loaded the class due to delegation model followed by the classloaders.

package classldr;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class TestClassLoader {

public static void main(String[] args) throws Exception {

/*
* Class loader 1 to create instance of Tree class. I have put the
* Person and Tree classes in C:\classldr\ directory.
*/
ClassLoader cl1 = new URLClassLoader(new URL[] { new URL(
"file:C:\\") });
Class c = cl1.loadClass("classldr.Tree");
Object treeNewInstance = c.newInstance();

/*
* Class loader 2 to create instance of Person and Tree class.
*/
ClassLoader cl2 = new URLClassLoader(new URL[] { new URL(
"file:C:\\") });
Class treeClass = cl2.loadClass("classldr.Tree");
Class personTreeClass = cl2.loadClass("classldr.Person");
Object personTreeObj = personTreeClass.newInstance();
Object treeClassObj = treeClass.newInstance();
Method method = personTreeClass.getMethod("doIT",new Class[]{Object.class} );


//pass the object of tree loaded by cl 1 to
//person object loaded by cl 1
method.invoke(personTreeObj,new Object[]{ treeClassObj});

//pass the object of tree loaded by cl 1 to
//person object loaded by cl 2
//should throw a ClassCastException
method.invoke(personTreeObj,new Object[]{ treeNewInstance});
}
}



After I spent a lot of time on this I realized it could be demonstrated in a much simpler way. I decided that my URLClassLoader could be a child of the Bootstrap class loader, not necessarily the system class loader.

package classldr;

import java.net.URL;
import java.net.URLClassLoader;

public class TestClassLoader2 {

public static void main(String[] args) throws Exception {

//get current class location
URL resource = TestClassLoader2.class.getClassLoader().getResource(".");

//create a new classloader to load this class,
//have the parent of the classloader as null
ClassLoader cl1 = new URLClassLoader(new URL[] { resource }, null);
Class c = cl1.loadClass("classldr.TestClassLoader");

//this throws ClassCastException
TestClassLoader2 treeNewInstance = (TestClassLoader2) c.newInstance();
}
}


This code was good enough to simulate the exception.

Finally I successfully generated the exception and was feeling very stupid about my first method. :(

Friday, June 8, 2007

Finding Class Version

Facing class mismatch error, I decided to find the JRE version and the compiler version used to compile the class file.

Its easy to get the details of the JRE version using System.getProperties(). A more difficult task was to find out the version of the class file. I could not find any API which did it :(. But I did find out that these details were available in the class file, so I wrote a small code to determine if the class will run on the current version of JRE.
import java.io.DataInputStream;
import java.io.FileInputStream;

public class ClassRuntimeVersion {
public static void main(String[] args) throws Exception {

FileInputStream fis = null;
DataInputStream dis = null;

try {
if (args.length != 1) {
throw new Exception("specify the class file");
}

fis = new FileInputStream(args[0]);
dis = new DataInputStream(fis);

if (dis.readInt() != 0xCAFEBABE) {
throw new Exception("not a class file");
}

short minorVersion = dis.readShort();
short majorVersion = dis.readShort();

System.out.println("Java Class version info");
System.out.println("1.6 50");
System.out.println("1.5 49");
System.out.println("1.4 48");
System.out.println("1.3 47");
System.out.println("-------------------------");

float classVersion = Float.parseFloat(majorVersion + "."
+ minorVersion);
System.out.println("Class file compiled version : " + classVersion);

float jreJavaVersion = Float.parseFloat(System
.getProperty("java.class.version"));

System.out.println("JRE version : " + jreJavaVersion);
if (jreJavaVersion < classVersion) {
System.err.println("You r dead dude, versions did not match");
}
} finally {
if (fis != null) {
fis.close();
}
if (dis != null) {
dis.close();
}
}
}
}

Tuesday, May 29, 2007

Sampling Java SE 6

A lot of new features and API enhancements have been introduced in Java 6 (Mustang). Some of them are discussed briefly.

Compiler API

The new Java Compiler API allows invoking a compiler, gives access to diagnostics, and control over how files are read through a file manager. The file manager allows applications such as IDEs and JSP servers to keep all files in memory, which significantly speeds up compilation. Sun's open source Java EE implementation, GlassFish claims to have already benefited from this API.

//get the java compiler reference
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

//compile the Java class
int compilationResult = compiler.run(
null,null,null, "C:\\Person.java");

The code snippet shows how to compile a Java file using the Compiler API.

Web Service

The new web services stack provides support for writing XML web service applications. The java classes can be exposed as a .NET interoperable web service with a simple annotation. Java SE 6 adds new parsing and XML to Java object-mapping APIs, previously only available in Java EE platform implementations or the Java Web Services Pack.

To create a web service on Mustang create a java class, annotate it as shown below.

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public class Hello {
public String echo() {
return "Hello THBS";
}
}


To deploy the web service we just need to write the main method.

public static void main (String [] args) throws Exception {
Hello server = new Hello();
Endpoint.publish("http://localhost:9090/Hello", server);
}


The deployment can be verified by displaying the wsdl file on the browser
http://localhost:9090/Hello?wsdl. This feature is intended to be used for testing only.

Scripting for the Java Platform

Java SE 6 provides support for scripting, which enables the developers to integrate Java technology and scripting languages by defining a standard framework and interface to do the following:
• Access and control Java based objects from a scripting environment
• Create web content with scripting languages
• Embed scripting environments within Java technology-based applications

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.

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
jsEngine.eval("function helloWorld(){"
+ " println('Hello, world!'); "
+ " return 's';" + "}");

Invocable invocableEngine = (Invocable) jsEngine;
invocableEngine.invokeFunction("helloWorld", (Object[]) null);

The example shows how to invoke a JavaScript function using java.

See: Carpe diem: Mustang released

Database

The Java SE 6 development kit co-bundles the all-Java JDBC database, Java DB based on Apache Derby. Out of the box developers have a database that can be used that implements the latest version of JDBC and is embeddable within desktop Java applications. Java DB has a small memory footprint and is fully transactional.

Also provided is JDBC 4.0, a well-used API with many important improvements, such as special support for XML as an SQL datatype and better integration of Binary Large OBjects (BLOBs) and Character Large OBjects (CLOBs) into the APIs.

Desktop Development

Desktop application development just became simpler with Java 6. It provides better platform look-and-feel in Swing technology, LCD text rendering, and snappier GUI performance overall. Java applications can integrate better with the native platform with things like new access to the platform's System Tray and Start menu. At long last, Java SE 6 unifies the Java Plug-in technology and Java WebStart engines, just makes sense. Installation of the Java WebStart application got a much needed makeover.

A new class added to the Java platform is java.awt.Desktop. It allows Java applications to launch associated applications registered on the native desktop to handle a java.net.URI or a file.


Desktop d = Desktop.getDesktop();
//opens the application associated with the txt file in your OS
d.browse(new URI("c:/text_file.txt"));


Similar enhancements have been made to make the development of a java desktop application simpler.

Class file structure update:

The class file structure in Java SE 6 has been modified to provide a much faster and simpler class verification process. The idea is to split the old verification process into two phases: type inferencing (compile time) and type checking (runtime). The new verifier (called the type-checking verifier) no longer needs to infer types because it uses type information embedded in the Java class file to check byte code type consistency. Removing the type inferencing process from the verifier significantly reduces the complexity of verifier code and improves verification performance. This provides performance improvements in byte code verification and thus class loading and start up time.