<?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/"
	>

<channel>
	<title>Thread.currentThread().join()</title>
	<atom:link href="http://www.ashishpaliwal.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ashishpaliwal.com/blog</link>
	<description>From Programmer, For Programmers</description>
	<lastBuildDate>Tue, 23 Aug 2011 03:53:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Updating Google Calendar with MS Project Tasks &#8211; 2 &#8211; Revisited</title>
		<link>http://www.ashishpaliwal.com/blog/2011/08/updating-google-calendar-with-ms-project-tasks-2-revisited/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/08/updating-google-calendar-with-ms-project-tasks-2-revisited/#comments</comments>
		<pubDate>Tue, 23 Aug 2011 03:53:36 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Application Programming]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Google Calendar]]></category>
		<category><![CDATA[MS Project]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=648</guid>
		<description><![CDATA[This is the 2nd part in the series. Please refer to Updating Google Calendar with MS Project Tasks - Revisited for Part 1, including how to build the code. In the previous post we saw, how to list all the Calendar's. In this post we shall build upon the code to list all the calendar's [...]]]></description>
			<content:encoded><![CDATA[<p>This is the 2nd part in the series. Please refer to <a href="http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/">Updating Google Calendar with MS Project Tasks - Revisited</a> for Part 1, including how to build the code.</p>
<p>In the previous post we saw, how to list all the Calendar's. In this post we shall build upon the code to list all the calendar's for a given user account, and update the MS Project tasks to the selected calendar.</p>
<p>We shall need to following three steps:</p>
<ul>
<li>List Calendars and select one</li>
<li>Parse MS Project tasks and convert them to Calendar events</li>
<li>Update Google Calendar with Events</li>
</ul>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h3>Step 1: List All calendar's</h3>
<p>We have already seen the code for this in previous <a href="http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited">post</a></p>
<h3> Step 2: Parse MS Project task and convert to Calendar Event</h3>
<p>Lets look at the code for the conversion</p>
<pre class="brush: java">
protected CalendarEventEntry convertTaskToCalenderEntry(Task task) {
    System.out.println(&quot;Task &quot;+task);
    CalendarEventEntry eventEntry = new CalendarEventEntry();
    eventEntry.setTitle(new PlainTextConstruct(task.getName()));

    When date = new When();
    date.setStartTime(new DateTime(task.getStart()));
    eventEntry.addTime(date);
    return eventEntry;
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
The code takes Start and End date of task, as well as title, and creates an CalendarEventEntry for the same. There can be additional logic built into this, like filtering events based on some rules etc.</p>
<h3> Step 3: Updating entries into Google Calendar </h3>
<pre class="brush: java">
public void updateCalenderWithEntry(List&lt;Task&gt; tasks, CalendarService calendarService, URL url) {
    for (Task task : tasks) {
        CalendarEventEntry entry = convertTaskToCalenderEntry(task);
        try {
            calendarService.insert(url, entry);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
Here we just iterate through the tasks and update the events using CalendarService. The Calendar URL can be retrieved from the CalendarEntry class.</p>
<p>A complete working example is part of com.ashishpaliwal.mpputils.examples.MppToGoogleCalendar</p>
<h4>Using the sample program</h4>
<p>>com.ashishpaliwal.mpputils.examples.MppToGoogleCalendar [MPP File] [Google User Name] [password]</p>
<h3>What's Next?</h3>
<p>Eager to hear from user, what they would like to see. Adding a UI and out-of-box working package is something that would be good. However, please do try using this and I shall try my best to improve this.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/08/updating-google-calendar-with-ms-project-tasks-2-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hunting down CPU hogging Java Thread</title>
		<link>http://www.ashishpaliwal.com/blog/2011/08/finding-java-thread-consuming-high-cpu/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/08/finding-java-thread-consuming-high-cpu/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 21:48:21 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[CPU]]></category>
		<category><![CDATA[Thread]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=632</guid>
		<description><![CDATA[Most of us have encountered a situation to find cause of high CPU usage in Java application. Profiling is the best way, but at times running Profiler in production is not an option. Fortunately, there is a simple way, if you are running your app on *nix. Lets explore how to find this. Find the [...]]]></description>
			<content:encoded><![CDATA[<p>Most of us have encountered a situation to find cause of high CPU usage in Java application. Profiling is the best way, but at times running Profiler in production is not an option. Fortunately, there is a simple way, if you are running your app on *nix.</p>
<p>Lets explore how to find this.</p>
<ul>
<li>Find the pid of the application, using <em>top</em> or <em>jps</em> command</li>
<li>Once you get the pid, run following command<br />
   <strong><strong>$ ps -L pid</strong></strong>
</li>
<p>We get an output as shown in the figure<br />
<div id="attachment_635" class="wp-caption aligncenter" style="width: 410px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/08/Screen-shot-2011-08-10-at-2.39.54-AM1.png"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/08/Screen-shot-2011-08-10-at-2.39.54-AM1.png" alt="" title="ps output" width="400" height="216" class="size-full wp-image-635" /></a><p class="wp-caption-text">ps output</p></div></p>
<p>The output displays all the Threads in the application along with the time spent. Find the Thread that has spent highest time in execution (Entry circled on right). Once we identify this, get the LWP ID of the Thread (Entry circled on left).</p>
<li>Using <em>jstack</em> or <em>visualvm</em>, take a Thread dump.</li>
<li>Convert LWP ID to Hex and search for the ID in Thread dump. </li>
</ul>
<p>Then you can narrow down the thread which is consuming max CPU and investigate further.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/08/finding-java-thread-consuming-high-cpu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Updating Google Calendar with MS Project Tasks &#8211; Revisited</title>
		<link>http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 11:04:51 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Google Calendar]]></category>
		<category><![CDATA[MS Project]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=619</guid>
		<description><![CDATA[Back in 2008, wrote the post on Updating Google Calendar with MS Project. Since then, lot many people had asked for the code, and myself felt that getting the code on github would be great. I shall keep complete the post in 2 parts, starting with setup, listing the calendars and then winding up with [...]]]></description>
			<content:encoded><![CDATA[<p>Back in 2008, wrote the post on <a href="http://www.ashishpaliwal.com/blog/2008/10/updating-google-calendar-with-ms-project-tasks/">Updating Google Calendar with MS Project</a>. Since then, lot many people had asked for the code, and myself felt that getting the code on github would be great. I shall keep complete the post in 2 parts, starting with setup, listing the calendars and then winding up with updating Google Calendar with MS Project entries.</p>
<p>To begin, you can get the code form github at following location</p>
<p><a href="https://github.com/paliwalashish/mpputils">https://github.com/paliwalashish/mpputils</a></p>
<h2>Building the code</h2>
<p>To build the code and download the dependencies, please refer to the wiki page <a href="https://github.com/paliwalashish/mpputils/wiki/Build">https://github.com/paliwalashish/mpputils/wiki/Build</a></p>
<h2> Retrieving Calendar's</h2>
<p>Now lets move to retrieving the list of all the Calendar's for a user<br />
The code is simple enough, here is the function which does the</p>
<pre class="brush: java">
public static List&lt;CalendarEntry&gt; getAllCalendars(String userName, String password) throws Exception {
        CalendarService myService = new CalendarService(&quot;CalendarService-&quot;+userName);
        myService.setUserCredentials(userName, password);

        // Send the request and print the response
        URL feedUrl = new URL(&quot;https://www.google.com/calendar/feeds/default/allcalendars/full&quot;);
        CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);

        return resultFeed.getEntries();
    }
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>This snippet shall return all the Calendar's for the specified user account.</p>
<p>The code has an example of using the same. Please refer to <em><strong>com.ashishpaliwal.mpputils.examples.ListAllCalendars</strong></em> class on the usage.</p>
<p>In the next part we shall see the code for updating of Google Calendar with MS Project task.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60TextOnly */
google_ad_slot = "8279148993";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/07/updating-google-calendar-with-ms-project-revisited/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Simple LRU Cache</title>
		<link>http://www.ashishpaliwal.com/blog/2011/05/a-simple-lru-cache/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/05/a-simple-lru-cache/#comments</comments>
		<pubDate>Fri, 13 May 2011 16:19:37 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=612</guid>
		<description><![CDATA[Recently, while working on a module has a need of very light weight fixed size LRU cache. There are definitely lot of caching solutions around, but decided to try a simple Map based solution. Surprisingly, the solution using LinkedHashMap turned out to be simplest. Here is the snippet. Removed all additional validation and other stuff [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, while working on a module has a need of very light weight fixed size LRU cache. There are definitely lot of caching solutions around, but decided to try a simple Map based solution. Surprisingly, the solution using LinkedHashMap turned out to be simplest.</p>
<p>Here is the snippet. Removed all additional validation and other stuff for simplicity.</p>
<pre class="brush: java">
public class LruCache {
    // cache data holder
    Map&lt;Object, Object&gt; cache;

    // Max size
    private int maxCacheSize;

    public LruCache(int maxSize) {
        this.maxCacheSize = maxSize;
        cache = new LinkedHashMap(maxSize, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() &gt; maxCacheSize;
            }
        };
    }

    public void put(Object key, Object value) {
        cache.put(key, value);
    }

    public Object get(Object key) {
        return cache.get(key);
    }
}
</pre>
<p>The implementation is fairly simple. The third parameter while initialization of LinkedHashMap is the key. a value of "true" means the implementation should use access-order while evicting the entry.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/05/a-simple-lru-cache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Terracotta Toolkit &#8211; Part 4 (Clustered Barrier)</title>
		<link>http://www.ashishpaliwal.com/blog/2011/02/terracotta-toolkit-part-4-clustered-barrier/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/02/terracotta-toolkit-part-4-clustered-barrier/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 08:53:05 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Clustered barrier]]></category>
		<category><![CDATA[Terracotta Toolkit]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=604</guid>
		<description><![CDATA[Recently I had a need to coordinate test drivers across JVM's, so that they all fire the load at the same time. There were many options, needed flexibility in terms that each had its own warm-up time and other dependencies. Terracotta's Clustered Barrier was a natural choice for this. Reason's were simple, I had already [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I had a need to coordinate test drivers across JVM's, so that they all fire the load at the same time. There were many options, needed flexibility in terms that each had its own warm-up time and other dependencies. Terracotta's Clustered Barrier was a natural choice for this. Reason's were simple, I had already seen it working and it was simple enough to integrate it within application.</p>
<p>What you need to run this sample<br />
1. <a href="http://www.terracotta.org/dl/?src=http://www.ashishpaliwal.com/blog">Terracotta Release Download here</a><br />
2. Include terracotta-toolkit-1.1-runtime-2.1.0.jar in classpath. You can find the jar in terracotta_install/common folder</p>
<p>The image below describes the scenario<br />
<div id="attachment_606" class="wp-caption aligncenter" style="width: 431px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/02/Toolkit.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/02/Toolkit.jpg" alt="" title="Scenario" width="421" height="403" class="size-full wp-image-606" /></a><p class="wp-caption-text">Scenario</p></div></p>
<p>Lets see how we use the Toolkit barrier to achieve this</p>
<pre class="brush: java">
public class ClusteredBarrierSample {
    static final String BARRIER_NAME = &quot;RUN_BARRIER&quot;;

    Barrier barrier;

    // Handle to the toolkit
    ClusteringToolkit clusterToolkit = null;

    public void initializeToolKit(String serverAdd, int barrierParties) {
        clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
        barrier = clusterToolkit.getBarrier(BARRIER_NAME, barrierParties);
    }

    /**
     * waits till all the parties have joined and once all drivers are ready
     * fires the test
     */
    public void fireTest() {
        try {
            barrier.await();
            // fire my network drivers
            System.out.println(&quot;firing the driver&quot;);
        } catch (Exception e) {
            e.printStackTrace();
       }
    }

    public static void main(String[] args) {
        ClusteredBarrierSample barrierSample = new ClusteredBarrierSample();
        barrierSample.initializeToolKit(args[0], Integer.parseInt(args[1]));
        barrierSample.fireTest();
    }
}
</pre>
<p>The implementation is straight simple and in 3 steps<br />
1. Intialize Terracotta Client<br />
2. Get the Barrier, with number of parties to wait for<br />
3. Call await() on the barrier</p>
<p>Using it was pretty simple and took less than 5 minutes to have the requirements met <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Next Steps:</p>
<p>Refer <a href="http://www.terracotta.org/documentation/?src=http://www.ashishpaliwal.com/blog">Terracotta Documentation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/02/terracotta-toolkit-part-4-clustered-barrier/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with Cassandra</title>
		<link>http://www.ashishpaliwal.com/blog/2011/01/getting-started-with-cassandra/</link>
		<comments>http://www.ashishpaliwal.com/blog/2011/01/getting-started-with-cassandra/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 13:59:35 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Cassandra]]></category>
		<category><![CDATA[Hector]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=563</guid>
		<description><![CDATA[After spending some time with Cassandra, thought about writing a small post. The post is an attempt to get started with Cassandra quick examples. This post does not try to explain the Data Model. Pre-requisite 1. Cassandra 0.7 2. Cassandra GUI 3. Hector (Cassandra client). You can use any other client with slight modifications You [...]]]></description>
			<content:encoded><![CDATA[<p>After spending some time with Cassandra, thought about writing a small post. The post is an attempt to get started with Cassandra quick examples. This post does not try to explain the Data Model. </p>
<h2>Pre-requisite</h2>
<p>1. <a href="http://cassandra.apache.org/download/">Cassandra 0.7</a><br />
2. <a href="http://code.google.com/p/cassandra-gui/">Cassandra GUI</a><br />
3. <a href="http://prettyprint.me/2010/02/23/hector-a-java-cassandra-client/">Hector</a> (Cassandra client). You can use any other client with slight modifications</p>
<p>You shall need following jars in your classpath (available with downloads above)<br />
1. apache-cassandra-0.7.0.jar<br />
2. hector-core-0.7.0-22.jar<br />
3. slf4j-log4j12-1.6.1.jar<br />
4. slf4j-api-1.6.1.jar<br />
5. libthrift-0.5.jar<br />
6. log4j-1.2.16.jar<br />
7. perf4j-0.9.12.jar<br />
8. high-scale-lib-1.0.jar</p>
<p><strong>NOTE:</strong> I did tweaked the Cassandra GUI to work with Cassandra 0.7. </p>
<p>The reason for using GUI is to see how things are stored within Cassandra and this visualization helps in understanding things faster</p>
<p>We shall explore Cassandra with 3 independent examples. </p>
<p>Downloading the example code from - <a href="https://code.google.com/p/cassandra-examples">https://code.google.com/p/cassandra-examples</a></p>
<p>Lets first do some house keeping stuff like starting Cassandra and applying the schema</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h3>Starting Cassandra</h3>
<p>1. Download and extract Cassandra 0.7<br />
2. Go to Cassandra-install-dir/bin directory<br />
3. Execute following command<br />
    > <strong>cassandra -f</strong></p>
<p>This shall start cassandra in foreground.</p>
<p><strong>NOTE</strong>: We are running Cassandra single node for the sake of simplicity</p>
<h3>Applying the Schema</h3>
<p>The schema used for the examples is part of example code</p>
<p><strong>Steps to apply the schema</strong><br />
1. Keep the schema file (cassandra.yaml) in classpath of Cassandra server like in conf directory<br />
2. Launch jconsole (from JAVA_HOME\bin)<br />
3. Connect to Cassandra</p>
<div id="attachment_571" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/jconsole-connect.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/jconsole-connect-300x295.jpg" alt="JConsole Connect Dialog" title="JConsole Connect Dialog" width="300" height="295" class="size-medium wp-image-571" /></a><p class="wp-caption-text">JConsole Connect Dialog</p></div>
<p>4. Click MBeans tab and navigate to org.apache.cassandra.db.StorageService MBean<br />
5. Expand Operations and click on loadSchemaFromYaml</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<div id="attachment_575" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/loadschema.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/loadschema-300x246.jpg" alt="Load Schema" title="Load Schema" width="300" height="246" class="size-medium wp-image-575" /></a><p class="wp-caption-text">Load Schema</p></div>
<p>6. Clock the button loadSchemaFromYaml in right pane</p>
<p>You shall receive a success message which means schema was loaded.</p>
<p>Lets see how the Schema looks in cassandra-gui</p>
<div id="attachment_580" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/schemaview.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/schemaview-300x229.jpg" alt="Schema View" title="Schema View" width="300" height="229" class="size-medium wp-image-580" /></a><p class="wp-caption-text">Schema View</p></div>
<p>So far so good, lets move to our first sample</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h3>Example 1: Tweets</h3>
<p>When I started with Cassandra, got Tweets examples a lot to learn. So here is my simple Tweet version. For those who are looking for complete Tweet application, <a href="https://github.com/riptano/twissjava">twissjava</a> is the way to go.</p>
<p>This idea of this sample is to store all the tweets that are received giving it a unique id.</p>
<p>The POJO has just three fields</p>
<pre class="brush: java">
public class Tweet implements Serializable {
    private final UUID key;
    private final String uname;
    private final String body;

    public Tweet(UUID key, String uname, String body) {
        this.key = key;
        this.uname = uname;
        this.body = body;
    }

    // Eliminated get/set for clarity
}
</pre>
<p>Now we need to get hold to Cluster. The usage is specific to Hector</p>
<pre class="brush: java">
final static Cluster cluster = HFactory.createCluster(&quot;LogsCluster&quot;,
            new CassandraHostConfigurator(&quot;localhost:9160&quot;));
final static Keyspace keyspace = HFactory.createKeyspace(&quot;LogData&quot;, cluster);
</pre>
<p>These 2 lines gets a reference to the Cassandra cluster and the keyspace we are using. The names have been specified in the cassandra.yaml that we specified.</p>
<p>Now lets see how we save the tweets</p>
<pre class="brush: java">
public void saveTweet(Tweet tweet) {
       Mutator&lt;String&gt; m1 = HFactory.createMutator(keyspace, ss);
        m1.addInsertion(tweet.getKey().toString(),
                              TWEETS,
                              HFactory.createStringColumn(&quot;uname&quot;, tweet.getUname()))
          .addInsertion(tweet.getKey().toString(),
                            TWEETS,
                            HFactory.createStringColumn(&quot;body&quot;, tweet.getBody()));
        m1.execute();
}
</pre>
<p>Here we create a Mutator for the given keyspace and insert the tweet details, like username and tweet data. The column is a UUID, to uniquely identify a tweet and acts as a key.</p>
<p>Now lets see the main function</p>
<pre class="brush: java">
public static void main(String[] args) {

        // Number of Tweets to be stored
        int count = 500;

        TweetSample sample = new TweetSample();
        System.out.println(&quot;Saving Tweets ....&quot;);

        for (int i = 0; i &lt; count; i++) {
            Tweet tweet = new Tweet(UUID.randomUUID(),
                                                 &quot;paliwalashish&quot;,
                                                 &quot;This is tweet# &quot;+ i);
            sample.saveTweet(tweet);
            System.out.println(&quot;Saving Tweet # : &quot;+ i);
        }

        System.out.println(&quot;Tweet Saved....&quot;);
    }
</pre>
<p>This is simple, we create tweet objects and insert them in a loop. So how does our Cassandra data looks after we run this program.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<div id="attachment_583" class="wp-caption aligncenter" style="width: 860px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/tweetsdb.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/tweetsdb.jpg" alt="Tweets DB View" title="Tweets DB View" width="850" height="650" class="size-full wp-image-583" /></a><p class="wp-caption-text">Tweets DB View</p></div>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>As we see for each key (UUID) we have stored two column, username and tweet data.</p>
<h3>Example 2: Saving User Action Log </h3>
<p>This example is very similar to our first example. Here we are storing userid, action and the URL in the DB.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h3>Example 3: Saving Logs per Hour</h3>
<p>In this example we wanted to save Log file per hour so that we can analyze them easily. I choose to use a SuperColumn for this, Day and hour as the keys. There can be other approaches of getting the same functionality. The idea is to have following structure for the logs</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<div id="attachment_591" class="wp-caption aligncenter" style="width: 273px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/2ServerEnv1.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/2ServerEnv1-263x300.jpg" alt="Log Storage" title="Log Storage" width="263" height="300" class="size-medium wp-image-591" /></a><p class="wp-caption-text">Log Storage</p></div>
<p>For each day, we will store logs per hour</p>
<p>Log POJO just has a string message to be saved. Real world scenario can be more sophisticated</p>
<p>Lets see how we add the data to the SuperColumn</p>
<pre class="brush: java">
 public void saveLogs(String tag, String hrTag, Log logMessage) {
       Mutator&lt;String&gt; mutator = HFactory.createMutator(keyspace, ss);
        mutator.insert(tag, LOGS, HFactory.createSuperColumn(hrTag,
                    Arrays.asList(HFactory.createStringColumn(UUID.randomUUID().toString(),
                                     logMessage.getLogMessage())),
                    ss, ss, ss));
        mutator.execute();
    }
</pre>
<p>The calls are essentially similar, but we just add more keys, like tag is Day key (YYYYMMDD), LOGS is the name of the SuperColumn. Inside the SuperColumn, we add log message with a unique id.</p>
<p>Here is how it looks, when stored in Cassandra.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<div id="attachment_585" class="wp-caption aligncenter" style="width: 860px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/logsview.jpg"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2011/01/logsview.jpg" alt="Logs DB View" title="Logs DB View" width="850" height="650" class="size-full wp-image-585" /></a><p class="wp-caption-text">Logs DB View</p></div>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>Cassandra Data Model is slightly tricky to understand in the begining. There are really wondeful posts out there explaining the same. Take some time to read about the Data Model and tweak the examples, and have fun.</p>
<p>Happy Scaling <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-6961884887741817";
/* 468x15LinkUnit */
google_ad_slot = "4400881690";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2011/01/getting-started-with-cassandra/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta Toolkit &#8211; Part 3 (Clustered Map)</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-3-clustered-map/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-3-clustered-map/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 11:40:29 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Clustered Map]]></category>
		<category><![CDATA[Terracotta Toolkit]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=532</guid>
		<description><![CDATA[Did you ever wanted to have a Map which can be clustered across JVM, without doing much work for replicating data, ensuring coherence of data? Terracotta Toolkit allows you to fullfill your dream, Use the same Map API's you have been using for long and see your data being clustered transparently with Terracotta. The fun [...]]]></description>
			<content:encoded><![CDATA[<p>Did you ever wanted to have a Map which can be clustered across JVM, without doing much work for replicating data, ensuring coherence of data? Terracotta Toolkit allows you to fullfill your dream, Use the same Map API's you have been using for long and see your data being clustered transparently with Terracotta. The fun begins, when you add new clients and they have the data with them without any additional programming.</p>
<p>Lets start with some general information about Toolkit. Refer Toolkit javadoc for more details <a href="http://www.terracotta.org/documentation" target="_blank">here</a><br />
<script type="text/javascript">// <![CDATA[
  google_ad_client = "pub-6961884887741817"; /* 468x15, created 8/2/10 */ google_ad_slot = "9956401459"; google_ad_width = 468; google_ad_height = 15;
// ]]&gt;</script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script></p>
<h2>Pre-requisite</h2>
<li>Download Terracotta 3.3.0 from <a href="http://www.terracotta.org/dl/" target="_blank">Download page</a></li>
<li>Include following <em>terracotta-toolkit-1.0-runtime-1.0.0.jar</em> into your classpath for using Toolkit. The jar is present inside Terracotta_Install_dir/common folder.</li>
<p>You can spend some time reading the following posts on Toolkit, although they can be read in any order</p>
<ul>
<li><a href="http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/" target="_blank">Getting Started with Terracotta Toolkit – Part 1</a></li>
<li><a href="http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%E2%80%93-part-2-cluster-events/" target="_blank">Getting Started with Terracotta Toolkit – Part 2 (Cluster Events)</a></li>
</ul>
<p>Lets explore a bit what do we achieve when we say Clustered Map</p>
<div id="attachment_536" class="wp-caption aligncenter" style="width: 414px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map1.png"><img class="size-full wp-image-536" title="Unclustered Map" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map1.png" alt="Unclustered Map" width="404" height="130" /></a><p class="wp-caption-text">Unclustered Map</p></div>
<p>As you can see in the figure above, we have different JVM's, each having a Map instance used by Application. Now if we were to share the same instance across app's running in different nodes, we would have to write a lot of infrastructure code to replicate data, keep data coherent etc.</p>
<div id="attachment_537" class="wp-caption aligncenter" style="width: 394px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map2.png"><img class="size-full wp-image-537" title="Clustered Map" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map2.png" alt="Clustered Map" width="384" height="137" /></a><p class="wp-caption-text">Clustered Map</p></div>
<p>The figure above depicts a Clustered Map. The Map instance is visible to App's across JVM's as if they are accessing a local instance. You can achieve this in a few lines, without worrying about the infrastructure code. Lets see how we can achieve this in few simple steps.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h4>Steps to creare Clustered Map</h4>
<li>Initialize Toolkit</li>
<li>Get a Map reference</li>
<li>Use the Map</li>
<p><br></p>
<h3>Initializing the Toolkit</h3>
<p>Before any operations can be performed using Toolkit, it needs to be initialized first. The initialization code is very simple, just single line</p>
<pre class="brush: java">
ClusteringToolkit clustering = new TerracottaClient(&quot;localhost:9510&quot;).getToolkit();
</pre>
<p>This line initializes the Terracotta Client and gets an instance of Toolkit to work with. The argument passed to the TerracottaClient is the IP Address and Port of the Terracotta Server.</p>
<p>Have created a simple function for initialization of the Toolkit.</p>
<pre class="brush: java">
ClusteringToolkit clusterToolkit = null;

public void initializeToolKit(String serverAdd) {
clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
}
</pre>
<h3>Get/Create the Map</h3>
<pre class="brush: java">
public void initializeMap() {
    clusteredMap = clusterToolkit.getMap(MAP_NAME);
}
</pre>
<p>The code above creates a Clustered Map. There is no more infrastructure code that you have to write. This gives us a Clustered Map reference. The best part is, there are no new API's to be learned, we continue to use the same old Map API's.</p>
<p>Let's see the data class that we would share across the Map.</p>
<pre class="brush: java">
public class SharedData implements Serializable {

    private String data;

    public SharedData(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
</pre>
<p>Its a no-brainer class. Just a simple class for demonstration purpose.</p>
<p>Just to keep life simple, we are going to create a function which populates the Map, and the Nodes can then consume the populated data. Consume here would mean just call a get() and print. In real life scenario, you can mutate the data, and the updated data shall be visible across the cluster.</p>
<p>Lets see the populate function</p>
<pre class="brush: java">
protected void populateMap(int objectCount) {
        for(int i = 0; i &lt; objectCount; i++) {
            SharedData data = new SharedData(&quot;&quot;+i);
            clusteredMap.put(i, data);
        }
    }
</pre>
<p>Its a simple function which just puts the data in the Map.</p>
<p>Lets look at the consume function</p>
<pre class="brush: java">
 protected void consumeMapData(int maxObjectId) {
        Range range = new Range(1, maxObjectId);
        while(true) {
            long key = range.getRandomKey();
            byte[] dataBytes = clusteredMap.get((int)key);
            System.out.println(&quot;Key = &quot;+key);
            if(dataBytes == null) {
                System.out.println(&quot;OOPS!.. somethings wrong dude...&quot;);
                return;
            }
            SharedData data = (SharedData)deserializeObject(dataBytes);
            if(data != null) {
                System.out.println(&quot;Data = &quot;+data.getData());
            }
            try {
                // Sleep for 5 secs
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
</pre>
<p>The function just takes a random key and call a get on the map.</p>
<p>To run this implementation, we would have 3 Nodes running, 1 producer and 2 consumer. The picture below gives an idea of the topology.<br />
<div id="attachment_540" class="wp-caption aligncenter" style="width: 411px"><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map3.png"><img src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Toolkit3-Map3.png" alt="Runtime Topology" title="Runtime Topology" width="401" height="130" class="size-full wp-image-540" /></a><p class="wp-caption-text">Runtime Topology</p></div></p>
<p><em>To run the implementation</em></p>
<li>Start Terracotta Server</li>
<li>Start Producer</li>
<li>Start one or more Consumer</li>
<p>You can get the complete source of the sample <a href="http://code.google.com/p/terracotta-samples/">here</a></p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x60ImageOnly */
google_ad_slot = "0221726572";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-3-clustered-map/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta Toolkit – Part 2 (Cluster Events)</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%e2%80%93-part-2-cluster-events/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%e2%80%93-part-2-cluster-events/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 07:52:58 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>
		<category><![CDATA[Terracotta Toolkit]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=513</guid>
		<description><![CDATA[In the last post we saw Terracotta toolkit Queue. In this Part, lets explore Cluster Events. Cluster Events are propagated across the Terracotta Cluster, whenever specific event happens inside the Cluster. In this post we shall explore what are the different types of Events available. Cluster Events As of 3.3.0, following are the four Events [...]]]></description>
			<content:encoded><![CDATA[<p>In the last post we saw Terracotta toolkit Queue. In this Part, lets explore Cluster Events. Cluster Events are propagated across the Terracotta Cluster, whenever specific event happens inside the Cluster. In this post we shall explore what are the different types of Events available.</p>
<h3>Cluster Events</h3>
<p>As of 3.3.0, following are the four Events that are available</p>
<ul>
<li>Node Joined</li>
<li>Node Left</li>
<li>Operations Enabled</li>
<li>Operations Disabled</li>
</ul>
<p>So what do we need to do, in order to receive these events? Just two simple steps</p>
<ul>
<li>Implement ClusterListener</li>
<li>Register the Listener with toolkit</li>
</ul>
<h2>Pre-requisite</h2>
<li>Download Terracotta 3.3.0 from <a href="http://www.terracotta.org/dl/" target="_blank">Download page</a></li>
<li>Include following <em>terracotta-toolkit-1.0-runtime-1.0.0.jar</em> into your classpath for using Toolkit. The jar is present inside Terracotta_Install_dir/common folder.</li>
<h4>Implementing ClusterListener</h4>
<p>Here is the code</p>
<pre class="brush: java">
class MyClusterListener implements ClusterListener {

        public void nodeJoined(ClusterEvent clusterEvent) {
            try {
                System.out.println(&quot;Event Type = &quot;+clusterEvent.getType());
                System.out.println(&quot;Node Joined &quot;+clusterEvent.getNode().getId()
                        + &quot;, IP=&quot;+clusterEvent.getNode().getAddress());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        public void nodeLeft(ClusterEvent clusterEvent) {
            try {
                System.out.println(&quot;Node Left &quot;+clusterEvent.getNode().getId()
                        + &quot;, IP=&quot;+clusterEvent.getNode().getAddress());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

        public void operationsEnabled(ClusterEvent clusterEvent) {
            System.out.println(&quot;Operations Enabled&quot;);
        }

        public void operationsDisabled(ClusterEvent clusterEvent) {
            System.out.println(&quot;Operations Disabled&quot;);
        }
    }
</pre>
<p>As you can see, the implementation is pretty simple. Now its time to register the listener</p>
<pre class="brush: java">
ClusterInfo clusterInfo = clusterToolkit.getClusterInfo();
clusterInfo.addClusterListener(new MyClusterListener());
</pre>
<p>Get the complete code <a href=" http://code.google.com/p/terracotta-samples/">here</a></p>
<p>Time to see the implementation in Action</p>
<ul>
<li>Start Terracotta Server</li>
<li>Start the Listener</li>
<li>Start/Stop Terracotta Clients and see the events being received</li>
</ul>
<p>There can be some innovative things that can be done inside the ClusterListener. For ex, you can send SNMP Traps to your management system for nodeJoined or nodeLeft events. </p>
<p>Stay tuned for more on Terracotta Toolkit...</p>
<p>Looking for more details, you find them here</p>
<li><a href="http://www.terracotta.org/documentation/ga/product-documentation">Terracotta Documentation</a></li>
<li><a href="http://www.terracotta.org/documentation/javadocs/terracotta-toolkit/">Terracotta Toolkit Javadoc </a></li>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-%e2%80%93-part-2-cluster-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Introducing Apache Vysper</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/introducing-apache-vysper/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/introducing-apache-vysper/#comments</comments>
		<pubDate>Wed, 04 Aug 2010 09:23:52 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Apache MINA]]></category>
		<category><![CDATA[Vysper]]></category>
		<category><![CDATA[Apache Vysper]]></category>
		<category><![CDATA[MINA]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=486</guid>
		<description><![CDATA[Apache Vysper aims to be a fully compliant XMPP Server. It's a sub-project of Apache MINA. Currently its latest release is 0.5 and work is in progress for 0.6 release. It already has an implementation of XEP0045 (Multi User Chat) and XEP0060 (Publish-Subscribe) extensions. Lets see it in action. Pre-requisite Download Apache Vysper from http://mina.apache.org/vysper/downloads.html [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://mina.apache.org/vysper/">Apache Vysper</a> aims to be a fully compliant XMPP Server. It's a sub-project of <a href="http://mina.apache.org">Apache MINA</a>. Currently its latest release is 0.5 and work is in progress for 0.6 release.  It already has an implementation of XEP0045 (Multi User Chat) and XEP0060 (Publish-Subscribe) extensions. Lets see it in action.</p>
<h3>Pre-requisite</h3>
<p>Download Apache Vysper from http://mina.apache.org/vysper/downloads.html</p>
<p>Vysper can be run in standalone mode as well as in an embedded mode.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h3>Running as Standalone Server</h3>
<p>Goto the bin directory and execute</p>
<p><em>run.sh</em></p>
<p>The Server shall start <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/vysperrun.png"><img class="aligncenter size-medium wp-image-488" title="vysperrun" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/vysperrun-300x149.png" alt="" width="300" height="149" /></a></p>
<h3>Running in an Embedded Mode</h3>
<p>Embedding Vysper into your own App is easy. Here is a glimpse</p>
<pre class="brush: java">
XMPPServer server = new XMPPServer(&quot;myembeddedjabber.com&quot;);
server.start();
</pre>
<p>There is still some glue code needed to get the Server function completely. Rather than me duplicating the stuff, please refer http://mina.apache.org/vysper/embed-into-another-application.html</p>
<p>Looks Interesting ! Give Vysper a try and let us know about your experience.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/08/introducing-apache-vysper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with Terracotta Toolkit &#8211; Part 1</title>
		<link>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/</link>
		<comments>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 10:09:55 +0000</pubDate>
		<dc:creator>ashish</dc:creator>
				<category><![CDATA[Terracotta]]></category>

		<guid isPermaLink="false">http://www.ashishpaliwal.com/blog/?p=457</guid>
		<description><![CDATA[Terracotta Toolkit was released as part of Terracotta 3.3.0. The Toolkit is a delight for developers working on Scalable Apps, Frameworks. For more details on features of Toolkit, refer this link. In this post we shall work out a few samples using the Toolkit. We shall start with looking at Cluster Events, Clustered Queues and [...]]]></description>
			<content:encoded><![CDATA[<p>Terracotta Toolkit was released as part of Terracotta 3.3.0. The Toolkit is a delight for developers working on Scalable Apps, Frameworks. For more details on features of Toolkit, refer this <a href="http://www.terracotta.org/documentation/ga/toolkit.html#432369256_pgfId-1175126">link</a>.<br />
In this post we shall work out a few samples using the Toolkit.  We shall start with looking at Cluster Events, Clustered Queues and move to clustered Locks.</p>
<p>Lets start with some general information about Toolkit. Refer Toolkit javadoc for more details <a href="http://www.terracotta.org/documentation" target="_blank">here</a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h2>Pre-requisite</h2>
<li>Download Terracotta 3.3.0 from <a href="http://www.terracotta.org/dl/" target="_blank">Download page</a></li>
<li>Include following <em>terracotta-toolkit-1.0-runtime-1.0.0.jar</em> into your classpath for using Toolkit. The jar is present inside Terracotta_Install_dir/common folder.</li>
<h2>Initializing the Toolkit</h2>
<p>Before any operations can be performed using Toolkit, it needs to be initialized first. The initialization code is very simple, just single line</p>
<pre class="brush: java">
ClusteringToolkit clustering = new TerracottaClient(&quot;localhost:9510&quot;).getToolkit();
</pre>
<p>This line initializes the Terracotta Client and gets an instance of Toolkit to work with. The argument passed to the TerracottaClient is the IP Address and Port of the Terracotta Server.</p>
<p>Have created a simple function for initialization of the Toolkit.</p>
<pre class="brush: java">
ClusteringToolkit clusterToolkit = null;

public void initializeToolKit(String serverAdd) {
clusterToolkit = new TerracottaClient(serverAdd).getToolkit();
}
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<h2>Playing with Toolkit Queue</h2>
<p>Toolkit provide various Data structures that you can use, Queue being one of them.</p>
<p>Lets try and create a Producer-Consumer sample, using Toolkit Queue. Here is what we are trying to do</p>
<p><a href="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Queue1.png"><img class="aligncenter size-medium wp-image-468" title="Queue" src="http://www.ashishpaliwal.com/blog/wp-content/uploads/2010/08/Queue1-300x137.png" alt="" width="300" height="137" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
We have a producer which is going to produce some work, and the consumer shall process the work in different JVM's.</p>
<p>To achieve we need to do the following</p>
<ul>
<li>Create a Work object which shall be pushed by Producer to consumers.</li>
<li>We need to create a Producer that shall produce the work</li>
<li>We need to create a Consumer which shall consume the work. We can have multiple instances of Consumers</li>
</ul>
<p>Lets have a look at Work Object</p>
<pre class="brush: java">
class Work implements Serializable, Runnable {
private String workItem;

Work(String workItem) {
this.workItem = workItem;
}

public String getWorkItem() {
return workItem;
}

public void setWorkItem(String workItem) {
this.workItem = workItem;
}

public void run() {
System.out.println(Thread.currentThread().getName() + &quot;processing - &quot;+getWorkItem());
}
}
</pre>
<p><strong>NOTE:</strong> The Objects that shall be pushed onto the Queue should implement Serializable.</p>
<p>What we have done here. Its a very simple implementation, where we just print what the Producer pushed.<br />
Implementing Runnable is not necessary. I just added it so that I can push the work unit directly to an Executor</p>
<h3>Creating Producer</h3>
<pre class="brush: java">

static final String QUEUE_NAME = &quot;DATA_QUEUE&quot;;

public void startProducer(int capacity) {
BlockingQueue&lt;byte[]&gt; queue = clusterToolkit.getBlockingQueue(QUEUE_NAME, capacity);
System.out.println(&quot;Starting Producer....&quot;);
int i = 0;
while (i &lt; capacity) {
queue.add(serializeObject(new Work(&quot;&quot;+i++)));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</pre>
<p>Creating a clustered Queue is a one line job. We have already initialized the Toolkit, now we just call getBlockingQueue() API from the toolkit, and we get a Distributed Queue backed by Terracotta <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
After creating the Queue, we keep on adding work to the queue till its capacity is reached.</p>
<h3>Creating Consumer</h3>
<pre class="brush: java">
public void startConsumer(int capacity) {
BlockingQueue&lt;byte[]&gt; queue = clusterToolkit.getBlockingQueue(QUEUE_NAME, capacity);

// Lets add some threads to consumer
ExecutorService executors = Executors.newFixedThreadPool(5);

// a dumb way for a loop
while(true) {
try {
executors.execute((Work)deserializeObject(queue.take()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</pre>
<p>Aha! no difference in creation, the only difference is our Consumer calls take() API on the Queue to consume the work objects. Here we have a fixed size Thread pool that keep consuming the work that the producer is pushing.</p>
<p>This is it. Our implementation is complete <img src='http://www.ashishpaliwal.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  We are ready to run the sample. To execute we need to do three steps</p>
<ul>
<li>Start Terracotta Server</li>
<li>Start Producer</li>
<li>Start one or more Consumers</li>
</ul>
<p>See them in action yourself.</p>
<p>The complete code can be found at http://code.google.com/p/terracotta-samples/</p>
<p>Some ideas around what can we do with Distributed queue<br />
1. Distributed SEDA stages across JVM's<br />
2. Distributed Task processing<br />
... add your own ideas..</p>
<p>Would be interested in knowing what you do around Terracotta Toolkit Queue. Please do add comments with your implementations.</p>
<h3>What's Next?</h3>
<p>In the next post we shall be exploring more about the Cluster Events as part of Terracotta Toolkit.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-6961884887741817";
/* 468x15, created 8/2/10 */
google_ad_slot = "9956401459";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ashishpaliwal.com/blog/2010/08/getting-started-with-terracotta-toolkit-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

