Knol Session : Scala with MongoDB

MongoDB is a document-oriented database management system designed for performance, horizontal scalability, high availability,open source NoSQL database(Schemaless or Non-relational),And advanced queryability.
MongoDB is a document-based database system, and as a result, all records, or data, in MongoDB are documents.

Posted in Scala | Leave a comment

Profile Management with Nice UI Interface in Node.js and MongoDB

Last week, we created a login demo template in Node.js and MongoDB. We also added signUp with FaceBook, Twitter and google. So that user would not need to signup manually.

Now we have added profile management feature with a nice UI interface. Now uses can modify his profile detail along with his photo. This is demo template, which can be used as a starting point for your application. You can add more fields in database.

To use this application, Pull the code from

Screenshot from 2014-04-15 21:49:59

Screenshot from 2014-04-15 21:50:59

Screenshot from 2014-04-15 21:51:10

We’ll be adding some more features in this application very soon such as Auto complete search, Create Friend List, Chatting, birthday reminder functionality etc..

Posted in Agile, AJAX, JavaScript, jQuery, MongoDB, News, Node.js, Web | Tagged , , , | Leave a comment

Employee-Self-Service: Reactive and Non-Blocking Database Access using Play Framework and Anorm – (Part-4)

Last week, We have added Database Access as Reactive and Non-Blocking behaviour in Employee-Self-Service  application.

Now we have added some more features. These are following:

  • Achieving, Futures to use more idiomatic error handling.
  • Replaced the embedded JS & CSS libraries with WebJars.
  • Achieving, table pagination and sorting functionality.


def list() = Action.async { implicit request =>
 val futureEmpList = scala.concurrent.Future { Employee.list }
 val timeoutFuture = Promise.timeout("Oops", 10.second)
 Future.firstCompletedOf(Seq(futureEmpList, timeoutFuture)).map {
   case data: List[Employee] => Ok(html.list(data))
   case t: String =>
      Logger.error("Problem found in employee list process")


 * Display the paginated list of employees.
 * @param page Current page number (starts from 0)
 * @param orderBy Column to be sorted
 * @param filter Filter applied on employee names
 def list(page: Int, orderBy: Int, filter: String) = Action.async { implicit request =>
   val futurePage: Future[Page[Employee]] = TimeoutFuture(Employee.list(page = page, orderBy = orderBy, filter = ("%" + filter + "%"))) => Ok(html.list(page, orderBy, filter))).recover {
     case t: TimeoutException =>
       Logger.error("Problem found in employee list process")

Cleaned up the Futures to use more idiomatic error handling. Implemented by James Ward

object TimeoutFuture {

    def apply[A](block: => A)(implicit timeout: FiniteDuration): Future[A] = {

      val promise = scala.concurrent.promise[A]()

      // if the promise doesn't have a value yet then this completes the future with a failure
      Promise.timeout(Nil, timeout).map(_ => promise.tryFailure(new TimeoutException("This operation timed out")))

      // this tries to complete the future with the value from block



Replaced the embedded JS & CSS libraries with WebJars. Implemented by James Ward

Do the following steps to implement WebJars functionality with Play Framework:

  1. Add following entry into build.sbt file.
"org.webjars" %% "webjars-play" % "2.2.2-1",
"org.webjars" % "bootstrap" % "3.1.0",
"org.webjars" % "bootswatch-yeti" % "3.1.1",
"org.webjars" % "html5shiv" % "3.7.0",
"org.webjars" % "respond" % "1.4.2"

2. Add following entry into  conf/routes file.

# Map the webjar static assets to the /webjars URL
GET     /webjars/*file          

3. Add following entry into app/views/main.scala.html file.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" media="screen" href=""bootswatch-yeti", "bootstrap.min.css"))">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src=""html5shiv.js"))"></script>
  <script src=""respond.min.js"))"></script>

<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src=""jquery.min.js"))"></script>
<!-- Latest compiled and minified JavaScript -->
<script src=""bootswatch-yeti", "bootstrap.min.js"))"></script>

Special thanks to James Ward for his contribution and valuable time to improve the code quality and implemented the WebJars functionality into this application.

Check the application and the code base on bellow links:

The live application is currently hosted at :
The Github code for the project is at :

This is the fourth edition of this application. If you have any changes then feel free to send in pull requests and we would do the merges :) Stay tuned.

Previous blogs related to this application:

  1. Employee-Self-Service – (Part-1)
  2. Employee-Self-Service – (Part-2)
  3. Employee-Self-Service – (Part-3)
Posted in Scala, Web, JavaScript, CSS, Bootstrap, jQuery, Play Framework, Reactive, Non-Blocking, Future | Tagged , , , , , , , , | Leave a comment

Mock Unit Testing using Mockito in Play Scala project

During Unit Testing in a Play Scala project, there arises a need to Mock certain Objects or Traits which are used in the unit, so that the unit being tested has a consistent interaction with its outside dependencies. But due to tight coupling or external dependencies, objects cannot be tested as a unit. So, we need to mock those external dependencies by adding fake external dependencies to it.

This can be done with the help of various mocking frameworks like Mockito, EasyMock or jMock. Selecting an appropriate mocking framework depends on the application that is being built.

This blog will tell you how to use Mockito for mocking objects or traits in a Play Scala project along with ScalaTest.

Mockito is an open source testing framework for Java/Scala released under the MIT License. The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of Test-driven Development (TDD).

To use Mockito in a Play Scala project follow these easy steps & you are done.

1. Add following dependencies to build.sbt ( or build.scala for version Play 2.1.x or earlier).

"org.scalatest" % "scalatest_2.10" % "2.0" % "test"
"org.mockito" % "mockito-core" % "1.9.5" % "test"

First one is for Scalatest and second one is for Mockito.

2. Import following libraries in your unit testing code.

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.mockito.Mockito._
import org.mockito.Matchers._

Also, import the necessary Scalatest libraries required for Unit Testing of your application

3. Now here is an example code of a test case using Mockito.

class UserControllerTest extends Specification with Mockito {

 val user = User("", encryptPassword("password"), "Knoldus Software LLP")

 val mockUserDALObject = mock[UserDALComponent]

 val userController = new UserController(mockUserDALObject)

 "UserControllerTesting: addUser is successful" in {
  running(FakeApplication()) {
   val result = userController.addUser(FakeRequest().withFormUrlEncodedBody("name" -> "Knoldus Software LLP", "email" ->
   "", "password" -> "password", "confirm_password" -> "password").withHeaders(CONTENT_TYPE -> "application/x-www-form-urlencoded"))
   status(result) must equalTo(200)

In this example we want to test addUser function(unit) of userController.scala.

addUser’s definition is as follows :-

class UserController(userDAL: UserDALComponent) extends Controller{
 def addUser: Action[play.api.mvc.AnyContent] = Action { implicit request =>
   formWithErrors => {
   userData => {
    searchUserByEmail( match {
     case None =>
      val encryptedPassword = encryptPassword(userData.password)
      val response = insertUser(User(, encryptedPassword,
     case Some(user) => Ok(views.html.user.signup(userForm, "Email Id Already Exist !"))


object UserController extends UserController(UserDAL)

As we can see that addUser function of userController.scala is dependent on insertUser & searchUserByEmail functions to add & search new user to/from database. But, while Unit Testing we want to test only addUser function of userController.scala & not insertUser function. So, to mock insertUser function, we made a mock object mockUserDALObject which mocked UserDALComponent.

UserDALComponent & insertUser are defined as follows :-

trait UserDALComponent {
  def insertUser(user: User): Int
  def searchUserByEmail(email: String): Option[String]

object UserDAL extends domains with UserDALComponent {

 * Inserting new user to DB
 def insertUser(user: User): Int = {
  Connection.databaseObject withSession { implicit session =>

 def searchUserByEmail(email: String): Option[String] = {
  Connection.databaseObject withSession { implicit session: Session =>
   (for { user <- users if ( === email) } yield

Then we made an object userController of UserController class, with mocked object as follows :-

val userController = new UserController(mockUserDALObject)

Using this object we can test all units/functions of UserController without using any external dependency.

Note :- For mocking any object a Trait of that object has to be created first & a Class & Object of the unit being tested. (As we have shown in above example)

Posted in Play Framework, Scala | Tagged , , | Leave a comment

Using Highcharts With Play Framework

Highcharts is a charting library written in pure HTML5/JavaScript, offering intuitive, interactive charts to your web site or web application.

Highcharts are interactive Javascript charts which you can use very easily with any Play application. Its using graphical representation of your data.

There are 2 types of Highchart API’s :

1. Highcharts API

2. Highstock API

Implementetation of Charts:

1. Adding libraries for Highcharts  in main.scala.html

<!-- HighCharts -->
<script src=""></script>
<script src=""></script>

<script src=""></script>

2. Adding a div where Highchart is rendered in html file

<div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-info">
                    <div class="panel-heading">
                        <h3 class="panel-title">@Messages("label.bubble")</h3>
                    <div class="panel-body">
                        <div id="bubbleChart" class="chart-holder"></div>

            </div><!-- /span12 -->
        </div><!-- /row -->
    </div><!-- /container -->

3. Adding javascript code in bubbleChartHandler.js which provides data for rendering chart

$(function () {
chart: {
type: 'bubble',
zoomType: 'xy'

title: {
text: 'Highcharts Bubbles'

series: [{
data: [[97,36,79],[94,74,60],[68,76,58],[64,87,56],[68,27,73],[74,99,42],[7,93,87],[51,69,40],[38,23,33],[57,86,31]]
}, {
data: [[25,10,87],[2,75,59],[11,54,8],[86,55,93],[5,3,58],[90,63,44],[91,33,17],[97,3,56],[15,67,48],[54,25,81]]
}, {
data: [[47,47,21],[20,12,4],[6,76,91],[38,30,60],[57,98,64],[61,17,80],[83,60,13],[67,78,75],[64,12,10],[30,77,82]]


4. Now Adding action in Application.scala

def bubbleChart = Action {


Check the application and the code base on bellow links:

This is the start, from next week onwards we would be working on this application to make it grow. We would look at how we can make it reactive, then we would be adding more modules to it together. If you have any changes then feel free to send in pull requests and we would do the merges :) Stay tuned.








Posted in Scala | Leave a comment

Brief introduction of Slick

Here I am going to briefly introduce about Slick

Posted in Scala | Leave a comment

Idiomatic Error Handling in Scala

Error handling in Scala can just be written like Java. Put in a little bit of pattern matching magic and you are done. However, given a little use of Scala built-in terrific beauties it can be made much better. Let us have a look.

Let us look at a quick example

def sayHello(any: Any) = {
    any match {
      case x: String => "Hello"
      case _ => throw new Exception("Huh!")
  }                      //> sayHello: (any: Any)String

  def letMeSayHello = {
  }                     //> letMeSayHello: => String

  letMeSayHello         //> java.lang.Exception: Huh!
                    //| 	at SomeThing$$anonfun$main$1.sayHello$1(SomeThing.scala:11)

So we have a method called sayHello which misbehaves when you do not pass a string to it. If you call it without a string, it blows up and hence the letMeSayHello invocation blows up as well.

Ok, now traditionally we have been so used to try catch blocks that we put them around.

def sayHello(any: Any) = {
    any match {
      case x: String => "Hello"
      case _ => throw new Exception("Huh!")
  }                    //> sayHello: (any: Any)String

  def letMeSayHello = {
    try {
    } catch {
      case e: Exception => "It's Ok if you dont want to say hello"
 }                    //> letMeSayHello: => String

  letMeSayHello       //> res0: String = It's Ok if you dont want to say hello

Ok, so far so good. So we can really write Java in Scala ;)
Continue reading

Posted in Scala | Tagged , | 4 Comments