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.

Monday, May 21, 2007

Mustang :- The Desktop bonus

One of the problems with java over the years is the lack on Desktop support. Sun has taken a major step with the release of Java 6.These changes have brought in a whole new flavour to the java desktop applications.

Java 6 now has system tray support.Now icons in the system tray can be added with menus and event handlers.Some applications that run in the background (eg mail client) can be seen in the system tray. Notifiers can also be provided to sent notification messages. The code demonstrates the use of the new functionality.
package com.sash.java6;

import java.awt.*;
import java.awt.TrayIcon.MessageType;
import java.awt.event.*;
import java.io.File;
import java.net.URI;

public class SystemTrayTest {

public SystemTrayTest() throws Exception {

if (SystemTray.isSupported()) {

SystemTray tray = SystemTray.getSystemTray();
//image for tray icon
Image image = Toolkit
.getDefaultToolkit().getImage("any_image.gif");

ActionListener exitListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}};

//pop menu for the tray
PopupMenu popup = new PopupMenu();
MenuItem alertItem = new MenuItem("Message");
popup.add(alertItem);

MenuItem defaultItem = new MenuItem("Exit");
defaultItem.addActionListener(exitListener);
popup.add(defaultItem);

final TrayIcon trayIcon = new TrayIcon(image, "Tray Demo", popup);

alertItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayIcon.displayMessage(
"Finally",
"Desktop support for Java",
MessageType.INFO);
}
});

trayIcon.setImageAutoSize(true);
trayIcon.setToolTip("Tooltip test");
tray.add(trayIcon);
} else {
System.err.println(
"System tray is currently not supported.");
}
}

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

//the system tray icon test
new SystemTrayTest();
}
}


Other enhancements include, the introduction of the Desktop API. Using this API now its very easy to open the default email client etc. It also provides an API to open any given file with the default application associated in the OS.

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

This code opens the default program associated with the text files, on my windows system it opens the file in notepad.

API enhancements have been made to the getTotalSpace, getUsableSpace and getFreeSpace methods have been added. These are very useful enhancements made.

Very nicely done by the sun guys, finally adding some much needed support for the desktop applications.
:)

Friday, April 20, 2007

Source code generator

Recently I had to write some code in Delphi .NET . Instead of using 'getters' and 'setters' like in java using properties is preferred. But writing the properties by hand is very painful.. Imagine having to write all the getters and setters in java by hand and your IDE ( I preferably use Eclipse ) not generate it. So I decided to write a code generator.

The first decision I had to make was which language to use. I can code in Java, C# and Delphi. I did not find any feature present in any of the languages that would make them preferable for the job, so I used Java since I am much more comfortable using this language.

The I had to decide what would be the input and output.

Input would be like :-
 // Make these properties!!!!!
id : integer; // the id

//blah blah comment
id2 : integer;
// so whats up

line_code : string;
rate : integer;



Output would be like:-

   //Variables :::::::

_id : integer;
_id2 : integer;
_line_code : string;
_rate : integer;


//Properties :::::::
Property id : integer
read _id
write _id ;
Property id2 : integer
read _id2
write _id2 ;
Property line_code : string
read _line_code
write _line_code ;
Property rate : integer
read _rate
write _rate ;




I also decided the coolest way to get the input and write the output was the clipboard. So I had to just copy the text into the clipboard and execute the java program. This would write the output into the clipboard.

Now the implementation specific details begin.
The first thing I needed to do was to remove the comments. Also what was needed was to get two lists, one containing the variable names and the other containing the variable types.

And then output it in any way wanted... My complete code is given below..

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SashClipboard
{

public static final String NEWLINE = "\n";

public static String TAB = " ";

public static void main(String[] args) throws UnsupportedFlavorException,
IOException
{

//gets data from clipboard
String data = copyFromClipboard();

// System.out.println(data);

//get the diff lies
String[] lines = data.split(NEWLINE);

// System.out.println(Arrays.asList(lines));
//remove comments '//' and if two stmts exist on same line
ArrayList linesList = removeSingleLineCommentAndMultiStmt(lines);

// System.out.println(linesList);

ArrayList varNameList = new ArrayList();
ArrayList varTypeList = new ArrayList();

getVarAndType(linesList, varNameList, varTypeList);

String output = createOutput(varNameList, varTypeList);

System.out.println(output);

//copy data to clipboard
copyToClipboard(output);
}

private static void copyToClipboard(String output)
{
StringSelection ss = new StringSelection(output);
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(ss, null);
}

public static String copyFromClipboard() throws UnsupportedFlavorException,
IOException
{
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = cb.getContents(null);
Object transferData = contents.getTransferData(DataFlavor.stringFlavor);
String data = transferData.toString();
return data;
}

private static String createOutput(ArrayList varNameList,
ArrayList varTypeList)
{
StringBuilder output = new StringBuilder();

output.append("//Variables :::::::\n\n");
for (int i = 0; i < varNameList.size(); i++)
{
output.append(TAB + "_" + varNameList.get(i) + " : "
+ varTypeList.get(i) + ";" + NEWLINE);
}

output.append("\n\n//Properties :::::::\n");

for (int i = 0; i < varNameList.size(); i++)
{
output.append(TAB + "Property " + varNameList.get(i) + ":"
+ varTypeList.get(i) + NEWLINE + TAB + TAB + " read " + "_"
+ varNameList.get(i) + NEWLINE + TAB + TAB + " write "
+ "_" + varNameList.get(i) + ";" + NEWLINE);
}
return output.toString();
}

private static void getVarAndType(ArrayList linesList,
ArrayList varNameList, ArrayList varTypeList)
{
for (int i = 0; i < linesList.size(); i++)
{
String line = linesList.get(i);
String[] colonSeperated = line.split(":");
if (colonSeperated.length != 2)
{
System.out.println("Something wrong " + line);
continue;
}

String[] commaSeperated = colonSeperated[0].split(",");

for (String var : commaSeperated)
{
varNameList.add(var);
varTypeList.add(colonSeperated[1]);
}
}
}

/**
* Remove comments '//' and if two stmts exist on same line
* e.g a: integer; b:string;
*
* if input on a line is
* a:integer; b:integer; //to do something
*
* it will give two lines i.e
* a:integer;
* b:integer
*
* @param lines multi lines
* @return a list containg different lines
* and without single line comments
*/
private static ArrayList removeSingleLineCommentAndMultiStmt(
String[] lines)
{
ArrayList linesList = new ArrayList();
for (int i = 0; i < lines.length; i++)
{
String[] comment = lines[i].split("//");

String[] multiStmt = comment[0].split(";");
for (String str : multiStmt)
{
if (!str.trim().equals(""))
{
linesList.add(str.trim());
}
}
}
return linesList;
}
}


It was not just the fact that I code generate the properties and save time, I also loved writing this code..

I think the code is self explanatory. If any doubts please do post your doubts.

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.