<?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>Meetu Maltiar&#039;s Weblogs</title>
	<atom:link href="http://meetumaltiar.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://meetumaltiar.wordpress.com</link>
	<description>Meetu&#039;s thoughts on technology and software development</description>
	<lastBuildDate>Fri, 30 Dec 2011 12:25:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='meetumaltiar.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Meetu Maltiar&#039;s Weblogs</title>
		<link>http://meetumaltiar.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://meetumaltiar.wordpress.com/osd.xml" title="Meetu Maltiar&#039;s Weblogs" />
	<atom:link rel='hub' href='http://meetumaltiar.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Using Akka Dispatchers In Scala</title>
		<link>http://meetumaltiar.wordpress.com/2011/09/24/using-akka-dispatchers-in-scala/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/09/24/using-akka-dispatchers-in-scala/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 14:29:04 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Akka]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=955</guid>
		<description><![CDATA[Akka dispatchers are extremely important in Akka framework. They are directly responsible for optimal performance, throughput and scalability. Akka supports dispatchers for both event-driven lightweight threads and thread-based Actors. For thread-based Actors each dispatcher is bound to a dedicated OS thread. Default dispatcher is a single event-based dispatcher for all Actors created. The dispatcher used [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=955&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://akka.io/docs/akka/1.1.1/scala/dispatchers.html" title="Akka Dispatchers" target="_blank">Akka dispatchers</a> are extremely important in Akka framework. They are directly responsible for optimal performance, throughput and scalability.</p>
<p>Akka supports dispatchers for both event-driven lightweight threads and thread-based Actors. For thread-based Actors each dispatcher is bound to a dedicated OS thread.</p>
<p>Default dispatcher is a single event-based dispatcher for all Actors created. The dispatcher used is this one:<br />
<pre class="brush: scala;">
Dispatchers.globalExecutorBasedEventDrivenDispatcher
</pre></p>
<p>For many cases it becomes mandatory to group Actors together for a dedicated dispatcher, then we can override the defaults and define our own dispatcher.</p>
<p><strong>Setting the Dispatcher</strong><br />
Normally we set the dispatcher in Actor itself<br />
<pre class="brush: scala;">
class EchoActor extends Actor {
     self.dispatcher = ..... // set the dispatcher
}
</pre><br />
Or we can set it in the ActorRef<br />
<pre class="brush: scala;">
actorRef.dispatcher = dispatcher
</pre></p>
<p>There are different kind of dispatchers</p>
<ul>
<li>Thread-based</li>
<li>Event-based</li>
<li>Priority event-based</li>
<li>Work-stealing</li>
</ul>
<p><strong>Thread-based</strong><br />
It binds dedicated OS thread to each Actor. The messages are posted to LinkedBlockingQueue which feeds messages to dispatcher one by one. It has worst performance and scalability.  We also cannot share it among actors. Although Actors do not block for threads in this case.<br />
Code example<br />
<pre class="brush: scala;">
class EchoActor extends Actor {
     self.dispatcher = Dispatchers.newThreadBasedDispatcher(self)
     ....
}
</pre></p>
<p><strong>Event-based</strong><br />
The ExecutorBasedEventDrivenDispatcher binds a set of Actors to a thread pool backed up by a BlockingQueue. The dispatcher must be shared among Actors. This dispatcher is highly configurable and here we can specify things like &#8216;type of queue&#8217;, &#8216;max items&#8217; , &#8216;rejection-policy&#8217;.<br />
Code example<br />
<pre class="brush: scala;">
class EchoActor extends Actor {
self.dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(name)
 .withNewThreadPoolWithLinkedBlockingQueueWithCapacity(100)
 .setCorePoolSize(16)
 .setMaxPoolSize(128)
 .setKeepAliveTimeInMillis(60000)
 .setRejectionPolicy(new CallerRunsPolicy)
 .build
 ....
}
</pre></p>
<p><strong>Priority event-based</strong><br />
It is meant for handling messages when priorities are assigned to messages. It is done by using PriorityExecutorBasedEventDrivenDispatcher. It requires a PriorityGenerator as an attribute in its constructor.</p>
<p>Let&#8217;s look at an example where we have a PriorityExecutorBasedEventDrivenDispatcher used for a group of messages fired on an actor.</p>
<p><pre class="brush: scala;">
package com.meetu.akka.dispatcher

import akka.actor.Actor.actorOf
import akka.actor.Actor
import akka.dispatch.PriorityExecutorBasedEventDrivenDispatcher
import akka.dispatch.PriorityGenerator

object PriorityDispatcherExample extends App {
  val actor = Actor.actorOf(
    new Actor {
      def receive = {
        case x =&gt; println(x)
      }
    })

  val priority = PriorityGenerator {
    case &quot;high priority&quot; =&gt; 0
    case &quot;low priority&quot; =&gt; 100
    case _ =&gt; 50
  }

  actor.dispatcher = new PriorityExecutorBasedEventDrivenDispatcher(&quot;foo&quot;, priority)

  actor.start
  actor.dispatcher.suspend(actor)

  actor ! &quot;low priority&quot;
  actor ! &quot;others&quot;
  actor ! &quot;low priority&quot;
  actor ! &quot;high priority&quot;

  actor.dispatcher.resume(actor)
  Actor.registry.shutdownAll
}
</pre></p>
<p><span id="more-955"></span></p>
<p>If we execute the code, high-priority messages are served first even when low-priority fired before the high-priority messages. This is how the output will appear if executed by <a href="https://github.com/harrah/xsbt" title="xsbt" target="_blank">sbt</a> on command line:</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/09/prioritydispatcherexample.png"><img src="http://phithoughts.files.wordpress.com/2011/09/prioritydispatcherexample.png?w=700" alt="" title="PriorityDispatcherExample"   class="alignleft size-full wp-image-2430" /></a></p>
<p><strong>Work-stealing</strong><br />
‘ExecutorBasedEventDrivenWorkStealingDispatcher’ is one of my favorite dispatcher. It redistributes work to actors that use the same dispatcher and that do not currently have any messages the mailbox. It is a great way to increase performance of the system.</p>
<p>Usual way to use it is to create an Actor companion object to hold the dispatcher and then set it in Actor explicitly.</p>
<p>Lets look at the code example which uses this dispatcher.</p>
<p><pre class="brush: scala;">
package com.meetu.akka.dispatcher

import akka.actor.Actor
import akka.actor.Actor._
import akka.dispatch.Dispatchers

object WorkStealingDispatcherExample extends App {
  val actor = actorOf[SimpleActor]
  actor.start
  actor ! &quot;Hello&quot;
  Actor.registry.shutdownAll
}

object SimpleActor {
  val dispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher(&quot;executordispatcher&quot;).build
}

class SimpleActor extends Actor {
  self.dispatcher = SimpleActor.dispatcher
  def receive = {
    case msg =&gt; println(msg)
  }
}
</pre></p>
<p>Now lets have a look at a code listing for ExecutorDispatcherApplicationExample. It&#8217;s constituents are a Scala Object ExecutorDispatcherApplicationExample. Two Pairs of Scala Class and Object (Object is there to share dispatchers) and last three case classes which corresponds to message passing between Actors. Functionally ProcessorUsingExecutorBasedDispatcher is a master actor as it spawns workers and ProcessorUsingExecutorBasedDispatcherWorker is a worker.</p>
<p><pre class="brush: scala;">package com.meetu.akka.dispatcher

import akka.actor.Actor.actorOf
import akka.actor.Actor
import akka.dispatch.Dispatchers
import akka.routing.CyclicIterator
import akka.routing.Routing

object ExecutorDispatcherApplicationExample extends App {
  val processorUsingExecutorBasedDispatcher = actorOf[ProcessorUsingExecutorBasedDispatcher]
  processorUsingExecutorBasedDispatcher.start
  processorUsingExecutorBasedDispatcher ! new SimpleMessage(&quot;Hello Actor!!&quot;)
}

object ProcessorUsingExecutorBasedDispatcher {
  val dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(&quot;ed1&quot;).setCorePoolSize(10).setMaxPoolSize(10).build
}

class ProcessorUsingExecutorBasedDispatcher extends Actor {
  self.dispatcher = ProcessorUsingExecutorBasedDispatcher.dispatcher
  var startTime: Long = -1
  var parallelCounter: Int = 1000

  def receive = {
    case SimpleReply =&gt; {
      parallelCounter -= 1
      if (parallelCounter == 0) {
        val endTime = System.currentTimeMillis
        println(&quot;Total Time:: &quot; + (endTime - startTime))
        Actor.registry.shutdownAll
      }
    }

    case SimpleMessage(msg) =&gt;
      startTime = System.currentTimeMillis
      val workers = Vector.fill(15)(actorOf[ProcessorUsingExecutorBasedDispatcherWorker].start)
      val router = Routing.loadBalancerActor(CyclicIterator(workers)).start
      for (i &lt;- 0 until parallelCounter) {
        router ! new SimpleRequest(msg)
      }
  }
}

object ProcessorUsingExecutorBasedDispatcherWorker {
  val dispatcher = Dispatchers.newExecutorBasedEventDrivenDispatcher(&quot;ed2&quot;).setCorePoolSize(10).setMaxPoolSize(10).build
}

class ProcessorUsingExecutorBasedDispatcherWorker extends Actor {
  self.dispatcher = ProcessorUsingExecutorBasedDispatcherWorker.dispatcher
  def receive = {
    case SimpleRequest(msg) =&gt; {
      val sleepTime = java.lang.Math.random() * 510
      Thread.sleep(sleepTime.toLong)
      self reply SimpleReply
    }
  }
}
</pre></p>
<p>The Application ExecutorDispatcherApplicationExample starts the ProcessorUsingExecutorBasedDispatcher Actor and passes a SimpleMessage to it.</p>
<p>ProcessorUsingExecutorBasedDispatcher Actor uses ExecutorBasedDispatcher and it does so by using a companion object. Please notice that the dispatcher of the object is assigned to self.<br />
<pre class="brush: scala;">
...
self.dispatcher = ProcessorUsingExecutorBasedDispatcher.dispatcher
...
</pre></p>
<p>The receiving block in ProcessorUsingExecutorBasedDispatcher &#8220;case SimpleMessage(msg) =&gt;&#8221; starts the workers and a Router over it. It also finally fires &#8220;parallelCounter&#8221; number of messages to the router.</p>
<p>The Worker Actor ProcessorUsingExecutorBasedDispatcherWorker also uses ExecutorBasedDispatcher. Its received block &#8220;case SimpleRequest(msg) =&gt;&#8221; replies back to ProcessorUsingExecutorBasedDispatcher after sleeping off for a while.</p>
<p>The Actor ProcessorUsingExecutorBasedDispatcher receives the response and it continue to receive it till all responses are received from Worker Actor. Finally it calculates total time elapsed for parallel process execution.</p>
<p>We also can code this using Work Stealing Dispatcher. The complete code example is given below:</p>
<p><pre class="brush: scala;">
package com.meetu.akka.dispatcher

import akka.actor.Actor.actorOf
import akka.actor.Actor
import akka.dispatch.Dispatchers
import akka.routing.CyclicIterator
import akka.routing.Routing

object WorkStealingDispatcherApplicationExample extends App {
  val processorUsingWorkStealingDispatcher = actorOf[ProcessorUsingWorkStealingDispatcher]
  processorUsingWorkStealingDispatcher.start
  processorUsingWorkStealingDispatcher ! new SimpleMessage(&quot;Hello Actor!!&quot;)
}

object ProcessorUsingWorkStealingDispatcher {
  val dispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher(&quot;wsd1&quot;).setCorePoolSize(10).setMaxPoolSize(10).build
}

class ProcessorUsingWorkStealingDispatcher extends Actor {
  self.dispatcher = ProcessorUsingWorkStealingDispatcher.dispatcher
  var startTime: Long = -1
  var parallelCounter: Int = 1000

  def receive = {
    case SimpleReply =&gt; {
      parallelCounter -= 1
      if (parallelCounter == 0) {
        val endTime = System.currentTimeMillis
        println(&quot;Total Time:: &quot; + (endTime - startTime))
        Actor.registry.shutdownAll
      }
    }

    case SimpleMessage(msg) =&gt;
      startTime = System.currentTimeMillis
      val workers = Vector.fill(15)(actorOf[ProcessorUsingWorkStealingDispatcherWorker].start)
      val router = Routing.loadBalancerActor(CyclicIterator(workers)).start
      for (i &lt;- 0 until parallelCounter) {
        router ! new SimpleRequest(msg)
      }
  }
}

object ProcessorUsingWorkStealingDispatcherWorker {
  val dispatcher = Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher(&quot;wsd2&quot;).setCorePoolSize(10).setMaxPoolSize(10).build
}

class ProcessorUsingWorkStealingDispatcherWorker extends Actor {
  self.dispatcher = ProcessorUsingWorkStealingDispatcherWorker.dispatcher
  def receive = {
    case SimpleRequest(msg) =&gt; {
      val sleepTime = java.lang.Math.random() * 510
      Thread.sleep(sleepTime.toLong)
      self reply SimpleReply
    }
  }
}

case class SimpleRequest(msg: String)

case class SimpleMessage(msg: String)

case class SimpleReply
</pre></p>
<p>That is all about dispatchers, they are a powerful way of managing performance, throughput and scalability of the system. All code examples are here at <a href="https://github.com/meetumaltiar/AkkaExperiments" title="Akka Experiments" target="_blank">my github repository</a>. It is a sbt project. The command<br />
<pre class="brush: plain;">
sbt run
</pre></p>
<p>will ask for the program to run, just enter the number and see how it executes.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/955/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/955/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/955/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/955/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/955/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/955/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/955/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/955/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=955&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/09/24/using-akka-dispatchers-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/09/prioritydispatcherexample.png" medium="image">
			<media:title type="html">PriorityDispatcherExample</media:title>
		</media:content>
	</item>
		<item>
		<title>Manage Akka Actors With Supervisors</title>
		<link>http://meetumaltiar.wordpress.com/2011/09/21/manage-akka-actors-with-supervisors/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/09/21/manage-akka-actors-with-supervisors/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 06:15:37 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Akka]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=946</guid>
		<description><![CDATA[We are building a concurrent and massively scalable system using Akka framework. Akka uses light-weight Actor paradigm of managing concurrency. Most of the times a bunch of Akka actors are required for a common functionality; therefore we do tend to manage them as a group. This is where Akka Supervisor comes into the picture. Akka [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=946&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We are building a concurrent and massively scalable system using <a href="http://akka.io" title="Akka" target="_blank">Akka</a> framework. Akka uses light-weight Actor paradigm of managing concurrency.</p>
<p>Most of the times a bunch of Akka actors are required for a common functionality; therefore we do tend to manage them as a group.</p>
<p>This is where <a href="http://akka.io/docs/akka/1.1.1/scala/fault-tolerance.html" title="Akka Supervisor" target="_blank">Akka Supervisor</a> comes into the picture. Akka Supervisors are responsible for starting, stopping and monitoring child Akka actors.</p>
<p>Lets look now how to use supervisor over Akka Actors. Just to keep things simple we have an Actor which simply echoes the message it receives. Here is the code listing for EchoActor:</p>
<p><pre class="brush: scala;">
/**
 * An Actor that echoes everything you send to it
 */
class EchoActor extends Actor {
  def receive = {
    case msg =&gt; {
      println(msg)
    }
  }
}
</pre></p>
<p>We will build supervision on a bunch of EchoActor, lets say our supervisor is EchoActorSupervisor. But before we actually look at its code listing we understand its constituent elements first.</p>
<p>The Supervisor first require SupervisorConfig. This SupervisorConfig in turn requires fault handling strategy for the group of actors. They are:</p>
<ul>
<li>AllForOneStrategy</li>
<li>OneForOneStrategy</li>
</ul>
<p>The AllForOne fault handler will restart all the components and OneForOneStrategy fault handler will restart just the component which died. Fault Handler takes as parameter a List of Exceptions which will be handled, maximum number of restart tries and within-time in millis</p>
<p>Lets have a look how does our SupervisorConfig looks like:</p>
<p><pre class="brush: scala;">
...
val supervisorConfig = SupervisorConfig(OneForOneStrategy(List(classOf[Exception]), 3, 500), Nil)
...
</pre></p>
<p>Supervisor can now be created by passing in SupervisorConfig created in previous listing:</p>
<p><pre class="brush: scala;">
...
val supervisorConfig = SupervisorConfig(OneForOneStrategy(List(classOf[Exception]), 3, 500), Nil)
val supervisor = Supervisor(supervisorConfig)
...
</pre></p>
<p>now we can link and unlink actors to the supervisor. In our case since we are using EchoActor we can link two Actor Reference to the supervisor. In the code below we are linking and starting two EchoActor.</p>
<p><pre class="brush: scala;">
...
val echoActor1 = actorOf[EchoActor]
val echoActor2 = actorOf[EchoActor]

val supervisorConfig = SupervisorConfig(OneForOneStrategy(List(classOf[Exception]), 3, 500), Nil)
val supervisor = Supervisor(supervisorConfig)

supervisor.link(echoActor1)
supervisor.link(echoActor2)

echoActor1.start
echoActor2.start
...
</pre></p>
<p><span id="more-946"></span></p>
<p>If you like a shorthand way of doing it where you can start and link the actors in a go, here is the code listing for that.</p>
<p><pre class="brush: scala;">
...
val echoActor1 = actorOf[EchoActor]
val echoActor2 = actorOf[EchoActor]

val supervisorConfig = SupervisorConfig(AllForOneStrategy(List(classOf[Exception]), 3, 1000),
    Supervise(echoActor1, Permanent) :: Supervise(echoActor2, Permanent) :: Nil)
val supervisor = Supervisor(supervisorConfig)
...
</pre></p>
<p>Since, we have provided Fault Tolerance Strategy we will also like to see it working in action. For that Echo Actor should die after throwing an Exception. </p>
<p>Let Echo Actor be changed to throw an Exception when it has an ErrorInducingMessage. For this to occur we will introduce a simple case class ErrorInducingMessage and we will change EchoActor to die when it gets this message. Here I also override a lifecycle method postRestart in EchoActor to show that actor came up after throwing exception.</p>
<p>The code listing for described changes:</p>
<p><pre class="brush: scala;">
/**
 * An Actor that echoes everything you send to it
 */
class EchoActor extends Actor {

  def receive = {
    case ErrorInducingMessage =&gt; throw new Exception(&quot;Dying due to error inducing message&quot;)
    case msg =&gt; println(msg)
  }
  
  override def postRestart(err:Throwable) = {
    println(&quot;I am back again...&quot;)
  }
}

case class ErrorInducingMessage
</pre></p>
<p>To show the fault handling strategy in action we will send one message each to actors. Then we send one ErrorInducingMessage to one of the actor and finally we send one message each again. Lets combine all of this together. </p>
<p><pre class="brush: scala;">
package com.meetu.akka

import akka.actor.Actor.actorOf
import akka.actor.Actor
import akka.actor.Supervisor
import akka.config.Supervision.OneForOneStrategy
import akka.config.Supervision.SupervisorConfig

object Application extends App {

  val echoActor1 = actorOf[EchoActor]
  val echoActor2 = actorOf[EchoActor]
  val supervisorConfig = SupervisorConfig(OneForOneStrategy(List(classOf[Exception]), 3, 500), Nil)
  val supervisor = Supervisor(supervisorConfig)

  supervisor.link(echoActor1)
  supervisor.link(echoActor2)

  echoActor1.start
  echoActor2.start
  
  echoActor1 ! &quot;Hello actor 1&quot;
  echoActor2 ! &quot;Hello actor 2&quot;
  
  echoActor1 ! ErrorInducingMessage
  Thread.sleep(1000)
  echoActor1 ! &quot;Hello actor 1&quot;
  echoActor2 ! &quot;Hello actor 2&quot;
}

/**
 * An Actor that echoes everything you send to it
 */
class EchoActor extends Actor {

  def receive = {
    case ErrorInducingMessage =&gt; throw new Exception(&quot;Dying due to error inducing message&quot;)
    case msg =&gt; println(msg)
  }
  
  override def postRestart(err:Throwable) = {
    println(&quot;I am back again...&quot;)
  }
}

case class ErrorInducingMessage
</pre></p>
<p>For want of shorter code where we do not explicitly start the actors here is the complete code listing.<br />
<pre class="brush: scala;">
package com.meetu.akka

import akka.actor.Actor.actorOf
import akka.actor.Actor
import akka.actor.Supervisor
import akka.config.Supervision.AllForOneStrategy
import akka.config.Supervision.Permanent
import akka.config.Supervision.Supervise
import akka.config.Supervision.SupervisorConfig

object Application extends App {

  val echoActor1 = actorOf[EchoActor]
  val echoActor2 = actorOf[EchoActor]

  val supervisorConfig = SupervisorConfig(AllForOneStrategy(List(classOf[Exception]), 3, 1000),
    Supervise(echoActor1, Permanent) :: Supervise(echoActor2, Permanent) :: Nil)
  val supervisor = Supervisor(supervisorConfig)

  echoActor1 ! &quot;Hello actor 1&quot;
  echoActor2 ! &quot;Hello actor 2&quot;

  echoActor1 ! ErrorInducingMessage
  Thread.sleep(1000)
  echoActor1 ! &quot;Hello actor 1&quot;
  echoActor2 ! &quot;Hello actor 2&quot;
}

/**
 * An Actor that echoes everything you send to it
 */
class EchoActor extends Actor {

  def receive = {
    case ErrorInducingMessage =&gt; throw new Exception(&quot;Dying due to error inducing message&quot;)
    case msg =&gt; println(msg)
  }

  override def postRestart(err: Throwable) = {
    println(&quot;I am back again...&quot;)
  }
}

case class ErrorInducingMessage
</pre></p>
<p>When we run this we see that there are two messages from each actors. There is some error trace as expected. Then we see that one of the actor is back again. Finally we see that two messages are printed by each actors.</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/09/application-trace.png"><img src="http://phithoughts.files.wordpress.com/2011/09/application-trace.png?w=700" alt="Application Execution" title="Application-Trace"   class="alignleft size-full wp-image-2350" /></a></p>
<p>Fault tolerance is important in the sense that we are sure of whether all actors managed by a supervisor are dead or none of them are dead. Instead of preventing from things to go wrong we think about recovery from a crash. This in sense encourages non-defensive programming. </p>
<p>The Akka code for this can be downloaded from <a href="https://github.com/meetumaltiar/AkkaExperiments" target="_blank">here</a>. This is a <a href="https://github.com/harrah/xsbt/wiki" title="sbt" target="_blank">sbt</a> project and code can be executed by executing following at command prompt<br />
<pre class="brush: plain;">
 sbt run
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/946/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/946/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/946/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/946/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/946/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/946/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/946/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/946/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=946&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/09/21/manage-akka-actors-with-supervisors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/09/application-trace.png" medium="image">
			<media:title type="html">Application-Trace</media:title>
		</media:content>
	</item>
		<item>
		<title>Starting Akka Project With SBT 0.10</title>
		<link>http://meetumaltiar.wordpress.com/2011/08/29/starting-akka-project-with-sbt-0-10/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/08/29/starting-akka-project-with-sbt-0-10/#comments</comments>
		<pubDate>Mon, 29 Aug 2011 05:23:45 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Akka]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[sbt]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=936</guid>
		<description><![CDATA[I was starting with Akka project with SBT but found that the latest SBT is quite different from before. I tried to create AKKA project with latest SBT but got stuck. Old SBT used to ask to create a new project in case it did not find any in the directory. With new SBT it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=936&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was starting with <a href="http://akka.io/" target="_blank">Akka</a> project with <a href="https://github.com/harrah/xsbt" target="_blank">SBT</a> but found that the latest SBT is quite different from before. </p>
<p>I tried to create AKKA project with latest SBT but got stuck. Old SBT used to ask to create a new project in case it did not find any in the directory. With new SBT it is not the case. If you want to know how to go about creating new Akka project with SBT read on.</p>
<p>After installing SBT if we type in sbt in the command prompt in an empty directory, this is what we are likely to see.</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/08/sbt-empty.png"><img src="http://phithoughts.files.wordpress.com/2011/08/sbt-empty.png?w=700" alt="" title="sbt-empty"   class="alignleft size-full wp-image-1991" /></a></p>
<p>In order to create project execute the following commands in the sbt session.</p>
<p><pre class="brush: plain;">
&gt; set name := &quot;AkkaQuickStart&quot;
&gt; set version := &quot;1.0&quot;
&gt; set scalaVersion := &quot;2.9.0-1&quot;
&gt; session save
&gt; exit
</pre></p>
<p>We should get the following output if we type the above mentioned commands in sbt session.</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/08/sbt-02.png"><img src="http://phithoughts.files.wordpress.com/2011/08/sbt-02.png?w=700" alt="" title="sbt command to create project"   class="alignleft size-full wp-image-2045" /></a></p>
<p>SBT creates files and directories when we executed the commands. It creates build.sbt and it contains the same values we typed in sbt session. Other directories like target and project are of little consequence to us. </p>
<p>Project directory will become important later when we will try to add <a href="https://github.com/typesafehub/sbteclipse" target="_blank">sbteclipse</a> plugin. My project directory contains the following subdirectories and files.</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/08/initialprojectdir.png"><img src="http://phithoughts.files.wordpress.com/2011/08/initialprojectdir.png?w=700" alt="" title="Initial Project Directory"   class="alignleft size-full wp-image-2048" /></a></p>
<p><span id="more-936"></span></p>
<p>This is how my my build.sbt files looks like after executing the commands in sbt session</p>
<p><pre class="brush: plain;">
name := &quot;AkkaQuickStart&quot;

version := &quot;1.0&quot;

scalaVersion := &quot;2.9.0-1&quot;
</pre></p>
<p>One thing that has also changed from the past is that the src directories are not created by default. I used the <a href="https://github.com/typesafehub/sbteclipse" title="sbteclipse" target="_blank">sbteclipse</a> plugin to do it for me.</p>
<p>Create directory plugins inside project and add build.sbt to it. Add following contents to it:</p>
<p><pre class="brush: plain;">
resolvers += {
  val typesafeRepoUrl = new java.net.URL(&quot;http://repo.typesafe.com/typesafe/releases&quot;)
  val pattern = Patterns(false, &quot;[organisation]/[module]/[sbtversion]/[revision]/[type]s/[module](-[classifier])-[revision].[ext]&quot;)
  Resolver.url(&quot;Typesafe Repository&quot;, typesafeRepoUrl)(pattern)
}

libraryDependencies &lt;&lt;= (libraryDependencies, sbtVersion) { (deps, version) =&gt; 
  deps :+ (&quot;com.typesafe.sbteclipse&quot; %% &quot;sbteclipse&quot; % &quot;1.3-RC1&quot; extra(&quot;sbtversion&quot; -&gt; version))
}
</pre></p>
<p>Execute the following command.</p>
<p><pre class="brush: plain;">
sbt &quot;eclipse create-src&quot;
</pre></p>
<p>It creates common source directories like src/main/scala, src/main/test, etc and also eclipse project files.</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/08/source-gen.png"><img src="http://phithoughts.files.wordpress.com/2011/08/source-gen.png?w=700" alt="" title="source-gen"   class="alignleft size-full wp-image-2061" /></a></p>
<p>The project is ready to imported in Eclipse IDE. We also require Akka dependencies in our project. This can be done by adding resolvers and library dependencies to build.sbt at the top level. Add the following entries in build.sbt:</p>
<p><pre class="brush: plain;">
name := &quot;AkkaQuickStart&quot;

version := &quot;1.0&quot;

scalaVersion := &quot;2.9.0-1&quot;

resolvers += &quot;Typesafe Repository&quot; at &quot;http://repo.typesafe.com/typesafe/releases/&quot;

libraryDependencies ++= Seq(
  &quot;se.scalablesolutions.akka&quot; % &quot;akka-actor&quot; % &quot;1.1.3&quot;,
  &quot;se.scalablesolutions.akka&quot; % &quot;akka-typed-actor&quot; % &quot;1.1.3&quot;,
  &quot;se.scalablesolutions.akka&quot; % &quot;akka-amqp&quot; % &quot;1.1.3&quot;,
  &quot;se.scalablesolutions.akka&quot; % &quot;akka-testkit&quot; % &quot;1.1.3&quot;
)
</pre></p>
<p>Whenever we add new dependencies we must execute &#8220;sbt eclipse&#8221; to regenerate the eclipse project configuration files. Now in order that code for Akka in our projects compiles correctly in Eclipse we execute the following command:</p>
<p><pre class="brush: plain;">
sbt eclipse
</pre></p>
<p>We have a skeleton project with all dependencies and build scripts ready for an AKKA project. Lets create a simple Echo Akka Actor to validate that our configurations work correctly.</p>
<p>The object Application starts EchoActor passes message to it and then stops it. EchoActor prints the message received from Application.</p>
<p><pre class="brush: scala;">
package com.meetu.akka

import akka.actor.Actor.actorOf
import akka.actor.Actor

object Application extends App {

  val actor = actorOf(new EchoActor)
  actor.start
  actor ! &quot;Hello Akka Echo Actor&quot;
  actor.stop
}

/**
 * An Actor that echoes everything you send to it
 */
class EchoActor extends Actor {
  def receive = {
    case msg =&gt; {
      println(msg)
    }
  }
}
</pre></p>
<p>If all is fine the code will compile without any issues but before we run this Application as scala application we need to download Akka from <a href="http://akka.io/downloads/" target="_blank">here</a> and set AKKA_HOME in PATH variable.</p>
<p>After AKKA_HOME points to the right directory we can run the application either from Eclipse or from SBT. For Eclipse run it as Scala Application. For SBT use the command provided below. You should see the &#8220;Hello Akka Echo Actor&#8221; message in the console.</p>
<p><pre class="brush: plain;">
sbt &quot;run-main com.meetu.akka.Application&quot;
</pre></p>
<p>That is all we need for creating Akka project using the latest SBT. We now know how to create an Akka project using SBT and also to add dependencies to it. We can also generate Eclipse IDE specific project files using sbteclipse.</p>
<p>I have created a sample project <a href="https://github.com/meetumaltiar/AkkaExperiments" target="_blank">AkkaExperiments</a> which has the code for starting Akka project using SBT.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/936/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/936/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/936/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/936/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/936/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/936/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/936/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/936/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=936&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/08/29/starting-akka-project-with-sbt-0-10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/08/sbt-empty.png" medium="image">
			<media:title type="html">sbt-empty</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/08/sbt-02.png" medium="image">
			<media:title type="html">sbt command to create project</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/08/initialprojectdir.png" medium="image">
			<media:title type="html">Initial Project Directory</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/08/source-gen.png" medium="image">
			<media:title type="html">source-gen</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting Started With Scala</title>
		<link>http://meetumaltiar.wordpress.com/2011/07/07/getting-started-with-scala/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/07/07/getting-started-with-scala/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 15:16:05 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=924</guid>
		<description><![CDATA[I and Vikas presented on &#8220;Getting Started With Scala&#8221; few years back. It was presented at OSS camp 2009 in New Delhi. I still remember the interest it created at the conference. Today I happened to have a look at it on Slideshare. Looking at the number of views it seems to be doing good. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=924&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I and <a href="http://in.linkedin.com/in/vikashazrati" target="_blank">Vikas</a> presented on &#8220;Getting Started With Scala&#8221; few years back. It was presented at OSS camp 2009 in New Delhi. I still remember the interest it created at the conference. </p>
<p>Today I happened to have a look at it on Slideshare. Looking at the number of views it seems to be doing good. Out of my previous employer presentations its having highest hits. Scala is really doing good in terms of popularity.</p>
<p>Presentation is still old. To get started concepts are still the same. Enjoy the presentation&#8230;</p>
<iframe src='http://www.slideshare.net/slideshow/embed_code/8905487' width='700' height='574'></iframe>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/924/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/924/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/924/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/924/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/924/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/924/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/924/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/924/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=924&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/07/07/getting-started-with-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>
	</item>
		<item>
		<title>Experiences at Cloud Computing Conference Pune 2011</title>
		<link>http://meetumaltiar.wordpress.com/2011/07/02/experiences-at-cloud-computing-conference-pune-2011/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/07/02/experiences-at-cloud-computing-conference-pune-2011/#comments</comments>
		<pubDate>Sat, 02 Jul 2011 06:21:25 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[GAE]]></category>
		<category><![CDATA[Objectify-Appengine]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=920</guid>
		<description><![CDATA[I was one of the speaker of the second IndicThreads conference held at Pune on 3-4th June 2011. Sessions at the conference dealt with key topics like Cloud Security, Amazon Elastic Beanstalk, Legal Issues in Cloud Computing, OpenStack, Xen Cloud Platform, Rails and CouchDB on the cloud, CloudFoundry, Gigapaces PAAS, Monitoring Cloud Applications, ORM with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=920&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was one of the speaker of the second <a href="http://u11.indicthreads.com/" title="IndicThreads" target="_blank">IndicThreads</a> conference held at Pune on 3-4th June 2011. </p>
<p>Sessions at the conference dealt with key topics like Cloud Security, Amazon Elastic Beanstalk, Legal Issues in Cloud Computing, OpenStack, Xen Cloud Platform, Rails and CouchDB on the cloud, CloudFoundry, Gigapaces PAAS, Monitoring Cloud Applications, ORM with Objectify-Appengine, Scalable Architecture on Amazon AWS Cloud, Cloud Lock-in, Cloud Interoperability, Apache Hadoop, Map Reduce and Predictive Analysis.</p>
<p>My talk focussed on managing persistence on GAE. It dealt with choices available to a developer and then focussed on doing it with <a href="http://code.google.com/p/objectify-appengine/" title="Objectify-Appengine" target="_blank">Objectify-Appengine</a>.</p>
<p><iframe src='http://www.slideshare.net/slideshow/embed_code/8905673' width='700' height='574'></iframe><br />
<BR /></p>
<p>Demo application is present here for <a href="http://code.google.com/p/indicthreads-objectify/" title="Demo Application" target="_blank">download</a>. For the instructions on how to run it please read the <a href="http://code.google.com/p/indicthreads-objectify/wiki/ExecutingAndDeploying" target="_blank">wiki</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/920/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/920/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/920/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/920/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/920/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/920/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/920/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/920/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=920&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/07/02/experiences-at-cloud-computing-conference-pune-2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>
	</item>
		<item>
		<title>Working With Scala Collections</title>
		<link>http://meetumaltiar.wordpress.com/2011/07/02/working-with-scala-collections/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/07/02/working-with-scala-collections/#comments</comments>
		<pubDate>Sat, 02 Jul 2011 05:59:08 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=913</guid>
		<description><![CDATA[We have a monthly iBAT (Inphina Beer and Technology Sessions). We look forward to this day and it was Scala day this time. I presented on Scala collections. Scala collection is elegant and concise. Scala Collections like java is object-oriented and we can work with generic types. It is optionally persistent i.e can be mutable [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=913&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We have a monthly iBAT (Inphina Beer and Technology Sessions). We look forward to this day and it was Scala day this time. I presented on Scala collections.</p>
<p>Scala collection is elegant and concise. Scala Collections like java is object-oriented and we can work with generic types. It is optionally persistent i.e can be mutable and immutable. It provides higher order methods like foreach, map and filter. </p>
<p>Scala collections follow uniform return type principle. Which basically means that when you perform an operation on a collection they return a collection of the same type. </p>
<p>The root Trait in Scala collections is <em>Traversable</em>. It may take some time to get used to it as Scala collections root Traits like Traversable have a big bunch of methods.</p>
<p>The <em>for</em> notation is more readable. It is basically like a for loop with a return type. Look for yourself how readable it is compared to the original code.</p>
<p>This code listing is without a for notation<br />
<pre class="brush: bash;">
scala&gt; val listOfNumbers = List(1, 2, 3)
listOfNumbers: List[Int] = List(1, 2, 3)

scala&gt; val flattenedListOfNumbers = listOfNumbers flatMap (0 to _)
flattenedListOfNumbers: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)
</pre></p>
<p>After using for notation<br />
<pre class="brush: bash;">
scala&gt; val listOfNumbers = List(1, 2, 3)
listOfNumbers: List[Int] = List(1, 2, 3)

scala&gt; val flattenedList = for(number &lt;- listOfNumbers; range &lt;- 0 to number) yield range
flattenedList: List[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)
</pre></p>
<p>One more interesting thing we can do with a Map is that we can reverse key and value with the following code<br />
<pre class="brush: bash;">
scala&gt; val aMap = Map(&quot;India&quot; -&gt; &quot;Delhi&quot;, &quot;France&quot; -&gt; &quot;Paris&quot;, &quot;Italy&quot; -&gt; &quot;Rome&quot;)
aMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(India -&gt; Delhi, France -&gt; Paris, Italy -&gt; Rome)

scala&gt; val reverseMap = aMap map{case(k, v) =&gt; (v, k)}
reverseMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(Delhi -&gt; India, Paris -&gt; France, Rome -&gt; Italy)

scala&gt; val alsoReverseMap = for((k, v) &lt;- aMap) yield (v -&gt; k) 
alsoReverseMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(Delhi -&gt; India, Paris -&gt; France, Rome -&gt; Italy)
</pre></p>
<p>Reference were from Martin&#8217;s Odersky talk on <a href="http://www.scala-lang.org/node/9952" target="_blank">Future Proofing Collections</a> and <a href="http://www.scala-lang.org/docu/files/collections-api/collections.html" target="_blank">Scala Collections API documentation</a>. Enjoy the presentation &#8230;</p>
<iframe src='http://www.slideshare.net/slideshow/embed_code/10648482' width='700' height='574'></iframe>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/913/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=913&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/07/02/working-with-scala-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>
	</item>
		<item>
		<title>Working With Scala Test</title>
		<link>http://meetumaltiar.wordpress.com/2011/06/01/working-with-scala-test/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/06/01/working-with-scala-test/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 02:48:35 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=900</guid>
		<description><![CDATA[Scala Test is an open source Test framework for the java platform. With Scala test we can either test java or Scala code. It integrates with popular existing tools like JUnit, TestNG and it is designed to do different styles of testing like Behavior Driven Design for example. Let&#8217;s have a look at a simple [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=900&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.scalatest.org/" target="_blank">Scala Test</a> is an open source Test framework for the java platform. With Scala test we can either test java or Scala code. It integrates with popular existing tools like <a href="http://www.junit.org/" target="_blank">JUnit</a>, <a href="http://testng.org/doc/index.html" target="_blank">TestNG</a> and it is designed to do different styles of testing like Behavior Driven Design for example.</p>
<p>Let&#8217;s have a look at a simple JUnit4 Test in Scala Test</p>
<p><pre class="brush: scala;">
package com.inphina.ibat.junit

import org.scalatest.junit.AssertionsForJUnit
import org.junit.Assert._
import org.junit.Test
import  org.junit.Before

class SimpleJunit4Demo extends AssertionsForJUnit {

  var sb: StringBuilder = _

  @Before def initialize() {
    sb = new StringBuilder(&quot;Welcome To &quot;)
  }

  @Test
  def verifyEasy() {
    sb.append(&quot;ScalaTest!&quot;)
    assertEquals(&quot;Welcome To ScalaTest!&quot;, sb.toString)
  }

}
</pre></p>
<p>This Test implementation is not very different from a normal JUnit Test we are accustomed to. In order to understand ScalaTest there are three concepts we need to be aware of.</p>
<ul>
<li>Suite: A collection of tests. A Test is anything that has a name and can succeed or fail</li>
<li>Runner: ScalaTest provides a Runner application that can run Suites of Tests</li>
<li>Reporter: As Tests are run events are fired to a reporter, it takes care of presenting results back to the user</li>
</ul>
<p>Let&#8217;s have a bit more detailed look at the Suite which is a Trait.</p>
<p><a href="http://phithoughts.files.wordpress.com/2011/05/suite.png"><img class="size-full wp-image-1799 alignnone" title="Suite" src="http://phithoughts.files.wordpress.com/2011/05/suite.png?w=700" alt="Suite"   /></a></p>
<p><span id="more-900"></span></p>
<p>When you run a Test in Scala Test you basically invoke run(Option[String], Reporter, .. ) on Suite Object.</p>
<ul>
<li>It then calls runNestedSuites(Reporter, ..).</li>
<li>And it calls runTests(Option[String], Reporter, ..)</li>
</ul>
<p>runNestedSuites(Reporter, ..) then invokes nestedSuites() : List[Suite] to get a List of nested Suites. Which are required for running tests.</p>
<p>runTests(Option[String], Reporter, ..) calls def testNames: Set[String] to get a Set of test names it needs to run. For each test name it calls runTest(Reporter, &#8230;) It wraps the test code as a Function Object with a name and passes it to withFixture(NoArgTest) which actually runs the test.</p>
<p>Way of working with Scala Test is working with Traits. Just like any other Trait we can do Mixin composition to have a different flavor of Tests we want to. Scala Test have some core Traits and then we can mix it with other available Traits.</p>
<p><strong>Core Traits</strong><br />
<a href="http://phithoughts.files.wordpress.com/2011/05/core-traits.png"><img src="http://phithoughts.files.wordpress.com/2011/05/core-traits.png?w=700" alt="" title="Core-Traits"   class="alignleft size-full wp-image-1823" /></a></p>
<p><strong>Mix In other Traits</strong><br />
<a href="http://phithoughts.files.wordpress.com/2011/05/other-traits.png"><img src="http://phithoughts.files.wordpress.com/2011/05/other-traits.png?w=700" alt="" title="Other-Traits"   class="alignleft size-full wp-image-1824" /></a></p>
<p>So, essentially working with Scala Test requires picking up a Core Trait and mixin it with other provided Traits. Some of the Core Traits are</p>
<ul>
<li>Suite</li>
<li>FunSuite</li>
<li>Spec</li>
<li>FlatSpec</li>
<li>WordSpec</li>
<li>FeatureSpec</li>
</ul>
<p>Let&#8217;s have a look at a Suite Example:<br />
Traits approach to writing tests. Simply create classes extending Suite and define test methods. Test methods have names testXXXX. All methods must be public. Scala Test provides === operator. It is defined in Traits Assertions. Allows the failure report to include both right and left values.</p>
<p><pre class="brush: scala;">
package com.inphina.ibat.suite

import org.scalatest.Suite

/**
 * Traits approach to writing tests. Simply create classes
 * extending Suite and define test methods.
 *
 * Test methods have names testXXXX. All methods must be public.
 *
 * Scala Test provides === operator. It is defined in Traits Assertions. Allows the failure report
 * to include both right and left values.
 */

class SimpleSuiteDemo extends Suite {

   def testAddition() {
        val sum = 1 + 1
        assert(sum === 3)
   }

  def testSubtraction() {
    val diff = 4 - 1
    assert(diff === 3)
  }
}
</pre></p>
<p>If we want to have some Mixin with other Traits in Scala Test then we can use ShouldMatchers. It provides DSL type of assertions and makes the code much more readable. Let&#8217;s have a look at the code listing below.</p>
<p><pre class="brush: scala;">
package com.inphina.ibat.suite

import org.scalatest.Suite
import org.scalatest.matchers.ShouldMatchers

/**
 * Mixin Traits ShouldMatchers for DSl type assertions
 */

class DSLMatchersSuiteDemo extends Suite with ShouldMatchers {

  def testAddition() {
    val sum = 1 + 1
    sum should equal (2)
    sum + 2 should equal (4)
  }

}
</pre></p>
<p>Both the Tests till now are not purely functional Tests. They resemble normal Java Tests use FunSuite Trait to write Functional Scala Tests.<br />
FunSuite</p>
<ul>
<li>&#8220;test&#8221; is a method defined in FunSuite Trait. Test name goes in parentheses and the test code goes in curly braces</li>
<li>The test code in curly braces is passed as a by-name parameter to &#8220;test&#8221; method which registers for later execution</li>
<li>A FunSuite&#8217;s life-cycle has two phases: the registration phase and the ready phase</li>
</ul>
<p>Let&#8217;s have a look at the code example<br />
<pre class="brush: scala;">
package com.inphina.ibat.funsuite

import org.scalatest.FunSuite

/**
 * For writing Functional Tests use FunSuite Fun =&gt; Functional Suite. &quot;test&quot; is a method defined in FunSuite Trait.
 * Test name goes in parentheses and the test code goes in curly braces. One benefit of using FunSuite compared to
 * Suite is that we need not name the test with testXXXX style names.
 *
 * The test code in curly braces is passed as a by-name parameter to &quot;test&quot; method which registers for later execution
 *
 * More benefits we can easily give long names in tests instead of camel case notation generally used.
 *
 * A FunSuite's life-cycle has two phases: the registration phase and the ready phase. It starts in registration phase
 * and enters ready phase the first time run is called on it. It then remains in ready phase for the remainder of its
 * lifetime.
 */

class SimpleFunSuiteDemo extends FunSuite {

  test(&quot;addition of numbers&quot;) {
    val sum = 1 + 2
    assert(sum === 2)
  }

  test(&quot;subtraction&quot;) {
    val diff = 5 - 2
    assert(diff === 3)
  }

}
</pre></p>
<p>One of the immediate benefits is that we can use more descriptive test names instead of Camel case method names we are so used to.</p>
<p>We have looked at Suite and FunSuite way of writing tests now lets have a look at the FeatureSpec which is a higher level way of writing Tests. It basically represents a Suite of Tests where each Test represent a scenario of a Feature. </p>
<p>A FeatureSpec  contains feature clauses and scenarios. Feature Clause and Scenario are defined by &#8220;feature&#8221; and &#8220;scenario&#8221;. Both of them are defined as methods in FeatureSpec.<br />
Let&#8217;s have a look at an example of FeatureSpec mixin with GivenWhenThen Trait. </p>
<p><pre class="brush: scala;">
package com.inphina.ibat.featurespec

import org.scalatest.FeatureSpec
import org.scalatest.GivenWhenThen
import scala.collection.mutable.Stack


class StackFeatureSpec extends FeatureSpec with GivenWhenThen {

  feature(&quot;The user can pop an element off the top of the stack&quot;) {

    info(&quot;As a programmer&quot;)
    info(&quot;I want to be able to pop items off the stack&quot;)
    info(&quot;So that I can get them in last-in-first-out order&quot;)

    scenario(&quot;pop is invoked on a non-empty stack&quot;) {

      given(&quot;a non-empty stack&quot;)
      val stack = new Stack[Int]
      stack.push(1)
      stack.push(2)
      val oldSize = stack.size

      when(&quot;when pop is invoked on the stack&quot;)
      val result = stack.pop()

      then(&quot;the most recently pushed element should be returned&quot;)
      assert(result === 2)

      and(&quot;the stack should have one less item than before&quot;)
      assert(stack.size === oldSize - 1)
    }

    scenario(&quot;pop is invoked on an empty stack&quot;) {

      given(&quot;an empty stack&quot;)
      val emptyStack = new Stack[String]

      when(&quot;when pop is invoked on the stack&quot;)
      then(&quot;NoSuchElementException should be thrown&quot;)
      intercept[NoSuchElementException] {
        emptyStack.pop()
      }

      and(&quot;the stack should still be empty&quot;)
      assert(emptyStack.isEmpty)
    }
  }
}
</pre></p>
<p>Major benefits by Scala Test are similar to scala itself. It is concise, provides you a flexible manner of testing your application be it Scala or Java. Works with popular Java frameworks like TestNg and JUnit and EasyMock. And last but not the least provides a nice way to introduce Scala in the project. </p>
<p>I presented it on iBat session at <a href="http://www.inphina.com/home.htm" target="_blank">Inphina</a>. Content is nearly the same, enjoy the presentation &#8230;</p>
<iframe src='http://www.slideshare.net/slideshow/embed_code/10648513' width='700' height='574'></iframe>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/900/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/900/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/900/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=900&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/06/01/working-with-scala-test/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/05/suite.png" medium="image">
			<media:title type="html">Suite</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/05/core-traits.png" medium="image">
			<media:title type="html">Core-Traits</media:title>
		</media:content>

		<media:content url="http://phithoughts.files.wordpress.com/2011/05/other-traits.png" medium="image">
			<media:title type="html">Other-Traits</media:title>
		</media:content>
	</item>
		<item>
		<title>Working With Spring Data JPA</title>
		<link>http://meetumaltiar.wordpress.com/2011/03/15/working-with-spring-data-jpa/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/03/15/working-with-spring-data-jpa/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 11:52:37 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=892</guid>
		<description><![CDATA[SpringSource have recently released the first milestone of Spring Data JPA project. What are its features? and how can we use them. Spring framework already provides support to build a JPA based data access layer. So, what does Spring Data adds to it. I used it for one small application and found significant reduction of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=892&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>SpringSource have recently released the first milestone of <a href="http://www.springsource.org/node/3022">Spring Data JPA</a> project. What are its features? and how can we use them. Spring framework already provides support to build a JPA based data access layer. So, what does Spring Data adds to it. I used it for one small application and found significant reduction of code. In this post we will use an Employee entity and EmployeeRepository as an example to work with Spring Data JPA.</p>
<p>We have a domain Employee :</p>
<p><pre class="brush: java;">
@Entity
public class Employee {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private String name;

  // … methods omitted
}
</pre></p>
<p>We also have a EmployeeRepository handling the Employee entities. The interface and the implementation are given below.</p>
<p><pre class="brush: java;">
package com.inphina.springdata.repository;

public interface EmployeeRepository {
	
	Employee save(Employee employee);
	
	List&lt;Employee&gt; findAll();
	
	Employee findById(Long id);
	
	List&lt;Employee&gt; findByName(String name, int page, int pageSize);

}
</pre><br />
<span id="more-892"></span><br />
<pre class="brush: java;">
@Repository
@Transactional(readOnly = true)
public class EmployeeRepositoryImpl implements EmployeeRepository {
	
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	@Transactional
	public Employee save(Employee employee) {
		if(employee.getId() == null) {
			entityManager.persist(employee);
		} else {
			entityManager.merge(employee);
		}
		return employee;
	}

	@Override
	public List&lt;Employee&gt; findAll() {
		return entityManager.createQuery(&quot;select e from Employee e&quot;, Employee.class).getResultList();
	}

	@Override
	public Employee findById(Long id) {
		return entityManager.find(Employee.class, id);
	}

	@Override
	public List&lt;Employee&gt; findByName(String name, int page, int pageSize) {
		TypedQuery&lt;Employee&gt; query = entityManager.createQuery(&quot;select e from Employee e where e.name = ?1&quot;, Employee.class);
		query.setParameter(1, name);
		query.setFirstResult(page * pageSize);
		query.setMaxResults(pageSize);
		return query.getResultList();
	}
}
</pre></p>
<p>the client need to decide whether to call merge(…) or persist(…) on the EntityManager. We use the id-field of the Employee to decide whether we consider an Employee object as new or not.</p>
<p>Spring Data JPA provides a repository programming model that starts with an interface per managed domain object. That means for the Employee domain there is an Interface such as EmployeeRepository .</p>
<p><pre class="brush: java;">
@Transactional(readOnly = true)
public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt; { ... }
</pre></p>
<p>by extending JpaRepository we get generic CRUD methods into our type that allows working with Employees. This also allow the Spring Data JPA repository infrastructure to scan the classpath for this interface and create a Spring bean for it.</p>
<p>To have Spring create a bean that implements this interface, we need to use the Spring JPA namespace and activate the repository support using the appropriate element:</p>
<p><pre class="brush: xml;">
&lt;jpa:repositories base-package=&quot;com.inphina.springdata&quot; /&gt;
</pre></p>
<p>This scans all the package below <code>com.inphina.springdata</code> for interfaces extending <code>JpaRepository</code> and creates a spring bean backed by an implementation of <code>SimpleJpaRepository</code></p>
<p>Now lets use a bit of Spring Data help in reducing the EmployeeRepositoryImpl code. We change the interface  EmployeeRepository to this:</p>
<p><pre class="brush: java;">
public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt;{
	Employee save(Employee employee);

	List&lt;Employee&gt; findByName(String name, int page, int pageSize);
}
</pre></p>
<p>The EmployeeRepositoryImpl can then implement <code>findByName(String name, int page, int pageSize)</code> and  <code>Employee save(Employee employee);<br />
</code> as shown in the code below.</p>
<p><pre class="brush: java;">
@Transactional(readOnly = true)
public class EmployeeRepositoryImpl implements EmployeeRepository {
	
	@Autowired
	private EmployeeRepository repository;

      @Override
	public Employee save(Employee employee) {
		return repository.save(employee);
	}

      @Override
	public List&lt;Employee&gt; findByName(String name, int page, int pageSize) {
		return repository.findByName(name, page, pageSize);
	}
}
</pre></p>
<p>Here we simply delegate the call to save(…) to the repository. By default the repository implementation considers an entity new if its id property is null similar to the first code listing of <code>EmployeeRepositoryImpl</code></p>
<p>Spring Data JPA provides an abstraction consisting of two interfaces: Pageable (to capture pagination request information) as well as Page (to capture the result as well as meta-information). We can add the  <code>findByName</code> in the interface itself. The need for the interface implementation is not required now. This is how the interface will look after the changes.</p>
<p><pre class="brush: java;">
@Transactional(readOnly = true)
public interface EmployeeRepository extends JpaRepository&lt;Employee, Long&gt; {

	/**
	 * Returns a Page of {@link Employee}s with the given name.
	 * @param name
	 * @param page
	 * @param pageSize
	 * @return
	 */
	Page&lt;Employee&gt; findByName(String name, int page, int pageSize);
}
</pre></p>
<p>To summarize we have seen that there is significant reduction of the code. After refactoring what remains is one interface and a XML declaration. Spring Data JPA does looks similar to Hades where simple queries can be generated from method names. However we might come to see integration of <a href="https://jira.springsource.org/browse/DATAJPA-8">QueryDsl</a> in near future.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/892/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=892&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/03/15/working-with-spring-data-jpa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>
	</item>
		<item>
		<title>Configuring Spring Application Using Configuration Annotation</title>
		<link>http://meetumaltiar.wordpress.com/2011/03/08/configuring-spring-application-using-configuration-annotation/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/03/08/configuring-spring-application-using-configuration-annotation/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 02:39:40 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=885</guid>
		<description><![CDATA[A Spring Module called Java Config has been there for some time now. With the release of Spring 3.0 SpringSource has pulled this module into the core Spring Framework as @Configuration. How can we use this @Configuration in our application? and should we use it when we have XML and annotations for configuration already? In [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=885&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A Spring Module called Java Config has been there for some time now. With the release of Spring 3.0 SpringSource has pulled this module into the core Spring Framework as @Configuration.</p>
<p>How can we use this @Configuration in our application? and should we use it when we have XML and annotations for configuration already?</p>
<p>In Spring 2.5 we find that there is a support for Property Externalization. Which was good in several ways than before. What it meant was, that the properties file could be modified for different build environments by the administrator.</p>
<p>One good thing about this approach is that the administrator need not edit the application context file. Editing verbose XML has plenty of room for errors. Editing the properties file on the other hand is a whole lot simpler and is less error prone.</p>
<p>For example for configuring the datasource this is what we do typically. We used Property externalization in Spring 2.5 using PropertyPlaceHolderConfigurer.</p>
<p><pre class="brush: xml;">
&lt;context:property-placeholder location=&quot;classpath:datasource.properties&quot; /&gt;
&lt;bean id=&quot;dataSource&quot; class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;&gt;
		&lt;property name=&quot;driverClassName&quot;&gt;&lt;value&gt;${dataSource.driverClassName}&lt;/value&gt;&lt;/property&gt;
		&lt;property name=&quot;url&quot;&gt;&lt;value&gt;${dataSource.url}&lt;/value&gt;&lt;/property&gt;
		&lt;property name=&quot;username&quot;&gt;&lt;value&gt;${dataSource.username}&lt;/value&gt;&lt;/property&gt;
		&lt;property name=&quot;password&quot;&gt;&lt;value&gt;${dataSource.password}&lt;/value&gt;&lt;/property&gt;
&lt;/bean&gt;
</pre><br />
<span id="more-885"></span><br />
What it does is that at the Configuration time right after the Spring has loaded the bean definitions it replaces these placeholders with the values defined in the externalized properties file. That means that whatever the values specified for driver class name, url, user name and password will now be set on the datasource bean for the application.</p>
<p>Important point to note here is that it is done at the configuration time. So, it is only done once while the application context file loads up.</p>
<p>This approach does have some drawbacks though:</p>
<ul>
<li>It only supports properties</li>
<li>Replacement is done at initialization time not at bean creation time</li>
<li>It does not support conditionals or other constructs</li>
<li>It is not Typesafe</li>
</ul>
<p>Let&#8217;s have a look how can we use a java based Spring configuration.</p>
<p>First we create a Java class and add @Configuration annotation to it. Then we define methods to instantiate the application&#8217;s classes and call other methods to configure the dependencies. We also add @Bean annotation to these methods.</p>
<p>For example If we have a bean name MyBean then we can create a Configuration annotated class like this</p>
<p><pre class="brush: java;">
@Configuration
public class ApplicationConfig {

  @Bean
  public AnyService AnyService() {
      return new AnyServiceImpl();
  }

}
</pre></p>
<p>This is equivalent to the following bean definition in standard xml based spring configuration.<br />
<pre class="brush: xml;">
&lt;beans&gt;
  &lt;bean id=&quot;anyService&quot; class=&quot;com.inphina.AnyServiceImpl&quot;/&gt;
&lt;/beans&gt; 
</pre></p>
<p>Both declarations make a bean called anyService available in the ApplicationContext bound to an object instance of type AnyServiceImpl.</p>
<p>If one bean depended on another bean then defining is as simple as having one bean call the other.<br />
<pre class="brush: java;">
@Configuration
public class ApplicationConfig {
  @Bean
  public DependentBean dependentBean() {
      return new DependentBean(primaryBean());
  }

  @Bean
  public PrimaryBean primaryBean() {
      return new PrimaryBean();
  }
}
</pre></p>
<p>It is very easy to take sides here but both the Java based configuration as well as XML based has its own benefits. On one hand XML is declarative, Java is Object Oriented. Most will swear by advantage of one over other. I think both ways provide different semantics of doing the same thing and both approaches to configuration is ok if it suits application needs.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/885/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/885/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/885/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/885/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/885/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/885/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/885/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/885/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=885&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/03/08/configuring-spring-application-using-configuration-annotation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>
	</item>
		<item>
		<title>Mailing Google Docs As Attachment On Google App Engine</title>
		<link>http://meetumaltiar.wordpress.com/2011/03/05/mailing-google-docs-as-attachment-on-google-app-engine/</link>
		<comments>http://meetumaltiar.wordpress.com/2011/03/05/mailing-google-docs-as-attachment-on-google-app-engine/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 04:57:01 +0000</pubDate>
		<dc:creator>Meetu Maltiar</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[GAE]]></category>
		<category><![CDATA[google spreadsheet]]></category>

		<guid isPermaLink="false">http://meetumaltiar.wordpress.com/?p=870</guid>
		<description><![CDATA[Our application works with Google Spreadsheet API to update spreadsheets. The application now needed to send mail with an attachment of a google spreadsheet. We posted our query on google docs community here and on Google app engine here and there were no clear directions of implementing it. Let&#8217;s see how we went about implementing [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=870&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Our application works with Google Spreadsheet API to update spreadsheets. The application now needed to send mail with an attachment of a google spreadsheet. We posted our query on google docs community <a href="http://www.google.com/support/forum/p/Google+Docs/thread?tid=7d2dd6e417327d75&amp;hl=en">here</a> and on Google app engine <a href="http://groups.google.com/group/google-appengine-java/browse_thread/thread/67b807e41bf55b39/2e421717a776c11f?lnk=gst&amp;q=hazrati#2e421717a776c11f">here</a> and there were no clear directions of implementing it.</p>
<p>Let&#8217;s see how we went about implementing this feature.</p>
<p>Google provides its <a href="http://code.google.com/apis/spreadsheets/">spreadsheet API</a> and it allows you to create and retrieve data in Google Spreadsheets, but it does not allow us to either create or manage their permissions. Google also has <a href="http://code.google.com/apis/documents/">Google Documents List API</a> which can be used to create and retrieve a list of Google Spreadsheets. For our case Google Documents List API provides exporting functionality such that we can export Google documents in common formats like pdf, rtf, xls and others. Google also provides <a href="http://code.google.com/appengine/docs/java/mail/overview.html">java mail api</a> and with its <a href="http://code.google.com/appengine/docs/java/mail/usingjavamail.html#Multi_Part_Messages">Multi-Part Messages</a> feature we can send attachment as well.</p>
<p>For implementing this, we used <a href="http://code.google.com/apis/spreadsheets/">spreadsheet API</a> to retrieve spreadsheet entry. Using the spreadsheet entry we used <a href="http://code.google.com/apis/documents/">Google Documents List API</a> to export it in the specified format and we used <a href="http://code.google.com/appengine/docs/java/mail/overview.html">java mail api</a> to send exported data as an attachment.</p>
<p>We used <a href="http://www.playframework.org/">play framework</a> for our implementation but it can also be applied on other java frameworks as well. The class EmailSender first creates a google spreadsheet service and document service.</p>
<p><pre class="brush: java;">
public class EmailSender extends Controller {

private static final String META_FEED_URL = &quot;https://spreadsheets.google.com/feeds/spreadsheets/private/full&quot;;
private static String spreadSheetName = &quot;spreadsheetname&quot;;
private static String yourApplicationName = &quot;emailSender-version1&quot;;
private static String userEmail = &quot;yourmail@gmail.com&quot;;
private static String recepientEmail = &quot;recepientmail@gmail.com&quot;;
private static String password = &quot;password&quot;;


public static void emailSpreadsheetAsAttachment() throws AuthenticationException, MessagingException, IOException {
	SpreadsheetService spreadSheetService = createSpreadSheetService();
	DocsService documentService = createDocumentService();
	SpreadsheetEntry spreadsheetEntry = loadSpreadSheet(spreadSheetService, spreadSheetName);
	byte[] spreadSheetData = getSpreadSheetData(spreadSheetService, documentService, spreadsheetEntry);
	sendMailWithAttachment(spreadSheetData);
	}
. . .
. . .
private static SpreadsheetService createSpreadSheetService() throws AuthenticationException {
	SpreadsheetService spreadSheetService = new SpreadsheetService(yourApplicationName);
	spreadSheetService.setUserCredentials(userEmail, password);
	return spreadSheetService;
	}

private static DocsService createDocumentService() throws AuthenticationException {
	DocsService docsService = new DocsService(yourApplicationName);
	docsService.setUserCredentials(userEmail, password);
	return docsService;
       }
. . .
. . .
}
</pre><br />
<span id="more-870"></span><br />
For creating these two services we need the application name which is used for logging purposes and the user credentials to work with the google document. The next method call loadSpreadSheet(spreadSheetService, spreadSheetName) actually loads the spreadsheet entry given it&#8217;s spreadsheet name. The code listing is given below.</p>
<p><pre class="brush: java;">
public class EmailSender extends Controller {
. . .

private static SpreadsheetEntry loadSpreadSheet(SpreadsheetService spreadSheetService, String sheetName) {
	SpreadsheetEntry spreadSheetEntry = null;
	try {
		URL metafeedUrl = new URL(META_FEED_URL);
		SpreadsheetFeed feed = spreadSheetService.getFeed(metafeedUrl, SpreadsheetFeed.class);

		List&lt;SpreadsheetEntry&gt; spreadsheets = feed.getEntries();
		for (int i = 0; i &lt; spreadsheets.size(); i++) {
			SpreadsheetEntry entry = spreadsheets.get(i);
			if (entry.getTitle().getPlainText().equals(sheetName)) {
				spreadSheetEntry = entry;
				break;
			}
		}
	} catch (Exception e) {
		Logger.info(&quot;Loading Worksheet failed:&quot; + e.getMessage());
	}

	return spreadSheetEntry;
	}

. . .
}
</pre></p>
<p>Next we use the <a href="http://code.google.com/apis/documents/">Google Documents List API</a> to export the spreadsheet in Excel sheet format. The code listing for method getSpreadSheetData is given below.</p>
<p><pre class="brush: java;">
public class EmailSender extends Controller {
. . .

private static byte[] getSpreadSheetData(SpreadsheetService spreadSheetService, DocsService documentService,
			SpreadsheetEntry spreadsheetEntry) throws IOException {
	String spreadSheetkey = spreadsheetEntry.getKey();
	byte[] data = null;
	InputStream inStream = null;
	ByteArrayOutputStream outStream = null;

	// Substitute the spreadsheets token for the docs token
	UserToken docsToken = (UserToken) documentService.getAuthTokenFactory().getAuthToken();
	UserToken spreadsheetsToken = (UserToken) spreadSheetService.getAuthTokenFactory().getAuthToken();
	documentService.setUserToken(spreadsheetsToken.getValue());

	String exportUrl = &quot;https://spreadsheets.google.com/feeds/download/spreadsheets&quot; + &quot;/Export?key=&quot;
				+ spreadSheetkey + &quot;&amp;fmcmd=&quot; + &quot;xls&quot;;

	Logger.info(&quot;Exporting document from &quot; + exportUrl);

	MediaContent mc = new MediaContent();
	mc.setUri(exportUrl);

	try {
		MediaSource ms = documentService.getMedia(mc);

		inStream = ms.getInputStream();
		outStream = new ByteArrayOutputStream();

		int c;
		while ((c = inStream.read()) != -1) {
			outStream.write(c);
		}

		// Restore docs token for our DocList client
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		documentService.setUserToken(docsToken.getValue());
		if (inStream != null) {
			inStream.close();
		}
		if (outStream != null) {
			data = outStream.toByteArray();
			outStream.close();
		}
	}

. . .
}
</pre></p>
<p>The important point to note in this method is that we substitute the spreadsheets token for the docs token and change it back to the original in the finally block. Since on Google App Engine we cannot work with the File system therefore we get data in ByteArrayOutputStream instead. You can read more on using the tokens and exporting spreadsheets <a href="http://code.google.com/apis/documents/docs/2.0/developers_guide_java.html#DownloadingSpreadsheets">here</a>. This method returns a byte array of the exported spreadsheet  data which we can use to send mail as an attachment.</p>
<p>The next method sendMailWithAttachment(spreadSheetData) uses <a href="http://code.google.com/appengine/docs/java/mail/usingjavamail.html#Multi_Part_Messages">java mail api Multi-Part Messages</a> to send this spreadSheetData as an attachment. The code listing is given below.</p>
<p><pre class="brush: java;">
public class EmailSender extends Controller {
. . .

private static void sendMailWithAttachment(byte[] spreadSheetData) throws UnsupportedEncodingException,
			MessagingException {
	Properties props = new Properties();
	Session session = Session.getDefaultInstance(props, null);

	Message message = new MimeMessage(session);
	message.setFrom(new InternetAddress(userEmail, &quot;Administrator&quot;));

	message.addRecipient(Message.RecipientType.TO, new InternetAddress(recepientEmail, recepientEmail));

	String textBody = &quot;Your Excel Sheet as attachment&quot;;

	Multipart mp = new MimeMultipart();

	MimeBodyPart textPart = new MimeBodyPart();
	textPart.setContent(textBody, &quot;text/html&quot;);
	mp.addBodyPart(textPart);

	MimeBodyPart attachment = new MimeBodyPart();
	String excelFileName = spreadSheetName + &quot;.xls&quot;;
	String filename = URLEncoder.encode(excelFileName, &quot;UTF-8&quot;);
	attachment.setFileName(filename);
	attachment.setDisposition(Part.ATTACHMENT);

	DataSource src = new ByteArrayDataSource(spreadSheetData, &quot;application/x-ms-excel&quot;);
	DataHandler handler = new DataHandler(src);
	attachment.setDataHandler(handler);
	mp.addBodyPart(attachment);

	message.setContent(mp);
	message.setSubject(String.format(&quot;Google Spreadsheet as attachment&quot;));

	Transport.send(message);

	Logger.info(&quot;Mail with attachment file: &quot; + excelFileName + &quot; sent successfully&quot;);

	}

. . .
}
</pre></p>
<p>I have uploaded this working project <a href="http://code.google.com/p/emailattachment/">here</a>. You will have to update values for spreadSheetName, yourApplicationName, userEmail, recepientEmail and password accordingly in EmailSender class. </p>
<p>You will also have to download <a href="http://download.playframework.org/releases/play-1.0.3.2.zip">Play-1.0.3.2</a>. Unzip it and add it in the path variable of your operating system.</p>
<p><pre class="brush: bash;">
user@user-laptop:~/emailattachment$ cd &lt;PATH_TO_PROJECT&gt;
user@user-laptop:~/emailattachment$ play eclipsify
user@user-laptop:~/emailattachment$ play run
</pre></p>
<p>The play eclipsify command converts the project in eclipse project. Now if you hit the url http://localhost:9000/EmailSender/emailSpreadsheetAsAttachment you should see the email sent successfully in the logs. You will have to deploy this application on Google App Engine to send a mail though. The example shown here mails a google spreadsheet but it will work fine for google documents in general.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/meetumaltiar.wordpress.com/870/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/meetumaltiar.wordpress.com/870/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/meetumaltiar.wordpress.com/870/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/meetumaltiar.wordpress.com/870/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/meetumaltiar.wordpress.com/870/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/meetumaltiar.wordpress.com/870/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/meetumaltiar.wordpress.com/870/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/meetumaltiar.wordpress.com/870/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=meetumaltiar.wordpress.com&amp;blog=2328397&amp;post=870&amp;subd=meetumaltiar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://meetumaltiar.wordpress.com/2011/03/05/mailing-google-docs-as-attachment-on-google-app-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/575b01c9d6081bd1489da2066957e478?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mmaltiar</media:title>
		</media:content>
	</item>
	</channel>
</rss>
