<?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>Krishna&#039;s Blog</title>
	<atom:link href="http://krishnasblog.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://krishnasblog.com</link>
	<description>Rumblings by a Java guy on Java and Scala</description>
	<lastBuildDate>Wed, 22 May 2013 11:04:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='krishnasblog.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Krishna&#039;s Blog</title>
		<link>http://krishnasblog.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://krishnasblog.com/osd.xml" title="Krishna&#039;s Blog" />
	<atom:link rel='hub' href='http://krishnasblog.com/?pushpress=hub'/>
		<item>
		<title>Incorporating LDAP with Play 2.x (Scala) application</title>
		<link>http://krishnasblog.com/2013/03/29/incorporating-ldap-with-play-2-x-scala-application/</link>
		<comments>http://krishnasblog.com/2013/03/29/incorporating-ldap-with-play-2-x-scala-application/#comments</comments>
		<pubDate>Fri, 29 Mar 2013 23:08:36 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2224</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I extend my earlier blog Incorporating Authorization into Play 2.x (Scala) application to integrate with LDAP instead of database. Again there might be better ways to do this, but right [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2224&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example with LDAP" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example-with-ldap">here is the code and the steps</a>.</p>
<p>In continuation of <a title="Permalink to Play 2.x (Scala) is it a Spring MVC contender? – Introduction" href="http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/" rel="bookmark">Play 2.x (Scala) is it a Spring MVC contender? – Introduction</a>, in this blog, I extend my earlier blog <a title="Permalink to Incorporating Authorization into Play 2.x (Scala) application" href="http://krishnasblog.com/2013/03/28/incorporating-authorization-into-play-2-x-scala-application/" rel="bookmark">Incorporating Authorization into Play 2.x (Scala) application</a> to integrate with LDAP instead of database.</p>
<p>Again there might be better ways to do this, but right now there is no clear documentation. A quick googling will display this <a title="Google group link" href="https://groups.google.com/forum/?fromgroups#!topic/play-framework/-xZ9Ei037DI">Google group link</a> and <a title="Jgoday's Blog" href="http://jgoday.wordpress.com/2009/11/16/scala-and-ldap/">this link </a>and this <a title="Github link" href="https://github.com/Normation/scala-ldap">Github code</a>. All of them were of little help to me. So I took the 1st step and put one of these. I have used <a title="Unboundid LDAP SDK" href="https://www.unboundid.com/products/ldapsdk/">Unboundid LDAP SDK</a>&#8216;s <a title="InMemoryDirectoryServer" href="https://www.unboundid.com/products/ldapsdk/docs/javadoc/com/unboundid/ldap/listener/InMemoryDirectoryServer.html">InMemoryDirectoryServer</a>.</p>
<p>As a first step we need to add the below dependency in <a title="Build.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-ldap/project/Build.scala">Build.scala</a>,</p>
<pre class="brush: plain; title: ; notranslate">
&quot;com.unboundid&quot; % &quot;unboundid-ldapsdk&quot; % &quot;2.3.1&quot;,
</pre>
<p>Next we implement an in memory LDAP helper class <a title="LdapUtil.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-ldap/app/util/LdapUtil.scala">LdapUtil.scala</a> as below,</p>
<pre class="brush: plain; title: ; notranslate">
  def start(): InMemoryDirectoryServer = {
    val config = new InMemoryDirectoryServerConfig(&quot;dc=org&quot;);
    val listenerConfig = new InMemoryListenerConfig(&quot;test&quot;, null, 12345, null, null, null);
    config.setListenerConfigs(listenerConfig);
    config.setSchema(null); // do not check (attribute) schema
    val server = new InMemoryDirectoryServer(config);
    server.startListening();
...
    server.add(&quot;dn: cn=user@test.com,dc=staticsecurity,dc=geomajas,dc=org&quot;, &quot;objectClass: person&quot;, &quot;locale: nl_BE&quot;,
      &quot;sn: NormalUser&quot;, &quot;givenName: Joe&quot;, &quot;memberOf: cn=testgroup,dc=roles,dc=geomajas,dc=org&quot;, &quot;userPassword: password&quot;);
    server.add(&quot;dn: cn=admin@test.com,dc=staticsecurity,dc=geomajas,dc=org&quot;, &quot;objectClass: person&quot;, &quot;locale: nl_BE&quot;,
      &quot;sn: Administrator&quot;, &quot;givenName: Cindy&quot;, &quot;memberOf: cn=testgroup,dc=roles,dc=geomajas,dc=org&quot;, &quot;userPassword: password&quot;);

    server
  }

  def authenticate(email: String, password: String): Option[Account] = {
    val server = start

    val conn = server.getConnection();
    val entry = conn.getEntry(&quot;cn=&quot; + email + &quot;,dc=staticsecurity,dc=geomajas,dc=org&quot;);

    val permission = entry.getAttributeValue(&quot;sn&quot;).toString
    val retPass = entry.getAttributeValue(&quot;userPassword&quot;)
    server.shutDown(true)

    if (retPass.equals(password)) {
      println(&quot;password valid&quot;)
      val account = new Account(email, password, permission)
      toOption(account)
    } else {
      None
    }
  }

  def findByEmail(email: String): Option[Account] = {
    val server = start
    val conn = server.getConnection();
    val entry = conn.getEntry(&quot;cn=&quot; + email + &quot;,dc=staticsecurity,dc=geomajas,dc=org&quot;);

    val permission = entry.getAttributeValue(&quot;sn&quot;).toString
    val retPass = entry.getAttributeValue(&quot;userPassword&quot;)
    server.shutDown(true)

    val account = new Account(email, retPass, permission)
    toOption(account)
  }
</pre>
<p>If you notice the normal user rights are email:= user@test.com, pwd:= password and admin rights are email:= admin@test.com, pwd:= password. As in my earlier blog, we need to customize the AuthConfig as below,</p>
<pre class="brush: plain; title: ; notranslate">
trait AuthConfigImpl extends AuthConfig {
  type Id = String
  type User = Account
  type Authority = String
  val idTag = classTag[Id]
...
  def resolveUser(email: Id) = LdapUtil.findByEmail(email)
...
  def authorize(user: User, authority: Authority) = (user.permission, authority) match {
    case (&quot;Administrator&quot;, _) =&gt; true
    case (&quot;NormalUser&quot;, &quot;NormalUser&quot;) =&gt; true
    case _ =&gt; false
  }
}
</pre>
<p>Login form looks as below as in <a title="Application.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-ldap/app/controllers/Application.scala">Application.scala</a>,</p>
<pre class="brush: plain; title: ; notranslate">
  val loginForm = Form {
    mapping(&quot;email&quot; -&gt; email, &quot;password&quot; -&gt; text)(LdapUtil.authenticate)(_.map(u =&gt; (u.email, &quot;&quot;)))
      .verifying(&quot;Invalid email or password&quot;, result =&gt; result.isDefined)
  }
</pre>
<p>Finally the usage looks as below refer <a title="CoffeesController.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-ldap/app/controllers/CoffeesController.scala">CoffeesControler.scala</a>,</p>
<pre class="brush: plain; title: ; notranslate">
def create = StackAction(AuthorityKey -&gt; &quot;Administrator&quot;) { implicit request =&gt;
    database withSession {
      Ok(html.coffees.createForm(form, supplierSelect))
    }
  }
</pre>
<p>I hope this blog helped.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2224/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2224&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/29/incorporating-ldap-with-play-2-x-scala-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>
	</item>
		<item>
		<title>Incorporating Authorization into Play 2.x (Scala) application</title>
		<link>http://krishnasblog.com/2013/03/28/incorporating-authorization-into-play-2-x-scala-application/</link>
		<comments>http://krishnasblog.com/2013/03/28/incorporating-authorization-into-play-2-x-scala-application/#comments</comments>
		<pubDate>Thu, 28 Mar 2013 19:17:55 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2215</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how to use play20-auth to adopt to coffee example. As a first step for this example we need to add dependency in Build.scala as below, We [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2215&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example with Authorization" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example-with-authen-author">here is the code and the steps</a>.</p>
<p>In continuation of <a title="Permalink to Play 2.x (Scala) is it a Spring MVC contender? – Introduction" href="http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/" rel="bookmark">Play 2.x (Scala) is it a Spring MVC contender? – Introduction</a>, in this blog, I will demonstrate how to use <a title="play20-auth" href="https://github.com/t2v/play20-auth">play20-auth</a> to adopt to coffee example.</p>
<p>As a first step for this example we need to add dependency in <a title="Build.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-authen-author/project/Build.scala">Build.scala</a> as below,</p>
<pre class="brush: plain; title: ; notranslate">
    &quot;jp.t2v&quot; %% &quot;play2.auth&quot;      % &quot;0.9&quot;,
    &quot;jp.t2v&quot; %% &quot;play2.auth.test&quot; % &quot;0.9&quot; % &quot;test&quot;,
</pre>
<p>We need to define a <a title="Account.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-authen-author/app/models/Account.scala">Account.scala</a> domain object with permissions as below,</p>
<pre class="brush: plain; title: ; notranslate">
object Account extends Table[Account](&quot;ACCOUNT&quot;) {
  lazy val database = Database.forDataSource(DB.getDataSource())

  def id = column[Int](&quot;ID&quot;)
  def email = column[String](&quot;EMAIL&quot;)
  def password = column[String](&quot;PASSWORD&quot;)
  def name = column[String](&quot;NAME&quot;)
  def permission = column[Permission](&quot;PERMISSION&quot;)
  // Every table needs a * projection with the same type as the table's type parameter
  def * = id ~ email ~ password ~ name ~ permission &lt;&gt; (Account.apply _, Account.unapply _)
</pre>
<p>In order for Account object to accept <a title="Permission.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-authen-author/app/models/Permission.scala">Permission.scala</a> object as one of the column we need to implement <a title="MappedTypeMapper" href="http://slick.typesafe.com/doc/0.11.0/api/index.html#scala.slick.lifted.MappedTypeMapper">MappedTypeMapper </a>for the Permission as below,</p>
<pre class="brush: plain; title: ; notranslate">
  implicit val PermissionTimeMapper = MappedTypeMapper.base[Permission, String](
    d =&gt; Permission.stringValueOf(d),
    t =&gt; Permission.valueOf(t))

  def valueOf(value: String): Permission = value match {
    case &quot;Administrator&quot; =&gt; Administrator
    case &quot;NormalUser&quot; =&gt; NormalUser
    case _ =&gt; throw new IllegalArgumentException()
  }

  def stringValueOf(value: Permission): String = value match {
    case Administrator =&gt; &quot;Administrator&quot;
    case NormalUser =&gt; &quot;NormalUser&quot;
    case _ =&gt; throw new IllegalArgumentException()
  }
</pre>
<p>Next step is, we need to implement a trait <strong>AuthConfigImpl</strong> extending <strong>AuthConfig</strong> in <a title="Application.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-authen-author/app/controllers/Application.scala">Application.scala</a> indicating what is the User class to authenticate, what is the column that contains the Permission information and what is the redirecting page as below,</p>
<pre class="brush: plain; title: ; notranslate">
trait AuthConfigImpl extends AuthConfig {

  type Id = Int

  type User = Account

  type Authority = Permission

  val idTag = classTag[Id]

  val sessionTimeoutInSeconds = 3600

  def resolveUser(id: Id) = Account.findById(id)

  def loginSucceeded(request: RequestHeader) = Redirect(routes.CoffeesController.index)

  def logoutSucceeded(request: RequestHeader) = Redirect(routes.Application.login)

  def authenticationFailed(request: RequestHeader) = Redirect(routes.Application.login)

  def authorizationFailed(request: RequestHeader) = Forbidden(&quot;no permission&quot;)

  def authorize(user: User, authority: Authority) = (user.permission, authority) match {
    case (Administrator, _) =&gt; true
    case (NormalUser, NormalUser) =&gt; true
    case _ =&gt; false
  }
}
</pre>
<p>Now we need to submit the loginForm to authenticate a user in <strong>Application.scala</strong> as below,</p>
<pre class="brush: plain; title: ; notranslate">
  val loginForm = Form {
    mapping(&quot;email&quot; -&gt; email, &quot;password&quot; -&gt; text)(Account.authenticate)(_.map(u =&gt; (u.email, &quot;&quot;)))
      .verifying(&quot;Invalid email or password&quot;, result =&gt; result.isDefined)
  }
</pre>
<p><a title="Account.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-authen-author/app/models/Account.scala">Account.scala</a> authenticate method looks as below,</p>
<pre class="brush: plain; title: ; notranslate">
  def authenticate(email: String, password: String): Option[Account] = {
    findByEmail(email).filter { account =&gt; password.equals(account.password) }
  }
</pre>
<p>For details about integration with the action in the controller refer <a title="CoffeesController.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-authen-author/app/controllers/CoffeesController.scala">CoffeesController.scala</a> as below,</p>
<pre class="brush: plain; title: ; notranslate">
object CoffeesController extends Controller with AuthElement with AuthConfigImpl {
  def delete(pk: String) = StackAction(AuthorityKey -&gt; Administrator) { implicit request =&gt;
    database withSession {
      Home.flashing(Coffees.findByPK(pk).delete match {
        case 0 =&gt; &quot;failure&quot; -&gt; &quot;Entity has Not been deleted&quot;
        case x =&gt; &quot;success&quot; -&gt; s&quot;Entity has been deleted (deleted $x row(s))&quot;
      })
    }
  }
}
</pre>
<p>Notice how we use StackAction and validate for Administrator permission in the controller.</p>
<p>I hope this blog helped you.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2215/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2215/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2215&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/28/incorporating-authorization-into-play-2-x-scala-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>
	</item>
		<item>
		<title>Play 2.x (Scala) is it a Spring MVC contender? &#8211; Introduction</title>
		<link>http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/</link>
		<comments>http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/#comments</comments>
		<pubDate>Fri, 22 Mar 2013 03:08:49 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2123</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. I have been playing with Scala and Play 2.x for past 6 months and have gained lot of knowledge. I have been working with Spring related technologies for past 8 yrs. In the next few blogs I will be really exploring if the Scala [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2123&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example">here is the code and the steps</a>.</p>
<p>I have been playing with<a title="Scala" href="http://krishnasblog.com/category/scala/"> Scala</a> and<a title="Play 2.x" href="http://www.playframework.com/"> Play 2.x</a> for past 6 months and have gained lot of knowledge. I have been working with<a title="Spring" href="http://krishnasblog.com/category/java/spring/"> Spring</a> related technologies for past 8 yrs. In the next few blogs I will be really exploring if the<i> Scala</i> flavor of<i> Play 2.x</i> is ready for prime time.</p>
<p>As usual, I will be exploring how well we can build Data Access Layer, Controller, Frontend integration with<strong> Play 2.x</strong> using<a title="Test Driven Development" href="http://en.wikipedia.org/wiki/Test-driven_development"> Test Driven Development</a>. I will also be exploring how well Play 2.x is integrated with<a title="Security" href="http://krishnasblog.com/category/java/spring/spring-security/"> Security</a> (Authentication/Authorization) capabilities and how well<strong> Scala</strong> is integrated with other Authentication systems like<a title="LDAP" href="http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol"> LDAP</a>.</p>
<p>The use case I will be talking in the next few blogs is the popular Coffee Supplier web application, which demonstrates a simple<a title="CRUD" href="https://github.com/ThomasAlexandre/playcrud"> CRUD</a> base application. And I will elaborate aspects only Admin users can create the Coffee and Normal users can see the list.</p>
<p>One common thing about Play 2.x and<i> Spring</i> MVC is both follow MVC design patterns. There are also other Scala Web frameworks like<a title="Lift" href="http://liftweb.net/"> Lift</a>, I haven&#8217;t played with it yet.</p>
<h2>Overall architecture of Play 2.1 MVC is as below</h2>
<div class="wp-caption alignnone" style="width: 508px"><img alt="Play 2.1 over all architecture" src="http://www.playframework.com/documentation/1.0/images/diagrams_path" width="498" height="353" /><p class="wp-caption-text">Play 2.1 over all architecture</p></div>
<p>In this example, I will use popular tools like<a title="Slick" href="http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/"> Slick</a> to access the Database,<a title="Play-Auth" href="https://github.com/t2v/play20-auth"> Play-Auth</a> to do authentication and authorization. And I will extensively use<a title="ScalaTest" href="http://www.scalatest.org/"> ScalaTest</a> to do<i> Test Driven Development</i>(<a title="TDD" href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>)/<a title="Behavior Driven Development" href="http://en.wikipedia.org/wiki/Behavior-driven_development"> Behavior Driven Development</a>(<a title="BDD" href="http://en.wikipedia.org/wiki/Behavior-driven_development"> BDD</a>).</p>
<p>The layers I will be developing in<i> TDD</i> in the order are,</p>
<ul>
<li><a title="Scala DAL layer implementation" href="http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/">DAL layer</a></li>
<li><a title="Controller layer implementation with ScalaMock" href="http://krishnasblog.com/2013/03/20/implementing-controller-using-play-2-x-scala-scalamock/">Controller Layer</a></li>
<li><a title="Frontend Integration" href="http://krishnasblog.com/2013/03/20/testing-frontend-integration-with-play-2-x-scala/">Frontend integration</a></li>
<li>Enabling <a title="Authentication" href="http://krishnasblog.com/2013/03/20/incorporating-login-authentication-into-play-2-x-scala-application/">Authentication</a> and <a title="Authorization" href="http://krishnasblog.com/2013/03/28/incorporating-authorization-into-play-2-x-scala-application/">Authorization</a></li>
<li>Enabling <a title="LDAP Authorization" href="http://krishnasblog.com/2013/03/29/incorporating-ldap-with-play-2-x-scala-application/">LDAP Authorization</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2123/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2123/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2123&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>

		<media:content url="http://www.playframework.com/documentation/1.0/images/diagrams_path" medium="image">
			<media:title type="html">Play 2.1 over all architecture</media:title>
		</media:content>
	</item>
		<item>
		<title>Incorporating Login/ Authentication into Play 2.x (Scala) application</title>
		<link>http://krishnasblog.com/2013/03/20/incorporating-login-authentication-into-play-2-x-scala-application/</link>
		<comments>http://krishnasblog.com/2013/03/20/incorporating-login-authentication-into-play-2-x-scala-application/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 13:46:47 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2130</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how to extend Security.Authenticated standard Play API to implement basic authentication in your application. I took this code play-test-security as my basis for implementing Security.Authenticated based authentication. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2130&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example-with-auth">here is the code and the steps</a>.</p>
<p>In continuation of <a title="Permalink to Play 2.x (Scala) is it a Spring MVC contender? – Introduction" href="http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/" rel="bookmark">Play 2.x (Scala) is it a Spring MVC contender? – Introduction</a>, in this blog, I will demonstrate how to extend <strong>Security.Authenticated</strong> standard Play API to implement basic authentication in your application.</p>
<p>I took this code <a title="play-test-security" href="https://github.com/oscarrenalias/play-test-security">play-test-security</a> as my basis for implementing <a title="Security.Authenticated" href="http://www.playframework.com/documentation/2.0.4/ScalaActionsComposition">Security.Authenticated</a> based authentication.</p>
<p>As a first step, I will extend this class to implement a Security trait as below,</p>
<pre class="brush: plain; title: ; notranslate">
trait Secured {
  self: Controller =&gt;

  /**
   * Retrieve the connected user id.
   */
  def username(request: RequestHeader) = request.session.get(&quot;email&quot;)

  /**
   * Redirect to login if the use in not authorized.
   */
  def onUnauthorized(request: RequestHeader): Result

  def IsAuthenticated(f: =&gt; String =&gt; Request[AnyContent] =&gt; Result) =
    Security.Authenticated(username, onUnauthorized) { user =&gt;
      Action(request =&gt; f(user)(request))
    }
}
</pre>
<p>As provided in the comment section it is clear what each method does. Next step is to plumb the login steps refer <a title="Application.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-auth/app/controllers/Application.scala">Application.scala</a> as below,</p>
<pre class="brush: plain; title: ; notranslate">
  lazy val loginForm = Form(
    tuple(
      &quot;email&quot; -&gt; text,
      &quot;password&quot; -&gt; text) verifying (&quot;Invalid user or password&quot;, result =&gt; result match {
        case (email, password) =&gt; {
          println(&quot;user=&quot; + email + &quot; password=&quot; + password);
          val userList = Users.authenticate(email, password)
          userList == 1
        }
        case _ =&gt; false
      }))

  def login = Action { implicit request =&gt;
    Ok(html.login(loginForm))
  }

  /**
   * Handle login form submission.
   */
  def authenticate = Action { implicit request =&gt;
    loginForm.bindFromRequest.fold(
      formWithErrors =&gt; BadRequest(html.login(formWithErrors)),
      user =&gt; Redirect(routes.CoffeesController.index).withSession(&quot;email&quot; -&gt; user._1))
  }

  /**
   * Logout and clean the session.
   */
  def logout = Action {
    Redirect(routes.Application.login).withNewSession.flashing(
      &quot;success&quot; -&gt; &quot;You've been logged out&quot;)
  }
</pre>
<p>The User <a title="Implementing DAL in Play 2x Scala Slick Scalatest" href="http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/">Slick</a> domain object and the authenticate method in <a title="User.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-auth/app/models/User.scala">User.scala</a> looks as below,</p>
<pre class="brush: plain; title: ; notranslate">
object Users extends Table[User](&quot;USER&quot;) {
  lazy val database = Database.forDataSource(DB.getDataSource())

  // -- Parsers

  def email = column[String](&quot;EMAIL&quot;, O.PrimaryKey)
  def name = column[String](&quot;NAME&quot;)
  def password = column[String](&quot;PASSWORD&quot;)

  def * = email ~ name ~ password &lt;&gt; (User.apply _, User.unapply _)
//....
  def authenticate(email: String, password: String): Int = {
    database withSession { implicit session =&gt;
      val q1 = for (u       println(&quot;^^^^^^^^&quot; + Query(q1.length).first)
      Query(q1.length).first
    }
  }
</pre>
<p>Finally the <a title="CoffeesController.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example-with-auth/app/controllers/CoffeesController.scala">CoffeesController.scala</a> where we need to override onUnauthorized method and put the IsAuthenticated block in each action as below,</p>
<pre class="brush: plain; title: ; notranslate">
  def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login())

  /**
   * Display the paginated list.
   *
   * @param page Current page number (starts from 0)
   * @param orderBy Column to be sorted
   * @param filter Filter applied on entity names
   */
  def list(page: Int, orderBy: Int, filter: String = &quot;%&quot;) = IsAuthenticated { username =&gt;
    implicit request =&gt;
      database withSession {
        Ok(html.coffees.list(
          Page(Coffees.list(page, pageSize, orderBy, filter).list,
            page,
            offset = pageSize * page,
            Coffees.findAll(filter).list.size),
          orderBy,
          filter))
      }
  }
</pre>
<p>To test if authentication worked, start play,</p>
<pre class="brush: plain; title: ; notranslate">
play run
</pre>
<p>And when you type the url <a href="http://localhost:9000/coffee" rel="nofollow">http://localhost:9000/coffee</a>, you get the login page as below,</p>
<div id="attachment_2201" class="wp-caption alignnone" style="width: 370px"><a href="http://krishnasblog1068.files.wordpress.com/2013/03/scala-secured-authenticated-login.png"><img class="size-full wp-image-2201" alt="Scala Secured.Authenticated-login" src="http://krishnasblog1068.files.wordpress.com/2013/03/scala-secured-authenticated-login.png?w=625"   /></a><p class="wp-caption-text">Scala Secured.Authenticated-login</p></div>
<p>I hope this blog helped you. In my next blog, I will show how you do authorization.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2130/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2130/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2130&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/20/incorporating-login-authentication-into-play-2-x-scala-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/03/scala-secured-authenticated-login.png" medium="image">
			<media:title type="html">Scala Secured.Authenticated-login</media:title>
		</media:content>
	</item>
		<item>
		<title>Testing Frontend integration with Play 2.x (Scala)</title>
		<link>http://krishnasblog.com/2013/03/20/testing-frontend-integration-with-play-2-x-scala/</link>
		<comments>http://krishnasblog.com/2013/03/20/testing-frontend-integration-with-play-2-x-scala/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 13:45:54 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2129</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how we implement a simple test to test the Web layer using TestServer. I will continue from my earlier example of Implementing Controller using Play 2.x [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2129&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example">here is the code and the steps</a>.</p>
<p>In continuation of <a title="Permalink to Play 2.x (Scala) is it a Spring MVC contender? – Introduction" href="http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/" rel="bookmark">Play 2.x (Scala) is it a Spring MVC contender? – Introduction</a>, in this blog, I will demonstrate how we implement a simple test to test the Web layer using <em>TestServer</em>. I will continue from my earlier example of <a title="Permalink to Implementing Controller using Play 2.x (Scala), ScalaMock" href="http://krishnasblog.com/2013/03/20/implementing-controller-using-play-2-x-scala-scalamock/" rel="bookmark">Implementing Controller using Play 2.x (Scala), ScalaMock</a> where I did the mock testing.</p>
<p>Refer <a title="Build.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example/project/Build.scala">Build.scala</a> for build configuration.</p>
<p>In this blog, I will be testing the routes refer <a title="CoffeesControllerTest.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example/test/controllers/CoffeesControllerTest.scala">CoffeesControllerTest.scala</a> for more details, the snippet is as below,</p>
<pre class="brush: plain; title: ; notranslate">
    it(&quot;POST /coffees/Colombian/delete should return SEE_OTHER&quot;) {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {

        val Some(result) = route(FakeRequest(POST, &quot;/coffees/Colombian/delete&quot;))
        status(result) should equal(SEE_OTHER)
      }
    }

    it(&quot;POST wrong url /coffees/Colombian/delete1 should return None&quot;) {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {

        val result = route(FakeRequest(POST, &quot;/coffees/Colombian/delete1&quot;))
        result should equal(None)
      }
    }
</pre>
<p>In the next block I will show how to do end to end testing from web layer using <strong>TestServer </strong>refer <a title="IntegrationTest.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example/test/controllers/IntegrationSpec.scala">IntegrationTest.scala<strong> </strong></a>,</p>
<pre class="brush: plain; title: ; notranslate">
class IntegrationSpec extends Specification {

  &quot;Application&quot; should {

    &quot;work from within a browser&quot; in {
      running(TestServer(3333), HTMLUNIT) { browser =&gt;

        browser.goTo(&quot;http://localhost:3333/coffees&quot;)
        browser.pageSource must contain(&quot;Colombian&quot;)
      }
    }

    &quot;work from within a browser&quot; in {
      running(TestServer(3333), HTMLUNIT) { browser =&gt;

        browser.goTo(&quot;http://localhost:3333/coffees&quot;)

        browser.pageSource must contain(&quot;Colombian&quot;)
      }
    }

    &quot;work from within a browser&quot; in {
      running(TestServer(3333), HTMLUNIT) { browser =&gt;

        browser.goTo(&quot;http://localhost:3333/coffees&quot;)
        browser.pageSource must not contain(&quot;Colombian1&quot;)
      }
    }

  }
}
</pre>
<p>Also while testing the application from web layer, we need to populate the data in the <a title="Global.scala" href="https://github.com/skprasadu/scala-example/blob/master/coffee-example/app/Global.scala">Global.scala</a> as below,</p>
<pre class="brush: plain; title: ; notranslate">
object Global extends GlobalSettings {

  override def onStart(app: Application) {

    lazy val database = Database.forDataSource(DB.getDataSource())

    database withSession {
      // Create the tables, including primary and foreign keys
      val ddl = (Suppliers.ddl ++ Coffees.ddl)

      ddl.create

      // Insert some suppliers
      Suppliers.insertAll(
        Supplier(Some(101), &quot;Acme, Inc.&quot;, &quot;99 Market Street&quot;, &quot;Groundsville&quot;, &quot;CA&quot;, &quot;95199&quot;),
//...
      // Insert some coffees (using JDBC's batch insert feature, if supported by the DB)
      Coffees.insertAll(
        Coffee(Some(&quot;Colombian&quot;), 101, 799, 0, 0),
    }
  }
}
</pre>
<p>I hope this blog helped you. In the next blog I will implement simple authentication.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2129/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2129/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2129&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/20/testing-frontend-integration-with-play-2-x-scala/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing Controller using Play 2.x (Scala), ScalaMock</title>
		<link>http://krishnasblog.com/2013/03/20/implementing-controller-using-play-2-x-scala-scalamock/</link>
		<comments>http://krishnasblog.com/2013/03/20/implementing-controller-using-play-2-x-scala-scalamock/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 13:44:46 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2126</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how we implement a simple Controller implementation using ScalaTest / ScalaMock. I will continue from my earlier example of Implementing DAL in Play 2.x (Scala), Slick, ScalaTest of [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2126&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example">here is the code and the steps</a>.</p>
<p>In continuation of <a title="Permalink to Play 2.x (Scala) is it a Spring MVC contender? – Introduction" href="http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/" rel="bookmark">Play 2.x (Scala) is it a Spring MVC contender? – Introduction</a>, in this blog, I will demonstrate how we implement a simple Controller implementation using ScalaTest / ScalaMock. I will continue from my earlier example of <a title="Permalink to Implementing DAL in Play 2.x (Scala), Slick, ScalaTest" href="http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/" rel="bookmark">Implementing DAL in Play 2.x (Scala), Slick, ScalaTest</a> of the basic <strong>CRUD</strong> operations on Coffee catalogue.</p>
<p>In this example as well we need the ScalaMock dependency in Build.scala as below,</p>
<pre class="brush: plain; title: ; notranslate"> 
&quot;com.typesafe.slick&quot; %% &quot;slick&quot; % &quot;1.0.0&quot;,
...
&quot;org.scalamock&quot; %% &quot;scalamock-scalatest-support&quot; % &quot;3.0&quot; % &quot;test&quot;,
</pre>
<p>In our Previous example, we have already implemented a <a title="DAL" href="http://en.wikipedia.org/wiki/Data_access_layer">DAL </a>trait called CoffeeComponent with basic<i> CRUD</i> as below,</p>
<pre class="brush: plain; title: ; notranslate">
trait CoffeeComponent {
  def find(pk: String): Query[Coffees.type, Coffee]
  def findall(pk: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def list(page: Int, pageSize: Int, orderBy: Int, filter: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def delete(pk: String): Int
}
</pre>
<p>We are construction injecting CoffeeComponent to the CoffeeController and create a<a title="Singleton" href="http://en.wikipedia.org/wiki/Singleton_pattern"> Singleton</a> object with the same name, as below,</p>
<pre class="brush: plain; title: ; notranslate">
class CoffeesController(coffeeComponent: CoffeeComponent) extends Controller {
...
  def delete(pk: String) = Action {
    database withSession {
      println(&quot;in db session&quot;)
      Home.flashing(coffeeComponent.delete(pk) match {
        case 0 =&gt; &quot;failure&quot; -&gt; &quot;Entity has Not been deleted&quot;
        case x =&gt; &quot;success&quot; -&gt; s&quot;Entity has been deleted (deleted $x row(s))&quot;
      })
    }
  }
}

object CoffeesController extends CoffeesController(new CoffeeComponentImpl)
</pre>
<p>As seen above, we have a delete method, we will build a<i> ScalaMock</i> to mock the delete method of coffeeComponent and control the expected behavior to return 1 row effected and assert for HTTP<a title="SEE_OTHER" href="http://www.playframework.com/documentation/2.1.0/JavaActions"> SEE_OTHER</a> status as below,</p>
<pre class="brush: plain; title: ; notranslate">
class CoffeesControllerTest extends FunSpec with ShouldMatchers with MockFactory {
  describe(&quot;Coffee Controller with Mock test&quot;) {

    it(&quot;should delete a coffee record with assert on status&quot;) {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
        val mockComponent = mock[CoffeeComponent]
        (mockComponent.delete _).expects(&quot;Columbian&quot;) returning (1) twice
        val controller = new CoffeesController(mockComponent)
        mockComponent.delete(&quot;Columbian&quot;) should equal (1)
        val result = controller.delete(&quot;Columbian&quot;)(FakeRequest())
        status(result) should equal (SEE_OTHER)
      }
    }
  }
}
</pre>
<p>If you notice, we are extending<i> FunSpec</i> of<a title="ScalaTest" href="http://www.scalatest.org/quick_start"> ScalaTest</a> for<a title="BDD" href="http://en.wikipedia.org/wiki/Behavior-driven_development"> BDD</a>. Also the HTTP status is<i> SEE_OTHER</i>, this is because the Success is redirected to Index page.</p>
<p>Now if you run the<i> ScalaTest</i> you will see the result in STS as below,</p>
<div id="attachment_2171" class="wp-caption alignnone" style="width: 635px"><a href="http://krishnasblog1068.files.wordpress.com/2013/03/scalatest-coffee-example-with-scalamock.png"><img class="size-full wp-image-2171" alt="ScalaTest Coffee Example with ScalaMock" src="http://krishnasblog1068.files.wordpress.com/2013/03/scalatest-coffee-example-with-scalamock.png?w=625&#038;h=219" width="625" height="219" /></a><p class="wp-caption-text">ScalaTest Coffee Example with ScalaMock</p></div>
<p>I hope this blog helped. In my next blog, I will talk about controller routes testing and Frontend testing.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2126/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2126&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/20/implementing-controller-using-play-2-x-scala-scalamock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/03/scalatest-coffee-example-with-scalamock.png" medium="image">
			<media:title type="html">ScalaTest Coffee Example with ScalaMock</media:title>
		</media:content>
	</item>
		<item>
		<title>Implementing DAL in Play 2.x (Scala), Slick, ScalaTest</title>
		<link>http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/</link>
		<comments>http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 13:44:09 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2125</guid>
		<description><![CDATA[For people in hurry here is the code and the steps. In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how we implement a simple Data Access Layer using ScalaTest and using Behavior Driven Development. The technical stack I will be using for this demo is [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2125&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Coffee Example" href="https://github.com/skprasadu/scala-example/tree/master/coffee-example">here is the code and the steps</a>.</p>
<p>In continuation of <a title="Permalink to Play 2.x (Scala) is it a Spring MVC contender? – Introduction" href="http://krishnasblog.com/2013/03/22/play-2-x-scala-is-it-a-spring-mvc-contender-introduction/" rel="bookmark">Play 2.x (Scala) is it a Spring MVC contender? – Introduction</a>, in this blog, I will demonstrate how we implement a simple<a title="Data Access Layer" href="http://en.wikipedia.org/wiki/Data_access_layer"> Data Access Layer</a> using<a title="Scala" href="http://krishnasblog.com/category/scala/"> Scala</a>Test and using<a title="Behavior Driven Development" href="http://en.wikipedia.org/wiki/Behavior-driven_development"> Behavior Driven Development</a>.</p>
<p>The technical stack I will be using for this demo is<a title="Java 7" href="http://www.oracle.com/technetwork/java/javase/downloads/index.html"> Java 7</a>,<a title="Play 2.1.0" href="http://www.playframework.com/download"> Play 2.1.0</a>,<i> Scala</i> 2.10.0,<a title="Slick" href="http://krishnasblog.com/2013/03/06/integrating-play-2-1-with-slick-1-0-0-database-query-dsl/"> Slick</a> 1.0.0,<strong> ScalaTest</strong> /<a title="ScalaMock" href="http://www.scalatest.org/user_guide/testing_with_mock_objects#scalamock"> ScalaMock</a> 3.0,<a title="STS IDE" href="http://www.springsource.org/downloads/sts-ggts"> STS IDE</a> for Scala Development,<a title="Scala IDE plugin" href="http://scala-ide.org/"> Scala IDE plugin</a> with<a title="ScalaTest" href="http://www.scalatest.org/"> ScalaTest</a>.</p>
<p>As a first step create a Play project called coffee-example and select the language as Scala as below,</p>
<pre class="brush: plain; title: ; notranslate">
play new coffee-example
</pre>
<p>Now we need to include these dependencies in Build.scala. In this example, we don&#8217;t need<i> ScalaMock</i> but we will still include that dependency as below,</p>
<pre class="brush: plain; title: ; notranslate">
&quot;com.typesafe.slick&quot; %% &quot;slick&quot; % &quot;1.0.0&quot;,
...
&quot;org.scalamock&quot; %% &quot;scalamock-scalatest-support&quot; % &quot;3.0&quot; % &quot;test&quot;,
</pre>
<p>Let us convert this project into Eclipse project as below,</p>
<pre class="brush: plain; title: ; notranslate">
play eclipse
</pre>
<p>Let us open<i> STS IDE</i> and create a DomainTest.scala under test folder. The intent is we create a new CoffeeComponent class and implement a method findById method and pass a Coffee name and return the Coffee object and assert for its price. We also need initialize the data we are supposed to assert.</p>
<pre class="brush: plain; title: ; notranslate">
class DomainSpec extends FunSpec with ShouldMatchers with InitTrait {

  lazy val database = Database.forDataSource(DB.getDataSource())

  describe(&quot;Coffee Data Access&quot;) {

    it(&quot;should find Coffee object for a given Coffee name&quot;) {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
        database withSession {
          init

          val cc = new CoffeeComponentImpl()
          val c = cc.find(&quot;Colombian&quot;)
          c.first.price should equal(799L)
        }
      }
    }
  }
}
</pre>
<p>One bug I noticed is, when there are multiple test cases opening database connection it will create <a title="Attempting to obtain a connection from a pool that has already been shutdown" href="https://groups.google.com/forum/#!topic/play-framework/dClYCObR9o4">Attempting to obtain a connection from a pool that has already been shutdown</a> error.</p>
<p>We create a CoffeeComponent trait and CoffeeComponentImpl, which create basic<a title="CRUD" href="https://github.com/ThomasAlexandre/playcrud"> CRUD</a> operations as below,</p>
<pre class="brush: plain; title: ; notranslate">
trait CoffeeComponent {
  def find(pk: String): Query[Coffees.type, Coffee]
  def findall(pk: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def list(page: Int, pageSize: Int, orderBy: Int, filter: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def delete(pk: String): Int
}

class CoffeeComponentImpl extends CoffeeComponent {

  def find(pk: String): Query[Coffees.type, Coffee] = {
    Coffees.findByPK(pk)
  }

  def findall(pk: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)] = {
    Coffees.findAll(pk)
  }

  def list(page: Int, pageSize: Int, orderBy: Int, filter: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)] = {
    Coffees.list(page, pageSize, orderBy, filter)
  }

  def delete(pk: String): Int = {
    find(pk).delete
  }
}
</pre>
<p>We also need to create the Initialize Data for the test as below,</p>
<pre class="brush: plain; title: ; notranslate">
trait InitTrait {
  def init = {
    val ddl = (Suppliers.ddl ++ Coffees.ddl)

    ddl.drop
    ddl.create
    // Insert some suppliers
    Suppliers.insertAll(
      Supplier(Some(101), &quot;Acme, Inc.&quot;, &quot;99 Market Street&quot;, &quot;Groundsville&quot;, &quot;CA&quot;, &quot;95199&quot;))
.....
    Coffees.insertAll(
      Coffee(Some(&quot;Colombian&quot;), 101, 799, 0, 0))
}
}
</pre>
<p>Now run the<i> ScalaTest</i> from Eclipse IDE, you will see something as below,</p>
<div id="attachment_2156" class="wp-caption alignnone" style="width: 635px"><a href="http://krishnasblog1068.files.wordpress.com/2013/03/scalatest-coffee-example.png"><img class="size-full wp-image-2156" alt="ScalaTest Coffee Example" src="http://krishnasblog1068.files.wordpress.com/2013/03/scalatest-coffee-example.png?w=625&#038;h=211" width="625" height="211" /></a><p class="wp-caption-text"><strong> ScalaTest</strong> Coffee Example</p></div>
<p>I hope this blog helped you. In the next blog I will demonstrate how we can mock a Controller and test the Controller.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2125/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2125&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/20/implementing-dal-in-play-2-x-scala-slick-scalatest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/03/scalatest-coffee-example.png" medium="image">
			<media:title type="html">ScalaTest Coffee Example</media:title>
		</media:content>
	</item>
		<item>
		<title>Integrating Play 2.1 with Slick 1.0.0 Database query DSL</title>
		<link>http://krishnasblog.com/2013/03/06/integrating-play-2-1-with-slick-1-0-0-database-query-dsl/</link>
		<comments>http://krishnasblog.com/2013/03/06/integrating-play-2-1-with-slick-1-0-0-database-query-dsl/#comments</comments>
		<pubDate>Wed, 06 Mar 2013 16:16:08 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2099</guid>
		<description><![CDATA[For people in hurry here is the code and the steps to setup. Refer this blog on Play 2.0: Building Web Application using Scala for details on Play and Scala. In the next few blogs I will be writing enterprise class web application using Play and Scala. I will be covering topics like Database modeling and Security. [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2099&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry <a title="Integrationg Play 2.1 with Slick 1.0.0" href="https://github.com/skprasadu/scala-example/tree/master/bookstore">here is the code and the steps to setup</a>.</p>
<p>Refer this blog on <a title="Permalink to Play 2.0: Building Web Application using Scala" href="http://krishnasblog.com/2012/11/04/play-2-0-web-development-framework-using-scala/" rel="bookmark">Play 2.0: Building Web Application using Scala</a> for details on Play and Scala.</p>
<p>In the next few blogs I will be writing enterprise class web application using Play and Scala. I will be covering topics like Database modeling and Security. Now officially Scala has adopted <a title="Slick" href="http://slick.typesafe.com/">Slick</a> as the <a class="zem_slink" title="Database" href="http://en.wikipedia.org/wiki/Database" target="_blank" rel="wikipedia">Database query</a> DSL. But when you create a new Play application and add Slick library as <a title="Getting Started with Play 2.1 , Scala 2.10 and Slick 0.11.1" href="http://www.jroller.com/ouertani/entry/getting_started_with_play_2">mentioned in this blog</a>, it is not working. It gives a strange error like <a title="No suitable driver found in tests" href="http://stackoverflow.com/questions/14033629/playframework-2-0-scala-no-suitable-driver-found-in-tests">No suitable driver found in tests.</a></p>
<p>I also found <a title="slick-play2-example" href="https://github.com/mgonto/slick-play2-example">slick-play2-example</a>, this sample expect us to create a DAL layer, but we cannot directly play with slick in our test code.</p>
<p>After much further research I <a title="play-slick plugin" href="https://github.com/freekh/play-slick">came across this plugin</a>. I tried integrating this with my Play application and it worked like a charm.</p>
<p>We will define a Coffee class and a Supplier class. One Coffee has multiple Suppliers. The class design is as below,</p>
<pre class="brush: plain; title: ; notranslate">
case class Coffee(name: String, supID: Int, price: Double, sales: Int, total: Int)

object Coffees extends Table[Coffee](&quot;COFFEES&quot;) {
def name = column[String](&quot;COF_NAME&quot;, O.PrimaryKey)
def supID = column[Int](&quot;SUP_ID&quot;)
def price = column[Double](&quot;PRICE&quot;)
def sales = column[Int](&quot;SALES&quot;)
def total = column[Int](&quot;TOTAL&quot;)
def * = name ~ supID ~ price ~ sales ~ total &lt;&gt; (Coffee.apply _, Coffee.unapply _)
// A reified foreign key relation that can be navigated to create a join
def supplier = foreignKey(&quot;SUP_FK&quot;, supID, Suppliers)(_.id)
}

case class Supplier(id: Int, name: String, street: String, city: String, state: String, zip: String)

// Definition of the SUPPLIERS table
object Suppliers extends Table[Supplier](&quot;SUPPLIERS&quot;) {
def id = column[Int](&quot;SUP_ID&quot;, O.PrimaryKey) // This is the primary key column
def name = column[String](&quot;SUP_NAME&quot;)
def street = column[String](&quot;STREET&quot;)
def city = column[String](&quot;CITY&quot;)
def state = column[String](&quot;STATE&quot;)
def zip = column[String](&quot;&lt;a class=&quot;zem_slink&quot; title=&quot;ZIP (file format)&quot; href=&quot;http://en.wikipedia.org/wiki/ZIP_%28file_format%29&quot; target=&quot;_blank&quot; rel=&quot;wikipedia&quot;&gt;ZIP&lt;/a&gt;&quot;)
// Every table needs a * projection with the same type as the table's type parameter
def * = id ~ name ~ street ~ city ~ state ~ zip &lt;&gt; (Supplier.apply _, Supplier.unapply _)
}
</pre>
<p>Below is the ScalaTest to test various capabilities of Slick,</p>
<pre class="brush: plain; title: ; notranslate">
DB.withSession{ implicit session =&gt;

//Populate sample data
val testSuppliers = Seq(
Supplier(101, &quot;Acme, Inc.&quot;,      &quot;99 Market Street&quot;, &quot;Groundsville&quot;, &quot;CA&quot;, &quot;95199&quot;),
Supplier( 49, &quot;Superior Coffee&quot;, &quot;1 Party Place&quot;,    &quot;Mendocino&quot;,    &quot;CA&quot;, &quot;95460&quot;),
Supplier(150, &quot;The High Ground&quot;, &quot;100 Coffee Lane&quot;,  &quot;Meadows&quot;,      &quot;CA&quot;, &quot;93966&quot;)
)
Suppliers.insertAll( testSuppliers: _*)

val testCoffees= Seq(
Coffee(&quot;Colombian&quot;,         101, 7.99, 0, 0),
Coffee(&quot;French_Roast&quot;,       49, 8.99, 0, 0),
Coffee(&quot;Espresso&quot;,          150, 9.99, 0, 0),
Coffee(&quot;Colombian_Decaf&quot;,   101, 8.99, 0, 0),
Coffee(&quot;French_Roast_Decaf&quot;, 49, 9.99, 0, 0)
)
Coffees.insertAll( testCoffees: _*)

//Assert coffee data equals to the test list of coffee
Query(Coffees).list must equalTo(testCoffees)

//List all coffee less than $10
val q1 = for { c &lt;- Coffees if c.price &lt; 10.0 } yield (c.name)

q1 foreach println
println(&quot;**************&quot;);

//return all suppliers for coffee less than $9.0
val q2 = for { c &lt;- Coffees if c.price &lt; 9.0
s &lt;- c.supplier } yield (c.name, s.name)

q2 foreach println
println(&quot;**************&quot;);

//return all suppliers for coffee using zip
val q3 = for {
(c, s) &lt;- Coffees zip Suppliers
} yield (c.name, s.name)

q3 foreach println
println(&quot;**************&quot;);

//Union
val q4 = Query(Coffees).filter(_.price &lt; 8.0)
val q5 = Query(Coffees).filter(_.price &gt; 9.0)
val unionQuery = q4 union q5
unionQuery foreach println
println(&quot;**************&quot;);

//Union second approach
val unionAllQuery = q4 unionAll q5
unionAllQuery foreach println
println(&quot;**************&quot;);

//Group by
val r = (for {
c &lt;- Coffees
s &lt;- c.supplier
} yield (c, s)).groupBy(_._1.supID)

//Aggregation
val r1 = r.map { case (supID, css) =&gt;
(supID, css.length, css.map(_._1.price).avg)
}

r1 foreach println
}
</pre>
<p>In my next blog, I will take a real example and implement using Slick. I hope this blog helped.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2099/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2099/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2099&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/03/06/integrating-play-2-1-with-slick-1-0-0-database-query-dsl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>
	</item>
		<item>
		<title>Integrating Kickstrap with Spring MVC application</title>
		<link>http://krishnasblog.com/2013/02/24/integrating-kickstrap-with-spring-mvc-application/</link>
		<comments>http://krishnasblog.com/2013/02/24/integrating-kickstrap-with-spring-mvc-application/#comments</comments>
		<pubDate>Sun, 24 Feb 2013 22:59:20 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Spring MVC]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=2007</guid>
		<description><![CDATA[Get the latest code from Github, In continuation of my earlier blogs on Introduction to Spring MVC, in this blog I will talk about Kickstrap, Less and how Kickstrap can be integrated with our Spring MVC based bookstore application. If you go to Kickstrap website they mention that it is Twitter Bootstrap on Steroids. It [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2007&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a title="Code for Spring Web Flow sample" href="https://github.com/skprasadu/spring-mvc-examples/tree/master/bookstore-example-with-mvc-webflow">Get the latest code from Github</a>,</p>
<p>In continuation of my earlier blogs on <a title="Introduction to Spring MVC" href="http://krishnasblog.com/2013/02/22/junit-testing-of-spring-mvc-application-introduction/">Introduction to Spring MVC,</a> in this blog I will talk about <a title="Twitter Bootstrap on Steroids" href="http://ajkochanowicz.github.com/Kickstrap/">Kickstrap</a>, <a title="Less the dynamic stylesheet language" href="http://lesscss.org/">Less</a> and how <em>Kickstrap </em>can be integrated with our Spring MVC based bookstore application.</p>
<p>If you go to <strong>Kickstrap</strong> website they mention that it is <a title="Twitter Bootstrap" href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> on Steroids. It is heavily based on <strong>Less</strong> which is a dynamic stylesheet language. You can <a title="Kickstrap download" href="https://s3.amazonaws.com/kickstrap/Kickstrap+Downloads/kickstrap1.3.1.zip">download Kickstrap from here</a>.</p>
<p>Advantages of using Kickstrap is,</p>
<ul>
<li>We can achieve Responsive web design refer <a title="Permalink to Responsive Web Design using Twitter Bootstrap, Spring MVC" href="http://krishnasblog.com/2012/10/08/responsive-web-design-using-twitter-bootstrap-spring-mvc/" rel="bookmark">Responsive Web Design using Twitter Bootstrap, Spring MVC. </a></li>
<li>Changing to different theme is easy</li>
</ul>
<p>As a 1st step we need to copy the Kickstrap in the application folder as below,</p>
<div id="attachment_2069" class="wp-caption alignnone" style="width: 557px"><a href="http://krishnasblog1068.files.wordpress.com/2013/02/kickstrap-bookstore-app.png"><img class="size-full wp-image-2069" alt="kickstrap bookstore-app" src="http://krishnasblog1068.files.wordpress.com/2013/02/kickstrap-bookstore-app.png?w=625"   /></a><p class="wp-caption-text">kickstrap bookstore-app</p></div>
<p>The tiles definition in <a title="tiles.xml" href="https://github.com/skprasadu/spring-mvc-examples/blob/master/bookstore-example-with-mvc/src/main/webapp/WEB-INF/tiles.xml" target="_blank">tiles.xml</a> in Spring MVC is as below,</p>
<pre class="brush: plain; title: ; notranslate">
&lt;tiles-definitions&gt;
&lt;definition name=&quot;template&quot; template=&quot;/WEB-INF/templates/template.jsp&quot;&gt;
&lt;put-attribute name=&quot;header&quot; value=&quot;/WEB-INF/templates/header.jsp&quot;/&gt;
&lt;put-attribute name=&quot;footer&quot; value=&quot;/WEB-INF/templates/footer.jsp&quot;/&gt;
&lt;/definition&gt;
...
&lt;/tiles-definitions&gt;
</pre>
<p>In the template.jsp you need to add Kickstrap.less and less-1.3.0.min.js as below,</p>
<pre class="brush: plain; title: ; notranslate">
&lt;link rel=&quot;stylesheet/less&quot; type=&quot;text/css&quot; href=&quot;/bookstore-example-with-mvc/resources/css/kickstrap.less&quot;&gt;
&lt;script src=&quot;/bookstore-example-with-mvc/resources/css/Kickstrap/js/less-1.3.0.min.js&quot;&gt;&lt;/script&gt;
</pre>
<p>If you see the template.jsp, we use some of the css class of Kickstrap like &#8220;container&#8221;, &#8220;row-fluid&#8221; and others. row-fluid helps in responsive web design.</p>
<h2>Changing to different theme</h2>
<p>In Kickstrap changing to different theme is easy. Open the <a title="theme.less" href="https://github.com/skprasadu/spring-mvc-examples/blob/master/bookstore-example-with-mvc/src/main/resources/META-INF/web-resources/css/theme.less">theme.less</a>, currently we are using cerulean theme, as below</p>
<pre class="brush: plain; title: ; notranslate">
@import &quot;Kickstrap/themes/cerulean/variables.less&quot;;
@import &quot;Kickstrap/themes/cerulean/bootswatch.less&quot;;
</pre>
<p>Now run the below command and open the browser and type <a href="http://localhost:8080/bookstore-example-with-mvc" rel="nofollow">http://localhost:8080/bookstore-example-with-mvc</a>,</p>
<pre class="brush: plain; title: ; notranslate">
mvn clean tomcat7:run
</pre>
<p>The theme looks as below,</p>
<div id="attachment_2084" class="wp-caption alignnone" style="width: 635px"><a href="http://krishnasblog1068.files.wordpress.com/2013/02/cerulean-theme.png"><img class="size-full wp-image-2084" alt="cerulean-theme" src="http://krishnasblog1068.files.wordpress.com/2013/02/cerulean-theme.png?w=625&#038;h=312" width="625" height="312" /></a><p class="wp-caption-text">cerulean-theme</p></div>
<p>Below are the themes when you drilldown Kickstrap folder as shown below,</p>
<div id="attachment_2087" class="wp-caption alignnone" style="width: 340px"><a href="http://krishnasblog1068.files.wordpress.com/2013/02/themes-bookstore-app1.png"><img class="size-full wp-image-2087" alt="themes-bookstore-app" src="http://krishnasblog1068.files.wordpress.com/2013/02/themes-bookstore-app1.png?w=625"   /></a><p class="wp-caption-text">themes-bookstore-app</p></div>
<p>If you want to change it to, let us say cyborg theme, you need to change kickstrap.less as below,</p>
<pre class="brush: plain; title: ; notranslate">
@import &quot;Kickstrap/themes/cyborg/variables.less&quot;;
@import &quot;Kickstrap/themes/cyborg/bootswatch.less&quot;;
</pre>
<p>Now run the below command and open the browser and type <a href="http://localhost:8080/bookstore-example-with-mvc" rel="nofollow">http://localhost:8080/bookstore-example-with-mvc</a>, you will see the change in theme,</p>
<pre class="brush: plain; title: ; notranslate">
mvn clean tomcat7:run
</pre>
<p>The theme is changed and looks as below,</p>
<div id="attachment_2085" class="wp-caption alignnone" style="width: 635px"><a href="http://krishnasblog1068.files.wordpress.com/2013/02/cyborg-theme.png"><img class="size-full wp-image-2085" alt="cyborg-theme" src="http://krishnasblog1068.files.wordpress.com/2013/02/cyborg-theme.png?w=625&#038;h=254" width="625" height="254" /></a><p class="wp-caption-text">cyborg-theme</p></div>
<p>I hope this blog helped you.</p>
<h2>Reference:</h2>
<p><a title="Pro Spring MVC: With Web Flow" href="http://www.amazon.com/Pro-Spring-MVC-Professional-Apress/dp/1430241551/ref=sr_1_1?ie=UTF8&amp;qid=1361479866&amp;sr=8-1&amp;keywords=pro+spring+mvc+with+web+flow">Pro Spring MVC: With Web Flow</a> by by Marten Deinum, Koen Serneels</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/2007/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/2007/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=2007&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/02/24/integrating-kickstrap-with-spring-mvc-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/02/kickstrap-bookstore-app.png" medium="image">
			<media:title type="html">kickstrap bookstore-app</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/02/cerulean-theme.png" medium="image">
			<media:title type="html">cerulean-theme</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/02/themes-bookstore-app1.png" medium="image">
			<media:title type="html">themes-bookstore-app</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/02/cyborg-theme.png" medium="image">
			<media:title type="html">cyborg-theme</media:title>
		</media:content>
	</item>
		<item>
		<title>JUnit testing of Spring MVC application &#8211; Introduction</title>
		<link>http://krishnasblog.com/2013/02/22/junit-testing-of-spring-mvc-application-introduction/</link>
		<comments>http://krishnasblog.com/2013/02/22/junit-testing-of-spring-mvc-application-introduction/#comments</comments>
		<pubDate>Fri, 22 Feb 2013 15:28:56 +0000</pubDate>
		<dc:creator>Krishna</dc:creator>
				<category><![CDATA[Spring MVC]]></category>

		<guid isPermaLink="false">http://krishnasblog.com/?p=1908</guid>
		<description><![CDATA[For people in hurry, here is the Github code and the steps to run the sample. Spring MVC is one of the leading Java Web application frameworks along with Struts. In the next few blogs, I will take an use case and demonstrate how to develop a good quality web application in an enterprise Java [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=1908&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For people in hurry, <a title="Building a Spring MVC application using Test driven development approach " href="https://github.com/skprasadu/spring-mvc-examples/tree/master/bookstore-example-with-mvc">here is the Github code and the steps to run the sample</a>.</p>
<p><a title="Spring MVC documentation" href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html">Spring MVC</a> is one of the leading Java Web application frameworks along with <a title="Struts, java web application framework" href="http://struts.apache.org/">Struts</a>. In the next few blogs, I will take an use case and demonstrate how to develop a good quality web application in an enterprise Java world. I will also demonstrate latest capabilities of <a title="WebApplicationInitializer new Spring MVC 3.1 feature" href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html">Spring like Annotation based configurations and its advantages over XML based configurations</a>. Prerequisite for this application is <a title="Java 7" href="http://www.oracle.com/technetwork/java/javase/downloads/java-se-jdk-7-download-432154.html">Java 7.x</a>, <a title="Tomcat 7" href="http://tomcat.apache.org/download-70.cgi">Tomcat 7.x</a>, <a title="Maven 3" href="http://maven.apache.org/ref/3.0/">Maven 3.x</a> and <a title="STS IDE" href="http://www.springsource.org/sts">STS IDE</a>.</p>
<p>The use case I will be talking about is a Bookstore application, where in user register to this application and purchase books. There is also an administration task like creating the book catalog.</p>
<h2>Spring MVC application architecture</h2>
<div class="wp-caption alignnone" style="width: 603px"><img alt="Source Java9s: Spring MVC Architecture" src="http://java9s.com/wp-content/uploads/2011/05/Spring-3-MVC-Basic-Flow.jpg" width="593" height="443" /><p class="wp-caption-text">Source Java9s: Spring MVC Architecture</p></div>
<p>For this sample application we extensively use the Latest <a title="WebApplicationInitializer new Spring MVC 3.1 feature" href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html">Spring MVC annotation capability</a>. The major advantage with this is we will not be depending on any xml configuration including web.xml. I personally like XML configuration with namespace, because it is readable. The advantage of annotation is, since everything is Java, if we use <strong>STS IDE</strong>, any typo can be caught at compilation time,  and we can write a good quality code and even measure the <strong>code coverage</strong>. We also used <a title="Kickstrap" href="http://ajkochanowicz.github.com/Kickstrap/">Kickstrap </a>as the css engine for this application. Here is a blog on <a title="Permalink to Integrating Kickstrap with Spring MVC application" href="http://krishnasblog.com/2013/02/24/integrating-kickstrap-with-spring-mvc-application/" rel="bookmark">Integrating Kickstrap with Spring MVC application.</a></p>
<h2>What is code coverage</h2>
<p><strong>Code coverage</strong> is a measure of how well you unit tested your code. If you use a good IDE like <em>STS IDE</em> we can install <a title="ecobertura" href="http://ecobertura.johoop.de/">ecobertura </a>using the <a title="ecobertura update site for STS IDE" href="http://ecobertura.johoop.de/update/">update site</a>. Once you setup ecobertura, you can start developing your application. When you run your JUnit test in &#8220;Cover as&#8221; mode, it will show the code coverage of your JUnit tests as below,</p>
<div id="attachment_1938" class="wp-caption alignnone" style="width: 635px"><a href="http://krishnasblog1068.files.wordpress.com/2013/02/ecobertura-stside-view.png"><img class="size-full wp-image-1938" alt="eCobertura STS-IDE view" src="http://krishnasblog1068.files.wordpress.com/2013/02/ecobertura-stside-view.png?w=625&#038;h=218" width="625" height="218" /></a><p class="wp-caption-text">eCobertura STS-IDE view</p></div>
<p>In the subsequent blogs I will use <a title="Test Driven Development" href="http://en.wikipedia.org/wiki/Test-driven_development">test driven development (TDD)</a> to build each layer and gradually increase the <strong>code coverage</strong> and write better quality code. The layers I will be developing in TDD in the order are,</p>
<ul>
<li><a title="Spring MVC DAO layer testing" href="http://krishnasblog.com/2013/02/21/junit-testing-of-spring-mvc-application-testing-dao-layer/">DAO layer</a></li>
<li><a title="Service Layer" href="http://krishnasblog.com/2013/02/21/junit-testing-of-spring-mvc-application-testing-service-layer/">Service layer</a></li>
<li><a title="Controller layer" href="http://krishnasblog.com/2013/02/21/junit-testing-of-spring-mvc-application-testing-controller/">Controller Layer</a></li>
<li><a title="Frontend web application" href="http://krishnasblog.com/2013/02/21/junit-testing-of-spring-mvc-application-testing-frontend-using-selenium/">Frondend web application</a></li>
<li><a title="Junit Testing With Spring Webflow" href="http://krishnasblog.com/2013/02/21/junit-testing-of-spring-mvc-application-testing-spring-webflow/">Spring Web Flow layer</a></li>
</ul>
<h2>Reference:</h2>
<p><a title="Pro Spring MVC: With Web Flow" href="http://www.amazon.com/Pro-Spring-MVC-Professional-Apress/dp/1430241551/ref=sr_1_1?ie=UTF8&amp;qid=1361479866&amp;sr=8-1&amp;keywords=pro+spring+mvc+with+web+flow">Pro Spring MVC: With Web Flow</a> by by Marten Deinum, Koen Serneels</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/krishnasblog1068.wordpress.com/1908/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/krishnasblog1068.wordpress.com/1908/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=krishnasblog.com&#038;blog=35510357&#038;post=1908&#038;subd=krishnasblog1068&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://krishnasblog.com/2013/02/22/junit-testing-of-spring-mvc-application-introduction/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/951f03f6ed6447db5d86432317750f97?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">praskrishna</media:title>
		</media:content>

		<media:content url="http://java9s.com/wp-content/uploads/2011/05/Spring-3-MVC-Basic-Flow.jpg" medium="image">
			<media:title type="html">Source Java9s: Spring MVC Architecture</media:title>
		</media:content>

		<media:content url="http://krishnasblog1068.files.wordpress.com/2013/02/ecobertura-stside-view.png" medium="image">
			<media:title type="html">eCobertura STS-IDE view</media:title>
		</media:content>
	</item>
	</channel>
</rss>
