Getting started with Play 2.0, Heroku and Scala

This is another tutorial of the category ‘quick start for absolute beginners’. This time the topic is on Play 2.0, Heroku and Scala. The reason for this tutorial is that recent announcements indicate that the three topics will have a bright future together. A really nice overview of all three topics can be found in this presentation on slideshare (simply skip the Akka part. Or even better, read it as well!).

Play 2.0

As the time of writing Play 2.0 is still in beta status and according to the official homepage, APIs are likely to change a bit in the future. Nevertheless, I guess it is time to have a quick look into the new features of the framework and create a simple application.

Installing Play

As we would like to access all latest features, we are going to build Play from the source code ourselves. Therefore, you need to retrieve the sources from GitHub. If you haven’t installed git yet, do so now. Next, clone the play repository by calling git clone git://github.com/playframework/Play20.git

Once you have the source code on your local machine, switch to the ../play20/framework folder and type build. This will start up an embedded sbt shell, in which you have to execute the build-repository command. (Make sure that you have a solid internet connection, as this step will require to download some megabytes of data. I tried it in the train, which was very frustrating…)

To complete the installation, you need to add the ../play20/ folder to your systems PATH environment variable.

More detailed instructions on how to install Play 2.0 (either from source, or from pre-compiled binary packages) can be found in the Play 2.0 wiki.

Creating a Simple Application

Once Play 2.0 is setup on your machine, you can create a simple applicationby typing play new myFirstApp. Provide the name of your application and as we would like to use Scala as our main development language, select the according entry. And that is it! You have just created your first Play application.

Play 2.0 comes with a nifty little console, which supports many development task out of the box. The most common command for you to execute is likely to be run. Others might include, console, clean, compile and test. The commands are more or less self explanatory. Nevertheless, there is also a help goal (you may guess what this one does), and a little bit of documentation.

If you don’t want to open the Play Console just to execute a single command, you can also type play [your_command]. For now, this is what you should do, type play run to start the server in development mode.

After the server has been started, open a browser and go to http://localhost:9000 You should see something similar to the screenshot below.

Creating and running a Play application

Play 2.0 Application

Where to go from here

In the previous section we have successfully created a simple Play 2.0 application. The second part of this post will show you how to get this application running on Heroku. But before we go there, I would like to point you to some further resources to get familiar with Play 2.0.

Most defiantly you should have a closer look on the anatomy of a Play 2.0 application. Furthermore, there are three nice sample applications, which are provided within the Play 2.0 sources and documented adequately in the wiki. Last but not least you might also want to browse through Play’s scala api manual.

Heroku

I promised you, that this article will show you how to get your Play application running on Heroku. So let’s see how this is done.

Quickstarting Heroku

First of all, go to heroku signup page and enter your E-Mail address. After you have received a confirmation mail and provided a password, you are successfully signed up.

Next go to the quickstart guide and download the heroku toolbelt corresponding to your system and install it. After the installation is completed you can start to access heroku from the command line. Type heroku login to connect to the heroku platform servers. The first time you connect to heroku you need to provide your personal SSH key (or simply hit enter to automatically create a new one).

Now that you are logged in to Heroku, you are ready to deploy your Play application. Unfortunately, your app isn’t ready for that process yet, so let’s apply some minor changes.

Making your app ready for Heroku

The following section is based on the Deploying Play to Heroku tutorial, you might either read the original source or the summary given here.

Heroku needs to know how to start your add, therfore you should add a start script provided by the great folks at typesafe. Simply add the following line to your project/plugins.sbt file (Ensure that you also place a blank line before and after this line): addSbtPlugin(“com.typesafe.startscript” % “xsbt-start-script-plugin” % “0.5.0”)

Next, you need to create a plain text file in your application’s root directory called Procfile containing the following line: web: target/start

The next thing to do is create a local git repository for your application. In your application root folder, just type git init to create the repo, then type git add . to add all files and folder and finally make a commit by typing git commit -m “init”.

Last thing to do is creating your app at heroku, do this by typing heroku create –stack cedar. (Make sure you are still logged in to heroku!) You shoud note down the url where your application is going to be available. In my case that is http://blooming-dawn-3920.heokuapp.com/

Making your app ready for heroku

Deploying your app

By now, everything you need to deploy your Play 2.0 application to Heroku should be set up. The last thing you need to do is simply push your contents from your local git repository to the heroku server. To do so, type git push heroku master, after your sources are transferred to the remote repository an automatic execution of sbt clean compile stage is triggered. If everything went well, you should see something similar to the screen shot below. You should also be able to go to your url and see your application running there.

Successful Heroku Deployment

You are now ready to develop some nice features for your application. Whenever you want to deploy a new version of your app heroku, simply push your changes by executing git push heroku master again. Three more hints before I leave you alone with your app: You can tpye heroku ps to check the state of your application, call heroku logs to access your applications log files, and even start a remote REPL session by executing heroku run sbt play.

And now, happy coding!

Advertisements

Maven 3 Site Plugin – How To

Creating various helpful reports in a Maven based project is quite easy and straight forward. Such reports vary from simple javadoc to dependency reports and code coverage analysis and having them can be a major advantage during development. In the following post, I present an understandable how-to of generating these reports.

Configuration

Site and report generation is not a base feature of Maven (anymore [see footnote below]) , instead there is a plugin that is responsible for this tasks. The site plugin can be configured in the plugins section of a pom.xml. The configuration itself can contain several report plugins. The following snippet configures the site plugin and adds a number of useful report plugins to it. Simply copy this configuration to your personal pom.xml and adopt any parameters to your needs. Make sure to remove or replace the configuration file location within the maven-checkstyle-plugin.

 
<build>
<plugins>
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-site-plugin</artifactId>
  <version>3.0-beta-3</version>
  <configuration>
    <reportPlugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>2.2</version>
        <reports>
          <report>index</report>
          <report>project-team</report>
          <report>license</report>
          <report>mailing-list</report>
          <report>dependencies</report>
          <report>dependency-convergence</report>
          <report>plugin-management</report>
          <report>cim</report>
          <report>issue-tracking</report>
          <report>scm</report>
          <report>summary</report>
        </reports>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.6</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.7</version>
      </plugin>     
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <!-- Adopt config location to your needs, or remove configuration entry completly to use default version.
          <configLocation>http://stud.hs-heilbronn.de/~nischmid/development/checkstyle-config.xml</configLocation&gt;
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>2.3.1</version>
        <configuration>
          <argLine>-Xmx256m</argLine>
          <argLine>-XX:MaxPermSize=256m</argLine>
        </configuration>
        <!-- Usually findbugs needs a lot of memory, change these values if needed. -->
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jdepend-maven-plugin</artifactId>
        <version>2.0-beta-2</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <version>2.4</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>taglist-maven-plugin</artifactId>
        <version>2.4</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jxr-plugin</artifactId>
        <version>2.1</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>2.5</version>
        <configuration>
          <linkXref>true</linkXref>
          <minimumTokens>100</minimumTokens>
          <minimumPriority>3</minimumPriority>
          <!-- Change minimum priority to see more or less messages -->
          <targetJdk>1.6</targetJdk>
        </configuration>
      </plugin>
    </reportPlugins>
  </configuration>
</plugin>
</plugins>
</build>

 

Report generation

Once, your configuration is set up, you can trigger a report generation with the command mvn site. Depending on the reports used, this may take a while. The final reports will be placed within the target folder. Just open target/site/index.html and you should see something similar to the following screenshot. Click on one of the two red-circled links to expand the report sections. Enjoy reading through the reports and improving your code.

Example Page - Maven Site Plugin

Note: With the introduction of Maven 3, there have been changes in the area of site and report generation, thus the shown pom.xml snippet does only work for Maven 3.0 or later.

Faster logging with SLF4J

Logging in Java has a long and obscure history. There are numerous APIs for logging, and there is for sure no answer which one is the best. Today, I started a project from scratch, which gave me the opportunity to try out SLF4J (Simple Logging Facede 4 Java). In most of my projects I have been using  Log4J so far. The switch was rather simple, anyways I would like to write down the most important steps here.

Why SLF4J

  • Log4J was initially created by Ceki Gülcü. After Log4J Ceki created SLF4J, so I guess he put everything he learned from Log4J into SLF4J.
  • SLF4J provides a nice way of creating short and easy to read logging statements in the code, that have only minor resource consumption if logging is turned off.
  • Some commonly used open-source projects use SLF4J compared with some of its provider bridges, in seldom cases this might struggle using the bridged logging APIs.
  • Last but not least: Why not? As previously mentioned, there is no best solution for logging, so why not trying alternatives.

How does it work

As the name suggests SLF4J is a logging facade that needs an actual logging implementation to be able to log anything at all. All the widespread logging solutions can be used by SLF4J. So you might use Log4J or JCL or even the Simple Implementation to do logging with SLF4J. In any case you will use the same API calls in your code (thus facade in the name).

Get the JARs

If you configure your JARs by copying them into some lib folder (I hope nobody is actually doing that any longer!), just go to their web page and download the latest versions of slf4j-api and the slf4j-{your favorite provide}. Don’t forget to put the JAR of your provider into the lib folder as well.

If you use maven or ivy, here is the sample configuration for SLF4J backed by Log4J. Please note, that the provider JAR will be automatically retrieved, so do not put it into your maven dependencies.

<properties>
    <slf4j.version>1.6.0</slf4j.version>
</properties>
...
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
</dependency>

Let’s log

Logging with SLF4J is pretty straight forward. Just have a look at the example below. The second logging statement shows how the API should be used to avoid to String conversion for large objects if logging is turned off (or the level is lower). Check the SLF4J FAQ for further details on performance of (non) logging. If you are wondering if you should declare your logger as a static or instance variable, make sure to look at that consideration.

final static Logger logger = LoggerFactory.getLogger(Slf4jTest.class);

public void someMethod(HeavyObject object) {
    logger.debug("This is a simple debug message");
    logger.debug("HeavyObject is {}", object);
}

Absolute First Step Tutorial for Amazon Web Services

I am currently playing around with Amazon Web Services (AWS) to get some hands on experience in the cloud. Today I would like to share some of the gained knowledge about the first steps with AWS. This tutorial will mainly cover setting up an EC2 instance backed up by an EBS storage and how to work with that instance.

Time to sign up

Amazon is giving away some free stuff to new customers. Among those is a Amazon EC2 Linux Micro Instance that can be opearte 24/7 for a whole year, as well as 10 GB of Amazon Elastic Block Storage and some I/O opeartions on it. Basicly, they are giving away all you need to get a 100% free look into parts of AWS. So if you don’t have an account yet, sign up here.

Create a new instance

Now it is time to launch a new instance. Open the AWS Console and select the EC2 tab. Select your desired region to launch the instance within (blue circle) and afterwards click on launch instance (red circle).

Next, select the Basic 32-bit Amazon Linux AMI and continue.

In the following screen switch the instance type from a Small Instance to a Micro Instance. Leave the other options with their defaults and continue.

Neither do we want to change any advanced settings nor add any tags to the instance. Thus, skip the next two dialogs (click continue twice), till you reach the key-pair dialog. As we haven’t created any key pair yet, we will do so now. Select Create a new Key Pair (bule circle), type in any appropriate name for the key pair (red circle) and click on Create & Download your Key Pair (green circle). This will generate a new key pair and you will be asked to store it on your machine. Do so!

The next thing you need to do is set up a security group for the instance. As we don’t wont to go with the default one for now, you need to create a new group. Select Create a new Security Group (blue circle), give it an appropriate name and description (red circle). You need to define some allowed connections. Select HTTP from the drop-down (green circle) and click on Add Rule (yellow circle). Repeat the last step for HTTPS and SSH, so you end up with all three rules added to your security group. Click on continue to create the group.

On the final screen you are able to review all your inputs regarding the instance. A click on Launch will start the instance, which in fact will take a couple of minutes (sometimes only seconds). If you refresh the My Resources panel in AWS console your newly created instance as well as the created EBS storage, key pair and security group will show up eventually.

If you click on 1 Running Instance it will take you to the My Instances screen, where you can select your new instance and see all its details. Among these details is the Public DNS, note it down for later use!

Connecting to the instance

Once your instance is running, you might connect to it via SSH. If you are using Unix/Linux, I probably don’t need to tell you how you do that, just take the the public DNS and ssh to it. On Windows systems you might want to use Putty to get an SSH connection to your instance. On Keyword Intellect is a great blog post how to do that, so I wont repeat it here. One thing to add, make sure to log on as ec2-user not root.

Installing Apache HTTP Server on the instance

As an example we are going to install the Apache HTTP Server on the instance. Type the following line to install Apache and reply with y to all questions popping up.

sudo yum install httpd

After the installation is completed type the following statement to start Apache.

sudo /etc/init.d/httpd start

Go with your web browser to http://$YOUR-PUBLIC-DNS. You should see a page similar to the following. So now you know how to get started with Amazon Web Services, it is time for you work with your instance now. Enjoy!

Practical Session with ANTLR 2.7.5 (Video Tutorial)

Today I have giving a short introduction into ANTLR (http://www.antlr.org), a famous Parser Generator written in Java and very often used within Java Applications. The introduction was given in form of a practical session at the university in Heilbronn, Germany. The session is based on the tutorial of Ashley J.S Mills (http://supportweb.cs.bham.ac.uk/docs/tutorials/docsystem/build/tutorials/antlr/antlr.html) and covers the following contents:

• Defining grammars (Writing lexers and parsers)
• Using ANTLR to generate (Java) code (parser and lexer) from a grammar
• Using ANTLR command line tools
• Using ANTLR Plug-ins for eclipse
• Using generated (Java) code in programs
• Parsing data from system-in prompt
• Parsing data from text files
• Let ANTLR generate abstract syntax trees
• Debugging an abstract syntax tree

While I have been given a lot of presentation on various topics, this was my first time recording it and producing a video out of it. I must say I had quite some problems in creating the final video (I also lost the first 45 seconds of video, but the voice is still there…), but I think the content might be usefull to some of you.

You can find the cut version of the session at: http://stud.hs-heilbronn.de/~nischmid/Antlr%20tutorial%20session%20held%20by%20Nils%20Schmidt.mp4

Yox can find the hand out of the session at: http://stud.hs-heilbronn.de/~nischmid/ANTLR-PracticalSession-NilsSchmidt.pdf

If you are interested in the source code, just write me an E-Mail, any feedback is also very welcomed and would help me to decide if I will do more of those videos in the future.