Tuesday, November 13, 2012

Hello World! with Scala Web Application using Play 2.0 and Scalate

In this post, we will look at how to make a hello-world web application in scala using the Play 2.0 Web Framework and change the template engine to work with Scalate. We assume your machine is all set up with Java and Scala configured.

Step 1 : DOWNLOAD AND CONFIGURE Play 2.0

Download the Play Framework 2.0 from http://download.playframework.org/releases/play-2.0.4.zip. Then extract the zip file to some location. I put mine at C:\Development\tools\play-2.0.4\. It is usually a good idea to leave the version number intact so as to easily know what version of any tool you are currently having on your machine.

The configuration portion is pretty simple – Update your PATH environment variable to include the root directory of the play-2.0.4 folder which has the “play.bat” (I am running windows).

To verify, launch your command line or powershell and type the command “play”. You should see something like shown below.

image

Step 2 : CREATE A NEW PLAY 2.0 WEB APPLICATION

Using command line (change directory – cd), go to a folder where you wish to place your application. Run the following command

play new helloworld-scalate

Here helloworld-scalate will be my application name.

Then from the command line go into the “helloworld-scalate” folder. And then run the following command.

play run

The first time you run, it takes a few seconds to initialize the project and upon success, you will see on-screen instructions that the application is hosted at 9000 port on localhost.

image

Verify by opening your browser and loading http://localhost:9000

You should see a welcome page.

Step 3 : INTEGRATING SCALATE INT YOUR APPLICATION

I found the proper instructions to do this here. But I will repeat them again.

Go to helloworld-scalate\project\Build.scala

3.a Add the following lines to appDependencies.

"org.fusesource.scalate" % "scalate-core" % "1.5.3"

What did we do? What we are doing is to add a dependency on scalate-core in an SBT friendly style. Play 2.0 takes care of fetching this dependency through its repositories which is listed at helloworld-scalate\project\plugins.sbt


To verify if things are fine, go back to command line and run the command


play run


You should see that SBT updates the dependencies. Just verify if your application can still be browsed from localhost:9000.



3.b Add ScalaIntegration.scala to helloworld-scalate\app\lib


You will need to create a folder “lib” inside helloworld-scalate\app folder. And then from the URL given below copy the content into a new file – ScalaIntegration.scala


https://raw.github.com/janhelwich/Play-2-with-Scala-and-Scalate/master/app/controllers/ScalateIntegration.scala


This does the necessary bootstrapping such that you can now use scalate in the current project.


Run the “play run” command again and reload the page at localhost:9000 to make sure you haven’t made a mistake.



Step 4 : UPDATE VIEWS & ACTION WITH TEMPLATE OF YOUR CHOICE


Scalate supports multiple template engines like Jade, Mustache, Scaml. The documentation indicates that Scaml gives the best performance given the strongly typed nature. But I might have misread the docs so read and check yourself.


To do this, rename your files inside “helloworld-scalate\app\views” folder such that extension is changed from .scala.html to .scaml. Note that you will see two files – the layout file (main) and the view file (index).


In the main.scaml, add the following code.

-@ var body: String
-@ var title: String = "Page"

%html
%head
%title= title
%body
!= body

In the index.scaml, add the following code.

-@ var message: String = "Page"
/Layout template file given here
-attributes("layout") = "main.scaml"

%h1= message

Notice that in the index.scaml, we specified that we want to apply the main.scaml layout using the attributes(“layout”) declaration.


You also need to change the application controller which is inside the helloworld-scala\app\controllers\application.scala


The Application controller has an action called “index” which is the one that gets executed when you were loading the browser. We need to change this action such that it renders using Scalate instead of the default one.

package controllers

import play.api._
import play.api.mvc._

object Application extends Controller {

def index = Action {
//Ok(views.html.index("Your new application is ready."))
Ok(Scalate("index.scaml").render(‘message -> "Hello World"))
}
}

As you can see in the index action, I commented the existing line added this one line.


Ok(Scalate("index.scaml").render(‘message-> "Hello World"))


Please pay attention to the ‘ in front of the title. Here the ‘message is a symbol literal. You can read more about them here. 


Now run the “play run” command again and you should see plain html page that prints “Hello World”.


I hope this step-by-step helped you get started with a new play 2.0 web application in Scala and also made you familiar with integrating the scalate engine. Note that the original url which I mentioned earlier has the same steps but step 4 where default Scalate template type is specified in the <application folder>\conf\application.conf is not performed. I skipped this step and it doesn’t appear that it will cause any problems. But again, after reading this tutorial, if you are a beginner, then you and I are at the same level so please feel free to explore more and learn.


Thanks!

Monday, November 05, 2012

Useless experiment with Asynchronous Procedure Calls from C#

While Hurricane Sandy hit the East Coast and gave me a full week of vacation without electricity and internet, I gathered enough motivation to read through the very good book – concurrent programming on Windows by Joe Duffy. So here, I came across the Asynchronous Procedure Calls and what they mean. So this post is just a journal about me trying to do something clever (actually stupid) and sharing my madness with others.

From what I learnt, an asynchronous procedure call (APC) is just a procedure that you can queue and request the OS that this procedure be performed on a particular thread. But that particular thread may be executing something right? So the question is when will the APC be executed? The answer for that is “it will be executed on the thread when it enters an ‘alertable wait’ state”. So what is an alertable wait?

Consider the code below.

void IExecuteOnAThread(){
lock(syncLock){
while(conditionIsNotMet)
Monitor.Wait(syncLock);
}
}

In the above snippet, the thread is actually waiting on the syncLock. When some other thread that makes the conditionIsNotMet as false and does a Pulse() on the syncLock, this current thread shall wake up and proceed with its execution.


Now back to “alertable wait” –> If a thread enters an alertable wait, then it can wake up properly (like in the case above) or can wake up for some other reason. This is how APC gets executed. When an APC gets queued on a thread, the OS will execute this APC the moment it finds that thread in an “alertable wait”.


So while I think about this concept, it stuck to me (given that I am not that smart) to run a simple experiment. Usually, we queue work items into ThreadPool to get executed. Now the execution can happen in parallel so there is no order guarantee. In some cases, I would like to execute some asynchronous operations “in-order”; as queued; in the background (for whatever reason). In these cases, we typically use some kind of “executor” classes where a queue is almost always involved and some thread/threads wait for the work to be queued and execute them one by one – classic Producer/Consumer style.


So what I wanted to try was to take advantage of APC and get away from not having to write any code to implement executors.



  • I would simply create an “Executor” which has one thread which is always in an alertable wait state (Note that CLR takes care of making sure the Waits are resumed properly in case of any spurious wake-ups)
  • The OS will take care of executing my operations one-by-one.

Note: For those who cannot wait till the end, do not do this – it is not worth it. I am just doing it because Sandy hit my head pretty hard.

 public class StupidExecutor
{
delegate void ApcProc(UIntPtr dwParam);

[DllImport("kernel32.dll")]
static extern uint QueueUserAPC(ApcProc pfnApc, IntPtr hThread, UIntPtr dwData);

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();

private readonly AutoResetEvent _waiter = new AutoResetEvent(false);
private IntPtr _threadId = IntPtr.Zero;

public StupidExecutor()
{
new Thread(WaitForApc).Start(null);
}

public void Stop()
{
_waiter.WaitOne();
}

private void WaitForApc(object none)
{
_threadId = GetCurrentThread();
_waiter.WaitOne();
}

public void QueueWork(Action action)
{
//while (Thread.VolatileRead(ref _threadId) == IntPtr.Zero)
// Thread.Sleep(0);
var localAction = action;
ApcProc apcProc = ((z) => localAction());
QueueUserAPC(apcProc, _threadId, UIntPtr.Zero);
}
}

When the StupidExecutor gets created, a thread is launched which when started waits for a signal on a Auto Reset Event. This will make the thread wait because it is non-signalled and will remain so until Stop is executed on the executor. The executor has one method “QueueWork” which takes a delegate.


So the usage of the stupid executor is as shown:

static void Main(string[] args)
{
var executor = new StupidExecutor();
double[] avg = {0.0};
int size = 1000;
for (int j = 0; j < size; j++)
{
var queued = DateTime.UtcNow;
executor.QueueWork(() => avg[0] += (DateTime.UtcNow - queued).TotalMilliseconds);
}
Console.ReadLine();
Console.WriteLine("Average Latency : "+avg[0]/size);
}

So the intention was to measure the latency (again not really the most efficient way). And I see an average latency of around 2 ms. So this must be a great way! Not really! First of all, for a lot of reasons like state corruption among other things this should not be done. Moreover, you are passing managed delegates to native code. So GC can always kick in. So to prove it, I am changing the sample size from 1000 to 100000.


Firstly, it wouldn’t work and you will be greeted with a nice dialog.


image


So run it in debug mode and you will get a nice little MDA called “CallbackOnCollectedDelegate" shall be raised. This simply says that the delegate you passed to native code is GC’d already.


image


Or even this:


image


So the experiment which was doomed to fail did fail. Long story short – don’t mess with your threads.

Sunday, October 28, 2012

A 5 min survey

Those who are unfortunate to see this post, can you please take this quick survey (7 questions)