<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>animesh kumar</title>
	<atom:link href="http://anismiles.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://anismiles.wordpress.com</link>
	<description>Running water never grows stale. Keep flowing!</description>
	<lastBuildDate>Sun, 27 May 2012 12:40:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='anismiles.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/136f6461102698029b64dc2ebc6a7db4?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>animesh kumar</title>
		<link>http://anismiles.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://anismiles.wordpress.com/osd.xml" title="animesh kumar" />
	<atom:link rel='hub' href='http://anismiles.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Securing, Versioning and Auditing REST (JAX-RS, Jersey) APIs</title>
		<link>http://anismiles.wordpress.com/2012/03/02/securing-versioning-and-auditing-rest-jax-rs-jersey-apis/</link>
		<comments>http://anismiles.wordpress.com/2012/03/02/securing-versioning-and-auditing-rest-jax-rs-jersey-apis/#comments</comments>
		<pubDate>Fri, 02 Mar 2012 13:49:33 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JAX-RS]]></category>
		<category><![CDATA[Jersey]]></category>
		<category><![CDATA[jsr250]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1903</guid>
		<description><![CDATA[Now that your functionalities are working, you want a layer of security to authenticate/authorize your APIs. Though this is a bad approach towards security, but – I know – real life is a tough game and nothing happens they way they should be&#8230; and so be it. Additionally, you might want to control API versions [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1903&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1903" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2012%2F03%2F02%2Fsecuring-versioning-and-auditing-rest-jax-rs-jersey-apis%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-uH%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2012%2F03%2F02%2Fsecuring-versioning-and-auditing-rest-jax-rs-jersey-apis%2F" height="61" width="51" /></a>
</div>
<p>Now that your functionalities are working, you want a layer of security to authenticate/authorize your APIs. Though this is a bad approach towards security, but – I know – real life is a tough game and nothing happens they way they should be&#8230; and so be it. Additionally, you might want to control API versions (i.e. expose newer APIs only to newer clients) and audit API usage. </p>
<p>Well, I am going to propose a <em>tangential</em> way to implement these concerns. You won&#8217;t need to touch any of your business logic as such. Only few annotations (custom and otherwise) would need to be applied. That way, you won&#8217;t feel bad about missing these things when you started the project and your concerns will be taken care of in the most un-obtrusive way possible. Wonderful&#8230; eh?</p>
<p>First, you will need to create some sort of <strong>sign-in</strong> API, which will accept username/password (or oAuth or whatever you fancy) and generate some sort of session information which you will store in some database (<a href="http://redis.io/" target="blank">Redis</a> maybe!) and share its ID, say <em>sessionId</em>, with client. Then, with every subsequent request, Client will attach this sessionId in the request header which server will pick and look up for associated session information (permission, roles etc.) and based upon that server will authenticate and authorize the request. </p>
<p>Here is your Session bean.<br />
<pre class="brush: java;">
package com.strumsoft.api;

import java.io.Serializable;
import java.util.Date;

/**
 * @author &quot;Animesh Kumar &lt;animesh@strumsoft.com&gt;&quot;
 *
 */
public class Session implements Serializable {
	// 
	private static final long serialVersionUID = -7483170872690892182L;
	
	private String sessionId;   // id
	private String userId;      // user
	private boolean active;     // session active?
	private boolean secure;     // session secure?

	private Date createTime;    // session create time
	private Date lastAccessedTime;  // session last use time

	// getters/setters here
}
</pre></p>
<p>And this is your User bean. This must implement <a href="http://docs.oracle.com/javase/6/docs/api/java/security/Principal.html" target="_blank">java.security.Principal</a>. </p>
<p><pre class="brush: java;">

package com.strumsoft.api;

import java.util.Set;

/**
 * @author &quot;Animesh Kumar &lt;animesh@strumsoft.com&gt;&quot;
 *
 */
public class User implements java.security.Principal {
	// Role
	public enum Role {
		Editor, Visitor, Contributor
	};

	private String userId;          // id
	private String name;            // name
	private String emailAddress;    // email
	private Set&lt;Role&gt; roles;        // roles

	@Override
	public String getName() {
		return null;
	}

	// getters/setters here
}
</pre></p>
<p>Now, you need to implement <a href="http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/core/SecurityContext.html" target="_blank">javax.ws.rs.core.SecurityContext</a>. This will be bound to incoming request and will decide whether to allow or deny it.  </p>
<p><pre class="brush: java;">
package com.strumsoft.api;

import java.security.Principal;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

/**
 * @author &quot;Animesh Kumar &lt;animesh@strumsoft.com&gt;&quot;
 *
 */
public class MySecurityContext implements javax.ws.rs.core.SecurityContext {

	private final User user;
	private final Session session;

	public MySecurityContext(Session session, User user) {
		this.session = session;
		this.user = user;
	}

	@Override
	public String getAuthenticationScheme() {
		return SecurityContext.BASIC_AUTH;
	}

	@Override
	public Principal getUserPrincipal() {
		return user;
	}

	@Override
	public boolean isSecure() {
		return (null != session) ? session.isSecure() : false;
	}

	@Override
	public boolean isUserInRole(String role) {

		if (null == session || !session.isActive()) {
			// Forbidden
			Response denied = Response.status(Response.Status.FORBIDDEN).entity(&quot;Permission Denied&quot;).build();
			throw new WebApplicationException(denied);
		}

		try {
			// this user has this role?
			return user.getRoles().contains(User.Role.valueOf(role));
		} catch (Exception e) {
		}
		
		return false;
	}
}
</pre></p>
<p>Then, you need a <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceFilter.html" target="_blank">ResourceFilter</a> which will intercept the request, look for sessionId in the header and generate and attach our SecurityContext implementation to it. Notice, how our implementation only gets applied on Request but not on Response. </p>
<p><pre class="brush: java;">
package com.strumsoft.api;

import javax.ws.rs.ext.Provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.flockthere.api.repository.SessionRepository;
import com.flockthere.api.repository.UserRepository;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;

/**
 * Filter all incoming requests, look for possible session information and use that
 * to create and load a SecurityContext to request. 
 * @author &quot;Animesh Kumar &lt;animesh@strumsoft.com&gt;&quot;
 * 
 */
@Component   // let spring manage the lifecycle
@Provider    // register as jersey's provider
public class SecurityContextFilter implements ResourceFilter, ContainerRequestFilter {

	@Autowired
	private SessionRepository sessionRepository;  // DAO to access Session

	@Autowired
	private UserRepository userRepository;  // DAO to access User

	
	@Override
	public ContainerRequest filter(ContainerRequest request) {
		// Get session id from request header
		final String sessionId = request.getHeaderValue(&quot;session-id&quot;);

		User user = null;
		Session session = null;

		if (sessionId != null &amp;&amp; sessionId.length() &gt; 0) {
			// Load session object from repository
			session = sessionRepository.findOne(sessionId);
			
			// Load associated user from session
			if (null != session) {
				user = userRepository.findOne(session.getUserId());
			}
		}

		// Set security context
		request.setSecurityContext(new MySecurityContext(session, user));
		return request;
	}

	@Override
	public ContainerRequestFilter getRequestFilter() {
		return this;
	}

	@Override
	public ContainerResponseFilter getResponseFilter() {
		return null;
	}
}
</pre></p>
<p>Okay, the hard part is over. All we need now is a way to fire our SecurityContextFilter. For this, we will create a <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceFilterFactory.html" target="_blank">ResourceFilterFactory</a>. During application startup, this factory will create a List of filters for all <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/model/AbstractMethod.html" target="_blank">AbstractMethod</a>s of each of our Resources. We are going to extend <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/container/filter/RolesAllowedResourceFilterFactory.html" target="_blank">RolesAllowedResourceFilterFactory</a> which will generate all Role based ResourceFilters for us. And then, we will add our SecurityContextFilter on the top of the list with VersionFilter and AuditFilter in the bottom. That way, SecurityContextFilter will executed first because you need to make auth decisions early. VersionFilter will be next. And Audit in the bottom. You want to audit when everything else has been done. No? </p>
<p><pre class="brush: java;">
package com.strumsoft.api;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.ext.Provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.flockthere.api.AllowAllVersions;
import com.flockthere.api.audit.Audit;
import com.flockthere.api.resource.interceptor.AuditingFilter;
import com.flockthere.api.resource.interceptor.SecurityContextFilter;
import com.flockthere.api.resource.interceptor.VersionFilter;
import com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory;
import com.sun.jersey.api.model.AbstractMethod;
import com.sun.jersey.spi.container.ResourceFilter;

/**
 * FilterFactory to create List of request/response filters to be applied on a particular
 * AbstractMethod of a resource.
 * 
 * @author &quot;Animesh Kumar &lt;animesh@strumsoft.com&gt;&quot;
 * 
 */
@Component // let spring manage the lifecycle
@Provider  // register as jersey's provider
public class ResourceFilterFactory extends RolesAllowedResourceFilterFactory {

	@Autowired
	private SecurityContextFilter securityContextFilter;

	// Similar to SecurityContextFilter to check incoming requests for API Version information and
	// act accordingly
	@Autowired
	private VersionFilter versionFilter;

	// Similar to SecurityContextFilter to audit incoming requests
	@Autowired
	private AuditingFilter auditingFilter;

	@Override
	public List&lt;ResourceFilter&gt; create(AbstractMethod am) {
		// get filters from RolesAllowedResourceFilterFactory Factory!
		List&lt;ResourceFilter&gt; rolesFilters = super.create(am);
		if (null == rolesFilters) {
			rolesFilters = new ArrayList&lt;ResourceFilter&gt;();
		}

		// Convert into mutable List, so as to add more filters that we need
		// (RolesAllowedResourceFilterFactory generates immutable list of filters)
		List&lt;ResourceFilter&gt; filters = new ArrayList&lt;ResourceFilter&gt;(rolesFilters);

		// Load SecurityContext first (this will load security context onto request)
		filters.add(0, securityContextFilter);

		// Version Control?
		filters.add(versionFilter);

		// If this abstract method is annotated with @Audit, we will apply AuditFilter to audit
		// this request.
		if (am.isAnnotationPresent(Audit.class)) {
			filters.add(auditingFilter);
		}

		return filters;
	}
}
</pre></p>
<p>VersionFilter will help control Client&#8217;s access to API methods based upon client&#8217;s version. Implementation would be similar to SecurityContextFilter. You will need to annotate API methods with @Version(&#8220;&gt;1.3&#8243;). VersionFilter will read this value (&#8220;&gt;1.3&#8243;), check request headers for API-Version keys and then decide whether to allow or reject the request. Similarly, AuditFilter will log all such annotated (@Audit(&#8220;audit-note&#8221;)) API methods. I will not discuss their actual implementations. You can very easily write them based upon your requirement or can remove them altogether if not needed. </p>
<p>Here is how these annotations will look like. </p>
<p><pre class="brush: java;">
// @Version
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface Version {
	String value();
}

// @Audit
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface Audit {
	String value();
}
</pre></p>
<p>And now, you will need to update you web.xml to include ResourceFilterFactory </p>
<p><pre class="brush: xml;">
...
	&lt;servlet&gt;
		&lt;servlet-name&gt;REST&lt;/servlet-name&gt;
		&lt;servlet-class&gt;
			com.sun.jersey.spi.spring.container.servlet.SpringServlet
		&lt;/servlet-class&gt;
		...		
		&lt;!-- Our resource filter for tangential concerns (security, logging, version etc.) --&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;com.sun.jersey.spi.container.ResourceFilters&lt;/param-name&gt;
			&lt;param-value&gt;com.strumsoft.api.ResourceFilterFactory&lt;/param-value&gt;
		&lt;/init-param&gt;
		...		
	&lt;/servlet&gt;
...
</pre></p>
<p>That&#8217;s it. All configuration is done. Now, you just need to annotate you Resources. Let&#8217;s see how. </p>
<p>Say, you have a BookResource which exposes APIs to create/edit/list books. And you want<br />
1. &#8220;Editor/Contributor&#8221; to be able to create a book, (<strong>@RolesAllowed({ &#8220;Editor&#8221;, &#8220;Contributor&#8221; })</strong>)<br />
2. Only &#8220;Editor&#8221; to be able to edit a book, (<strong>@RolesAllowed({ &#8220;Editor&#8221; })</strong>)<br />
3. While, anyone can see all the books. (<strong>@PermitAll</strong>)</p>
<p>Also, let&#8217;s say editing a book was released in API 1.3, so any client still using older APIs should not be able to update (<strong>@Version(&#8220;&gt;1.3&#8243;)</strong>) an existing book. (Assuming you implemented VersionFilter properly)</p>
<p>Additionally, create or edit book should be audited with respective notes &#8220;create-book&#8221; and &#8220;edit-book&#8221; given your AuditFilter is in place. </p>
<p><pre class="brush: java;">
package com.strumsoft.api;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;

import com.flockthere.api.audit.Audit;

/**
 * Book Resource
 * 
 * @Path(&quot;/book/&quot;)
 * @author &quot;Animesh Kumar &lt;animesh@strumsoft.com&gt;&quot;
 * 
 */
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public interface BookResource {

	// Only Editor and Contributor can create a book entry
	@javax.annotation.security.RolesAllowed({ &quot;Editor&quot;, &quot;Contributor&quot; })
	@Audit(&quot;create-book&quot;)  // Audit
	@POST
	public Book createBook(@Context SecurityContext sc, @FormParam(&quot;title&quot;) String title,
			@FormParam(&quot;author&quot;) String author, @FormParam(&quot;publisher&quot;) String publisher,
			@FormParam(&quot;isbn&quot;) String isbn, @FormParam(&quot;edition&quot;) String edition);

	// Only Editor can edit an existing book entry
	@javax.annotation.security.RolesAllowed({ &quot;Editor&quot; })
	@Audit(&quot;edit-book&quot;)   // Audit
	@Version(&quot;&gt;1.3&quot;)  // Available only on API version 1.3 onwards
	@PUT
	public Book editBook(@Context SecurityContext sc, @FormParam(&quot;title&quot;) String title,
			@FormParam(&quot;author&quot;) String author, @FormParam(&quot;publisher&quot;) String publisher,
			@FormParam(&quot;isbn&quot;) String isbn, @FormParam(&quot;edition&quot;) String edition);
	
	// Anyone can see these books
	@javax.annotation.security.PermitAll
	@GET
	public Book listBooks();

}
</pre></p>
<p>And at last, you will need to add <a href="http://jcp.org/en/jsr/detail?id=250" target="_blank">jsr250-api</a> to your project dependencies which defines javax.annotation.security.* annotations. </p>
<p><pre class="brush: xml;">
	&lt;!-- securty tags: javax.annotation.security.* (@RolesAllowed, @PermitAll, @DenyAll etc.) --&gt;
	&lt;dependency&gt;
		&lt;groupId&gt;javax.annotation&lt;/groupId&gt;
		&lt;artifactId&gt;jsr250-api&lt;/artifactId&gt;
		&lt;version&gt;1.0&lt;/version&gt;
	&lt;/dependency&gt;
</pre></p>
<p>Chill. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/java/'>Java</a>, <a href='http://anismiles.wordpress.com/tag/jax-rs/'>JAX-RS</a>, <a href='http://anismiles.wordpress.com/tag/jersey/'>Jersey</a>, <a href='http://anismiles.wordpress.com/tag/jsr250/'>jsr250</a>, <a href='http://anismiles.wordpress.com/tag/rest/'>REST</a>, <a href='http://anismiles.wordpress.com/tag/security/'>Security</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1903/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1903/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1903/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1903/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1903/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1903/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1903/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1903/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1903&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2012/03/02/securing-versioning-and-auditing-rest-jax-rs-jersey-apis/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>AspectJ + Spring for method click records</title>
		<link>http://anismiles.wordpress.com/2011/09/29/aspectj-spring-for-method-click-records/</link>
		<comments>http://anismiles.wordpress.com/2011/09/29/aspectj-spring-for-method-click-records/#comments</comments>
		<pubDate>Thu, 29 Sep 2011 11:50:26 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Aspect Oriented Programming]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Java Annotation]]></category>
		<category><![CDATA[Method Interceptor]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1868</guid>
		<description><![CDATA[In one of the projects we recently did, we had a Spring and Jersey based JSON/XML REST API server. Clients would connect to this API server and access various resources. Now, for one of the reporting scenario, we needed to log who accessed which API method and when. This appeared to be very simple initially. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1868&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1868" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F09%2F29%2Faspectj-spring-for-method-click-records%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-u8%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F09%2F29%2Faspectj-spring-for-method-click-records%2F" height="61" width="51" /></a>
</div>
<p>In one of the projects we recently did, we had a <a href="http://www.springsource.org/documentation" target="_blank">Spring</a> and <a href="http://jersey.java.net/" target="_blank">Jersey</a> based JSON/XML <a href="http://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank">REST</a> API server. Clients would connect to this API server and access various resources. Now, for one of the reporting scenario, we needed to log <strong>who</strong> accessed <strong>which</strong> API method and <strong>when</strong>. This appeared to be very simple initially. I decided to intercept every http call, and log that.</p>
<p>However, when I dug deep, I found that one method might call another method internally, depending upon the situation. For example, say <strong>User-A</strong> is trying to login from <strong>Device-1</strong>, and he is already logged on to some other device, say <strong>Device-2</strong>. So, <strong>LoginResource</strong> would make a call to <strong>LogoutResouce</strong> to invalidate User-A&#8217;s session with <strong>Device-2</strong>. We couldn&#8217;t track this just by intercepting http calls. We needed to adopt some other strategy. Initially, I thought of logging each API method with brute force&#8230; but that was too inelegant to actually code. Then I looked at <a href="http://www.eclipse.org/aspectj/" target="_blank">AspectJ</a>, and I was enlightened.</p>
<p>First, Added AspectJ dependencies to pom.<br />
<pre class="brush: xml;">
...
	&lt;dependencies&gt;
		&lt;!-- aspectj --&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.aspectj&lt;/groupId&gt;
			&lt;artifactId&gt;aspectjtools&lt;/artifactId&gt;
			&lt;version&gt;1.6.8&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.aspectj&lt;/groupId&gt;
			&lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;
			&lt;version&gt;1.6.8&lt;/version&gt;
		&lt;/dependency&gt;
		...
	&lt;dependencies&gt;
...
</pre></p>
<p>And updated spring config file.<br />
<pre class="brush: xml;">
&lt;beans ... xsi:schemaLocation=&quot;... http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd ...&quot;
 xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot; ... &gt;
...
&lt;aop:aspectj-autoproxy proxy-target-class=&quot;true&quot; /&gt;
...
</pre></p>
<p>Then created a <a href="http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm" target="_blank">Java Method Annotation</a> class.<br />
<pre class="brush: java;">
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface RecordClick {
	String action();  // Name of the action
	String comment() default &quot;&quot;; // Comment, if any?
}
</pre></p>
<p>Every method we want to track, I just need to annotate it with @RecordClick. Like this: </p>
<p><pre class="brush: java;">

// API to signup
@RecordClick(action = &quot;signup&quot;, comment = &quot;User initiated signup&quot;)
public User explicitSignup(String firstName, String lastName, String email, String phone, String password, Role role) throws ValidationException {
}

// API to signup
@RecordClick(action = &quot;signup&quot;, comment = &quot;System initiated signup&quot;)
public User implicitSignup(String email, String phone) throws ValidationException {
}

// API to signin
@RecordClick(action = &quot;signin&quot;, comment = &quot;User initiated signin&quot;)
public Session explicitSignin(String username, String password) {
}

</pre></p>
<p>Okay, so now I have everything in place. I just need to create an Aspect to advice pertinent methods. So, I will create an <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-ataspectj" target="_blank">Aspect</a> class. This will intercept all public methods that are annotated with @RecordClick annotation, and create a click record for this call.<br />
<pre class="brush: java;">
@Aspect
@Component
public class RecordClickMethodInterceptor {

	private static final Logger log = LoggerFactory.getLogger(RecordClickMethodInterceptor.class);

	// This will create and save an individual click
	@Autowired
	private ClickResource clickResource;

	/**
	 * Intercepts all public methods annotated with @RecordClick
	 *
	 * @param pjp
	 * @param recordClick
	 * @return
	 * @throws Throwable
	 */
	@Around(&quot;execution(public * *(..)) &amp;&amp; @annotation(recordClick)&quot;)
	public Object doClickRecord(ProceedingJoinPoint pjp, RecordClick recordClick) throws Throwable {
		log.info(&quot;Intercepted method={} with action={}&quot;, pjp.getSignature().getName(), recordClick.action());

		List&lt;String&gt; paramNames = new ArrayList&lt;String&gt;();
		try {
			MethodSignature signature = (MethodSignature) pjp.getSignature();
			// Fetch method argument names.
			// Note: to enable this, you must compile the code in debug mode.
			paramNames = Arrays.asList(signature.getParameterNames());
		} catch (Exception e) {
			log.error(&quot;Can't record clicks. You must compile the code with debug=true&quot;);
			// Proceed with method call
			return pjp.proceed();
		}

		log.info(&quot;paramNames={}&quot;, paramNames);

		String user = &quot;anonymous&quot;;
		Map&lt;String, Object&gt; methodArguments = new HashMap&lt;String, Object&gt;();

		int index = 0;
		// Iterate through method arguments
		for (Object arg : pjp.getArgs()) {
			// name of this argument
			String name = paramNames.get(index++);
			log.info(&quot;{} ==&gt; {}&quot;, name, arg);

			// if arg is null, skip
			if (null == arg) {
				continue;
			}

			// Fetch user from argument '@Context SecurityContext'
			if (arg instanceof SecurityContext) {
				Principal principal = ((SecurityContext) arg).getUserPrincipal();
				if (null != principal) {
					log.info(&quot;Found user={}&quot;, principal.getName());
					user = principal.getName();
				}
			}
			// Fetch user from argument 'Principal principal;
			else if (arg instanceof Principal) {
				Principal principal = (Principal) arg;
				log.info(&quot;Found user={}&quot;, principal.getName());
				user = principal.getName();
			}
			// save to methodArguments
			else {
				methodArguments.put(name, arg.toString());
			}
		}

		// execute the method
		Object returned = pjp.proceed();

		// Process the returned value

		// Record this click
		String action = recordClick.action();
		String comment = recordClick.comment();
		clickResource.createClick(user, action, methodArguments, comment);
		return returned;
	}
}
</pre></p>
<p>I also need to compile the code in debug mode, unless I do this, I will not be able to fetch method argument names which I desperately need in order to make any sense of these records. So, I needed to update <a href="http://maven.apache.org/plugins/maven-compiler-plugin/" target="_blank">maven-compiler-plugin</a> to enable debug mode.<br />
<pre class="brush: xml;">
&lt;plugin&gt;
	&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
	&lt;configuration&gt;
		&lt;source&gt;${java-version}&lt;/source&gt;
		&lt;target&gt;${java-version}&lt;/target&gt;
		&lt;!-- compile with debug so as to get param names in aspects --&gt;
		&lt;debug&gt;true&lt;/debug&gt;
		&lt;debuglevel&gt;lines,vars,source&lt;/debuglevel&gt;
	&lt;/configuration&gt;
&lt;/plugin&gt;
</pre></p>
<p>That&#8217;s it! have fun. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/aop/'>AOP</a>, <a href='http://anismiles.wordpress.com/tag/aspect-oriented-programming/'>Aspect Oriented Programming</a>, <a href='http://anismiles.wordpress.com/tag/aspectj/'>AspectJ</a>, <a href='http://anismiles.wordpress.com/tag/java-annotation/'>Java Annotation</a>, <a href='http://anismiles.wordpress.com/tag/method-interceptor/'>Method Interceptor</a>, <a href='http://anismiles.wordpress.com/tag/spring/'>Spring</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1868/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1868/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1868/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1868/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1868/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1868/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1868/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1868/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1868&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/09/29/aspectj-spring-for-method-click-records/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>In Studio: Javascript Primitives</title>
		<link>http://anismiles.wordpress.com/2011/06/22/in-studio-javascript-primitives/</link>
		<comments>http://anismiles.wordpress.com/2011/06/22/in-studio-javascript-primitives/#comments</comments>
		<pubDate>Wed, 22 Jun 2011 18:19:19 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Objects]]></category>
		<category><![CDATA[Primitives]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1844</guid>
		<description><![CDATA[Javascript – and for that matter most other languages – has two kinds of stuffs: primitives and objects. Primitives are immutable and stored in a variable entirely. That is, when you do assignments among primitives, the assigned receives a copy from the assigner. Objects are not stored in the variable. They stay somewhere else, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1844&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1844" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F06%2F22%2Fin-studio-javascript-primitives%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-tK%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F06%2F22%2Fin-studio-javascript-primitives%2F" height="61" width="51" /></a>
</div>
<p>Javascript – and for that matter most other languages – has two kinds of stuffs: <em>primitives</em> and <em>objects</em>. Primitives are immutable and stored in a variable entirely. That is, when you do assignments among primitives, the assigned receives a copy from the assigner.</p>
<p><pre class="brush: jscript;">y = x; // y receives a copy of x.</pre></p>
<p>Objects are not stored in the variable. They stay somewhere else, and the variable only holds a reference to that location. So, in case of object assignments only references get copied.</p>
<p><pre class="brush: jscript;">obj2 = obj1; // obj2 receives a copy of reference to the object referred by obj1.</pre></p>
<p>That is, both obj1 and obj2 now points to the same object, and if you change this object – the change will be observed by both obj1 and obj2.</p>
<p>In Javascript, there are 5 kinds of primitives: <em>undefined</em>, <em>null</em>, <em>boolean</em>, <em>string</em> and <em>number</em>. So, string “abc”, number 1, 1.34, boolean true, false – these all are primitives. Rest everything are Objects. </p>
<p>I know what you are thinking? Primitives are not Objects, and so they must not be able to execute any method on themselves – because they don’t have any – then how come this works?</p>
<p><pre class="brush: jscript;">console.log(“abc”.length); // prints 3</pre></p>
<p>Well, the reason this works is that Javascript wraps these primitives with their Object counterparts.</p>
<blockquote><p>“abc” ==&gt; new String(“abc”)<br />
true ==&gt; new Boolean(true)<br />
1 ==&gt; new Number(1)</p></blockquote>
<p>Recall Java’s wrapper objects? Well, this is almost the same and with more juicy <a href="http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html" target="_blank">auto-boxing</a> in play. Javascript automatically coerces between primitives and Objects. In this case,</p>
<ol>
<li>string value is coerced into a String Object,</li>
<li>property ‘length’ is accessed, and then</li>
<li>the coerced Object is discarded for garbage collection!</li>
</ol>
<p>Now, the hacker in you must have started thinking: If Javascript automatically coerces primitives to Objects; then certainly, you should be able to assign properties to a primitive too, like this:</p>
<p><pre class="brush: jscript;">var my_bank_account = “State Bank of India”;
my_bank_account.city = “Indore”;
console.log(my_bank_account.city); // prints undefined.</pre></p>
<p>Oops. It failed. But why?</p>
<p>Well, what you guessed was right. The moment you tried to assign a property to the primitive, Javascript did indeed coerce primitive string into the wrapper Object – in this case, String. This new Object got itself assigned a brand new property – ‘city’ – too. But, since there wasn’t any placeholder to store the reference to this new Object, it was quickly discarded and sent for garbage collection. And when you went back to access the property ‘city’, Javascript again coerced your primitive to the wrapper Object – which incidentally is a new Object and doesn’t know anything about your ‘city’ property hence you see ‘undefined’.</p>
<p>Let me show you – roughly – what happens behind the scene:</p>
<p><pre class="brush: jscript;">var my_bank_account = “State Bank of India”;
my_bank_account.city = “Indore”;  ==&gt; (new String(“State Bank of India”)).city = “Indore”;
console.log(my_bank_account.city);  ==&gt; console.log(  (new String(“State Bank of India”)).city );</pre></p>
<p>This whole game seems messy? No. How do I know when am I dealing with primitives and when with Objects?</p>
<p>Well, you use ‘<em>typeof</em>’ operator.</p>
<p><pre class="brush: jscript;">typeof false; // ‘boolean’
typeof new Boolean(false); // ‘object’
typeof “Animesh”;// ‘string’
typeof new String(“Animesh”); // ‘object’
typeof 1.45; // ‘number’
typeof new Number(1.45); // ‘object’</pre></p>
<p>Enlightened? Good. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>One more thing: this entire coercion business is a <em>double-way</em> traffic. The way Javascript turns your primitives into Objects when needed, it can turn Objects into primitives too when required.</p>
<p><pre class="brush: jscript;">var s = new String(‘hello’);
typeof s; // ‘object’
var p = s.valueOf(); // converts to primitive
typeof p; // ‘string’</pre></p>
<p>Javascript will automatically use ‘valueOf’ (<a href="http://stackoverflow.com/questions/2485632/valueof-vs-tostring-in-javascript" target="_blank">and sometimes, ‘toString’</a>) method whenever such a need arises. Watch this:</p>
<p><pre class="brush: jscript;">var x = new String(“abc”);
typeof x; // ‘object’
var y = x + 1; // automatically calls valueOf() on Object x.
typeof y; // ‘string’</pre></p>
<p>Normally, you don’t need to worry about this thing. But knowing what goes on certainly helps at times. Don’t you think? Follow this:</p>
<p><pre class="brush: jscript;">var b = new Boolean(false);
typeof b; // ‘object’
if (b){
    console.log(“b is true.”); // Ah! When did b become true?
}</pre></p>
<p>What’s wrong with the above code? You must have thought that Javascript would coerce the Boolean object into primitive while evaluating &#8216;if&#8217;? Well, Javascript didn’t think so. It just went ahead and evaluated the Object directly for the condition&#8230; and since that Object was neither null nor undefined, it evaluated to true.</p>
<p>If you had done this:</p>
<p><pre class="brush: jscript;">if (b.valueOf(){
    console.log(“b is true”);
} else {
    console.log(“b is false”); // thank God!
}</pre></p>
<p>It would have come out differently. Remember this: unless there is a dire need, Javascript doesn’t perform any coercion. </p>
<p>I hope this article was helpful. I&#8217;ll be writing more on Javascript internals. </p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/javascript/'>JavaScript</a>, <a href='http://anismiles.wordpress.com/tag/node-js/'>Node.js</a>, <a href='http://anismiles.wordpress.com/tag/objects/'>Objects</a>, <a href='http://anismiles.wordpress.com/tag/primitives/'>Primitives</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1844/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1844/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1844/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1844/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1844/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1844/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1844/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1844/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1844&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/06/22/in-studio-javascript-primitives/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>Fun with Singleton (Python, Javascript, Java)</title>
		<link>http://anismiles.wordpress.com/2011/05/27/fun-with-singleton-python-javascript-and-java/</link>
		<comments>http://anismiles.wordpress.com/2011/05/27/fun-with-singleton-python-javascript-and-java/#comments</comments>
		<pubDate>Fri, 27 May 2011 10:29:32 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[java singleton]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript singleton]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Singleton]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1795</guid>
		<description><![CDATA[They say that Singletons, like global variables, are evil. They hide dependencies; are harder to test and even harder to extend. Singletons are lies, and it’s best to keep away from them. But, there are scenarios where you need them. For example, when you want a shared resource like printer spooler or file manager or [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1795&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1795" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F05%2F27%2Ffun-with-singleton-python-javascript-and-java%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-sX%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F05%2F27%2Ffun-with-singleton-python-javascript-and-java%2F" height="61" width="51" /></a>
</div>
<p>They say that <a href="http://en.wikipedia.org/wiki/Singleton_pattern" target="new">Singletons</a>, like global variables, are <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/" target="new">evil</a>. They hide dependencies; are <a href="http://www.ibm.com/developerworks/webservices/library/co-single/index.html" target="new">harder to test</a> and even harder to extend. Singletons are <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html" target="new">lies</a>, and it’s best to keep away from them. But, there are scenarios where you need them. For example, when you want a shared resource like printer spooler or file manager or log manager, you want a single object to handle requests from all the various parts of your application.</p>
<p>In this blog, I am going to explore various ways to make Singletons in languages like <a href="http://anismiles.wordpress.com/tag/python/">Python</a>, <a href="http://anismiles.wordpress.com/tag/java/">Java</a> and <a href="http://anismiles.wordpress.com/tag/javascript/">Javascript</a> so as to keep it simple, elegant and usable. Let&#8217;s talk about Python first. I love it, and it&#8217;s a really really wonderful language, and in here, there are <em>n</em> different ways to solve a problem. Singletons are no exception. The most natural way to do it is to create a decorator.</p>
<p><pre class="brush: python;">
class Singleton(object):
	def __init__(self, klass):
		self.klass = klass   # class which is being decorated
		self.instance = None  # instance of that class
	def __call__(self, *args, **kwargs):
		if self.instance is None:
			# new instance is created and stored for future use
			self.instance = self.klass(*args, **kwargs)
		return self.instance
</pre></p>
<p>Now, let&#8217;s say you have a Resource class. To make it singleton, you just need to decorate it with &#8216;<strong>@Singleton</strong>&#8216;, and you are done.</p>
<p><pre class="brush: python;">
@Singleton
class Resource(object):
	def __init__(self, klass):
		self.name = None
</pre></p>
<p>Cool&#8230;eh? There are other &#8211; nerdy &#8211; ways too. Python uses an internal dictionary &#8216;<strong>__dict__&#8217;</strong> variable to keep track of an Object&#8217;s properties and methods. So, if you can share &#8216;<strong>__dict__</strong>&#8216; across multiple instances of a Class, you can share the state between them. And isn&#8217;t that Singleton? Yes, that is. You might have many many instances, but all of them behave exactly the same.</p>
<p><pre class="brush: python;">
class Singleton(object):
	_shared = {}
	def __init__(self):
		self.__dict__ = Singleton._shared
class Resource(Singleton):
	def __init__(self, klass):
		self.name = None
</pre></p>
<p>Since &#8216;<strong>self.__dict__</strong>&#8216; now refers to &#8216;<strong>_shared</strong>&#8216; dictionary, all instances of Resource would use the same dictionary and hence they will all have the same behavior. Geeky? Let me show you an even geekier way to do it.</p>
<p>In Python, when you instantiate a class, the interpreter calls &#8216;<strong>__new__</strong>&#8216; method &#8211; a class method which returns an instance of the class &#8211; and then &#8216;<strong>__init__</strong>&#8216; method &#8211; constructor of the class &#8211; is called which initializes the object. So, you can hack into &#8216;<strong>__new__</strong>&#8216; and return the single instance whenever it is being called.</p>
<p><pre class="brush: python;">
class Singleton(object):
	_instance = None
	def __new__(cls, *args, **kwargs):
	# cls is the Class and the rest are constructor arguments
		if cls._instance is None:
			# create an instance and store it
			cls._instance = Object.__new__(cls, *args, **kwargs)
		return cls._instance
class Resource(Singleton):
	def __init__(self, klass):
		self.name = None
</pre></p>
<p>Aweomse! Isn&#8217;t it? There are other ways that deal with &#8216;<strong>__metaclass__</strong>&#8216; etc. but let&#8217;s save them for another day. Let&#8217;s use it now:</p>
<p><pre class="brush: python;">
# get resource r1
r1 = Resource();
# get resource r2  (since Resource is singleton, r1 == r2)
r2 = Resource();
# to verify, let's set 'name' onto r1
r1.name = &quot;Animesh Kumar&quot;
print r1.name
# and the same 'name' appears in r2 as well!
print r2.name
</pre></p>
<p>Let&#8217;s now see how do we do this in Javascript. For the most simple form, just define an <a href="http://www.dyn-web.com/tutorials/obj_lit.php" target="_blank">Object Literal</a>, and you are done.</p>
<p><pre class="brush: jscript;">
var resource = {
	getName : function() {
		return this.name;
	},
	setName: function(name){
		this.name = name;
	}
}
</pre></p>
<p>Easy. You have an object which you can now share across your application modules and it just works. For more complex scenarios, like private variables and all, you might have to resort to something like this:</p>
<p><pre class="brush: jscript;">
// self-executable wrapper function
var Resource = (function(){
	// Resouce class which is to made 'singleton'
	function _Resource() {
    	var name; // private variable
    	this.getName = function() {	// getter
    		return this.name;
    	};
		this.setName= function(name){ // setter
			this.name = name;
		};
		// do more stuffs
    }
    // instance holder
    var instance = new _Resource();&lt;/p&gt;
    // return an object with 'getInstance' method
    return = {
        getInstance: function(){
            return instance;
        }
   };
})();
</pre></p>
<p><strong>_Resource</strong> (line-04) is your function of interest, and you want to make it singleton. So, you create another function &#8216;<strong>Resource</strong>&#8216; which wraps over <strong>_Resource</strong> and returns an object with method &#8216;<strong>getInstance</strong>&#8216; which would return the same instance of <strong>_Resource</strong> every time it will be called.</p>
<p>Let&#8217;s try to use it now:</p>
<p><pre class="brush: jscript;">
// get resource r1
r1 = Resource.getInstance();
// get resource r2  (since Resource is singleton, r1 == r2)
r2 = Resource.getInstance();
// to verify, let's set 'name' onto r1
r1.setName(&quot;Animesh Kumar&quot;);
console.log(r1.getName());
// and the same 'name' appears in r2 as well!
console.log(r2.getName());
</pre></p>
<p>So it was easy. No? Great. </p>
<p>Now, Java. I know every one of you would already know it. I would write about it anyway, just for the sake of completeness. In Java, you create a private static instance of the class, and use that instance wherever necessary.</p>
<p><pre class="brush: java;">
public class Resource {
	// static instance (Note: Resource instantiation is done here, not in getInstance)
	private static Resource instance = new Resource();
	// property
	private String name;
	// private constructor to disable 'new'
	private Resource() {
	}
	// public staic method to get an instance of this class
	public static Resource getInstance() {
		return instance;
	}
	// getter
	public String getName() {
		return name;
	}
	// setter
	public void setName(String name) {
		this.name = name;
	}
}
</pre></p>
<p>Now, let&#8217;s use it.</p>
<p><pre class="brush: java;">
	public static void main(String[] args) {
		// get resource r1
		Resource r1 = Resource.getInstance();
		// get resource r2  (since Resource is singleton, r1 == r2)
		Resource r2 = Resource.getInstance();
		// to verify, let's set 'name' onto r1
		r1.setName(&quot;Animesh Kumar&quot;);
		System.out.println(r1.getName());
		// and the same 'name' appears in r2 as well!
		System.out.println(r2.getName());
	}
</pre></p>
<p>Loud and clear. And this also stops you from instantiating &#8216;<strong>Resource</strong>&#8216; with &#8216;<strong>new</strong>&#8216; operator. Try this: </p>
<p><pre class="brush: java;">
	Resource r1 = new Resource();  // java.lang.Error: Unresolved compilation problem:
</pre></p>
<p>Your code will not compile. I know you know why. I will write anyways: because the constructor is private! So, there is no way to get an instance of Resource class but through ‘<strong>getInstance</strong>’ method which ensures single instance of the class. Also, If you noticed: I have instantiated ‘instance’ during declaration itself, not in &#8216;getInstance&#8217; method. This way, the object gets created at the time of class loading, and you save yourself from a <a href="http://www.ibm.com/developerworks/java/library/j-dcl/index.html" target="new">lot of issues</a> that creeps in because of  <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation" target="new">Java Just in Time</a>.</p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/design-pattern/'>Design Pattern</a>, <a href='http://anismiles.wordpress.com/tag/java/'>Java</a>, <a href='http://anismiles.wordpress.com/tag/java-singleton/'>java singleton</a>, <a href='http://anismiles.wordpress.com/tag/javascript/'>JavaScript</a>, <a href='http://anismiles.wordpress.com/tag/javascript-singleton/'>javascript singleton</a>, <a href='http://anismiles.wordpress.com/tag/python/'>Python</a>, <a href='http://anismiles.wordpress.com/tag/python-singleton/'>Python Singleton</a>, <a href='http://anismiles.wordpress.com/tag/singleton/'>Singleton</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1795/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1795/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1795/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1795/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1795/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1795/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1795/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1795/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1795&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/05/27/fun-with-singleton-python-javascript-and-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>IBM has no idea what Node.js is</title>
		<link>http://anismiles.wordpress.com/2011/05/13/ibm-has-no-idea-what-node-js-is/</link>
		<comments>http://anismiles.wordpress.com/2011/05/13/ibm-has-no-idea-what-node-js-is/#comments</comments>
		<pubDate>Fri, 13 May 2011 07:04:04 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[DeveloperWorks]]></category>
		<category><![CDATA[IBM]]></category>
		<category><![CDATA[IBM Node.js]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[What is Node.js?]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1754</guid>
		<description><![CDATA[People, don&#8217;t read this article on IBM&#8217;s developer works Just what is Node.js?. And you have read it already, don&#8217;t believe it. IBM has no idea what Node is, really. Read my rebuttal http://wkp.me/wkk6g For more gory details, read Marak Squires&#8217; blog here. IBM must pull the article or ask the author to rewrite it. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1754&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1754" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F05%2F13%2Fibm-has-no-idea-what-node-js-is%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-si%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F05%2F13%2Fibm-has-no-idea-what-node-js-is%2F" height="61" width="51" /></a>
</div>
<p>People, don&#8217;t read this article on IBM&#8217;s developer works <a href="http://www.ibm.com/developerworks/opensource/library/os-nodejs/index.html" target="_blank">Just what is Node.js?</a>. And you have read it already, don&#8217;t believe it. IBM has no idea what Node is, really. </p>
<p>Read my rebuttal <a href="http://wkp.me/wkk6g" target="_blank">http://wkp.me/wkk6g</a> </p>
<p>For more gory details, read <a href="http://blog.nodejitsu.com/ibm-doesnt-care-about-nodejs-people" target="_blank">Marak Squires&#8217; blog</a> here. </p>
<p>IBM must pull the article or ask the author to rewrite it. The article is providing a dis-service to any new developers who might stumble along it as their first introduction to node.js.</p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/developerworks/'>DeveloperWorks</a>, <a href='http://anismiles.wordpress.com/tag/ibm/'>IBM</a>, <a href='http://anismiles.wordpress.com/tag/ibm-node-js/'>IBM Node.js</a>, <a href='http://anismiles.wordpress.com/tag/javascript/'>JavaScript</a>, <a href='http://anismiles.wordpress.com/tag/node/'>Node</a>, <a href='http://anismiles.wordpress.com/tag/what-is-node-js/'>What is Node.js?</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1754/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1754&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/05/13/ibm-has-no-idea-what-node-js-is/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>Node and Its Many Incarnations (Node Version Management)</title>
		<link>http://anismiles.wordpress.com/2011/05/03/node-and-its-many-incarnations-node-version-management/</link>
		<comments>http://anismiles.wordpress.com/2011/05/03/node-and-its-many-incarnations-node-version-management/#comments</comments>
		<pubDate>Tue, 03 May 2011 05:47:08 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node Version Management]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NVM]]></category>
		<category><![CDATA[server side javascript]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1711</guid>
		<description><![CDATA[Node.js is under active development. And every other day, a new build is released. It’s awesome to see how fast Node is growing and how vibrant the community is… but on the down side, it’s becoming increasingly difficult to keep track of its many versions, and API changes. Very often, while developing an app, you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1711&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1711" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F05%2F03%2Fnode-and-its-many-incarnations-node-version-management%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-rB%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F05%2F03%2Fnode-and-its-many-incarnations-node-version-management%2F" height="61" width="51" /></a>
</div>
<p><a href="http://nodejs.org" target="_blank">Node.js</a> is under active development. And every other day, a new build is released. It’s awesome to see how fast Node is growing and how vibrant the community is… but on the down side, it’s becoming increasingly difficult to keep track of its many versions, and API changes.</p>
<p>Very often, while developing an app, you find yourself married into a particular Node version, because a newer one might have some API changes (mind you, Node is witnessing heavy transformations, especially at the API level) which might break you app… and then, you would be forced to revert back to the older version. That means, uninstall the current node and re-install the older one. Ouch! So much work for a mere upgrade. </p>
<p>Well, there is a nicer way to do it. Check out this project by <a href="https://github.com/creationix/" target="_blank">Tim Caswell</a>: <a href="https://github.com/creationix/nvm" target="_blank">Node Version Manager</a>. It does exactly what it says. It manages various Node versions on your machine, development, stage, production whatever. How? </p>
<p>It creates a virtual Node environment for each version you want to keep. Let’s say, you want to stay with the last stable release <a href="https://github.com/joyent/node/tree/v0.2.6" target="_blank">v0.2.6</a> (from the time you started your app) but also want to experiment with <a href="https://github.com/joyent/node/tree/v0.4.7" target="_blank">v0.4.7</a> to keep an eye on new additions.  NVM will install two separate Node(s) for you, and each will <strong><u>run in its own sandbox like environment, that is, you will have to install all your third party Modules/Libraries separately for each Node installation</u></strong>. That might seem to be a lot of work, but trust me, it’s the safest way to avoid conflicts. Okay. Let’s get to work.</p>
<h2>Installation</h2>
<p>Note: I am assuming that you have basic knowhow of <a href="http://git-scm.com/" target="_blank">GIT</a> (the most awesome source control management system).</p>
<ol>
<li>Clone NVM repository to your local machine:<br />
<pre class="brush: bash;">$ git clone git://github.com/creationix/nvm.git ~/.nvm</pre></p>
<p>Above command would close the NVM repository to a folder ‘.nvm’ in your home directory. (I am using Ubuntu 10.0.4)</li>
<li>Switch to folder ‘.nvm’ and make file ‘nvm.sh’ executable:<br />
<pre class="brush: bash;">$ chmod 755 ~/.nvm/nvm.sh</pre></li>
<li>‘nvm.sh’ is just a shell script, so in order to run it, you must source it to every terminal you open. To do this automatically, simply edit either ‘.bashrc’ or ‘.profile’ file to have this line in the very end:<br />
<pre class="brush: bash;">. ~/.nvm/nvm.sh</pre></li>
<li> That’s it. Open a new terminal and run,<br />
<pre class="brush: bash;">$ nvm</pre></li>
<li>You will see a set of useful commands you can use. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Easy huh?</li>
</ol>
<h2>Getting dirty</h2>
<p>Before you get any further, just make sure that you have ‘<a href="http://www.gnu.org/software/wget/" target="_blank">wget</a>’ installed in your machine. I know, I know… you might already have it. I just want you to make sure.</p>
<p>Check which <strong>versions of Node</strong> are available.</p>
<p><pre class="brush: bash;">$ nvm sync // update the local machine with available versions from server
$ nvm ls   // displays all available and installed versions</pre></p>
<p>Now <strong>install</strong> <a href="https://github.com/joyent/node/tree/v0.4.7">Node v0.4.7</a>.</p>
<p><pre class="brush: bash;">$ nvm install v0.4.7 // will install Node v.0.4.7</pre></p>
<p>Note: You might get this error, &#8220;<strong>Could not autodetect OpenSSL support. Make sure OpenSSL development packages are installed. Use configure &#8211;without-ssl to disable this message</strong>&#8221; which says, that you need to install SSl library:</p>
<p><pre class="brush: bash;">$ sudo apt-get install libssl-dev</pre> </p>
<p>NVM creates a folder ‘src’ either in your home directory or in ‘.nvm’ directory where it downloads the bundled release, extracts and installs it. NVM also installs <a href="http://npmjs.org/" target="_blank">NPM</a> (node package manager) for each installation of Node. </p>
<p>Select a <strong>particular version</strong></p>
<p><pre class="brush: bash;">$ nvm use v0.4.7 // start using Node-v0.4.7</pre></p>
<p>That&#8217;s it. You have set up a system which will enable you to quickly and cleanly switch between various Node versions. You can test your app&#8217;s compatibility with any of them, and if need be, easily switch to the one your app was most comfortable with. </p>
<p>Now, since you have set up a congenial Node development machine, in the next blog, I will talk about how to go live with your Node app. </p>
<p>Note: for CentOs-5.x, please make sure that you have following packages installed:<br />
<pre class="brush: bash;">$sudo yum install gcc-c++ screen git-core openssl openssl-devel</pre></p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/javascript/'>JavaScript</a>, <a href='http://anismiles.wordpress.com/tag/node-version-management/'>Node Version Management</a>, <a href='http://anismiles.wordpress.com/tag/node-js/'>Node.js</a>, <a href='http://anismiles.wordpress.com/tag/nvm/'>NVM</a>, <a href='http://anismiles.wordpress.com/tag/server-side-javascript/'>server side javascript</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1711/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1711/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1711/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1711&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/05/03/node-and-its-many-incarnations-node-version-management/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>shutdown hooks in java</title>
		<link>http://anismiles.wordpress.com/2011/03/28/shutdown-hooks-in-java/</link>
		<comments>http://anismiles.wordpress.com/2011/03/28/shutdown-hooks-in-java/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 11:11:05 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[ShutDownHook]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1702</guid>
		<description><![CDATA[You know what? You can add your custom hooks to JVM to be called when JVN shuts down. Interesting… no? What happens is very simple: you create a Thread and write you logic in there, and then register this Thread to the Runtime instance. Here is a sample: output will be: closing down the shop&#8230; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1702&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1702" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F03%2F28%2Fshutdown-hooks-in-java%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-rs%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F03%2F28%2Fshutdown-hooks-in-java%2F" height="61" width="51" /></a>
</div>
<p>You know what? You can add your custom hooks to JVM to be called when JVN shuts down. Interesting… no?</p>
<p>What happens is very simple: you create a Thread and write you logic in there, and then register this Thread to the Runtime instance. Here is a sample:<br />
<pre class="brush: java;">
public class JVMShutdownTest {

	public static void main(String[] args) {
		
		// Add a shutdown hook
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run(){
				System.out.println (&quot;closing down the shop...&quot;);
			}
		});
		
		// Exit now
		System.exit(0);
	}
}
</pre></p>
<p>output will be: closing down the shop&#8230; </p>
<p>This attached Thread is initialized but not yet started. When JVM starts to shut down, it starts all registered hooks in an uncontrollable (that is, there is no way to enforce your will) order, and all of them run concurrently.</p>
<p>One thing you must take in consideration is that these hooks get executed at a very delicate time and so you must keep them light, thread-safe and independent of heavy dependencies. Thump rule: hooks must finish quick.</p>
<p><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)">Read more &gt;&gt;</a></p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/java/'>Java</a>, <a href='http://anismiles.wordpress.com/tag/shutdownhook/'>ShutDownHook</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1702/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1702/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1702/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1702/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1702/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1702/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1702/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1702/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1702&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/03/28/shutdown-hooks-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>WebSocket support in Android’s Phonegap apps</title>
		<link>http://anismiles.wordpress.com/2011/02/03/websocket-support-in-android%e2%80%99s-phonegap-apps/</link>
		<comments>http://anismiles.wordpress.com/2011/02/03/websocket-support-in-android%e2%80%99s-phonegap-apps/#comments</comments>
		<pubDate>Thu, 03 Feb 2011 06:22:44 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Phonegap]]></category>
		<category><![CDATA[WebSocket]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1662</guid>
		<description><![CDATA[We are developing a small game which can be played from multiple users using variety of clients, web-browser, Android, iPhone, iPad etc. It’s like, there is a server and all clients connect to this server, and send and receive messages. We decided to use WebSocket for underlying connection between clients and server, and Phonegap to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1662&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1662" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F02%2F03%2Fwebsocket-support-in-android%25e2%2580%2599s-phonegap-apps%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-qO%26tweetmeme_source%3Danismiles"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F02%2F03%2Fwebsocket-support-in-android%25e2%2580%2599s-phonegap-apps%2F" height="61" width="51" /></a>
</div>
<p>We are developing a small game which can be played from multiple users using variety of clients, web-browser, Android, iPhone, iPad etc. It’s like, there is a server and all clients connect to this server, and send and receive messages. We decided to use <a href="http://anismiles.wordpress.com/2011/01/25/websocket-and-node-js-why-shud%e2%80%99ya-care/">WebSocket</a> for underlying connection between clients and server, and <a href="http://phonegap.com/" target="_blank">Phonegap</a> to build clients. Our idea is to write the client once and then run it on variety of platforms. Since, Phonegap enables app development using HTML, CSS and JavaScripts, it generously fits into our requirement.</p>
<p>But <a href="http://phonegap.com/" target="_blank">Phonegap</a> doesn’t support WebSocket yet, it’s in their Plan-of-Action for 1.x release though. So, it was needed to be addressed. I found <a href="https://github.com/FreakDev" target="_blank">Mathias Desloge</a>’s <a href="https://github.com/FreakDev/PhoneGap-Android-HTML5-WebSocket" target="_blank">PhoneGap-Android-HTML5-WebSocket</a> project. It was good but it used old <strong><a href="http://download.oracle.com/javase/6/docs/api/index.html?java/io/package-summary.html" target="_blank">java.io.*</a></strong> packages. I would have preferred to use <strong><a href="http://download.oracle.com/javase/6/docs/api/index.html?java/nio/package-summary.html" target="_blank">java.nio.*</a></strong> for better and efficient non-blocking behavior. So, I decided to write my own small library.</p>
<p>Library can be found here: <a href="https://github.com/anismiles/websocket-android-phonegap">websocket-android-phonegap</a>.</p>
<h2>How to use?</h2>
<ol>
<li>Copy <a href="https://github.com/anismiles/websocket-android-phonegap/tree/master/src" target="_blank">Java source</a> into your source folder.</li>
<li>Copy <a href="https://github.com/anismiles/websocket-android-phonegap/blob/master/assets/www/js/websocket.js" target="_blank">websocket.js</a> in your assets/www/js folder</li>
<li>Attach <a href="https://github.com/anismiles/websocket-android-phonegap/blob/master/src/com/strumsoft/websocket/phonegap/WebSocketFactory.java" target="_blank">com.strumsoft.websocket.phonegap.WebSocketFactory</a> to WebView, like<br />
<pre class="brush: java;">
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.loadUrl(&quot;file:///android_asset/www/index.html&quot;);

		// attach websocket factory
		appView.addJavascriptInterface(new WebSocketFactory(appView), &quot;WebSocketFactory&quot;);
	}
</pre></li>
<li>In your <a href="https://github.com/anismiles/websocket-android-phonegap/blob/master/assets/www/index.html" target="_blank">page</a>, create a new WebSocket, and overload its method &#8216;onmessage&#8217;, &#8216;onopen&#8217;, &#8216;onclose&#8217;, like<br />
<pre class="brush: jscript;">
	// new socket
	var socket = new WebSocket('ws://192.168.1.153:8081');

	// push a message after the connection is established.
	socket.onopen = function() {
	 alert('connected');
	};

	// alerts message pushed from server
	socket.onmessage = function(msg) {
	 alert(JSON.stringify(msg));
	};

	// alert close event
	socket.onclose = function() {
	 alert('closed');
	};
</pre></li>
</ol>
<h2>How it works?</h2>
<p>When you create a new WebSocket object in your page, behind the scene, <a href="https://github.com/anismiles/websocket-android-phonegap/blob/master/assets/www/js/websocket.js" target="_blank">websocket.js</a> delegates the responsibility to <a href="https://github.com/anismiles/websocket-android-phonegap/blob/master/src/com/strumsoft/websocket/phonegap/WebSocketFactory.java" target="_blank">com.strumsoft.websocket.phonegap.WebSocketFactory</a> to instantiate new <a href="https://github.com/anismiles/websocket-android-phonegap/blob/master/src/com/strumsoft/websocket/phonegap/WebSocket.java" target="_blank">com.strumsoft.websocket.phonegap.WebSocket</a> object. </p>
<p><pre class="brush: jscript;">
		// websocket.js
		// get a new websocket object from factory (check com.strumsoft.websocket.WebSocketFactory.java)
		this.socket = WebSocketFactory.getWebSocket(url);
</pre></p>
<p>WebSocketFactory simply instantiates a new WebSocket object, connects it to the designated server and returns the instance. </p>
<p><pre class="brush: java;">
// com.strumsoft.websocket.phonegap.WebSocketFactory

public WebSocket getWebSocket(String url) throws URISyntaxException {
	WebSocket socket =  new WebSocket(appView, new URI(url));
	socket.connect();   // connects to server
	return socket;
}
</pre></p>
<p>Now, whenever an event occurs, say, ‘onmessage’, WebSocket class delegates that event to Javascript.</p>
<p><pre class="brush: java;">
// com.strumsoft.websocket.phonegap.WebSocket

public void onMessage(String message) {
	appView.loadUrl(buildLoadData(&quot;message&quot;, message));
}
private String buildLoadData(String _event, String _data) {
	String _d =  &quot;javascript:WebSocket.on&quot; + _event + &quot;(&quot; + 
				&quot;{&quot;
				+ &quot;\&quot;_target\&quot;:\&quot;&quot; + webSocketId + &quot;\&quot;,&quot; + 
				&quot;\&quot;_data\&quot;:'&quot; + data + &quot;'&quot; + 
				&quot;}&quot; + 
			&quot;)&quot;;
	Logger.log(_d);
	return _d;
}
</pre></p>
<p>Finally, ‘WebSocket.onmessage’ from websocket.js is called. It parses the payload, finds out the target WebSocket object, and calls the corresponding event on the target object with event data. </p>
<p><pre class="brush: jscript;">
	// websocket.js
	// static event methods to call event methods on target websocket objects
	WebSocket.onmessage = function (evt) {
		WebSocket.registry[evt._target]['onmessage'].call(global, evt._data);
	}
</pre></p>
<p>That&#8217;s it!</p>
<h2>Amendment</h2>
<p>(Date: Thu Aug 25 12:40:52 IST 2011)</p>
<p>There was a serious bug! The Websocket connection runs in a separate thread to manage persistent state with the server. And the front end Javascript (websocket.js) stays within UI/Main thread. And <a href="http://developer.android.com/resources/articles/painless-threading.html" target="_blank">Android doesn&#8217;t want other threads to communicate with UI thread directly</a>. These threads must employ an additional thread to bridge the communication. So, here is the fix!</p>
<p><pre class="brush: java;">
	// a message is sent to server! 
	public void send(final String text) {
		// new thread
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (instance.readyState == WEBSOCKET_STATE_OPEN) {
					try {
						instance._send(text);
					} catch (IOException e) {
						instance.onError(e);
					}
				} else {
					instance.onError(new NotYetConnectedException());
				}
			}
		}).start();
	}

	// when a message is received
	public void onMessage(final String msg) {
		// post a new thread to View
		appView.post(new Runnable() {
			@Override
			public void run() {
				appView.loadUrl(buildJavaScriptData(EVENT_ON_MESSAGE, msg));
			}
		});
	}
</pre></p>
<p>Commit link:<br />
<a href="https://github.com/anismiles/websocket-android-phonegap/commit/a7ccb815cce3a446c3ec92058187cdb20e5a41e8" target="_blank">https://github.com/anismiles/websocket-android-phonegap/commit/a7ccb815cce3a446c3ec92058187cdb20e5a41e8</a><br />
<a href="https://github.com/anismiles/websocket-android-phonegap/commit/087f7a93d46f92cb037d2b451a4d253a65f5f015" target="_blank">https://github.com/anismiles/websocket-android-phonegap/commit/087f7a93d46f92cb037d2b451a4d253a65f5f015</a></p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a> Tagged: <a href='http://anismiles.wordpress.com/tag/android/'>Android</a>, <a href='http://anismiles.wordpress.com/tag/javascript/'>JavaScript</a>, <a href='http://anismiles.wordpress.com/tag/phonegap/'>Phonegap</a>, <a href='http://anismiles.wordpress.com/tag/websocket/'>WebSocket</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1662/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1662&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/02/03/websocket-support-in-android%e2%80%99s-phonegap-apps/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>WebSocket and node.js: why shud’ya care?</title>
		<link>http://anismiles.wordpress.com/2011/01/25/websocket-and-node-js-why-shud%e2%80%99ya-care/</link>
		<comments>http://anismiles.wordpress.com/2011/01/25/websocket-and-node-js-why-shud%e2%80%99ya-care/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 09:55:43 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Long Polling]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[WebSocket]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1639</guid>
		<description><![CDATA[Traditional HTTP messages are heavy. Every message is sent with HTTP headers. Now, let’s say you have an application that has a real-time component, like chat or some twitter client or may be some traffic analysis stuff. And let’s say you have around 100,000 users connected to your app. To make your app real-time, you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1639&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1639" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F01%2F25%2Fwebsocket-and-node-js-why-shud%25e2%2580%2599ya-care%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-qr%26tweetmeme_source%3D%E2%80%9Danismiles%E2%80%9D"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F01%2F25%2Fwebsocket-and-node-js-why-shud%25e2%2580%2599ya-care%2F" height="61" width="51" /></a>
</div>
<p>Traditional HTTP messages are heavy. Every message is sent with HTTP headers. Now, let’s say you have an application that has a real-time component, like chat or some twitter client or may be some traffic analysis stuff. And let’s say you have around 100,000 users connected to your app. To make your app real-time, you need to have a mechanism which will enable server to push data almost as soon as this data becomes available. You could do it in two ways: Write a script which will connect to server every few seconds to check if there is any data. With each attempt, full set of HTTP headers moves back and forth between client and server. That’s not very efficient. To save yourself with all these bandwidth hassles, you could use a popular trick known as long-polling, where your browser connects to server and server holds the connection open until there is some data available to be pushed.</p>
<p>Now, let’s assume that there are 100,000 users connected to your app and every 10 seconds some data is sent from server to clients. Following HTTP specs, every time some data is sent, full set of headers are shared between client and server. This is how they look,</p>
<p><span style="text-decoration:underline;">Request header</span></p>
<p><pre class="brush: jscript;">GET / HTTP/1.1
User-Agent: ...some long user agent string...
Host: animesh.org
Accept: */*
</pre></p>
<p><span style="text-decoration:underline;">Response header</span></p>
<p><pre class="brush: jscript;">HTTP/1.1 200 OK
Date: Tue, 25 Jan 2011 17:32:19 GMT
Server: Apache
X-Powered-By: PHP/5.2.3
X-Pingback: http://animesh.org/endpoint/
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
</pre></p>
<p>That’s approximately <span style="text-decoration:underline;">350 bytes</span> of data, per user every 10 seconds. That’s roughly 28,400,000 bits per second of network throughput for 100,000 users. Roughly <strong>26.7 Mbps for only HTTP headers</strong>. Gosh!</p>
<h2>WebSocket</h2>
<p>WebSocket comes to resue. With web sockets, once a handshake is done between client and server, messages can be sent back and forth with a minimal overhead. That&#8217;s awesome. You do a handshake while establishing the connection, and of course handshaking needs all those HTTP headers, but after that, you only need to send the data&#8230; no headers. This greatly reduces the bandwidth usage and thus improves the performance. Let’s see how. This is how handshake headers look like,</p>
<p><span style="text-decoration:underline;">Handshake Request header</span></p>
<p><pre class="brush: jscript;">GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: animesh.org
Origin: http://animesh.org
WebSocket-Protocol: sample
</pre></p>
<p><span style="text-decoration:underline;">Handshake Response header</span></p>
<p><pre class="brush: jscript;">HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin: http://animesh.org
WebSocket-Location: ws://animesh.org/
WebSocket-Protocol: sample
</pre></p>
<p>And now, the connection has been established and data can freely flow between server and client without having to exchange any HTTP headers until this connection is closed or broken and you do another handshake. Imagine how much bandwidth you are saving! Whoa!</p>
<h2>Example</h2>
<p>Let’s write a simple application to see and learn how this thing actually works. This application will have a server all the clients will connect to, and whenever one client writes something to the server, all clients will be notified.</p>
<p>Here is our server, written in <a href="http://anismiles.wordpress.com/tag/node-js/" target="_blank">Node.js</a>. Let&#8217;s name it <span style="text-decoration:underline;">server.js</span></p>
<p><em>Note: Though you can very well write a web socket server using Node&#8217;s native APIs, however I chose to use <a href="https://github.com/miksago" target="_blank">Micheil Smith</a>&#8216;s <a href="https://github.com/miksago/node-websocket-server" target="_blank">node-websocket-server</a> library. This library is simple, elegant and very easy to work with. It works by wrapping and extending Node&#8217;s server object.</em></p>
<p><pre class="brush: jscript;">var sys = require(&quot;sys&quot;);
// Library https://github.com/miksago/node-websocket-server
var	websocket = require('./lib/node-websocket-server/lib/ws/server');

// create web socket server
var server = websocket.createServer();
// listen on port 8078
server.listen(8078);

// when the server is ready
server.addListener(&quot;listening&quot;, function() {
  sys.log(&quot;Listening for connections on localhost:8078&quot;);
});

// when a traditional HTTP request comes
server.addListener(&quot;request&quot;, function(req, res) {
	res.writeHead(200, {
		&quot;Content-Type&quot; : &quot;text/plain&quot;
	});
	res.write(&quot;This is an example WebSocket server.&quot;);
	res.end();
});

// when a client websocket connects
server.addListener(&quot;connection&quot;, function(conn) {

	// when client writes something
	conn.addListener(&quot;message&quot;, function(message) {

		// iterate thorough all connected clients, and push this message
		server.manager.forEach(function(connected_client) {
			connected_client.write(JSON.stringify(conn.id + &quot;: &quot; + message));
        });
	});
});
</pre></p>
<p>Now, let&#8217;s write a simple client. We will create one HTML file and run it in Google Chrome. Let&#8217;s name is <span style="text-decoration:underline;">client.html</span></p>
<p><pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;WebSocket - Simple Client&lt;/title&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;

	$(function() {
		// bind form
		$('#payload-form').submit(function() {
			var payload = ($(&quot;input#payload&quot;).val());
			socket.send(payload);  // write to server
			return false;
		});

		// open websocket
		var socket = new WebSocket('ws://localhost:8078');

		socket.onopen = function() {
	    	// Web Socket is connected. send an initial random message.
	    	socket.send(Math.floor(Math.random()*11) + ' &gt;&gt; Hi, I am Mr. so-and-so!');
	    };
		// append to '#log' whatever server pushes.
		socket.onmessage = function(ev){
			msg = JSON.parse(ev.data);
			$('#log').append(JSON.stringify(msg) + '&lt;/br&gt;');
		}
	})
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;div id='payload-container'&gt;
		&lt;form id='payload-form'&gt;
			&lt;input type='text' name='payload' id='payload' value='Hello World' style=&quot;width:500px;&quot;/&gt;
			&lt;input type='submit' value='push'/&gt;
		&lt;/form&gt;
	&lt;/div&gt;

	&lt;div id='log' style='display:block; border:1px solid lightgray;'&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre></p>
<p>Now, run your server, and open your client in multiple Chrome windows/tabs.</p>
<p><pre class="brush: jscript;">
// run server
$ node server.js
</pre></p>
<p>That&#8217;s it! Was is fun? I will write more on how to establish WebSocket connections from a Java client in the next blog.</p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/technology/'>Technology</a>, <a href='http://anismiles.wordpress.com/category/uncategorized/'>Uncategorized</a> Tagged: <a href='http://anismiles.wordpress.com/tag/http/'>HTTP</a>, <a href='http://anismiles.wordpress.com/tag/javascript/'>JavaScript</a>, <a href='http://anismiles.wordpress.com/tag/long-polling/'>Long Polling</a>, <a href='http://anismiles.wordpress.com/tag/node-js/'>Node.js</a>, <a href='http://anismiles.wordpress.com/tag/websocket/'>WebSocket</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1639/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1639/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1639/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1639/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1639/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1639/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1639/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1639/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1639&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/01/25/websocket-and-node-js-why-shud%e2%80%99ya-care/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
		<item>
		<title>i&#8217;m a joke</title>
		<link>http://anismiles.wordpress.com/2011/01/19/i-m-a-joke/</link>
		<comments>http://anismiles.wordpress.com/2011/01/19/i-m-a-joke/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 09:59:07 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Poetry]]></category>
		<category><![CDATA[joke]]></category>
		<category><![CDATA[laugh]]></category>
		<category><![CDATA[Poem]]></category>
		<category><![CDATA[ridicule]]></category>
		<category><![CDATA[what am i]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1633</guid>
		<description><![CDATA[I&#8217;m a joke may be, a laugh. Don’t trust me not worth it I come cheap and easy like wild scrubs at every nook and cranny. Never taken home but, used and cast away and laughed at worst, ridiculed sometimes I’m not worth it. Filed under: Poetry Tagged: joke, laugh, Poem, Poetry, ridicule, what am [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1633&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1633" style='float: right; margin-left: 10px; margin-bottom: 5px; padding: 4px 0 2px 4px; background: #fff;'>
<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F01%2F19%2Fi-m-a-joke%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-ql%26tweetmeme_source%3D%E2%80%9Danismiles%E2%80%9D"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2011%2F01%2F19%2Fi-m-a-joke%2F" height="61" width="51" /></a>
</div>
<p>I&#8217;m a joke<br />
may be, a laugh.</p>
<p>Don’t trust me<br />
not worth it<br />
I come cheap<br />
and easy<br />
like wild scrubs<br />
at every nook<br />
and cranny.</p>
<p>Never taken home<br />
but, used<br />
and cast away<br />
and laughed at<br />
worst, ridiculed sometimes<br />
I’m not worth it.</p>
<br />Filed under: <a href='http://anismiles.wordpress.com/category/poetry/'>Poetry</a> Tagged: <a href='http://anismiles.wordpress.com/tag/joke/'>joke</a>, <a href='http://anismiles.wordpress.com/tag/laugh/'>laugh</a>, <a href='http://anismiles.wordpress.com/tag/poem/'>Poem</a>, <a href='http://anismiles.wordpress.com/tag/poetry/'>Poetry</a>, <a href='http://anismiles.wordpress.com/tag/ridicule/'>ridicule</a>, <a href='http://anismiles.wordpress.com/tag/what-am-i/'>what am i</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1633/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1633/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1633/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1633/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1633/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1633/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1633/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1633/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&#038;blog=13717969&#038;post=1633&#038;subd=anismiles&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2011/01/19/i-m-a-joke/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cec21c5c740ad285817815e209701ceb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">smileanimeshblog</media:title>
		</media:content>
	</item>
	</channel>
</rss>
