Archive for the ‘Scala’ Category

Implementing an async servlet in Scala with less than 10 lines of code

Tuesday, January 3rd, 2012

What is async servlet and why use it? An async servlet can tell the container that it will handle a request later, so that the current thread is not tied up and can be used for another request. Why is it useful? For example, if the request is going to do something relatively time consuming (e.g., generating a report from a DB), instead of tying up the thread doing nothing waiting for the data, you can free up the thread for other requests and wait for the data in a background thread. When the data is received, you can complete the response.

It turns out to be very easy to implement an async servlet (new in servlet 3.0). In Scala, it took less than 10 lines of code (not counting brace brackets and imports):

package com.ttdev.webqos
import javax.servlet.http._
import java.util.concurrent._

class MyServlet extends HttpServlet {
  private val pool = Executors.newFixedThreadPool(1) // create a thread pool

  override def doGet(req: HttpServletRequest, res: HttpServletResponse) {
    req.startAsync  //tel the container the response will be generated later
    pool.execute(new Runnable() {  // add the runnable to the queue
      def run {  // when a thread in pool picks up the runntable...
        res.getWriter.append("hello world!")  // write the response
        req.getAsyncContext.complete  // tell the container that the response is done
      }
    })
    // return without a response yet
  }

}

Reaction to “Clojure: Towards The Essence Of Programming” from a Scala perspective

Sunday, August 28th, 2011

How Scala addresses those problems

Just watched Howard Lewis Ship’s Clojure: Towards The Essence Of Programming, which is an excellent introduction to Clojure and how it addresses the problems in Java. As a Scala fan, I thought it would be a good idea to see how one could use Scala to do the same.

Ceremony vs Essence

Howard uses the example below to show how much ceremony (code with little real info) is required, hiding the essence (the real intention) when using Java to sort a list of Stock objects (a portfolio) either using different properties such as open values or last trade values:

 public static void sortByOpen(List<Stock> portfolio) {
    //ceremony: a lot of code but very little real info
    Comparator<Stock> c = new Comparator<Stock>() {
       public int compare(Stock o1, Stock o2) {
          return o1.getOpen() - o2.getOpen(); //essence: the beef is here
       }
    };
    Collections.sort(portfolio, c);
}

The Clojure version is:

//a Stock object is just a map with each field as a key. ":open" is the key to get the open value.
(sort-by :open portfolio)

In Scala, it can be as simple as the Clojure version:

//full version: using an anonymous function instead of a comparator object
portfolio.sortBy((s: Stock) => s.open)

//simpified version: sortBy is expecting the argument to be a function
// (Stock) => SOME-RESULT-TYPE, so we don't need to declare the
//type for "s".
portfolio.sortBy((s) => s.open)

//final version: as "s" only appears once in the function body, just use
//an underscore and get rid of the parameter declaration.
portfolio.sortBy(_.open)

The Clojure version is like the final Scala version in the first attempt because it doesn’t need typing information in the code. In Scala, the compiler infer it from the code.

In addition, in Clojure the object is just a map so people can refer to a property directly with its name without referring to the object. In Scala, we must use something to denote the object in the form of obj.property. However, the underscore syntax eliminates the need to declare that object, so the code is still very succinct.

The benefits of the Scala approach are:

  • Compile time checking: if the property name mismatches the Stock class, in the Scala the compiler will tell us immediately.
  • Runtime performance: it is a lot faster to access the property by offset than by looking up a key.

The cost we pay is mainly the learning curve: we must learn how Scala infers the typing information so that we know what to type and what to NOT type and learn the meaning of the underscore in an anonymous function.

Form is structure

I may not be fully understanding this example. Howard uses the Fahrenheit conversion, f =9*c/5+32, to show that in Clojure the form (the look on the surface) is the same as the structure (the actual relationship):

//the look is the same as the actual syntax tree
(+
  (/
    (* 9 c)
    5)
  32)

I definitely think the Java or Scala version is much simpler and more concise:

9*c/5+32

This is, after all, what we call DSL. Arithmetics has its rules of precedence and associativity, allowing us to write in a very succinct form to express more complex structure.

Read Eval Print Loop

Scala has it too. I like it very much too.

Functional programming

Howard that moves onto functional programming with examples using filter, reduce, map, for comprehension, stream. Obviously, Scala can do all these in a similar fashion. For example, to get the last trade total value of the portfolio, we can map each stock to its last trade value and then use reduce to sum them all up. In Clojure:

//#() means anonymous function. % refers to the one and only parameter (the stock).
(reduce + (map #(* (% :last-trade) (% :shares)) portfolio))

In Scala:

//+ in Scala is not a function, but a method. So we can't use it directly;
//instead, use an anonymous function with underscores again.
portfolio.map((s)=>s.lastTrade*s.shares).reduceLeft(_+_)

There is not much difference. However, I think the significance is much deeper. The question is not whether functional programming is supported or not, but how much it is intended to be used in place of procedural programming. Scala allows both styles of programming, which may or may not be a good thing, depending on how you view it. If you’re committed to the functional programming style for concurrency, testability, predictability, then using a language that is less capable of procedural programming is actually a good thing. If you’re more comfortable with procedural programming and just using functional programming in a smaller scale, then a hybrid language would be better.

Extending the language with DSL

Then Howard moves onto extending Clojure with DSL. One example he uses is building a DOM tree with a DSL.

(defview root-index
  [env]
  :html [
    :head [
      :title [ "Cascade Blog" ]
    ]
    :body [
      :h1 [ "Cascade Blog" ]
      :ul { :class "recent-postings" } [
        (template-for [posting (recent-postings env)]
          :li [
             (render-link env show-posting (posting :id) (posting :title))
           ])
      ]
    ]
  ])

As an exercise I implemented a similar DOM DSL in Scala:

//the DSL is implemented in the Html object
import Html._

//using the DSL to define a DOM tree
p @@ ("style" -> "color: red") containing (
        "This is an ",
        b containing ("interesting"),
        "DOM tree"
        )

They aren’t that different except that in Clojure each list item is separate from its neighbors by being enclosed in its own () but in Scala we must use a comma to separate the list items. So, choose your own poison: either tolerate a million ()’s or the ugly commas in the DSL.

Another difference is that in Clojure text can be freely mixed in the DOM tree as there is no typing restriction, while in Scala text is magically converted into a TextNode object. Again, the latter provides structure, compile-time protection and runtime performance, but we must learn the implicit conversion mechanism to understand what is going on.

Just to be complete, the DOM DSL is implemented in Scala as below:

//a DOM node
class Node

//a text node
case class TextNode(val text: String) extends Node

//an element node
case class Element(val name: String,
                   val attrs: Map[String, String],
                   val children: Seq[Node]) extends Node {
  def this(name: String) = this (name, Map(), List())

  //we can use symbols as method names, but @ is a reserved keyword in Scala,
  //so I used @@ as the name of the method that adds attributes to the element.
  def @@(attrPairs: (String, String)*) =
    //just add each pair to the map
    Element(name, attrPairs.foldLeft[Map[String, String]](Map())(_ + _), children)

  //add the child nodes (elements or text nodes) to this element
  def containing(children: Node*) = Element(name, attrs, children)
}

object Html {
  //convert strings into text nodes automatically
  implicit def string2TextNode(s: String) = TextNode(s)
  def p = new Element("p")
  def b = new Element("b")
}

Howard also shows the need for lazy evaluation so that some code is only executed on demand. For example, the DSL code to generate each <li> is repeatedly called in a loop. In Clojure lazy evaluation is implemented with macros which generate well-form code instead of arbitrary text. This seems to be more powerful (able to do more) than the call-by-name mechanism Scala, although I don’t know if/when this extra power is really needed.

Revealing the Scala magician’s code: method vs function

Sunday, August 21st, 2011

How’s a method different from a function in Scala?

A method can appear in an expression as an internal value (to be called with arguments) but it can’t be the final value, while a function can:

//a simple method
scala> def m(x: Int) = 2*x
m: (x: Int)Int

//a simple function
scala> val f = (x: Int) => 2*x
f: (Int) => Int = <function1>

//a method can't be the final value
scala> m
<console>:6: error: missing arguments for method m in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       m
       ^

//a function can be the final value
scala> f
res11: (Int) => Int = <function1>

Parameter list is optional for methods but mandatory for functions

A method can have no parameter list or have one (empty or not), but a function must have one (empty or not):

//a method can have no parameter list
scala> def m1 = 100
m1: Int

//a method can have an empty parameter list
scala> def m2() = 100
m2: ()Int

//a function must have a parameter list
scala> val f1 = => 100
<console>:1: error: illegal start of simple expression
       val f1 = => 100
                ^
//a function's parameter list could be empty
scala> val f2 = () => 100
f2: () => Int = <function0>

Why a method can have no parameter list? See below.

Method name means invocation while function name means the function itself

Because methods can’t be the final value of an expression, so if you write a method name and if it doesn’t take any argument (no argument list or an empty argument list), the expression is meant to call that method to get the final value. Because functions can be the final value, if you just write the function name, no invocation will occur and you will get the function as the final value. To force the invocation, you must write ():

//it doesn't have a parameter list
scala> m1
res25: Int = 100

//it has an empty parameter list
scala> m2
res26: Int = 100

//get the function itself as the value. No invocation.
scala> f2
res27: () => Int = <function0>

//invoke the function
scala> f2()
res28: Int = 100

Why we can provide a method when a function is expected?

Many Scala methods such as map() and filter() take functions arguments, but why can we provide methods to them like:

scala> val myList = List(3, 56, 1, 4, 72)
myList: List[Int] = List(3, 56, 1, 4, 72)

//the argument is a function
scala> myList.map((x)=>2*x)
res29: List[Int] = List(6, 112, 2, 8, 144)

//try to pass a method as the argument instead
scala> def m3(x: Int) = 3*x
m3: (x: Int)Int

//still works
scala> myList.map(m3)
res30: List[Int] = List(9, 168, 3, 12, 216)

This is because when a function is expected but a method is provided, it will be automatically converted into a function. This is called the ETA expansion. This makes it a lot easier to use the methods we created. You can verify this behavior with the tests below:

//expecting a function
scala> val f3: (Int)=>Int = m3
f3: (Int) => Int = <function1>

//not expecting a function, so the method won't be converted.
scala> val v3 = m3
<console>:5: error: missing arguments for method m3 in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       val v3 = m3
                ^

With this automatic conversion, we can write concise code like:

//10.< is interpreted as obj.method so is still a method. Then it is converted to a function.
scala> myList.filter(10.<)
res31: List[Int] = List(56, 72)

Because in Scala operators are interpreted as methods:

  • prefix: op obj is interpreted as obj.op.
  • infix: obj1 op obj2 is interpreted as obj1.op(obj2).
  • postfix: obj op is interpreted as obj.op.

You could write 10< instead of 10.<:

scala> myList.filter(10<)
res33: List[Int] = List(56, 72)

How to force a method to become a function?

When a function is not expected, you can still explicitly convert a method into a function (ETA expansion) by writing an underscore after the method name:

scala> def m4(x: Int) = 4*x
m4: (x: Int)Int

//explicitly convert the method into a function
scala> val f4 = m4 _
f4: (Int) => Int = <function1>

scala> f4(2)
res34: Int = 8

A call by name parameter is just a method

A call by name parameter is just a method without a parameter list. That's why you can invoke it by writing its name without using ():

//use "x" twice, meaning that the method is invoked twice.
scala> def m1(x: => Int) = List(x, x)
m1: (x: => Int)List[Int]

scala> import util.Random
import util.Random

scala> val r = new Random()
r: scala.util.Random = scala.util.Random@ad662c

//as the method is invoked twice, the two values are different.
scala> m1(r.nextInt)
res37: List[Int] = List(1317293255, 1268355315)

If you "cache" the method in the body, you'll cache the value:

//cache the method into y
scala> def m1(x: => Int) = { val y=x; List(y, y) }
m1: (x: => Int)List[Int]

//get the same values
scala> m1(r.nextInt)
res38: List[Int] = List(-527844076, -527844076)

Is it possible to maintain the dynamic nature of x in the body? You could cache it as a function by explicitly converting it:

//explicit conversion, but then you must invoke the function with ().
scala> def m1(x: => Int) = { val y=x _; List(y(), y()) }
m1: (x: => Int)List[Int]

scala> m1(r.nextInt)
res39: List[Int] = List(1413818885, 958861293)

equals() and Scala

Saturday, August 6th, 2011

Problem with equals()

The problem with equals() is that it is difficult to get it right. For example, for a simple class Foo, you may write the equals() method as:

class Foo(val i: Int) {
  override def equals(that: Any) = {
    that match {
      case f: Foo => f.i == i
      case _ => false
    }
  }
}

The problem is that what happens if the other object (“that”) belongs to a subclass of Foo, which may have its own fields? As the equals() method is only comparing the “i” field, it will ignore the other fields and return true prematurely. Below is such a subclass Bar:

class Bar(i: Int, val j: Int) extends Foo(i) {
  override def equals(that: Any) = {
    that match {
      case b: Bar => super.equals(b) && b.j == j
      case _ => false
    }
  }
}

With the erroneous equals() method in Foo, we could get incorrect results:

scala> val f1 = new Foo(2)
f1: Foo = Foo@14c0275

scala> val b1 = new Bar(2, 3)
b1: Bar = Bar@171bc3f

scala> f1.equals(b1)
res0: Boolean = true

scala> b1.equals(f1)
res1: Boolean = false

A solution to the problem

The problem is that the equals() method in Foo is treating the Bar object exactly as a base Foo object, but the equality contract in Bar has changed from that in Foo. Of course, not every subclass of Foo will use a different equality contract; some do and some don’t (by default, we should assume that they don’t). Therefore, the equals() method in Foo should make sure that the “that” object uses the same equality contract as “this”:

object FooEqualityContract {
}

class Foo(val i: Int) {
  //by default all Foo objects and subclass objects use this equality contract
  val equalityContract: Any = FooEqualityContract

  override def equals(that: Any) = {
    that match {
      //make sure the two objects are using the same equality contract
      case f: Foo => f.equalityContract == this.equalityContract && f.i == i
      case _ => false
    }
  }
}

Now, as Bar is using its own equality contract, it should say so:

class Bar(i: Int, val j: Int) extends Foo(i) {
  //tell others that we're using our own equality contract
  override val equalityContract: Any = BarEqualityContract

  override def equals(that: Any) = {
    that match {
      case b: Bar => super.equals(b) && b.j == j
      case _ => false
    }
  }
}

Now, the equals() method in Foo will rightly determine that a Bar object is using a different equality contract and thus will never be equal to a bare Foo object:

scala> val f1 = new Foo(2)
f1: Foo = Foo@34b350

scala> val b1 = new Bar(2, 3)
b1: Bar = Bar@7c28c

scala> f1.equals(b1)
res2: Boolean = false

scala> b1.equals(f1)
res3: Boolean = false

scala> val b2 = new Bar(2, 3)
b2: Bar = Bar@5dd915

scala> b1.equals(b2)
res6: Boolean = true

Of course, it should also work for subclasses that use the same equality contract:

scala> val f2 = new Foo(2) { }
f2: Foo = $anon$1@a594e1

scala> f1.equals(f2)
res9: Boolean = true

scala> f2.equals(f1)
res10: Boolean = true

Revealing the Scala magician’s code: expression

Sunday, May 1st, 2011

Scala is truly magical. However, sometimes it is not easy to understand how it performs the magic. Below are some common questions and their answers.

Why some of expressions below work (can be evaluated and printed) but the other don’t?

Math.min  //doesn't work
Math.min _  //works
val f: (Int, Int)=>Int = Math.min  //works

The first expression doesn’t work because Math.min is a method, but a method is not a value in Scala. The second expression works because the underscore asks Scala to convert the method to a function, which is indeed a value in Scala. The third expression also works because when Scala is expecting a function value from the expression but finds a method, it will convert it to a function automatically.

Why some of expressions below work but the other don’t?

List(2, 3, 5) foreach println  //works
List(2, 3, 5) foreach println(_) //doesn't work
List(2, 3, 5) foreach (println(_)) //works

The first one works because foreach is expecting a function, while println (of the Predef object which has been imported automatically) is a method, not a function, but as mentioned above Scala will convert it into a function automatically because a function is expected. So it works.

The second one is trying to create an anonymous function:

List(2, 3, 5) foreach ((x)=>println(x))

However, in Scala only a “top level” expression can be a function. In this case, println(_) is only a “term” in an expression (foreach is the operator) but not a top level expression, so the compiler won’t try to make it an anonymous function. Instead, it will search further to find the first enclosing top level expression (in this case, the whole expression you entered) and turn it into an anonymous function:

(x)=>List(2, 3, 5) foreach println(x)

But then the type of x can’t be inferred, so it is an error. Also, println(x) returns a value of (), the only value of the class Unit, which is not what foreach wants anyway (a function taking an Int).

With this knowledge, you can see why the third expression works:

List(2, 3, 5) foreach (println(_)) //works

This is because with the parentheses, a top level expression is expected, so Scala will make println(_) an anonymous function:

List(2, 3, 5) foreach ((x)=>println(x)) //works

Why some of expressions below work but the other don’t?

List(2, 3, 5) foreach (println("hi"+_))  //doesn't works
List(2, 3, 5) foreach (println "hi"+_)  //doesn't works
List(2, 3, 5) foreach (Predef println "hi"+_)  //works

The first expression doesn’t work because the first top level expression found is “hi”+_ due to the parentheses. So, Scala will treat it as:

List(2, 3, 5) foreach (println((x)=>"hi"+x))  //doesn't works

So you’re printing a function to the console and returning a unit value () to foreach. In order to fix the problem, you may try to get rid of the parentheses so “hi”+_ is no longer a top level expression:

List(2, 3, 5) foreach (println "hi"+_)

The problem is that Scala will now try to parse:

println "hi"+_

as:

expr1 op1 expr2 op2 ...

println is assumed to be an expression instead of a prefix operator because only !, ~, +, – can be prefix operators. So, println will be treated as an expression while the String “hi” will be treated as an operator, which is obviously incorrect.

To fix this problem, you can provide a real object as expr1, which is the Predef object:

List(2, 3, 5) foreach (Predef println "hi"+_)

Note that there are two operators: println and +. Because all symbolic operators have higher precedence than identifier operators, + will be applied first.

So, the first enclosing top level expression is turned into an anonymous function:

List(2, 3, 5) foreach ((x)=>Predef println "hi"+x)

Because in Scala “e1 op e2″ is treated as e1.op(e2), the code is treated as:

List(2, 3, 5) foreach ((x)=>Predef.println("hi".+(x)))

Great way to learn the Scala API: Scala interpreter

Friday, April 22nd, 2011

If you have already learned the language construct of Scala, the next step is to learn its API. If you’re a Java programmer, usually you’ll try to do that by writing small Scala programs in an IDE. However, there is a much better way: using the Scala interactive interpreter. This way you can inspect the effect of each line of code as soon as you press Enter. This is quite non-obvious for Java programmers because there is no such thing in the Java tool set.

For example, you’d like to learn about the Seq trait in Scala. So you open the API page of it and find a long list of methods. Let’s say you’re interested in learning the behaviors of the following methods:

/** Appends all elements of this sequence to a string builder. The written text consists of the string representations (w.r.t. the method toString) of all elements of this sequence without any separator string. */
def addString(b: StringBuilder): StringBuilder

To do that, you issue the “scala” command from a shell/command prompt and then explore the method like:

kent@dragon:~$ scala
Welcome to Scala version 2.8.0.r20327-b20091231020112 (Java HotSpot(TM) Server VM, Java 1.6.0_20).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val a = List("a", "b", "c")
a: List[Int] = List(a, b, c)

scala> val b = new StringBuilder
b: StringBuilder = 

scala> b.append("hi")
res0: StringBuilder = hi

scala> a.addString(b)
res1: StringBuilder = hiabc

From the experiment, it is clear that the addString() method will append all the elements of the Seq to the string builder.

Let’s consider another. You’re interested in:

/** Multiplies up the elements of this collection. num is an implicit parameter defining a set of numeric operations which includes the * operator to be used in forming the product.
*/
def product[B >: A](num: Numeric[B]): B

So, try it in the Scala interpreter:

scala> val a = List(3, 5, 2)
a: List[Int] = List(3, 5, 2)

scala> a.product
res2: Int = 30

So it seems to work fine. Possible to override the * operator? From the API doc it is clear that the default being used is the IntIsIntegral object:

package scala.math

class Numeric {
  object IntIsIntegral extends IntIsIntegral with IntOrdering {
     ...
  }
}

So, the first try is:

scala> import scala.math.Numeric._
import scala.math.Numeric._

scala> val x = new IntIsIntegral {
     | override def times(x: Int, y: Int) = x+y;
     | }
<console>:9: error: object creation impossible, since method compare in trait Ordering of type (x: Int,y: Int)Int is not defined

Oops, forgot to specify the IntOrdering trait which defines the compare() method. So, do it now:

scala> import scala.math.Ordering._
import scala.math.Ordering._

scala> val x = new IntIsIntegral with IntOrdering {
     | override def times(x: Int, y: Int) = x+y;
     | }
x: java.lang.Object with math.Numeric.IntIsIntegral with math.Ordering.IntOrdering = $anon$1@1e5d007

We have successfully created a new object to redefine the * operator as just addition. Now, pass it to the product() method:

scala> a
res5: List[Int] = List(3, 5, 2)

scala> a.product(x)
res6: Int = 11

It should be 3+5+2=10 but why the result is 11? Recall that it is doing multiplication, so it is using 1 as the seed for calculation (1+3+5+2). To change the seed from 1 to, say, 0, we can override the one() method:

scala> val x = new IntIsIntegral with IntOrdering {
     | override def times(x: Int, y: Int) = x+y;
     | override def one = 0;
     | }
x: java.lang.Object with math.Numeric.IntIsIntegral with math.Ordering.IntOrdering = $anon$1@11a9f20

scala> a.product(x)
res7: Int = 10

Obviously now it works.

Scala exercise 6: Tackling the Wicket hierarchy mismatch problem

Sunday, November 7th, 2010

Introduction

This is the sixth exercise in my Scala exercises series. If you haven’t seen it before, you may want to start from the previous exercises. Below is exercise 6: Tackling the Wicket hierarchy mismatch problem.

Some people have alleged that a weakness in Wicket is that you have to keep the hierarchy of the component tree in sync with that of the HTML elements. For example, for the HTML code:

<html>
    <form wicket:id="f">
        <input type="text" wicket:id="num">
        <input type="submit" value="OK">
    </form>
    <span wicket:id="result">10</span>
</html>

You would construct a component tree (in Scala) like:

class MyPage extends WebPage {
    val f = new Form[MyPage]("f") {
      override def onSubmit() {
        ...
      }
    }
    add(f)  //add the form to the page
    val numField = new TextField[Int]("num")
    f.add(numField)  //add the text field to the form
    val r = new Label("result")
    add(r) //add the label to the page
}

The problem is that, if, say, you’d like to move the result span into the form, you must change the code accordingly:

class MyPage extends WebPage {
    ...
    val r = new Label("result")
    f.add(r) //you must add the label to the form, not to the page!
}

and a common problem is that we may forget to do so. While there is no easy way to solve this problem, you could make the Scala code reflect the HTML structure visually (and look more like a declarative UI):

class MyPage extends WebPage {
  //the "ctx" represents a surrounding container context for the
  //construction of child components
  this containing { ctx =>
    val f = ...
    ctx.add(f)  //add the form to the context (the page)
    f containing { ctx =>
      val numField = ...
      ctx.add(numField) //add the text field to the context (the form)
    }
    val r = new Label("result")
    ctx.add(r)  //add the label to the context (the page)
  }
}

Note that the Scala code reflects the structure of the HTML code so you can compare them visually. In addition, if you need to move the label into the form, you can simply cut and paste the construction code of the label into that context of the form:

class MyPage extends WebPage {
  //the "ctx" represents a surrounding container context for the
  this containing { ctx =>
    val f = ...
    ctx.add(f)
    f containing { ctx =>
      val numField = ...
      ctx.add(numField)
      //the following lines were simply cut and pasted into here
      val r = new Label("result")
      ctx.add(r)
    }
  }
}

Now, your task is to implement this solution by creating the necessary code. Try to do it now.

See the answer here.

Scala exercise 5: monitoring pattern

Tuesday, November 2nd, 2010

Introduction

This is the fifth exercise in my Scala exercises series. If you haven’t seen it before, you may want to start from the previous exercises. Below is exercise 5: monitoring pattern.

Suppose that you have created a web application displaying product information to and taking order from customers. From your testing, let’s say you have determined that it can at most display the product page 100 times per minute, otherwise it will get painfully slow or even crash. Now, you’d like to monitor the application in production to make sure its loading is not approaching that limit. If yes, you’ll promptly allocate more computing resources to it.

In order to do that, it would be great if the application would support something like SNMP and provide a variable named “display counter” for you to access. Then you could use a monitoring system like zabbix or nagios to monitor it. The good news is, there is something similar for Java: it is called JMX (Java Management eXtension).

Next, you’ll do it step by step. Your job is to fill in the missing code.

First, create a Maven project. Use the following pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>scala-jmx</groupId>
    <artifactId>scala-jmx</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>
    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>
    <repositories>
        <repository>
            <id>java.net2</id>
            <name>Repository hosting the jee6 artifacts</name>
            <url>http://download.java.net/maven/2</url>
        </repository>
        <repository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </pluginRepository>
    </pluginRepositories>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.0.2</version>
                </plugin>
                <plugin>
                    <groupId>org.scala-tools</groupId>
                    <artifactId>maven-scala-plugin</artifactId>
                    <version>2.9.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1-beta-1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>add-source</goal>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

There is nothing special except that you’ll use Spring. Next, create a Scala trait PerfCountersMBean in the com.foo package:

trait PerfCountersMBean {
  def getDisplayCounter(): Int
}

It says that you’ll have an “MBean” that has a property named displayCounter. MBean stands for managed bean, which is just a Java bean that can be inspected or called from a remote management console. Next, create a Scala class to implement the MBean in the com.foo package (fill in the code later):

...
class PerfCounters extends PerfCountersMBean {
  ...
}

In order to initialize the MBean, you’ll turn it into a Spring bean (you’ll do it later by annotating the PerfCounters class). Then, to register it with the JVM, you’ll create a Spring bean that performs the registration. So, create a beans.xml file in the src/main/resources folder:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.foo"/>
    <!-- init this exporter eagerly as nobody will ask it to export the MBeans -->
    <bean id="mbeansExporter" class="org.springframework.jmx.export.MBeanExporter" lazy-init="false">
        <property name="beans">
            <map>
                <!--
                   the key is the name of the MBean, which starts with the domain
                   name (foo.com) and then some name=value pairs.

                   the value is the Spring bean acting as the MBean
                -->
                <entry key="com.foo:name=performance-counters" value-ref="perfCounters"/>
            </map>
        </property>
    </bean>
</beans>

Of course, you need to increment the counter whenever the product page is displayed. So, create a servlet which should display something as the product information and more importantly, get access to your MBean (a Spring bean) and increment the counter (you’ll fill in the code later):

class DisplayServlet extends HttpServlet {
  ...
}

Finally, create the web.xml file the src/main/webapp/WEB-INF folder:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>com.foo.DisplayServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/product</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/beans.xml</param-value>
    </context-param>
    <!-- initialize Spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

Run “mvn package” to build the war file. Then deploy it into Tomcat. To enable JMX in the JVM on which Tomcat runs, you need to pass some JVM arguments by setting the CATALINA_OPTS environment variable before running startup.sh (or startup.bat). On Linux:

export CATALINA_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1234 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"

On Windows:

set CATALINA_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1234 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"

Now, fill in all the missing code above.

To verify that it is working, run Tomcat with startup.sh (or startup.bat). Use netstat to check if it is listening on port 1234 (the port you specified above). Finally, run jconsole and connect to localhost:1234. Choose the “MBeans” tab and you should see your MBean in the com.foo folder. Check the value of the DisplayCounter. Access the product page at http://localhost:8080/scala-jmx/product. Then check the value again and it should have been incremented.

See the answer here.

Scala exercise 4: circuit breaker pattern

Sunday, October 24th, 2010

Introduction

This is the fourth exercise in my Scala exercises series. If you haven’t seen it before, you may want to start from exercise 1: template method, exercise 2: observer design pattern and exercise 3: decorator and composite design patterns. Below is exercise 4: circuit breaker pattern.

Problem: Create a console program that reads commands from the user. If the command is “q”, it will query a hard-coded URL (e.g., http://localhost:1234) and print the result to the console. If the command is “x”, it will exit. Below is a sample session:

Enter: q
Hello <-- this is the content at the URL
Enter: q
Hello <-- ditto
Enter: x
Exiting

In practice, if the remote server is overloaded, out of order or the firewall is mis-configured, every time you try to access the URL, it may take up to several minutes for your client to timeout or receive an error. It would also place unnecessary load on that server which possibly is already overloaded. Therefore, a better way to do it is, if the server returns an error (or does that for a consecutive number of times), your client will not try to access it anymore (treat it as an error immediately), until the administrator resets it. This is called the “circuit breaker” pattern.

Now, your task is to implement this behavior by filling in the code below. There is also a new command “r” to reset the circuit breaker. For simplicity, you’ll stop calling the server as long as one exception is caught.

//it extends the CircuitBreaker trait to obtain the functionality. Unit is the return
//type of the code block to be protected by the circuit breaker.
object HttpClient extends CircuitBreaker[Unit] {
  def main(args: Array[String]) {
    while (true) {
      print("Enter: ")
      try {
        readLine match {
          case "q" => queryHttpServer
          case "r" => reset
          case "x" => {
            println("Exiting")
            return
          }
          case _ => println("Unknown command")
        }
      } catch {
        case e: Exception => e.printStackTrace
      }
    }
  }

  def queryHttpServer {
    //run the code block in the protect() method
    protect {
      ... //get the content at http://localhost:1234
    }
  }
}

trait CircuitBreaker[T] {
  var isOpen = false

  //run the code block only if the circuit breaker is not open. If it is,
  //thrown an CircuitOpenException immediately.
  def protect(codeBlock: ...): T = {
    ...
  }

  def reset {
    println("Resetting the circuit")
    isOpen = false
  }
}

class CircuitOpenException extends Exception

In addition, for your own testing, you can create a simple HTTP server with netcat. Just run:

  echo -e "HTTP/1.0 200 OK\n\nHello\n" | nc -l 1234

It will quit after serving one request. So, you need to run it again to serve multiple requests.

Try to do it now! Then, click here to see the answer.

Scala exercise 3: decorator and composite design patterns

Saturday, October 16th, 2010

Introduction

This is the third  exercise in my Scala exercises series. If you haven’t seen it before, you may want to start from exercise 1: template method and exercise 2: observer design pattern. Below is exercise 3: decorator and composite design patterns.

Problem: In most UI frameworks including JSF, Wicket or Swing, you will need to provide a callback/listener object to handle requests from the user. Typically in such a callback, if there are some errors, you’d like to display a specific error message instead of propagating it to the framework, otherwise the framework would simply display a generic error to the user.

To hand code such a callback, you may do it like:

new Callback() {
  def onCallback(ev: Any) {
    try {
      //perform the business logic here
    } catch {
      case e: LoginException => {
        //assuming that error() will display the error
        error("failed to login")
      }
      case e: SQLException => {
        error("error accessing the database")
      }
    }
  }
}

The problem with this approach is that there is a lot of boilerplate code there, while most usually we only want to say for exception class E1, display some error message M1:

new ErrorHandlingCallback(
  //classOf[Foo] is the same as Foo.class in Java
  classOf[LoginException], "failed to login",
  classOf[SQLException], "...") {
  def performBusinessLogic(ev: Any) {
      //perform the business logic here
  }
}

But what if you’d like to extract some information from the exception and include it into the error message or would like to do something special? Then, ideally, you should be able to specify a function as the error handler:

new ErrorHandlingCallback(
  classOf[LoginException], "failed to login",
  classOf[SQLException], "...",
  (e: Exception) => doSomething(e)) {
  def performBusinessLogic(ev: Any) {
      //perform the business logic here
  }
}

Finally, you should be able to pre-define an object to handle the commonly seen exceptions:

//ideally you should be able to "add" the error
//handlers together to get a compound error
//handler
val defaultErrorHandler =
  (classOf[IOException], "I/O error") +
  (classOf[Exception], "Unknown catch all error")

new ErrorHandlingCallback(
  classOf[LoginException], "failed to login",
  ...,
  defaultErrorHandler) {
  def performBusinessLogic(ev: Any) {
      //perform the business logic here
  }
}

Your task is to complete the code below and create the other necessary classes as needed:

trait Callback {
  def onCallback(ev: Any)
}

abstract class ErrorHandlingCallback(errorHandler: ErrorHandler) extends Callback {
  //overload the constructor to take multiple error handlers (the star does that)
  def this(errorHandlers: ErrorHandler*) = ...

  def performBusinessLogic(ev: Any)

  def onCallback(ev: Any) {
    ...
  }
}

object ErrorHandlerUtil {
  //allow you to use a function as an error handler
  implicit def fromFunc(f: Exception => Boolean): ErrorHandler = ...
  //allow you to use a pair (error class, error message) as an error handler
  implicit def fromPair(p: (Class[_ <: Exception], String)): ErrorHandler = ...
}

Then, the following code should compile and run:

object ErrorHandlerTest {
  //in order to use the implicit conversion methods, you
  //must import these objects so that those methods can
  //be invoked without a prefix.
  import ErrorHandlerUtil._

  def main(args: Array[String]) {
    //assume that this is the default error handler in this context
    //classOf[Foo] is the same as Foo.class in Java
    val defaultErrorHandler = (classOf[IOException], "I/O error") + (classOf[Exception], "Unknown catch all error")
    //create a decorator to handle additional errors
    val decorator = new ErrorHandlingCallback(
      //convert a pair to an error handler
      (classOf[IndexOutOfBoundsException], "index out of bound"),
      //ditto
      (classOf[NullPointerException], "hit a null pointer"),
      //you can define a custom error handler using a function to, say,
      //access the info in the exception (not just its class).
      (e: Exception) => if (e.getMessage.contains("xyz")) {
        println(e.getMessage)
        true //indicate that it has been handled
      } else false,
      //specify the default error handler here
      defaultErrorHandler) {
      def performBusinessLogic(ev: Any) {
        println("called")
        ev match {
          //do nothing. No error.
          case "foo" =>
          //try to access the 100th element of an array which has only 3 elements
          case "bar" => Array[Int](1, 2, 3).apply(100)
          //Try to call a method on null
          case "baz" => null.equals("oops!")
          //throw a custom exception
          case "baz2" => throw new RuntimeException("I am xyz!")
          //divided by zero (something unexpected to test the ultimate fallback)
          case "baz3" => 100 / 0
        }
      }
    }
    decorator.onCallback("foo")
    decorator.onCallback("bar")
    decorator.onCallback("baz")
    decorator.onCallback("baz2")
    decorator.onCallback("baz3")
  }
}

Try to do it now! Then, click here to see the answer.