Sunday, December 20, 2009

Real Time Web Application Development Challenges and HTML 5


In the traditional web architecture the reliable message flow between the server and the browser is a problem , as the server is not only forwarding the message but also most of the other work like translating the messages. This might result in Server becoming non scalable.

There were many attempts to simulate two way communication initiated by the server towards the client. One of the most notable approach is Comet.

Comet uses a technique referred as hanging GET or pending POST. In this the completion of an HTTP response is delayed until the server has something to send. This is generally implemented in JavaScript.

But there are some problems with this approach -
-Resource consumption is high as many connections are opened and closed.
-Setup and teardown of connections will consume more resources if secure connections are used.

HTML 5 may be the answer to these issues.

This provides many enhancements to the browsers and will redefine how internet communicates. The communication section of HTML 5 specification defines WebSockets and ServerSentEvents. These features will enable two way communication a reality for browsers. This will change the way in which real time web applications are created.

The main features are

  1. Web Sockets : Usually most of what is transmitted in web will be protocol information and padding. Web Sockets establishes a true two-way connection between server and the browser. This is essentially a pure TCP socket through which any application data can flow in either direction. This is more efficient than traditional HTTP requests as the non payload information is not required.
  2. Server sent Events : Two-way real time communication pattern common in web today is not taken into account in traditional HTTP. Through Sever Sent Events, a server can initiate the transmission of data. This is a standard describing how servers can initiate transmission of data to client once the initial connection with client is established.
  3. Cross Document Messaging : This provides a system in which different documents are allowed to securely communicate across different origins. This will allow an application to communicate with server over many different channels.
  4. Cross Origin resource Sharing : This will allow browsers to do site aggregation. Result may be better performance.







Monday, December 14, 2009

Java EE 6 Features

Lets look at the new sexy Java EE6 features

EJB Lite

EJB Lite is coming from the fact that- most of the ejb applications simply use features like persistence management, declarative transaction, stateless session beans etc.

EJB Lite will allow simple , lightweight implementations. This will also reduce the learning curve required (It might be just learning a handful of annotations). Very soon there may be Java EE application servers which implement EJB Lite instead of the complete Ejb3.1 spec.

Some of the features in the EJB Lite are
  1. Stateless, State full, Singleton session beans
  2. Interceptors
  3. Declarative Security
  4. Declarative Transactions etc
EJB Lite does not have the following features
  1. Message driven beans
  2. Remote interfaces
  3. Asynchronous invocation
  4. Corba interoperability etc.

Managed Beans 1.0

This is simply a POJO which is treated as a managed component by the container.
It can make use of some of the predefined Java EE features like lifecycle management and injection.

  1. @Resource
  2. @PostConstruct
  3. @PreDestroy etc

More Later...

Sunday, December 6, 2009

Project COIN

Project coin is aiming to find out the small language changes that should be added to the JDK.
Around 70 proposals were submitted in the period of Feb-27, 2009 to Mar-30, 2009 and discussed in coin developer forum.

Out of these proposals 5 or so are selected for including in Jdk7.

Some of the accepted proposals are -

1. Using Strings in switch
- Ability to switch on string values

2. Automatic resource management
- Having try like statement to declare one or more Resources. Scope of the resource is limited by that of the statement. When the statement completes normally or abruptly , all the resources are closed automatically.

3. Improved Type Inference for Generic Instance Creation
- When the full parameterized type is obvious from the context, then the parameterized type of the constructor could be replaced with empty set of type parameters.

4. Simplified Varargs method invocation.
- Reduces the total number of warnings reported to and suppressed by programmers.

5. Language support for JSR 292

Some of the proposals which are considered but not accepted are



This project is sponsored by The Compiler Group


Wednesday, December 2, 2009

Project Lombok


How much boilerplate code we write in our Java classes? Most of the time it will be minimum 100 lines. Even if we have a simple pojo - we have to write all the getters and setters, toString, equals, hashcode method etc.
Finally with all these code it will be easy to lose any bug which is hidden in the code.

Project Lombok is the answer to this problem (if you think this is a problem :) )

Instead of writing all these boilerplate code we can just give the annotation @Data.
Lombok is completely integrated with Eclipse , so all these generated methods will be visible in the outline view.

To make Lombok work with Javac, just add lombok.jar to the classpath.
Other annotation provided by Lombok is @Getter and @Setter.

Another interesting annotation is @Cleanup - this will help by automatically generate try finally blocks to call close on resource objects.

The full list can be found here - Project Lombok Overview


Project Jigsaw

Project Jigsaw is focused on the goal of modularizing JDK. Such a thing will allow applications to be installed with only the required components of JDK.

In the upcoming Jdk7 SUN's primary goal is to modularize jdk.




Wednesday, November 4, 2009

Read data from web page

Let us look at sample code for reading data from a given url

//
// Create an url object
URL url = new URL("http://www.someUrl.com");
//
// Open connection to the url
URLConnection conn= url.openConnection();
//
// Open input stream to read
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
//
// read the content
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
//
// Do something with inputLine .
}




Wednesday, September 30, 2009

Thursday, July 9, 2009

Using Dynamic model in Hibernate

When using Hibernate we are not forced to have POJOs alawsys for representing persistent entities. Hibernate also supports Dynamic models like Maps and DOM4J trees.

In plain english what this means is - we need to have only a mapping file (.hbm.xml) and no pojo class is required. However be careful when using this feature , as it may undergo change in the future releases.

Here we will see how to use the Hashmap for dynamic model.

Our table is
TEST_EMPLOYEE
+---------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| id | varchar(255) | NO | PRI | | |
| name | varchar(255) | YES | | NULL | |
| emailId | varchar(255) | YES | | NULL | |
+---------+--------------+------+-----+---------+-------+

Lets have a look at the curresponding mapping file -


<hibernate-mapping>
<class entity-name="com.check.Employee" table="TEST_EMPLOYEE" polymorphism="implicit" lazy="false">

<id name="id" type="string">
<column name="id" null="true">
</column></id>

<property name="name" column="name" type="string">
<property name="emailId" column="emailId" type="string">

</property></property></class>
</hibernate-mapping>

Check the use of "entity-name", this is required for dynamic model. We need not specify any class name here.

Sample code for CRUD operations.
Here HibernateHandler is a utility class used for managing sessionFactory.











01 public void createEmp(String id) {

02 Map emp = new HashMap();

03 emp.put("id", id);

04 emp.put("name", "emp_" + id);

05 emp.put("emailId", "emailId_" + id);

06

07 Session sess = HibernateHandler.getSession();

08 HibernateHandler.beginTransaction();

09 sess.save("com.check.Employee", emp);

10 HibernateHandler.commitTransaction();

11 HibernateHandler.closeSession();

12 }

13 public void readEmpUsingId(String id) {

14 Session sess = HibernateHandler.getSession();

15 Map empRead = (Map) sess.load("com.check.Employee", id);

16 System.out.println(empRead);

17 HibernateHandler.closeSession();

18 }

19 public void readUsingQuery(String mailId) {

20 String hsql = "from com.check.Employee where emailId = :emailId";

21 Session sess = HibernateHandler.getSession();

22 HibernateHandler.printStats();

23 Query q = sess.createQuery(hsql);

24 q.setString("emailId", mailId);

25 List data = q.list();

26 Map emp = (Map) data.get(0);

27 System.out.println(emp);

28 HibernateHandler.closeSession();

29 HibernateHandler.printStats();

30 }

31 public void updateEmpSimpleId(String id) {

32 Session sess = HibernateHandler.getSession();

33 HibernateHandler.beginTransaction();

34 Map empRead = (Map) sess.load("com.check.Employee", id);

35 System.out.println(empRead);

36 empRead.put("emailId", empRead.get("emailId")+"_updated");

37 System.out.println(empRead);

38 HibernateHandler.commitTransaction();

39 HibernateHandler.closeSession();

40 }

41 public void readEmpUsingObject(String id) {

42 HashMap emp = new HashMap();

43 emp.put("id", id);

44 emp.put("name", "emp_" + id);

45

46 Session sess = HibernateHandler.getSession();

47 Map empRead = (Map) sess.load("com.check.EmployeeCompo", emp);

48 System.out.println(empRead);

49 HibernateHandler.closeSession();

50 }





Here "readEmpUsingObject" is used for reading object with composit id.
Curresponding mapping file will contain -

<composite-id >
<key-property name="id" type="string" column="id" />
<key-property name="name" type="string" column="name" />
</composite-id>

Tuesday, June 30, 2009

Apache Wicket - How to run and get response from JavaScript

If you dont know what is Wicket - you are realling missing something. It is a b'ful framework from Apache which will make our life very much easier when doing web application development.
You can read more about Apache Wicket here

Here let us check how to invoke Javascript from a Wicket component and how receive/handle response. Assume the requirement is having a webpage where we will load some control using Javascript(For example - Google Earth ;) ) , and once the javascript execution is completed the page should do something.

01 public class MyPage extends WebPage {
02 /**
03 * Def constructor.
04
05 */

06 public MyPage() {
07 //
08 // Create and add a panel.
09 final JSPanel panel = new JSPanel("jsPanel");
10 panel.setOutputMarkupId(true);
11 add(panel);
12 }

Here we are creating a webpage and adding a panel to that. The panel is the place where we will
display the GoogleEarth through loading JavaScript.

But before going to the panel let us check how to get a call back from the JavaScript.
For acheiving this we will add an AjaxBehavior to the panel

01 public MyPage() {
02 ...
03 //
04 // Add an Ajax behaviour, this will be called by the javaScript
05 // when the streaming is completed.

06
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
07 protected void respond(final AjaxRequestTarget target) {
08 //
09 // Read the parameters send by JavaScript
10 Map map = ((WebRequestCycle)RequestCycle.get()).getRequest().getParameterMap();
11 Set keys = map.keySet();
12 Iterator it = keys.iterator();
13 while(it.hasNext()) {
14 String key = (String) it.next();
15 String[] value = (String[]) map.get(key);
16 }
17 }
18 };
19 panel.add(behave);
20 }


Curresponding html files are simple enough.

Now lets look at the JSPanel. Here we need to call the javascrip onLoad of the page. This is acheived through RenderHead method.


01 public class JSPanel extends Panel implements IHeaderContributor {
02 /**
03 * Def constructor.
04
05 */

06 public GEPanel(String id) {
07 super(id);
08 }

09
public void renderHead(IHeaderResponse response) {
10 //
11 // Check the behavior to get the callback URL
12 List list = getBehaviors();
13 String url = "";
14 if (list != null && list.size() > 0) {
15 AbstractDefaultAjaxBehavior beh = (AbstractDefaultAjaxBehavior) list.get(0);
16 url = beh.getCallbackUrl().toString();
17 }
18 String methodCall = "Your JS Method call";
19 response.renderOnLoadJavascript(methodCall);
20 }
21 }


Lets look at the relevant javascript now

function init(urlVal) {
url = urlVal;
//
//Create an instance of GE.
google.earth.createInstance("map3d", initCallback, failureCallback);
}

function initCallback(object) {
//
// Show GE and move camera to decired location.
ge = object;
ge.getWindow().setVisibility(true);
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
...
ge.getView().setAbstractView(lookAt);
...
//
// Make a call to the wicket callback url from here
var arg = "&key=" + value;
var wcall = wicketAjaxGet(url + arg , function() { }, function() { });
}

That is it. Let me know if you need the complete sample code for this.

Java code displayed as html here is using a tool HTML4Java, you can check it here http://www.toolbuddy.org/html4java.htm








Saturday, June 20, 2009

Capturing Image From Google Earth


Please note that images from Google Earth may be copy right protected, so you should carefully check before using such images.

Easiest way is - if you have a stand alone Google Earth application, start it and move to the decired location. This can be done through opening a KML file. Then use a screen capture program to take the screen shot (Or just use PrintScrn button)

What if there is no stand alone application available? Google static maps comes to the rescue.
Just load the url in a browser it will load the curresponding image.

Let us see how to do this from Java .

Use a url string.

String url = "http://maps.google.com/staticmap?center=%LAT%,%LON%&zoom=%ZOOM%&size=512x512&maptype=satellite&key=%KEY%";
Replace the place holders
%LAT% - Latitude
%LON% - Longitude
%ZOOM% - Zoom level
%KEY% - Google map key

//
// Load the image from url.
url = new URL(uri);
BufferedImage bi = ImageIO.read(url);
ImageIO.write(bi,"PNG",new File("image.PNG"));









ServiceMix MessageExchange memory leak


Are you observing memory leak in JBI components deployed in ServiceMix? First place to check will be whether the message exchanges are closed properly.

In the InOut message exchanges, after receiving message from provider , consumer should set the status as DONE in the exchange and again send it to provider.

Note - just setting the status to DONE is not enough , it must be send back to provider, otherwise the message exchanges will not be properly closed and will result in a memory leak.

E.g.-
inOutexchange.setStatus(ExchangeStatus.DONE); context.getDeliveryChannel().send(inOutexchange);

Memory leak in Java application


What are the first steps to do when notice that the newly developed Java application is not running continuously? Most of the time it may be due to memory leak.

First thing to do is study the memory usage/ thread creation patterns of the application. Different profiler tools are available in market for this.

Two tools I commonly use are
1. JProfiler
2. YourKit

In JProfiler - if there are memory leaks , total memory of the objects (which are leaking) will be shown against the class which created the memory.
Sometimes this may be misleading as the object references may be held by someone else , and that class is the real reason for the leak.

In my experience , identifying those classes were bit easier in YourKit.



Taking ScreenShot (PrintScreen) in Java

It is pretty easy to take a screen shot from Java code

Try
Rectangle rect = new Rectangle(0, 0, 700, 500);
BufferedImage screencapture = new Robot()
.createScreenCapture(rect);

// Save as JPEG
File file = new File("FileName.Jpg");
ImageIO.write(screencapture, "jpg", file);


Interesting question is what will happen if this code is executed in an environment where display devices are not available? You will get an AWT exception indicating "headless environment".

Getting position of HTML component

What if we want to read position of a html control in Javascript?
Only time I tried this was to get a screenshot of a particular area in the page, I doubt whether there is any valid usecases.
Try using the below function in JS

function getPositionOfElement(elemID) {
var offsetTrail = document.getElementById(elemID);
var offsetLeft = 0;
var offsetTop = 0;
while (offsetTrail) {
offsetLeft += offsetTrail.offsetLeft;
offsetTop += offsetTrail.offsetTop;
offsetTrail = offsetTrail.offsetParent;
}
return { left: offsetLeft, top: offsetTop };
}
Possible usage
getPositionOfElementElement('div_id').left;
getElementPosition('div_id').left;
Dont forget to check the properties like
self.screen.height
self.screen.availHeight
self.screenTop