Scala in Business | Knoldus Newsletter – March 2015


Hello Folks

We are back again with March 2015, Newsletter. Here is this Scala in Business | Knoldus Newsletter – March 2015

In this newsletter, you will get the business related news for Scala. How organisation are adopting Scala for their business, how Scala related technologies increasing the performance of application and how Scala is getting popular in the industry

So, if you haven’t subscribed to the newsletter yet then make it hurry and click on Subscribe Monthly Scala News Letter

Scala days Pics :

92IpR

Knoldus CTO with Martin Odersky

92JGX

Knoldus sponsored Scala days

leaflet_front_new_letter_size (1) leaflet_back_letter_size (1)

Posted in Akka, Architecture, Cloud, Future, Java, News | Tagged , , , | Leave a comment

Tutorial #2: Using WebJars, jQuery, Bootstrap & Bootswatch with Play application


We have already discussed about the Play development environment in Tutorial #1.

So, In this blog we would set up the WebJars, jQuery, Bootstrap & Bootswatch with Play Framework which would drive us through rest of the tutorial series. We would be running this blog as a series and we would be looking at various aspects of play with this blog.

In this tutorial we will discuss about the following topics:

  • WebJars : A client-side web libraries (e.g. jQuery & Bootstrap) packaged into JAR files.
  • Bootstrap : The most popular HTML, CSS, and JS framework
  • BootswatchFree themes for Bootstrap

WebJars work with most JVM-based containers and web frameworks. Using a WebJar requires:

  1. The WebJar needs to be a dependency of your application
  2. The WebJar needs to be in your application’s running CLASSPATH
  3. Your container, web framework, or application needs to serve static assets from Jar files

Instructions for Play 2.3 (Sample Source)

WebJars can be added as dependencies to an app by simply adding them to the build.sbt file. There is also a helper library named webjars-play that makes it easy to reference WebJar assets. Here is an example build.sbt file with webjars-play and the bootstrap WebJar as dependencies:

build.sbt


libraryDependencies ++= Seq(
"org.webjars"    %%   "webjars-play"          % "2.3.0-2",
"org.webjars"    %    "bootstrap"             % "3.1.1-2",
"org.webjars"    %    "bootswatch-cerulean"   % "3.3.1+2",
"org.webjars"    %    "html5shiv"             % "3.7.0",
"org.webjars"    %    "respond"               % "1.4.2"
)

In Play 2.3 WebJars are automatically available as static assets. If you have a route like:

GET /assets/*file controllers.Assets.at(path="/public", file)

Then a WebJar file like `bootstrap.css` is available at:

/assets/lib/bootstrap/css/bootstrap.css

The webjars-play helper library has a wrapper around the Play Static Asset Controller that can locate and serve WebJar assets. A new route to WebJarAssets needs to be added to the conf/routes file:

conf/routes

GET   /webjars/*file   controllers.WebJarAssets.at(file)

To use Play 2’s reverse routing to resolve the URL to an asset you can do the following in a template:

<link rel="stylesheet" media="screen" href="@routes.WebJarAssets.at(WebJarAssets.locate("bootswatch-cerulean", "bootstrap.min.css"))">
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">

<script src="@routes.WebJarAssets.at(WebJarAssets.locate("jquery.min.js"))"></script>
<script src="@routes.WebJarAssets.at(WebJarAssets.locate("bootswatch-cerulean", "bootstrap.min.js"))"></script>
<script src="@routes.Assets.at("javascripts/app.js")" type="text/javascript"></script>

Bootstrap : Bootstrap WebJar here

Bootswatch : Bootswatch full distribution as WebJars here

Screenshot from 2015-03-23 00:51:00

Now we know about client-side web libraries and these libraries are free for use. So we will use these libraries for the up coming  tutorials. We would look at how we can make it more usable and readable, then we would be adding next tutorials related to Play Framework. If you have any question then feel free to comment on the same :) Stay tuned.

Posted in Akka, Bootstrap, Bootswatch, JavaScript, jQuery, Play Framework, Scala, Web, WebJars | Tagged , , , , , , , , , , | 4 Comments

CRUD operations with PostgreSQL using SLICK with LOGBACK EMAIL functionality.


This article is about to show how to send logging email using logback-test.xml, the backend is postgresql and the queries format is in slick, language used is scala.

The code is well commented so, files to be noticed are:

  1. KnolRepo.scala
  2. KnolRepoTest.scala
  3. logback-test.xml

Download the source code to check the functionality. GitHub

Posted in Scala | 2 Comments

Playing MultipartFormData: A basic example to handle and test MultipartFormData request in Play Framework 2.3.8


Playing MultipartFormData

The following blog and attached code represent an example to upload file using MultipartFormData request and Testing it into Play Application.

A basic example to handle and test MultipartFormData request in Play Framework 2.3.8

The standard way to upload files in a web application is to use a form with a special multipart/form-data encoding, which lets you mix standard form data with file attachment data. Please note: the HTTP method used to submit the form must be POST (not GET).


Code in action for Controller and Service


  val uploadService: UploadService

  def upload = Action(parse.multipartFormData) { implicit request =>
    val result = uploadService.uploadFile(request)
    Redirect(routes.Application.index).flashing("message" -> result)
  }
  /**
   * Get file from the request and move it in your location
   *
   * @param request
   * @return
   */
  def uploadFile(request: Request[MultipartFormData[TemporaryFile]]): String = {
    log.error("Called uploadFile function" + request)
    request.body.file("file").map { picture =>
      import java.io.File
      val filename = picture.filename
      val contentType = picture.contentType
      log.error(s"File name : $filename, content type : $contentType")
      picture.ref.moveTo(new File(s"/tmp/$filename"))
      "File uploaded"
    }.getOrElse {
      "Missing file"
    }
  }


Test Code for Controller and Service


ApplicationSpec.scala

"should be valid" in new WithApplication {
  val request = mock[Request[MultipartFormData[TemporaryFile]]]
  mockedUploadService.uploadFile(request) returns "File Uploaded"
  val result: Future[Result] = TestController.upload().apply(request)
  status(result) must equalTo(SEE_OTHER)
}

UploadServiceSpec.scala

"UploadService" should {
    "uploadFile returns (File uploaded)" in new WithApplication {
      val files = Seq[FilePart[TemporaryFile]](FilePart("file", "UploadServiceSpec.scala", None, TemporaryFile("file", "spec")))
      val multipartBody = MultipartFormData(Map[String, Seq[String]](), files, Seq[BadPart](), Seq[MissingFilePart]())
      val fakeRequest = FakeRequest[MultipartFormData[Files.TemporaryFile]]("POST", "/", FakeHeaders(), multipartBody)
      val success = UploadService.uploadFile(fakeRequest)
      success must beEqualTo("File uploaded")
    }

    "uploadFile returns (Missing file)" in new WithApplication {
      val files = Seq[FilePart[TemporaryFile]]()
      val multipartBody = MultipartFormData(Map[String, Seq[String]](), files, Seq[BadPart](), Seq[MissingFilePart]())
      val fakeRequest = FakeRequest[MultipartFormData[Files.TemporaryFile]]("POST", "/", FakeHeaders(), multipartBody)
      val success = UploadService.uploadFile(fakeRequest)
      success must beEqualTo("Missing file")
    }
}

Build and Run the application :-


  • To run the Play Framework, you need JDK 6 or later
  • Install Typesafe Activator if you do not have it already. You can get it from here
  • Execute ./activator clean compile to build the product
  • Execute ./activator run to execute the product
  • playing-multipartform should now be accessible at localhost:9000

Test the application with code coverage


  • Execute $ ./activator clean coverage test to test
  • Execute $ ./activator coverageReport to generate coverage report

File Upload Form

multipartform

Test Coverage

code_coverage


References :-


Code on GitHub

Posted in JUnit, Mockito, MultipartFormData, Play Framework, Reactive, Scala, Specification, specs2, Test, Tutorial, Web | Tagged , , , , , , , , , , , , , | 5 Comments

Knolx : Logging with Logback in Scala


In this presentation, I have explained brief introduction about logback and its components. I also explained about configuration of logback.xml file, appenders as File and SMTP.

Posted in Java, Play Framework, Reactive, Scala | 6 Comments

Play i18n Messages: Playing with i18n messages of Play Framework on client-side


Playing JsMessages

The following blog and attached code represent an example to compute localized messages of Play Application on client side.

Basically, Play JsMessages library takes the i18n messages of our Play application, sends them to the client-side as a JSON object and defines a JavaScript function returning a message value from a given language and the message key and arguments.

alt tag

  • Used Play JsMessages library to access i18n messages from client-side
  • Embedded JS & CSS libraries with WebJars.
  • Integrating with a CSS framework (Twitter Bootstrap 3.1.1)
  • Bootswatch-Darkly with Twitter Bootstrap 3.1.1 to improve the look and feel of the application

Instructions :-


  • To run the Play Framework, you need JDK 6 or later
  • Install Typesafe Activator if you do not have it already. You can get it from here
  • Execute ./activator clean compile to build the product
  • Execute ./activator run to execute the product
  • playing-jsmessages should now be accessible at localhost:9000

References :-


Code on GitHub

Posted in Bootstrap, CSS, JavaScript, jQuery, Play Framework, Scala, Web | Tagged , , , , , | 6 Comments

Play with Reactive Slick: A Simple CRUD application in Play! framework using Slick 3.0


Recently Typesafe released Slick 3.0.0-RC1, the first release candidate for “Reactive Slick”. Reactive Slick has many new features like Support for Reactive Streams API, a new API for composing and executing database actions and many more.

Before moving forward, we recommended you to go through the Slick 3.0.0-RC1 Upgrade guide. So, that you can get a hint of major changes in Slick 3.0.

In this post, we will see how to build a Reactive Play application with Reactive Slick. In order to build a simple CRUD application in Play framework using Reactive Slick (Slick-3.0.0-RC1) we need to follow these steps:

1) Run activator new play-reactive-slick play-scala to create a new Play application.

2) Add following dependencies in build.sbt file

"com.typesafe.slick" %% "slick" % "3.0.0-RC1"
"org.slf4j" % "slf4j-nop" % "1.6.4"
"postgresql" % "postgresql" % "9.1-901.jdbc4"

Here we are using PostgreSQL as database. So, if you have not installed it yet, you can download it from here.

3) Next, we need to add bidirectional mapping of our case class with the table, like this:

case class Employee(id: Option[Long], name: String, address: String, dob: Option[Date], joiningDate: Date, designation: Option[String])

class Employees(tag: Tag) extends Table[Employee](tag, "EMPLOYEE") {

 implicit val dateColumnType = MappedColumnType.base[Date, Long](d => d.getTime, d => new Date(d))

 def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
 def name = column[String]("name")
 def address = column[String]("address")
 def dob = column[Date]("date_of_birth")
 def joiningDate = column[Date]("joining_date")
 def designation = column[String]("designation")

 def * = (id.?, name, address, dob.?, joiningDate, designation.?) <> (Employee.tupled, Employee.unapply _)

Important thing to note in above mapping is that we have omitted O.Nullable/O.NotNull. The reason behind it is that both O.Nullable/O.NotNull are deprecated in Slick-3.0.0-RC1. Instead, we have provided the mapping for optional fields in projection itself.

4) Then, we can write a Database Access Object (DAO) to perform CRUD operations:

object EmployeeDAO {

  val employees = TableQuery[Employees]

  def db: Database = Database.forDataSource(DB.getDataSource())

  def filterQuery(id: Long): Query[Employees, Employee, Seq] =
    employees.filter(_.id === id)

  def findById(id: Long): Future[Employee] =
    try db.run(filterQuery(id).result.head)
    finally db.close

  def insert(employee: Employee): Future[Int] =
    try db.run(employees += employee)
    finally db.close

  def update(id: Long, employee: Employee): Future[Int] =
    try db.run(filterQuery(id).update(employee))
    finally db.close

  def delete(id: Long): Future[Int] =
    try db.run(filterQuery(id).delete)
    finally db.close
}

As we can see in above code that now Slick returns result in Future. Also, now the database instance db have an associated connection pool and thread pool, so, it is important to call db.close when we are done using it.

5) At last, we need to provide Asynchronous Action response in controller. Example:

def delete(id: Long): Action[AnyContent] = Action.async { implicit request =>
 val futureEmpDel = EmployeeDAO.delete(id)
 futureEmpDel.map { result => Home.flashing("success" -> "Employee has been deleted") }.recover {
   case ex: TimeoutException =>
     Logger.error("Problem found in employee delete process")
     InternalServerError(ex.getMessage)
   }
 }

Here we are using Action.async to handle Future response from database.

In this way we can build a simple CRUD application in Play framework using Reactive Slick. For more information on Reactive Slick click here.

To download a demo Application click here.

Posted in Agile, Future, Non-Blocking, Play Framework, Reactive, Scala, Slick, Web | Tagged , , , , | 5 Comments

Handling Twitter share response


Twitter  share is a way to allow user  to share website / tweet on the twitter . There are various methods to share data  on twitter , but here we are using  javascript method .We can customize tweet  using data attributes .
Followings are steps need to be followed
1) Add javascript in file . It would be better to add javascript  just below <body> .

<script>
window.twttr=(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs"));
</script>

2) Add below anchor tag  where you would like to render the Tweet Button .

 

<a class="twitter-share-button" href="https://twitter.com/share" data-size="small" data-url="http://knoldus.com" data-text="Hello" data-count="none" >Tweet</a>

To display count box (number of share) remove data-count=”none” attribute  or set data-count=”horizontal”
3) If you would like to handle the tweet response , you need to bind the twitter response by using following script .

 

<script src="https://platform.twitter.com/widgets.js"></script>
<script>
twttr.events.bind('tweet' , function(event) {
  // do somethings here
alert("Tweet has been successfully posted");
});
</script>

twttr.events.bind method would be called when tweet posted successfully .

 

Posted in JavaScript, Tutorial, Web | 2 Comments

Play-Slick-PostgreSQL: Reactive Play application with Slick extensions for PostgreSQL


playing-slick-pg

Building Reactive Play application with Slick extensions for PostgreSQL

This is a classic CRUD application, backed by a PostgreSQL database. It demonstrates:

  • Handling asynchronous results, Handling time-outs
  • Achieving, Futures to use more idiomatic error handling.
  • Accessing a JDBC database, using Slick.
  • Achieving, table pagination and sorting functionality.
  • Embedded JS & CSS libraries with WebJars.
  • Play and Scala-based template engine implementation
  • Integrating with a CSS framework (Twitter Bootstrap 3.1.1). Twitter Bootstrap requires a different form layout to the default one that the Play form helper generates, so this application also provides an example of integrating a custom form input constructor.
  • Bootswatch-Yeti with Twitter Bootstrap 3.1.1 to improve the look and feel of the application

Continue reading

Posted in Bootstrap, Future, JavaScript, jQuery, Non-Blocking, Play Framework, Reactive, Scala, Slick, Web | Tagged , , , , | 3 Comments

Meetup: Introduction to Play Framework !!


Reactive Application Programmers in Delhi NCR

Hi Folks,

Knoldus have organized an one hour session on 4th Feb 2015 at 5:00 PM. Topic is  Introduction to Play Framework. So many people have joined and enjoyed the session. I am going to share that slide here. Please let me know if you have any question related to linked slide.

Slide: Introduction to Play framework

Posted in Play Framework, Reactive, Scala, Tutorial | Tagged , , | 1 Comment