Play 2.3.x PDF : Basic example for generating PDF documents dynamically from Play Application with the help of play2-pdf module


alt tag

In this blog I have created a basic example for generating PDF documents dynamically from Play Application with the help of play2-pdf module

Play 2.3.x PDF module: This module helps generating PDF documents dynamically from your Play! web application. It simply renders your HTML- and CSS-based templates to PDF. It is based on the Flying Saucer library, which in turn uses iText for PDF generation.

Usage

You can use a standard Play! Scala template like this one:

@(message: String)

@main("Play!ng PDF") {
    Image: <img src="/public/images/favicon.png"/><br/>
    Hello world! <br/>
    @message <br/>
}

Check the below template list for more complex template design:

  1. Letter PDF
  2. News Letter PDF

Then this template, after having imported it.innove.PdfGenerator, can simply be rendered as:

    def letter: Action[AnyContent] = Action { implicit request =>
        Ok(PdfGenerator.toBytes(views.html.letter("Play!ng PDF"), host)).as("application/pdf")
    }

Template rules

Templates must generate XHTML.

If the template is using an image, stylesheet, etc., it usually is loaded via an http call. The PDF modules tries to optimize that resource loading: If you specify the URI as a path into the classpath of your Play! app, the resource is loaded directly instead. See the above sample template for an example.

Of course you can link to CSS files in your class path also, but be aware not to use the media="screen"qualifier.

Fonts you use must be explicitely packaged with your app.

<html>
    <head>
        <style type="text/css"><!--
        body {
            ...
            font-family: FreeSans;
        }
        -->style> 
    head>
    <body>
        ...
    body>
html>

Since the FreeSans font is not available to the java VM, you are required to add the corresponding font file, “FreeSans.ttf” to your Play! app. You can add your fonts with PdfGenerator.loadLocalFonts method, for example if you put the font in the folder /conf/fonts you load the font with:

PdfGenerator.loadLocalFonts(new String[]{"fonts/FreeSans.ttf"})

alt tag

alt tag

  • Used Play2-PDF Module to generate PDF from HTML template
  • Embedded JS & CSS libraries with WebJars
  • Integrating with a CSS framework (Twitter Bootstrap 3.1.1)
  • Bootswatch-Cerulean 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-pdf-module should now be accessible at localhost:9000

References


Posted in Bootstrap, Bootswatch, CSS, Play Framework, Play2-PDF, Web, WebJars | Tagged , , , , , , , , , , , | 4 Comments

Play framework security with Silhouette


Silhouette is a security library for Play framework. Its basically a core only fork of Secure Social, which is another security library for play framework. Secure Social is a great framework for lots of user but my experience with secure social is not that good, nor with some of my friends and colleagues who use Play framework in their application. It’s been thrown out from the projects we worked on. However I am not going to talk about secure social here, technologies are like that only, it works for some people and doesn’t work for some other people, and for whom it do not work they find or build some alternatives. Silhouette is born because of securesocial’s problems, mostly because of its tight coupling. Silhouette is a loosely coupled security library. It gives users the flexibility to inject their own implementation when things don’t seem work with the given implementation.

We can use the library in the play controllers by extending the Silhouette trait.

class ApplicationController @Inject() (implicit val env: Environment[User, JWTAuthenticator])
extends Silhouette[User, JWTAuthenticator] {}

In this code an implementation of the environment is given implicitly and all the requirements for the environment is given through Guice dependency injection. At this point it looks a bit confusing, so lets see how the stuffs inside Silhouette works.

Inside Silhouette the codes are divided in two categories api and impl. Here api is the main engine of the library. All the work flow is handled here and it’s mostly consist of traits. And there is the impl part which gives us the default implementation of things we generally required in our applications e.g. implementation for the providers – OAuth1, OAuth2, OpenId , some service implementations, some authenticator implementations etc. The trait Silhouette is the main trait in this library it handles all the function calling and that sort of stuffs of the library. It needs an environment to handle all the functionality. The environment holds all the required services to drive the library according to the user’s perspective. Below is a diagram which tells shows what are the services the environment holds.

Silhouette_strcture

So here we can see the environment holds IdentityService, AuthenticatorService, RequestProvider s and EventBus. Out of these services IdentityService needs to be implemented by the user, other services however are present in the impl package, i.e. we can use their implementation of give our own implementation.

In order to implement identity service we have to extend the trait IdentityService. The only method the IdentityService holds is the retrieve method which takes a parameter LoginInfo(LoginInfo is a case class which holds two parameters providerId, providerKey as string). However we can add our own methods here as well. Below is implementation of IdentityService.

case class User(
userID: UUID,
loginInfo: LoginInfo,
firstName: Option[String],
lastName: Option[String],
fullName: Option[String],
email: Option[String],
avatarURL: Option[String],
userType: UserTypes.Value) extends Identity

trait UserService extends IdentityService[User] {
def save(user: User): Future[User]
}

class UserServiceImpl @Inject() (userDAO: UserDAO) extends UserService {
def retrieve(loginInfo: LoginInfo): Future[Option[User]] = userDAO.find(loginInfo)
def save(user: User) = userDAO.save(user)
}

Here we have implemented User by extending trait Identity. Then we have given the type of IdentityService as User and extends the UserService where we have added one more method save which takes a user parameter. And finally we have implemented it in the UserServiceImpl. Here the userDao implementation is being injected by guice, it has all the implementation of the database interaction.

Then there is the AuthenticatorService which basically deals with authentication, it helps to identify if the user’s session has expired or not. There are two traits to deal with the authentication Authenticator and StorableAuthenticator. The Authenticator trait consists of type value, which is used for identifying, with which type the authenticator will be serialized, then it has loginInfo: LoginInfo, I have mentioned about LoginInfo before, then it has isValid:Boolean which indicates if the returning customer’s session has expired or not. StorableAuthenticator extends Authenticator and adds another method called id to reference the authenticator in the backing store. AuthenticatorService trait has all the operation for Authenticator such as create, retrieve, init, embed, touch, update, renew and discard. In the impl package we can find the implementation for both these two things i.e. Authenticator and AuthenticatorService. Again it’s up to the library user to use what’s the best option for their application, either use the given implementation or implement according to your preference.

The Environment holds collection of Providers. Provider basically is a service to identify the user in the applicaiton. Silhouette is providing 14 different implementation for different providers including facebook, linkedin, github, twitter, yahoo, google etc. Its up to the user to use the implemented providers or implement their own providers by implementing the traits Provider and RequestProvider. We can embed more than one provider in our application and that is why environment takes the providers as collection…Seq[Provider].
The EventBus basically handles the events that occured in the application. We can give our own implementation of events by implementing the trait SilhouetteEvent. Its basically based on Akka’s event bus.

That was all about the environment that is required for the Silhouette to work on. Once the environment is ready we are good to go to secure our endpoints. While developing the application we might want some actions to be accessed by authenticated users only, some actions to be used by any user, or some actions need some authorization for it. All these stuffs are implemented in the Silhouette trait. We can use SecuredAction to secure an action which needs to be performed by authenticated users only e.g.

def user = SecuredAction.async { implicit request =>;
Future.successful(Ok(Json.toJson(request.identity)))
}

Or when we want some action to be authorized we can do this

def adminActions = SecuredAction(AdminRights).async{
implicit request =>;
Future.successful(Ok(Json.toJson(request.identity)))
}

object AdminRights extends Authorization[User]{
override def isAuthorized(identity: User)(implicit request: RequestHeader, lang: Lang): Boolean = {
identity.userType == UserTypes.Admin
}
}

object UserTypes extends Enumeration{
val Admin, NormalUser = Value
}

Here the SecuredAction is taking AdminRights as parameter which is implemented by extending Authroization trait. It uses UserTypes which is an enum and has values Admin and Normal User. So when we pass AdminRights to the SecuredAction that simply means only the admin can access that action. I am just giving a simple implementation to it, if required we can put more stuffs in the isAuthorized method.

UserAwareAction basically does not need any authentication or authorization for it, but if the user is authenticated or authorized it follows the other things, like keep the user session alive or stuffs like that. We can use it simply like below

def view(template: String) = UserAwareAction { implicit request =>;
template match {
case "home" =>; Ok(views.html.home())
case "signUp" =>; Ok(views.html.signUp())
case "signIn" =>; Ok(views.html.signIn())
case "navigation" =>; Ok(views.html.navigation.render())
case _ =>; NotFound
}
}

To summarize the topic let’s divide the user actions in two parts Signin/Signup and Any Other actions. Singin/Signup does not really need any authentication or authorization however other actions will need authentication or authorization to perform.

Silhouette_workflow (3)

Silhouette_workflow (2)

The diagrams that I am using here are just to visualize the flow, more actions are included in the workflow in real. Users can directly use signin throw the OAuth1 or OAuth2 or similar providers, their signup process is generally included in this part. So whenever the Signin/Signup happens Identity service is used to save or retrieve the identity then the Authentication service is called to create the authenticator and initiates the authentication process e.g. sending some token in the cookies, set timeout option etc. Publishing of the Signin/Signup event occurs here. Then finally the code block gets called and the result is send back to the result. Result could be the json or the play template here.

However in case of any other actions, the flow becomes a bit different. For these actions some sort of identities are sent from the user end. Then the Authentication service validates this identification, once its get validated the identity service is called to retrieve the identity and authorization action gets performed if there are any. Once its get authenticated or authorized the code block gets invoked. Once the code block gets invoked the result is sent to the user. So thats all about it. More about Silhouette could be find here.

Note: Most of the code snippets used here are taken form here.

Posted in Play Framework, Scala, Web | Tagged , , | 3 Comments

Playing Gravatar: A basic example to generate gravatar using email address with Play Framework


Playing Gravatar Image

In this blog I have created a basic example to generate gravatar using email address with Play Framework

Gravatar: An “avatar” is an image that represents you online—a little picture that appears next to your name when you interact with websites.

A Gravatar is a Globally Recognized Avatar. You upload it and create your profile just once, and then when you participate in any Gravatar-enabled site, your Gravatar image will automatically follow you there.

Gravatar images may be requested just like a normal image, using an IMG tag. To get an image specific to a user, you must first calculate their email hash.

The most basic image request URL looks like this:

http://www.gravatar.com/avatar/HASH

where HASH is replaced with the calculated hash for the specific email address you are requesting. For example:

http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50

Size : By default, images are presented at 80px by 80px if no size parameter is supplied. You may request a specific image size, which will be dynamically delivered from Gravatar by using the s= or size= parameter and passing a single pixel dimension (since the images are square):

http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=200

Default Image : What happens when an email address has no matching Gravatar image? By default, this:

http://www.gravatar.com/avatar/00000000000000000000000000000000

If you’d prefer to use your own default image (perhaps your logo, a funny face, whatever), then you can easily do so by supplying the URL to an image in the d= or default= parameter. The URL should be URL-encoded to ensure that it carries across correctly, for example:

http://www.gravatar.com/avatar/00000000000000000000000000000000?d=http%3A%2F%2Fexample.com%2Fimages%2Favatar

In addition to allowing you to use your own image, Gravatar has a number of built in options which you can also use as defaults. Most of these work by taking the requested email hash and using it to generate a themed image that is unique to that email address. To use these options, just pass one of the following keywords as the d= parameter to an image request:

  • 404: do not load any image if none is associated with the email hash, instead return an HTTP 404 (File Not Found) response
  • mm: (mystery-man) a simple, cartoon-style silhouetted outline of a person (does not vary by email hash)
  • identicon: a geometric pattern based on an email hash
  • monsterid: a generated ‘monster’ with different colors, faces, etc
  • wavatar: generated faces with differing features and backgrounds
  • retro: awesome generated, 8-bit arcade-style pixelated faces
  • blank: a transparent PNG image (border added to HTML below for demonstration purposes)

alt tag

  • Used Java Image Requests technique to generate hex format md5 of an input string
  • Used Gravatar Image Requests technique to access gravatar image
  • 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-gravatar should now be accessible at localhost:9000

References


Posted in Akka, Gravatar, Java, JavaScript, Play Framework, Reactive, Scala | Tagged , , , , , , | 1 Comment

Tutorial #3: Getting started with HTTP Programming in Play Framework


We have already discussed about the Play development environment in Tutorial #1 and use of WebJars, jQuery, Bootstrap & Bootswatch with Play in Tutorial #2

So, In this blog we would discuss about HTTP programming in 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 of HTTP programming in Play Framework:

  • Actions, Controllers and Results
  • HTTP routing
  • Manipulating results
  • Session and Flash scopes
  • Body parsers
  • Actions composition
  • Content negotiation

 

 

Now we know about HTTP Programming in Play. So we will follow the same HTTP Programming 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, Future, Play Framework, Reactive, Scala, Tutorial, Web | Tagged , , , , , , , , , | 3 Comments

Knolx Session: Role of FSM in Akka


Here I am going to explain what is FSM , why we should use FSM And features of FSM. I am going to explain FSM using live example.

Posted in Scala | Leave a comment

Digging Macroid – The first sod (Scala on Android)


Android, an operating system runs on millions of devices, based on Linux Kernel and and uses Dalvik/ ART as their process virtual machine with trace-based just-in-time compilation to run Dalvik “dex-code”, which is usually translated from the Java bytecode.Most of the application that runs on Android are made with Java , which is an imperative programming language with powerful features. However rise of the functional programming paradigm in recent years, make us think about taking alternative approach in building new softwares. When we talk about functional programming now a days, Scala always takes a special place in our thoughts because of its strong functional features. Scala however supports both functional and object features. Scala source code is intended to be compiled to Java bytecode, so that the resulting executable code runs on a Java Virtual Machine. Hence we can definitely have some second thoughts on building android apps with Scala, and there are libraries built already for it e.g vanilla android, scaloid etc. Recently I have gone through a new scala on android library called Macroid. In the recent scala conference Scala days 2015, the official android app was built with this library and after watching Nikolay Stanchenko’s presentation video I had the urge to go and play with it.

So Macroid is another library for making android apps with scala, having pros like concise code, fantastic concurrency support, advance dsls and with cons like build time according to the macroid docs. It definitely has strong features within it, however we have to reconsider the fact that learning to build android app with macroid would not be an easy task ;) , as most of the learning sources are based on java. One has to know how to build the app in java first or at least has to know what sort of components or activities need to use for it. I have tried my hands on macroid and will try to explain it. The ideal IDE for it is Intellij Idea or android studio(which is the same).

Android UIs are mainly based on xml files, all the view and viewgroup are mentioned on the xml file. However using macroid we can do these stuffs by avoiding xml upto and extent and coding directly in scala with a cleaner approach.

It uses Bricks, which defines the parts of the UI like layouts, buttons, Text etc. It gets denoted as follows w[Button], l[LinearLayout] etc. It uses tweaks to change the styles and behaviour of the widgets. It has something call tweaks, using what we change the behaviour of the widgets or layers. For examplehttp://

l[LinearLayout](
w[TextView] <~ text("Hey I think i work")
)

Here, l[LinearLayout] has defined the layout and within the layout we have a text box, so basically a widget for text view is created with w[TextView] and text is being put here using the tweak.

In this way it will be well composable for any complex view, with a cleaner and concise approach with macroid. For example

getUi(
l[DrawerLayout](
l[LinearLayout](
w[TextView] <~ text("Hey I think i work"),
l[FrameLayout]() <~ wire(fragmentContent) <~ id(Id.mainFragment) <~ fragmentContentStyle
) <~ contentStyle,
l[FrameLayout]() <~ wire(fragmentMenu) <~ id(Id.menuFragment) <~ drawerLayoutStyle
) <~ wire(drawerLayout) <~ drawerStyle
)

Here we are using different layout for the view as well as for each layer it has specific layer, and it is applied easily. (For the drawer layout click here). The DrawerLayout is the main layout here under which we have two more layouts, Linear Layout and Frame Layout. In the LinearLayout we have some text, and we have a FrameLayout inside, which gets the fragmentContentStyle applied. And on the LinearLayout the ContentStyle is applied. The other framelayout is got applied with drawerLayoutStyle and drawerStyle is applied to the main drawer layout.

DiggingMacroid

The example given here is just a portion of the complete app and we can see that doing it this way makes the code quite concise without playing with the xml files. In order to run the complete app we have to deal with some more stuffs like Activity, Contexts etc. In the next blog I will try to cover the remaining stuffs to build a complete app in Scala’s way and will explore the other advantages of it.

Posted in Mobile, Scala | Tagged , , | 2 Comments

Scala in Business | Knoldus Newsletter – April 2015


Hello Folks

We are back again with April 2015, Newsletter. Here is this Scala in Business | Knoldus Newsletter – April 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

Screenshot from 2015-04-27 18:16:11

Posted in Agile, Akka, Amazon EC2, Cloud, Java, JavaScript, LiftWeb, Mockito, MongoDB, Play Framework, Scala, Slick, Spark, Web | 1 Comment

AWS Services: AWS SDK on the Scala with Play Framework


playing-aws-scala

The following blog and attached code represent a simple example of Amazon Web Services in the Scala way with Play Framework using AWScala but in this blog I have implemented only Amazon Simple Storage Service (Amazon S3) functionalities.

AWScala: AWS SDK on the Scala REPL

AWScala enables Scala developers to easily work with Amazon Web Services in the Scala way.

Though AWScala objects basically extend AWS SDK for Java APIs, you can use them with less stress on Scala REPL or sbt console.


AWScala Supported Services


  • AWS Identity and Access Management (IAM)
  • AWS Security Token Service (STS)
  • Amazon Elastic Compute Cloud (Amazon EC2)
  • Amazon Simple Storage Service (Amazon S3)
  • Amazon Simple Queue Service(Amazon SQS)
  • Amazon Redshift
  • Amazon DynamoDB
  • Amazon SimpleDB

Amazon Simple Storage Service (Amazon S3)


package utils

import awscala._, s3._

object S3Utility extends S3Utility

trait S3Utility {

  implicit val s3 = S3()

  /**
   * Get all the available buckets
   *
   * @return
   */
  def getBuckets(): Seq[Bucket] = s3.buckets

  /**
   * Get the bucket by given name
   *
   * @param name The Bucket name
   * @return
   */
  def getBucketByName(name: String): Option[Bucket] = s3.bucket(name)

  /**
   * Create new bucket for given name
   *
   * @param name The Bucket name
   * @return
   */
  def createBucket(name: String): Bucket = s3.createBucket(name)

  /**
   * Create an object into given bucket by name
   *
   * @param bucket The Bucket
   * @param name The Object name
   * @param file The Object
   * @return
   */
  def createObject(bucket: Bucket, name: String, file: File): PutObjectResult = bucket.put(name, file)

  /**
   * Get the Object by given name from given bucket
   *
   * @param bucket The Bucket
   * @param name The Object name
   * @return
   */
  def getObject(bucket: Bucket, name: String): Option[S3Object] = bucket.getObject(name)

}
  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 { file =>
      import java.io.File
      val filename = file.filename
      val contentType = file.contentType
      log.error(s"File name : $filename, content type : $contentType")
      val uniqueFile = new File(s"/tmp/${UUID.randomUUID}_$filename")
      file.ref.moveTo(uniqueFile, true)
      if (Play.isProd) {
        try {
          val bucket = s3Utility.getBucketByName("test").getOrElse(s3Utility.createBucket("test"))
          val result = s3Utility.createObject(bucket, filename, uniqueFile)
          s"File uploaded on S3 with Key : ${result.key}"
        } catch {
          case t: Throwable => log.error(t.getMessage, t); t.getMessage
        }
      } else {
        s"File(${filename}) 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")
    }
}

AWS credentials! Make sure about environment or configuration


export AWS_ACCESS_KEY_ID=<ACCESS_KEY>
export AWS_SECRET_KEY=<SECRET_KEY>

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-aws-scala 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

References :-


This is the start of AWS Services implementation, from next week onwards we would be working on this application to make it grow. We would look at how we can make it more functional, then we would be adding more AWS 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 Akka, Amazon, Amazon EC2, AWS, AWS Services, Bootstrap, Bootswatch, Future, MultipartFormData, Play Framework, S3 | Tagged , , , , , , , , , | 3 Comments

Play Framework has lost its relevance. Or has it?


The last few weeks, rather months have been very interesting for Play Framework at least at Knoldus. We end up working and custom developing large sophisticated products and very niche reactive products. Over the last few months there has been a healthy (the part where people starting pulling each others hair is omitted on purpose) on whether we should be using the Play Framework at all. The usual suspects being the client side html generation hippies who would not buy the Play philosophy at all and then we have the Play Framework fan boys who would not code in anything but Play. I carried on this debate to the Scala Days conference in SFO and also discussed it with Typesafe’s Rich Dougherty (@richdougherty) to get an idea about his thoughts. We decided to do a rundown of all the pros and cons of one approach versus the other and this is the list that we came up with.

Client Side Rendering

Here, client code drives everything from reacting to user input, querying the server for data using APIs which in most cases would return JSON, presenting the resulting data back to the user. Backbone, Angular, Ember etc would be good illustration of this strategy.

Advantages of client side rendering

  1. High Re-usability – The back-end code only needs to spit out JSONs. There could be n number of clients for the same service who would be consuming these JSONs on the webapp level as well as mobile.
  2. Front end can be tested in isolation from the back end.
  3. The front end is totally independent of the back end and the back end can be swapped out to a different language. We did this when we converted the back-end of a product from Node.js to Scala. Read our ServiceSource case study.
  4. Saving power on the server – Well, I would debate this one, but this came up as an advantage that we are pushing the processing to the client machine than the server.

Server Side Rendering
Here, the server decides what the client should render. The pieces of HTML returned by the server may contain complex client-side behaviour, which may include client-side HTML generation. This behaviour however would be limited and might not suit well for all the desktop like client applications and front ends.

The advantages are as follows

  1. Code is type-safe, cleaner and easier to debug.
  2. There are set standards for writing server side code. Ok, with the advent of frameworks in js there are very well defined standards in js world as well, but how many of us follow them.
  3. It is faster to generate and send back HTML from server. Twitter moved from server to client only rendering and them moved back to server side rendering only to realize load time gain of 400% across different browsers.
  4. Server side rendering requires a constant time over load but client side rendering defines a linear increase with load.
  5. Content is visible to search engines for better indexing.
  6. There is less data going down the pipe.

In general the mantra to remember is that it is a bad practice to send JSON if all that we are doing on the front end is to incorporate that JSON in page’s DOM structure. Also it is a bad practice to send HTML to the client side when the client would need to parse the HTML and do some calculations with that.

So what is the best strategy?

In my opinion, it is a hybrid approach. That means instead of delivering JSON data and baking them into the template on client side, you could render the template on server side. Once the page is loaded, next the smaller interactions come into play, thus AJAX call has to append html templates to the DOM instead of processing JSON data.

Play has a robust templating engine which would allow us to define HTML generation in a type-safe manner and then render it on the client fast. Hot reload for all code, templates, config changes, etc allows you to iterate much faster. The stateless design of the framework helps you with performance and also enables you to write non-messy code. Play is also an amazing combination of best practices like non blocking and is built on Akka thereby getting the resilience and concurrency support. Finally LinkedIn, Guardian, Klout and other high scalability sites use play which endorses its value.

So does that mean Backbone and Angular have lost the battle? No, but they need to co-exist with Play. I would propose to always render the first view with Play templating and then make JS based calls to the server to generate JSON for rendering portions on the page based on user actions. Thoughts and brickbats welcome ;)

Posted in JavaScript, Play Framework, Scala | Tagged , , | 12 Comments

Conditional logging with Logback in Scala


Hello Folks

In my project , i got a scenario where I wanted conditional logging. I was using Logback framework for the same. I wanted to set different logging level for staging and production.

Either i could do manually changes in logback.xml for logging level for staging and production both. But this is not the good practice. Then I found the solution of implementing the conditions in logback.xml itself and that provided me the better and efficient solution.

First, we will see the way of implementing the conditions in logback.xml. There are 2 ways to do the same :

if-then form


<if condition="some conditional expression">
 <then>
 ...
 </then>
 </if>

if-then-else form


<if condition="some conditional expression">
 <then>
 ...
 </then>
 <else>
 ...
 </else> 
 </if>

Now we have learnt how to make conditions. Now we will see what conditional expressions we can use in logback.xml.

There are 3 ways to do this :

1. Using property() or p() :

Only context properties or system properties are accessible. For a key passed as argument, the property() or its shorter equivalent p() methods return the String value of the property.


property("someKey").contains("someValue")

or

p("someKey").contains("someValue")

2. Using isDefined() :

It is used to check whether a property is defined or not.


isDefined("someKey")

3. Using isNull() :

It is used to check whether a property is null or not.


isNull("someKey")

A full Example to make different logging level for staging and production.

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
   <appender name="CON" class="ch.qos.logback.core.ConsoleAppender">
     <encoder>
       <pattern>%d %-5level %logger{35} - %msg %n</pattern>
     </encoder>
   </appender>
   <if condition='p("runMode").contains("prod")'>
     <then>
       <root level="warn">
         <appender-ref ref="CON" />
       </root>
     </then>
     <else>
       <root level="info">
         <appender-ref ref="CON" />
       </root>
     </else>
   </if>
</configuration> 

Set the property as : export runMode=prod

Cheers !!!

Posted in Agile, Akka, Best Practices, Cloud, Java | Tagged , , , , , | 1 Comment