And You Thought Option is Just Another Way to Handle null


Ok, to start with, the recommendation is to use None instead of null. Ideally if in Scala code, we end up getting a NPE then that is sin! Well at least at Knoldus :)

null in Java is used as a placeholder for denoting no value or a non-fatal error situation. It is widely accepted as a Billion dollar mistake of Java. The way to work around it is to have a NullObjectPattern which is present as a pattern in variety of languages and which people seldom use.

Scala is smart. It has an option which is a container. Now the container can either have something or it can be empty. Most of the times developers working in Scala use it in either of the two situations

First, when they are working with a Java API which possibly returns null. Since you would not want to work with null in Scala then you would wrap the Java API call in an Option. Something like this

def someCrappyJavaService = null   //> someCrappyJavaService: => Null
val result = Option(someCrappyJavaService)  //> result  : Option[Null] = None
if (result==None) println("bla")   //> bla

If you would notice, most of the developers coming from the Java world would be writing code like this.

However, Option provides us with lot of cool ways to implement our logic. For starters, instead of checking == you could instead do

def someCrappyJavaService = null     //> someCrappyJavaService: => Null
val result = Option(someCrappyJavaService)//> result  : Option[Null] = None
if (!result.isDefined) println("bla") //> bla

Ok, i see you throwing a stone at me. What is the big deal here? You could also do a getOrElse

def someCrappyJavaService = null
val result = Option(someCrappyJavaService).getOrElse("bla")
println(result)

Still, what is the big deal? Well, we have just started!

One of the cool feature of option is that it can be treated like a collection. What? Yes, you can call methods like map, flatMap, foreach and use it in for comprehensions. Let us see how that makes things easier for us.

for

We want to execute a portion of the logic only if we have got a value in the Option container. There is “a” way and then a better way to do it. See the code below

val result = None //Some("Hello")
def someProcessingLogic(x: String) = 
  println(s"I would execute when there is some value like $x")
//Standard Way
if (result != None) someProcessingLogic(result.get)
// Better Way!
for (res <- result) someProcessingLogic(res)

Now the for comprehension would evaluate only if res is not an empty box i.e. it has some value. But, what if there are multiple options that we want to compose together. For example the following code block
Continue reading

Posted in Scala | Tagged , | Leave a comment

Adding Scalastyle in a Multi-Module SBT Scala Project


Nowadays, building a Multi-Module SBT project is becoming very common. It helps us to keep multiple related projects in a single build. Moreover, each sub-project in the build has its own SBT default directory. Also, it generates its own build and works like any other project.

But, adding Scalastyle in a Multi-Module SBT Scala project is not easy because Scalastyle does not support Multi-Module SBT projects yet. So, in this post we will see how to add Scalastyle in a Multi-Module SBT project in an easy way.

In this following example we have a main project called parent and two sub-projects – child1 and child2. Now, lets get started with building the parent project.

1. To create multiple projects in a single build, we must first declare each project and also that how they relate in Build.scala file. So, here’s an example of a Build.scala file which defines a root project parent, where the parent project aggregates two sub-projects, child1 and child2.

import sbt._
import Keys._
import org.scalastyle.sbt.ScalastylePlugin

object BuildSettings {

 lazy val buildSettings =
   Defaults.defaultSettings ++
     Seq(
       version := "1.0",
       scalaVersion in ThisBuild := "2.11.2",
       parallelExecution in ThisBuild := false,
       scalacOptions := Seq(
         "-feature",
         "-language:implicitConversions",
         "-language:postfixOps",
         "-deprecation",
         "-encoding", "utf8",
         "-Ywarn-adapted-args"))

}

object SBTMultiBuild extends Build {

  import BuildSettings._

  // Common settings for all build modules.
  val commonSettings = buildSettings ++ Seq(ScalastylePlugin.Settings: _*)

  lazy val parent = Project(
    id = "parent",
    base = file(".")),
    settings = buildSettings) aggregate(child1, child2)

  lazy val child1 = Project(
    id = "child1",
    base = file("child1"),
    settings = commonSettings)

  lazy val child2 = Project(
    id = "child2",
    base = file("child2"),
    settings = commonSettings)
}

This code resides under parent/project/Build.scala. Having common buildSettings for all projects helps in managing all common settings for all projects under one object. Besides we also have commonSettings which contains Scalastyle settings in it, so that we don’t have to add it separately in all projects.

2. Next we have added commonSettings in all sub-projects

lazy val child1 = Project(
  id = "child1",
  base = file("child1"),
  settings = commonSettings)

lazy val child2 = Project(
  id = "child2",
  base = file("child2"),
  settings = commonSettings)

By adding commonSettings in all sub-projects we get Scalastyle settings added in all of them. So, we don’t have to add Scalastyle settings in sub-projects separately.

3. Now we have to add following line of code in parent/project/plugins.sbt file

// SBT plugin for ScalaStyle
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "0.5.0")

This code will help SBT to add Scalastyle as a Plugin in the project.

4. At last we need to add scalastyle-config.xml file in the parent folder.

5. Now if we run – sbt scalastyle command on the parent project we can see the warnings on the terminal for all sub-projects in a single go.

knoldus@knoldus-desktop:~/parent$ sbt scalastyle
[info] Loading project definition from /home/knoldus/parent
[info] Compiling 2 Scala sources to /home/knoldus/parent/target/scala-2.11/sbt-0.13/classes...
[info] Set current project to parent (in build file:/home/knoldus/parent)
[info] Processed 1 file(s)
[info] Found 0 errors
[info] Found 0 warnings
[info] Found 0 infos
[info] Finished in 10 ms
[success] created: sbt.SettingKey$$anon$4@54449f9d
[info] Processed 2 file(s)
[info] Found 0 errors
[info] Found 0 warnings
[info] Found 0 infos
[info] Finished in 1 ms
[success] created: sbt.SettingKey$$anon$4@54449f9d
[warn] /home/knoldus/parent/child1/src/main/scala/sample.scala:16:55: magic.number.message
[info] Processed 1 file(s)
[info] Found 0 errors
[info] Found 1 warnings
[info] Found 0 infos
[info] Finished in 4 ms
[success] created: sbt.SettingKey$$anon$4@54449f9d
[warn]/home/knoldus/parent/child2/src/main/scala/sample.scala:10:8: method.name.message
[info] Processed 3 file(s)
[info] Found 0 errors
[info] Found 1 warnings
[info] Found 0 infos
[info] Finished in 1 ms
[success] Total time: 1 s, completed 14 Sep, 2014 1:02:50 PM

So, we saw in this post that how easy it is to add Scalastyle in a Multi-Module SBT Scala Project.

Posted in Agile, Architecture, Scala | Tagged , , , | Leave a comment

SCALA : Finding Patterns in Strings


To determine whether a String contains a regular expression pattern , create a “regex object” by using “.r” method on a string .

And then use the pattern with findFirstIn when you’re looking for one match, and findAllIn when looking for all matches.

First create a Regex for the pattern you want to search for, in this case, a sequence of one or more numeric characters:

scala> val numPattern = "[0-9]+".r

numPattern: scala.util.matching.Regex = [0-9]+

Next, create a sample String you can search:

scala> val address = "123 Main XYZ"

address: java.lang.String = 123 Main XYZ

The findFirstIn method finds the first match:

scala> val match1 = numPattern.findFirstIn(address)

match1: Option[String] = Some(123)

When looking for multiple matches, use the findAllIn method:

scala> val matches = numPattern.findAllIn(address)

matches: scala.util.matching.Regex.MatchIterator = non-empty iterator

As you can see, findAllIn returns an iterator, which lets you loop over the results:

scala> matches.foreach(println)

123

101

If findAllIn doesn’t find any results, an empty iterator is returned, so you can still write your code just like that—you don’t need to check to see if the result is null. If you’drather have the results as an Array, add the toArraymethod after the findAllIn call:

scala> val matches = numPattern.findAllIn(address).toArray

matches: Array[String] = Array(123, 101)

If there are no matches, this approach yields an empty Array. Other methods like toList, toSeq, and toVector are also available. You can also create regex object by importing the Regex class

scala> import scala.util.matching.Regex

import scala.util.matching.Regex

scala> val numPattern = new Regex("[0-9]+")

numPattern: scala.util.matching.Regex = [0-9]+

Posted in Scala | Tagged , | Leave a comment

Finagle By Twitter Engineer @ Knoldus


This week, Puneet Khanduri, member of Twitter core engineering team, introduced us to Finagle in the MeetUp organized by Knoldus. It was a great session. We are thankful to Puneet. It was quite inspiring and appreciated by all attendees.

IMG-20140910-WA0001

Please find slide deck of this meetup.

Posted in Agile, Scala | Tagged , | Leave a comment

Easiest Way to Implement Google Map in Scala.js


In this blog, I would explain how to implement Google Map in scala .js. If you are developing your web application in Scala and you want to write javascript functionality in Scala then you should go with scala.js.

Screenshot from 2014-09-10 22:51:44

To implement Google Map in scala.js, please follow below steps:-

1) Add below code in your HTML file

<script src="https://maps.googleapis.com/maps/api/js"></script>


<div id="map_canvas" style="height: 430px; width: 512px;"></div>

2) Add below function in your Scala class file

@JSExport
def initialize(lat: Double, long: Double) = {
val map_canvas = document.getElementById("map_canvas")
val map_options = lit(center = (jsnew(g.google.maps.LatLng))(lat, long), zoom = 3, mapTypeId = g.google.maps.MapTypeId.ROADMAP)
val gogleMap = (jsnew(g.google.maps.Map))(map_canvas, map_options)
val marker = (jsnew(g.google.maps.Marker))(lit(map = gogleMap, position = (jsnew(g.google.maps.LatLng)(lat, long))))
}

3) Call initialize function in your HTML file.

<script type="text/javascript">


com.knoldus.weather.Weather().initialize(42.2781410217,-74.9159927368)

</script>

For complete source code, go to https://github.com/knoldus/ScalaJs_Weather_Report

Posted in Agile, AJAX, CSS, JavaScript, jQuery, Scala, Web | Tagged , , | Leave a comment

How to implement infinite scroll on canvas using paper.js


We make drawing on canvas using paper.js. In this blog, i would explain that how can we implement infinite scroll on canvas.

Suppose we have a fixed size canvas :

<canvas id="myCanvas" width="2500" height="1000"></canvas>

But we want to implement infinite scroll i.e. we can draw infinite items on canvas using paper.js. As we will either scroll down or scroll up, then it should scroll infinitely.

First of all, we have to detect mouse scroll event. We have to do separate event handling for scroll up and scroll down.
You can use any method to detect mouse scroll. I am using below approach for that :


var canvas= document.getElementById("myCanvas");
function mouseDown(e) {

		if (parseInt(navigator.appVersion) > 3) {

			var evt = e ? e : window.event;
			var delta = evt.wheelDelta ? evt.wheelDelta / 120
					: evt.detail ? -evt.detail : 0;

			/* For canvas scrolling */
			if (delta > 0) { // Scroll up
                             
		               // Perform action for scroll up

			} else { // Scroll down

                              // Perform action for scroll down

			}

		}
		return true;
}

	if (parseInt(navigator.appVersion) > 3) {
		canvas.onmousewheel = mouseDown;
		if (navigator.appName == "Netscape"
				&& parseInt(navigator.appVersion) == 4) {
			canvas.captureEvents(Event.MOUSEDOWN);
		}
	}

Now we will create a paper.js scope :

var scope = new paper.PaperScope();
var canvas= document.getElementById("myCanvas");
scope.setup(canvas);

As we know, paper.js scope has one project and its view, by default. Whatever items we draw, it holds by the project and using view, we can handle drawing and user interaction with mouse and keyboard.
So for infinite scrolling, we have to play with view.

For scroll Up :

 // Perform action for scroll up
scope.view.scrollBy(new scope.Point(0,-100));

As we scroll up, view should also be scroll by (0,100) i..e x = 0, y = 100. You can change the y value as per your need.

For scroll down :

 // Perform action for scroll down
scope.view.scrollBy(new scope.Point(0,100));

As we scroll down, view should also be scroll by (0,-100) i..e x = 0, y = -100. You can change the y value as per your need.
Its done. Now you will be able to get infinite scrolling.

Cheers !!!

Posted in Bootstrap, CSS, JavaScript, jQuery, Scala, Web | Leave a comment

Scala’s evolving ecosystem – Introduction to Scala.js


In this MeetUp, We introduced Scala.js as Scala’s evolving ecosystem. Scala.js- A scala to JavaScript compiler. If We are developing any web application in Scala, we don’t need to sacrifice javascript interoperability.

20140903_181617

Posted in Agile, AJAX, JavaScript, News, Scala, Web | Tagged , , | 2 Comments

How to deal with multiple projects in one scope in paper.js


Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas. It offers a clean Scene Graph / Document Object Model and a lot of powerful functionality to create and work with vector graphics and bezier curves, all neatly wrapped up in a well designed, consistent and clean programming interface.

First of all, we will see the architecture of Paper.js. When working with PaperScript, each script is run in its own scope, a PaperScope object. Each scope or context holds a row of objects that describe its state, such as a list of open projects, a reference to the active project, a list of views that each represent a canvas element, the currently active view, a list of mouse tools, the currently active tool, etc.

To explain the relation between scopes, projects, views and tools: Each scope can hold one or multiple projects, which are displayed through one or multiple views (each representing a Paper.js canvas). Views are not associated with a specific project, but in fact render all visible projects that have items within the visible area. Tools can work on any project within any view, as long as they belong to the same scope.

So, in this blog we will see that how can we deal with multiple projects in one scope.

First, I am creating a global scope.

var scope = new paper.PaperScope();

I have 2 canvas element to deal with :

<canvas id="canvas_1"></canvas>
<canvas id="canvas_2"></canvas>

Now i will setup the canvas element in scope which will create separate projects for 2 canvas element.

var canvas_1 = document.getElementById('canvas_1');
scope.setup(canvas_1);

var canvas_2 = document.getElementById('canvas_2');
scope.setup(canvas_2)

Now, whatever the action we will perform like drawing, it will be drawn at the project which is created later. In our case, all the drawings would happen at canvas_2 project.
But we want to handle these 2 projects separately.

So to handle these projects separately, we have to do following :
1. First, get the view of the canvas by its id :

var view_1 = scope.View._viewsById['canvas_1'];

1. And, activate that particular project :

view_1._project.activate();

Now whatever you will draw, it will happen on canvas_1.

So conclusion is that if you want to perform drawing on particular canvas project, just get the view of that and activate the project. You are done.

Cheers !!!

Posted in AJAX, JavaScript, jQuery, Web | Leave a comment

Dribbling with Filter.js: client-side JS filtering of JSON objects


Dribbling Filter.js

Play framework with client-side JS filtering of JSON objects and rendering HTML snippets via jQuery.

Big chunk to display? Interactive filtering? Most importantly it has to be really fast. Isn’t it like dribbling against Netherland! Big ground, lots of hooting and most importantly have to be fast and win
 
UI programming is an exciting ground to play, That’s why i chose reactive platform play framework. But problem was how to dribble at client side. Need an api to provide fast filtering of data. Answer is Filter.js

In this post we are integrating Filter.js with Play Framework for reactive data streaming using Ajax and filtering data on client side using Filter.js magic.

Filter.js is client-side JSON objects filter to show/hide HTML elements. Multiple filter criteria can be specified and used in conjunction with each other.

Mustache.js is a logic-less template syntax. It can be used for HTML, config files, source code – anything. It works by expanding tags in a template using values provided in a hash or object.


Instructions :-


  • The Github code for the project is at : playing-json-object-filter-js
  • Clone the project into local system
  • To run the Play framework 2.3.3, you need JDK 6 or later
  • Install Typesafe Activator if you do not have it already. You can get it from here: download
  • Execute activator clean compile to build the product
  • Execute activator run to execute the product
  • playing-json-object-filter-js should now be accessible at localhost:9000

References :-


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 more functional, 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, Web, AJAX, JavaScript, Bootstrap, jQuery, Play Framework, Reactive | Tagged , , , , , , , , | 2 Comments

Knolx Session : Introduction to Selenium


In this presentation, I have briefly explained about the Selenium IDE.

 

Posted in Scala, Web | Leave a comment