Comparison of Amazon EC2 & Google App Engine GAE/J

After spending few weeks with some of the Cloud services and reading the comparisons between them, I felt tempted to jot down my own views about atleast two of them.

Firstly, hands down to Google for providing such a brilliant service for free. It gives developers great opportunity to try new things and bring it infront of the people without investing huge amount on that. It also helps Small Business Enterprises to not invest huge into infrastructure and develop application on such a robust platform which is highly scalable without you need to get into the network setup and infrastructure. Not to leave Amazon EC2 services which are a great advantage for people/enterprise who wants to launch a product without investing on the network infrastructure and still being scalable and add more systems when demand increases.

Now on the comparison side, in my view two services are totally different, they may give you the same advantage of you not investing huge into the infrastructure, but they both have their own usages.

Introduction: EC2 service give you access to the boxes in the cloud with the operating system and you do the whole setup required for your application, or you can use the AMI(Amazon Machine Image) and yes even in the AMI’s you can configure your own security if desired.  whereas on the same lines Google doesn’t do that instead you create the application and just ask the App Engine SDK(which also comes an Eclipse plugin) to deploy it, it will deploy the application to one or more of the Google Cloud infrastructure instances and you can access the same once you login into your App Engine url. So in a nutshell, you have full control over Amazon EC2 and you can scale any computer instance to n-instances, whereas App Engine abstracts the instances from the developer and uses SDK for an interface between the developer and the Systems.

Lockin: Here i would like to bring third player Salesforce.com into the picture and then compare all of them. Also as previously mentioned you have complete control over the Amazon EC2 system which might or might not be completely true incase of App Engine as appengine provides lot of services which uses its proprietary api which if used locks you into App Engine, but it has its own advantages which I will discuss later. Similarly Salesforce force.com is mostly locked in as you use its own api to develop and deploy the their cloud. Salesforce has its own custom language and its own SQL/ORM layer.

ThoughtClicks - Comparision of App Engine, EC2 & force.com

Cost Factor: This is one of the important factor need to be considered when deciding between these two choices. Google App Engine has a free quota which is sufficient for applications with around 1 million page views. You can also enable the billing account once you go beyond that point & billing account is also reasonable, Price is based on CPU/hr, Outgoing/Incoming bandwidth, store data & number of emails exchanged etc. Google App Engine Billing Quota Unit Cost. On the other hand Amazon EC2 Services comes with a cost which is again nominal but no free stuff instead pay as you go. You can look at the pricing plan for Amazon EC2 here. but on top of EC2, if you persist some data you need to pay have EBS volume and it again comes for  cost after 1GB and costs $0.10 per GB-month & $0.10 per 1 million I/O requests, which is again very reasonable.

Services Infrastructure: Here Google App Engine gets an edge as it provides lot of ready to use services which comes very handy when you want your application to be up & running quickly, This all doesn’t comes for free instead if you use any of these services they are totally  based on proprietary api which locks you in Google App Engine. Some of the commonly used services are as follows.
1) Memcache – Ready to use cache already available on App Engine Servers, you can use JSR 107 api to 
    add or remove objects from this cache, so this comes as a nice feature without lockin.
2) XMPP – Can be used to talk to any XMPP enable clients like jabber etc.(Proprietary API)
3) Task Queues – This can be used like jms queues to handle tasks without user keep waiting. (Proprietary
    API)
4) Mail – It is again one of the feature which can be used using Java Mail api
5) Cron jobs – You can also run cron jobs in your application(Proprietary API)
6) Authorization – App Engine also give you OAuth out of the box and it can be very easily implemented in
    your application.
As far as i know Amazon, on the other hand doesn’t provides any of its services readily on the system except the mail or maybe cron, but it doesn’t either limits you from creating any such service the way you want.

Reliability: As far as my knowledge both are very reliable options except last year in june when once Appengine was down for more then couple of hours. and both have

Datastore: Appengine at present heavily relies on Bigtable, for which developer needs to think from a totally different angle then how we all are use to using relational databases. It has a JPA & JDO api to access it but it doesn’t supports all the JPA & JDO feature specially the relations part of it. Google also have recently announced that they will soon be launching the App Engine for business with proper SQL Support but again as Amazon it comes at a cost. where as on Amazon EC2 it all boils down to you choice of SQL database you want to use. You can use Oracle, My sql etc which gives you quick and easy development of backend code.

One of my experience using Google App Engine is that it a great resource for a person to kickstart stuff but once product get matured you might want a little bit of more control then provided. Having used Google App Engine for quite some time now, one of the major drawbacks i felt with Google App Engine atleast on the free version is that it recycles the applications very aggressively. Incase your application has very less traffic then you application has very high chances of being brought down when not in use and restarted when the request comes in, this leads to slow response on the initial requests. Developers including me have already requested Google to find different solutions for this. Out of which one is “Pay to reserve a JVM” Please help us by starring this issue.

Also Please keep in mind that Google App Engine does not support complete Java stack instead it does support the complete JRE Class whitelist which enables you to play around with the following Java EE Technologies.

For any issues or support related to App Engine or EC2 you can contact us at: cloud@thoughtclicks.com

HTML 5 Notification Feature

HTML5 is going to be the De facto for the web application and sites like facebook, twitter & not to mentioned Google chrome extensions which is going to extensively use Notification to replace all tab alert based extensions with notification api from HTML 5.

The new Notification API allows websites to send notifications directly to your desktop which can be facebook chat alerts, email alerts with first few lines of email etc. The below post will explain you three different methods which can be used to achieve this functionality. in simple steps. You can try these methods in one html page on any html5 ready browser as Chrome/Safari etc.

First step will be to check if the notification support is there in the browser, which you can do with the following method.

if (window.webkitNotifications) {
  //Notifications are supported!
}else{
  //Notification is not supported.
}

Next step would be to check if user has granted you the permissions to receive notification from your website or your webapp. If you don't have the permissions yet you can request the permission and this whole permission request does makes sense as otherwise there will be popups all over. You can do this with the following code:

if (window.webkitNotifications.checkPermission() == 0) {
  //You have permissions 
}else{
     window.webkitNotifications.requestPermission();//requesting the permissions
}

Note: webkitNotifications is the present name of the method as it is a draft, once it goes live this method name will be changed to Notifications

Once the user has granted the permissions you can call window.webkitNotifications.createNotification method with the icon, notification title & notification content as follows.

window.webkitNotifications.createNotification('tclicks-icon.png', 'Notification Title', 'Notification content...');

That's all you need to do to get the notifications on desktop. Happy Notifying !

Icefaces - Developing user interfaces became so easy

I have blogged about icefaces in past and since then icefaces has changed a lot, with lot of new components added to the already rich ajax based library.

Being a server side developer the best thing i liked about icefaces is that it can create rich ajax enabled user interfaces without knowing a single line of java script. so icefaces is definitely a useful framework when you want to leverage your existing team of java developers to make a web interfaces.

The fact is you can achieve all this icefaces provides you with any other javascript framework but the time and resources utilized in that is much more and never forget the nightmare of debugging JavaScript at-least for the Java developers if not for the ui folks.

Some of the interesting things added in recent releases of Icefaces in 1.8.x and Icefaces 2.

1) Rounder Corners - If you have worked with user interface, I am sure you know about how to get the rounded corners either with the images or with jquery and all that. So icefaces does help you in that and does the whole stuff behind the scenes with one simple tag, which can be defined as follows, for which more details can be found at the following url - Icefaces rounded corners



2) New scopes introduced to the library which bridges the gap left in jsf2.

3) Expandable Table - Once of the good user interfaces features should be, it should show only that much data to the user which is required and should not display the whole dataset on the page as the page will look very cluttered and busy. Icefaces has given a component for rendering such useful layout with expandable table. You can have a look at the details of the same at the following url. Expandable Table

4) Rich Data-grid table - now has an inline editing enabled in it if required. Not sure how much work or java-script you need to write if you want to write this component yourself.

5) IcePush - Not to mention one of the biggest benefit which icefaces provide is AjaxPush which a strong framework supporting both synchronous and asynchronous types. IcePush can also be integrated with any other web frameworks if required.

6) Google Maps - In one of my previous projects, i also had a requirement where we had to show the map to the user for the location of offices. Icefaces google maps tag came in so handy. you can either pass the address as a string or pass longitude and latitude as follows.


Or


other properties you can pass with the map is zoom level, type of the map as satellite or hybrid etc. Also you can add any of the controls as follows.






Here is the brief comparison of icefaces with other ui framework in terms of AJAX Push, Icefaces Comparison with Echo 2, ZK etc

I myself also tried looking at GWT after such a buzz around it, but as a java developer who have never worked with Swing, i was not bought by the concept of coupling your ui pages so tightly with the java classes and defining labels and everything in the classes. JSF concept still goes far better then that.

Some of the other things in which icefaces gives you an edge is extending its component or even writing your own. For eg. In one of my previous projects we had the requirement in which we had to show the table to the user and once the user click on any column in the table the table should slide down and it should show the complete details of that column including the image from the details. Below is the brief code for the same which can help you in achieving this.

Writing a component can be done as follows.
Start with writing a component class by extending the UIInput or UIOuput in this case. Then override the following method in case you are writing for output. Also encode ever children in the loop as done below.
public void encodeBegin(FacesContext facesContext)
 throws IOException {
  ResponseWriter responseWriter = facesContext.getResponseWriter();
  DOMContext domContext = DOMContext.getDOMContext(facesContext, this);
  Element parentTd = (Element)domContext.getCursorParent();
  parentTd.setAttribute(HTML.STYLE_ELEM, "background-color:blue; background-repeat:repeat-x;border-bottom: medium none");
  Element tbody = (Element)domContext.getCursorParent().getParentNode().getParentNode();
  Element tr = (Element) domContext.createElement(HTML.TR_ELEM);
  tbody.appendChild(tr);
  String id = getClientId(facesContext);
  tr.setAttribute(HTML.ID_ATTR, id);
  Element td = domContext.createElement(HTML.TD_ELEM);
  tr.appendChild(td);
  td.setAttribute(HTML.BORDER_ATTR,"1px");
  td.setAttribute(HTML.COLSPAN_ATTR, "5");//TODO
  td.setAttribute(HTML.BGCOLOR_ATTR,"#ffffff");
  
  Node oldCursorParent = domContext.getCursorParent();
  domContext.setCursorParent(td);
  domContext.streamWrite(facesContext, this,
    domContext.getRootNode(), td);
  
  Iterator children = getChildren().iterator();
  while (children.hasNext()) {
   UIComponent nextChild = (UIComponent) children.next();
   if (nextChild.isRendered()) {
    DomBasicRenderer.encodeParentAndChildren(facesContext, nextChild);
   }
  }
 }
   

Once you have create the component class you need to define the component type & class in the faces-config and create a custom tag in custom-taglib if you are using facelets & you are ready to use the tags you created in your xhtml or jspx.

There are various other ways of writing a component which can be used also you can create a different renderer for different components.

Not to ignore icefaces can be very well used with iphone or other mobile devices which leaves you flexible enough to extend your application to mobile platform.

But what i am eagerly waiting for now is final release of Icefaces 2 which is presently in alpha. Icefaces 2 is drastically new framework with lot of enhanced ajax capability and the use of JSF 2.


Also very soon I will cover the integration of spring with icefaces.

LRU Cache implementation with LinkedHashMap

If you are reading this article then you might have reached here hunting for implementation of LRU Cache. Below is simple code which can help you in understanding the LRU Cache and its implementation.

import java.util.LinkedHashMap;
import java.util.Map.Entry;

/**
 * @author ThoughtClicks Inc
 *
 */
public class LRUCache extends LinkedHashMap {

 private static final long serialVersionUID = 1L;
 private final int capacity;
 private long accessCount = 0;
 private long hitCount = 0;

 public LRUCache(int capacity) {
  super(capacity + 1, 1.1f, true);
  this.capacity = capacity;
 }

 @Override
 public Object get(Object key) {
  accessCount++;
  if (super.containsKey(key)) {
   hitCount++;
  }
  Object value = super.get(key);
  return value;
 }

 @Override
 public boolean containsKey(Object key) {
  accessCount++;
  if (super.containsKey(key)) {
   hitCount++;
   return true;
  }else{
   return false;
  }
 }

 protected boolean removeEldestEntry(Entry eldest) {
  return size() > capacity;
 }

 public long getAccessCount() {
  return accessCount;
 }

 public long getHitCount() {
  return hitCount;
 }
}



To use the above cache you just need to call the constructor of the above LRUCache with the maximum size of your cache and then just set the value as you do in a hashmap.

Have fun !

Validation in JAXB 2 vs JAXB 1

The release of JAXB 2 brought lot of advantages to the developer like putting annotations on the objects etc, at the same time it has given a liberty to the user about how does he/she wants to handle the validation using the JAXP validation APIs.

Validation in JAXB1
If JAXB detects error or inconsistency in the data received and it is unable to recover it throws an UnmarshalException.

eg:

JAXBContext jc = JAXBContext.newInstance( "com.thoughtclicks" );
Umarshaller u = jc.createUnmarshaller();
u.setValidating(true);


Validation in JAXB2
Developer has the choice of what and how to handle the incosistency in error validation.

eg:

JAXBContext jc = JAXBContext.newInstance( "com.thoughtclicks" );
Umarshaller u = jc.createUnmarshaller();
SchemaFactory factory = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File("order.xsd"));
u.setSchema(schema);


Either you can use the default validation handler like

u.setEventHandler(new DefaultValidationEventHandler())


or you can have your own custom validation handler and set that to the umarshaller


public class CustomValidationEventHandler implements ValidationEventHandler{
public boolean handleEvent(ValidationEvent ve) {
if (ve.getSeverity()==ve.FATAL_ERROR ||
ve .getSeverity()==ve.ERROR){
ValidationEventLocator locator = ve.getLocator();
//log the message
System.out.println("Message is " + ve.getMessage());
//log the error reference
System.out.println("Column is " +
locator.getColumnNumber() +
" at line number " + locator.getLineNumber());
}
return true;
}

}


You are all set to handle the validations.

Good luck !

OpenSymphony Quartz Scheduler in Spring

Spring offers a very seamless integration with Quartz to create some scheduled tasks. Below i will explain the steps in which you can do that.

To get started what you need is a spring.jar downloaded along with a download of Quartz jar files.

Spring simply gives you extension of all the core classes provided by Quartz which includes:
1. org.springframework.scheduling.quartz.JobDetailBean - which extends QuartzJobBean
2. org.springframework.scheduling.quartz.SimpleTriggerBean - which extends SimpleTrigger
3. org.springframework.scheduling.quartz.SchedulerFactoryBean - which implements the main scheduling functionality.

So by using these three classes you can write scheduled jobs very quickly. All you need to do is defined three beans in your spring - config file. The definition is as follows.

Declare the job:


<bean name="sendmailsjob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.thoughtclicks.SendEmailsJob" />
<property name="jobDataAsMap">
<map>
<entry key="to" value="rahul.juneja@thoughtclicks.com" />
</map>
</property>
</bean>


Now add the job class as follows.

public class SendEmailsJob extends QuartzJobBean {
@Override
protected void executeInternal (JobExecutionContext ctx) throws JobExecutionException {
String touser = (String) ctx.getJobDetail().getJobDataMap().get("to");
sendmail(to);//this will send the mail to the user defined in the to address.
}
}


You have a choice of fetching the properties from the context i have done in the previous code or you can also add the properties in the bean for the same and provide getter and setters and Spring will do the injection for you and provide the populated properties.

now you need to define the trigger using the job you created above.


<bean id="emailTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="sendmailsjob" />
<property name="startDelay" value="0" />
<property name="repeatInterval" value="10000" />
</bean>


Now finally you need to define the scheduler for scheduling this very trigger, which can be done as follows.


<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="emailTrigger" />
</list>
</property>
</bean>


After the steps defined above once you start the application including the spring config the job you just created is started automatically and will run in every 10 seconds as defined in the trigger with property "repeat interval"

You can also use your existing methods to be called by the scheduler rather then creating the whole new scheduler bean and the only change you need for that is creating the job as follows.


<bean name="sendmailsjob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="existingbeanallreadydefined" />
<property name="targetMethod" value="methodsendMail" />
</bean>


If you need any further code or tips. you can drop me an email at rahul.juneja@thoughtclicks.com

Rest and JSON in JQuery - Twitter Gadget

I am sure you guys must have seem lot of gadget floating around the web for twitter, yahoo, google and what not.

Did you ever thought that writing a small gadget is such a small and minutes job with jquery and the apis exposed by these social networking sites like facebook and twitter. I just tried hands on one of the those and it was quick to get this twitter gadget ready to be shared.

Simple JSON script like the one below can do the whole trick for you.


$(document).ready(function(){
var tweeturl = "http://twitter.com/status/user_timeline/
rahuljuneja.json?count=5&callback=?";
$.getJSON(tweeturl, function(data){
$.each(data, function(i, item) {
$('

').addClass(i%2 ? 'even' : 'odd')
.html(item.text)
.prependTo('#tweet');
});
});
});