Tuesday, March 27, 2007

Java accesibility hack

Invoking a private method/variable using reflection in java is very simple. In the example I invoke the private methodA of the class.

public class A
{
private void methodA()
{
System.out.println("methodA");
}
}
This is pretty simple. But can we achieve this by setting setAccessible(true) for the Method.

public class B
{
public static void main(String[] args) throws Exception
{
A a = new A();
Method method = A.class.getDeclaredMethod("methodA");
method.setAccessible(true);
method.invoke(a,new Object[]{});
}
}


And the result is that methodA is printed on the console.

Now can we achieve this without the use of reflection? Yes we can and thats the java hack. I'll
explain how...

First write the class A, but mark the methodA as public. Then create a class B as

public class B
{
public static void main(String[] args) throws Exception
{
A a = new A();
a.methodA();
}
}

Compile class A and class B.
javac A
javac B

Run class B.
java B

The output is methodA as expected.

But where is the hack?
Now it comes..

Change the class A and change methodA as private again. Compile class A again only.
javac A

Do not try to compile class B, it will result in an comilation error. Now run B
java B

The output is not an Runtime error, but is methodA.

You can decompile using any java decompiler and see that methodA is still private but still B can invoke it. The probable reason for this is that accessiblity is a compile time check not a runtime one. At runtime it cannot be determined whether it is invoked using this hack or reflection. I cannot think of any other reason this is not done.

Wednesday, March 14, 2007

The role of Representational State Transfer in Web Based computing

A brief introduction to Representational State Transfer (REST)

REpresentational State Transfer or REST is an architectural style consisting of the set of constraints applied to elements within the network architecture. By examining the impact of each constraint as it is added to the evolving style, the properties induced by the Web’s constraints were identified.

But what does Representational State Transfer mean?

Representation
Resources are first-class objects; “object” is a subtype of “resource”. Resources are retrieved not as character strings or Blobs but as complete representations
A web page is a representation of a resource.

State means application/session state; is maintained as part of the content transferred from client to server back to client, thus any server can potentially continue transaction from the point where it had left off.

Transfer of State
Connectors (client, server, cache, resolver, tunnel) are unrelated to sessions and is an abstract mechanism which mediates communication, coordination, or cooperation among components. State is maintained by being transferred from clients to servers and back to clients.

REST is centered around two design principles:

Resource as URLs. A resource is something like a “business entity” which we wish to expose as a part of an API. Each resource is represented as a unique URL.

Operations as HTTP method. REST leverages the existing HTTP methods, particularly GET, POST, PUT and DELETE.

REST provides a set of architectural constraints that, when applied as a whole, emphasizes scalability of component interactions, generality of interfaces, independent deployment of components, and intermediary components to reduce interaction latency, enforce security, and encapsulate legacy systems.

Role of REST in web based applications

REST's "client-stateless-server" constraint forbids session state on the server. Designing within this constraint promotes the system properties of visibility, reliability, and scalability. But the server-side Web applications wish to provide a great deal of personalization to a single user, so they must choose between two designs. The first is to send a massive amount of state information with each client request, so that each request is context-complete and the server can remain stateless. A second simpler solution favored by application developers and middleware vendors alike is to send a simple user identity token and associate this token with a "user session" object on the server side. The second design directly violates the client-stateless-server constraint. It certainly enables desirable user functionality (especially personalization), but it places tremendous strain on the architecture.

The REST constraints provide scalability; say in a clustered environment if the state of client is maintained at the server side then the state has to be replicated across the servers which will be a huge performance overhead.

An AJAX application does not require full page refresh. The fact that Ajax lets us interact with a server without a full refresh puts the option of a stateful client back on the table. This has profound implications for the architectural possibilities for dynamic immersive Web applications: Because application resource and data resource binding is shifted to the client side, these applications can enjoy the best of both worlds the dynamic, personalized user experience we expect of immersive Web applications and the simple, scalable architecture we expect from RESTful applications.

Because the Ajax application engine is just a file, it's also proxyable. On a large corporate intranet, only a single employee might ever download a particular version of the application's Ajax engine, and everyone else just picks up a cached copy from the intranet gateway. So with regard to application resources, a well-designed Ajax application engine aligns with REST principles and provides significant scalability advantages versus server-side Web applications.

RESTful Web Services

The problem of interoperability is very fundamental and deals with what we call the “accidental architecture” where an organization consists of several different technologies and has to make them interoperable. The simpler the solution less will be the overhead in making such systems interoperable. The fundamental problem the web services world solves is interoperability. The question is whether to use SOAP based Web Services or REST web services.

Despite the lack of vendor support, Representational State Transfer (REST) web services have been very successful. For example, Amazon's web services have both SOAP and REST interfaces, and 85% of the usage is on the REST interface. Compared with other styles of web services, REST is easy to implement and maintain.

The SOAP based web services are standardized and standards have been published for the SOAP based web services. They can be used over several transports layer protocols like HTTP, JMS and FTP. REST makes the web service more WEB based. It uses only the HTTP protocol and thus can’t be used with JMS or FTP.

HTTP is not a transport protocol. SOAP treats HTTP as a transport protocol like TCP. HTTP only exists to carry bits, namely SOAP messages, with or without a method name. HTTP is an application protocol; it doesn't send bits, it transfers representational state.

REST isn't the best solution for every Web service. Data that needs to be secure should not be sent as parameters in URIs. If large amounts of data are used in the URI it can become very difficult to maintain and in extreme cases it can even go out of bounds. In such cases SOAP is a preferable solution. But it's important to try REST first and resort to SOAP only when necessary. This helps keep application development simple and accessible.

Fortunately, the REST philosophy is catching on with developers of Web services. The latest version of the SOAP specification now allows certain types services to be exposed through URIs (although the response is still a SOAP message). Similarly, users of Microsoft .NET platform can publish services so that they use GET requests. All this signifies a shift in thinking about how best to interface Web services.

Developers need to understand that sending and receiving a SOAP message isn't always the best way for applications to communicate. Sometimes a simple REST interface and a plain text response does the trick—and saves time and resources in the process.

Should we use REST ?

Arguments against non-REST designs

They break Web architecture, particularly caching. They don't scale well. They have significantly higher coordination costs

Scaling

What kind of scaling is most important is application-specific. Not all apps are Hotmail, Google, or Amazon Integration between two corporate apps has different scaling and availability needs
The right approach to one isn't necessarily the right approach to the other

The REST argument

A service offered in a REST style will inherently be easier to consume than some complex API:
• Lower learning curve for the consumer
• Lower support overhead for the producer

What if REST is not enough?

What happens when you need application semantics that don't fit into the GET / PUT / POST / DELETE generic interfaces and representational state model?

Nearly all the applications can fit into the GET / PUT / POST / DELETE resources / representations model. These interfaces are sufficiently general. Other interfaces considered harmful because they increase the costs of consuming particular services.

Asynchronous operations

There is no complete solution for asynchronous operations available for REST.
Notifications can be sent back as POSTs (the client can implement a trivial HTTP server). Piggyback them on the responses to later requests.

Transactions

The client is ultimately responsible for maintaining the transactions. Other designs for REST aren't much better.

The beginning


The use of REST is on the rise. The ease of use and scalability of the REST based applications stand apart. REST is the beginning of the next generation of Web based computing.

Friday, March 2, 2007

Running a class not in the classpath

This piece of code displays the invocation of a class not in the classpath of the application. This can be used to write utilities.

Say I have a jar file present on my system in say a directory "c:/MyUtils" (I have used windows locations, no reason why this should not work on any other OS) named SystemUtils.jar which has a main class in a class com.sash.DoIt. This jar is not in my classpath and I need to execute it. The following piece of code executes the main method.
 File file = new File("c:\\MyUtils\\SystemUtils.jar");
ClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL()});
Class cls = cl.loadClass("com.sash.DoIt");
Method mainMethod = cls.getDeclaredMethod("main", new Class[]{String[].class});
mainMethod.invoke(null, new Object[]{null});

Very interesting stuff. Never used it but waiting for the first oppertunity to use this in one of my projects :).