<?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>Sat, 28 Jan 2012 07:24:45 +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>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&amp;blog=13717969&amp;post=1868&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1868&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1844&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1844&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1795&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1795&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1754&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1754&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1711&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1711&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1702&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1702&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1662&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1662&amp;subd=anismiles&amp;ref=&amp;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>18</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&amp;blog=13717969&amp;post=1639&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1639&amp;subd=anismiles&amp;ref=&amp;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>12</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&amp;blog=13717969&amp;post=1633&amp;subd=anismiles&amp;ref=&amp;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&amp;blog=13717969&amp;post=1633&amp;subd=anismiles&amp;ref=&amp;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>
		<item>
		<title>Maven, SQL and ordered execution</title>
		<link>http://anismiles.wordpress.com/2010/12/28/maven-sql-ordered-execution/</link>
		<comments>http://anismiles.wordpress.com/2010/12/28/maven-sql-ordered-execution/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 07:01:24 +0000</pubDate>
		<dc:creator>Animesh</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[fileSets]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[maven ordered sql execution]]></category>
		<category><![CDATA[Postgres]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sql-maven-plugin]]></category>
		<category><![CDATA[srcFiles]]></category>

		<guid isPermaLink="false">http://anismiles.wordpress.com/?p=1619</guid>
		<description><![CDATA[I have been re-architecting this new project. This is huge. And broken. And I was called upon to clean, refactor and re-architect it. Phew! I thought a good strategy would be to deal with it in outside-in style, which is, fixing the build part first then moving down to various parts. One of the interesting [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&amp;blog=13717969&amp;post=1619&amp;subd=anismiles&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme-button" id="tweetmeme-button-post-1619" 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%2F2010%2F12%2F28%2Fmaven-sql-ordered-execution%2Ftweetmeme_alias%3Dhttp%3A%2F%2Fwp.me%2FpVyFz-q7%26tweetmeme_source%3D%E2%80%9Danismiles%E2%80%9D"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fanismiles.wordpress.com%2F2010%2F12%2F28%2Fmaven-sql-ordered-execution%2F" height="61" width="51" /></a>
</div>
<p>I have been re-architecting this new project. This is huge. And broken. And I was called upon to clean, refactor and re-architect it. Phew!</p>
<p>I thought a good strategy would be to deal with it in outside-in style, which is, fixing the build part first then moving down to various parts. One of the interesting things that they had done was using <a href="http://maven.apache.org/" target="_blank">Maven</a> to populate <a href="http://www.postgresql.org/" target="_blank">PostgreSQL</a> DB Schemas and then load data into the DB. </p>
<h2>Steps of execution</h2>
<ol>
<li>Drop everything</li>
<li>Create users</li>
<li>Create schemas</li>
<li>Load data</li>
<li>Load upgrade data</li>
</ol>
<p>They used <a href="http://mojo.codehaus.org/sql-maven-plugin/" target="_blank">sql-maven-plugin</a> underwhich they had multiple execution tasks. The whole thing was very untidy and I didn’t like it. </p>
<h2>Summary</h2>
<ol>
<li>They used <strong>&lt;fileSets&gt;</strong> to import sql files. FileSets are an elegant choice if you want to import files with ANT like wildcard patterns. But the files are alphabetically sorted. So, unless you don’t care about the order in which the files will be executed, you should avoid using FileSets. In their case, they wanted to run ‘<strong>drop_users_databases.sql</strong>’ before ‘<strong>create_users_databases.sql</strong>’. With FileSets, it was impossible to do, they would be re-ordered just the opposite. Solution? They should have used <strong>&lt;srcFiles&gt;</strong>, but instead they created 2 separate <strong>&lt;execution&gt;</strong> tasks to run in order. Too much verbosity. Eh?</li>
<li>Another issue was with loading upgrade data. Now, they follow agile methodologies and keep updating their DB schemas, and so after few iterations, before they merge the changes in the main script, they end up with a number of files like <strong>upgrade-schema-2.0.4.sql</strong>, <strong>upgrade-schema-2.0.5.sql</strong>, <strong>upgrade-schema-2.0.5.1.sql</strong> and so on. Pain is, they don’t have any automated mechanism to execute these files in order, so the developers would be forced to do it manually. If the number of these files were low, that wouldn’t have been a problem… but how about thirty or forty such files? Pissed off.</li>
</ol>
<h2>Strategy</h2>
<ol>
<li>Kick &lt;fileSets&gt; out of the window</li>
<li>Use &lt;srcFiles&gt; instead (because I cared more about order)</li>
<li>Logically partition the operations</li>
<li>Create a new profile to help run these DB executions at will</li>
</ol>
<h2>Code</h2>
<p><pre class="brush: xml;">
&lt;profiles&gt;  
&lt;profile&gt;  
	&lt;!-- profile id --&gt;
	&lt;id&gt;init-db&lt;/id&gt; 
	&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
				&lt;artifactId&gt;sql-maven-plugin&lt;/artifactId&gt;
				
				&lt;!-- postgresql dependencies --&gt;	
				&lt;dependencies&gt;
				  &lt;dependency&gt;
					&lt;groupId&gt;postgresql&lt;/groupId&gt;
					&lt;artifactId&gt;postgresql&lt;/artifactId&gt;
					&lt;version&gt;8.3-603.jdbc4&lt;/version&gt;
					&lt;scope&gt;clean&lt;/scope&gt;
				  &lt;/dependency&gt;
				&lt;/dependencies&gt;
				
				&lt;!-- DB Configuration --&gt;
				&lt;configuration&gt;
					&lt;url&gt;jdbc:postgresql:my_db&lt;/url&gt;
					&lt;driver&gt;org.postgresql.Driver&lt;/driver&gt;
					&lt;username&gt;user&lt;/username&gt;
					&lt;password&gt;pass&lt;/password&gt;
					&lt;autocommit&gt;true&lt;/autocommit&gt;							
				&lt;/configuration&gt;
				
				&lt;executions&gt;
					&lt;!-- 1. drop everything, create users and load data --&gt;
					&lt;execution&gt;
						&lt;id&gt;drop-and-create-database&lt;/id&gt;
						&lt;phase&gt;clean&lt;/phase&gt;
						&lt;goals&gt;&lt;goal&gt;execute&lt;/goal&gt;&lt;/goals&gt;
						&lt;configuration&gt;
							&lt;srcFiles&gt;
								&lt;srcFile&gt;src/main/sql/drop_users_databases.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/create_users_databases.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/create_schema.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/load_data.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/test_data.sql&lt;/srcFile&gt;						
							&lt;/srcFiles&gt;    															
						&lt;/configuration&gt;
					&lt;/execution&gt;			
					&lt;!-- 2. run all upgrade scripts --&gt;
					&lt;execution&gt;
						&lt;id&gt;upgrade-schema&lt;/id&gt;
						&lt;phase&gt;clean&lt;/phase&gt;
						&lt;goals&gt;&lt;goal&gt;execute&lt;/goal&gt;&lt;/goals&gt;
						&lt;configuration&gt;
							&lt;srcFiles&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-2.0.6.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/upgrade-schema-2.1.5.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/upgrade-schema-2.1.7.sql&lt;/srcFile&gt;						
								&lt;srcFile&gt;src/main/sql/upgrade-schema-2.1.8.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-2.2.1.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.0.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.1.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.2.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.3.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.4.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.5.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.6.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.6.1.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.8.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.9.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.10.sql&lt;/srcFile&gt;
								&lt;srcFile&gt;src/main/sql/upgrade-schema-3.0.11.sql&lt;/srcFile&gt;
							&lt;/srcFiles&gt;    						
						&lt;/configuration&gt;
					&lt;/execution&gt;
				&lt;/executions&gt; 
			&lt;/plugin&gt;
		&lt;/plugins&gt;  
	&lt;/build&gt;  
&lt;/profile&gt;  
&lt;/profiles&gt;  	  
</pre></p>
<h2>How to run?</h2>
<p>Note that I have bound the executions with phase &#8216;clean&#8217; within a profile with id &#8216;init-db&#8217;. So, I just need to let maven know about the phase and profile, like this:</p>
<p><pre class="brush: xml;">mvn -Pinit-db clean</pre></p>
<p>I hope this will help someone in need. I will post more adventurous code cleaning stuffs as I will encounter them. Cheers! </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/filesets/'>fileSets</a>, <a href='http://anismiles.wordpress.com/tag/maven/'>Maven</a>, <a href='http://anismiles.wordpress.com/tag/maven-ordered-sql-execution/'>maven ordered sql execution</a>, <a href='http://anismiles.wordpress.com/tag/postgres/'>Postgres</a>, <a href='http://anismiles.wordpress.com/tag/sql/'>SQL</a>, <a href='http://anismiles.wordpress.com/tag/sql-maven-plugin/'>sql-maven-plugin</a>, <a href='http://anismiles.wordpress.com/tag/srcfiles/'>srcFiles</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/anismiles.wordpress.com/1619/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/anismiles.wordpress.com/1619/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/anismiles.wordpress.com/1619/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/anismiles.wordpress.com/1619/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/anismiles.wordpress.com/1619/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/anismiles.wordpress.com/1619/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/anismiles.wordpress.com/1619/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/anismiles.wordpress.com/1619/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=anismiles.wordpress.com&amp;blog=13717969&amp;post=1619&amp;subd=anismiles&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://anismiles.wordpress.com/2010/12/28/maven-sql-ordered-execution/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>
	</channel>
</rss>
