For a year I’ve been working on two projects using the Play! Framework. The JRebel License Server and LiveRebel. I was evaluating different frameworks for these tasks and it boiled down to a choice between Struts and Play! Framework. Play! seemed the risky, cool, rebellious choice, while Struts was something more like the work horse (somewhat old) who delivers for sure. After some debate within the team we took a chance and went with Play!. During this time I’ve grown to love some features of Play! more than others and would like to share the love.
Play! framework jobs provide a way of running program logic “in the background”. Play! will take care of the lifecycle and the timings. For example if you need something to run every 5 minutes you will use an annotation @Every(“5min”) and the job will be run every 5 minutes. I’ve included an example called MemoryUsageLogger which logs the memory usage of the application. Its just dead simple.
So far I’ve used JSPs (old and XML syntax), Jelly (Hudson plugins), XTemplate and Smarty for PHP as templating engines. I’ve never felt productive in these, writing custom tags that choke when changing the container, fighting with bloated XML or even just learning an obscure templating expression language has not been fun.
Play! template engine uses Groovy as an expression language and also a tag system for reusable components. Groovy is a clean, intuitive, powerful language which is really easy for Java devs to pick up. I also like that it is a separate, well established project vs something that is only meant for templating.
This all comes with great error messages, even for the templating code. You can quickly tell where you’ve made a mistake. I just hope the templating language will be supported by Eclipse to provide content assist and highlighting.
URL mappings and redirects
Your controllers in Play! contain ton of static methods that adhere to the URLs of your application. For example, if you need to show something for a URL /contacts/list you would implement a method list in a controller contacts (this is the default naming convention that can be changed). Or if you want a page to show an actual contact you would have a method showContact and it will get mapped to /contacts/showcontact.
What if I want to redirect from the list page to a show contact page when there is only a single contact to show? In your Java code in the list method just invoke the showContact method, it’s going to be an HTTP redirect. So easy and readable in Java that it is scary.
Testing
Automated app testing is a difficult subject, there are tons of approaches out there and its all about you picking a couple and trying to use them with your app written in framework X. Play! has a different approach and it comes bundled with a slick interface to run unit, functional and selenium tests against your app. As testing is something that is so easy to “forget about” then something halfway enforced is really welcomed. Besides automating this you can use the same interface while developing vs configuring the tests to run from your IDE or ant/maven/shell.
Quick Turnaround
We at ZeroTurnaround are really into developer productivity. Our flagship product JRebel lets you change your application code and just hit refresh in your browser and you’ll see the changes instantly. Play! framework offers something similar. I have not read enough source code but it seems that with custom extra metadata (see your app’s tmp/bytecode/DEV), a stateless model and the custom runner (play run) they will give you the power of changing code on the fly. If they don’t support the change they will restart your app automatically for you. This is actually a really big thing compared to other frameworks out there.
Conclusions
Play! framework is packed with cool features and this is only my top 5. Of course Play! is no silver bullet and it does have its own set of problems, but that is something for another article. So far Play! has proven to be a productive and intuitive environment to develop in. What are your favourite features of Play!?
Toomas Römer is the co founder and product lead of ZeroTurnaround. Once a Linux junkie, he was fooled by Apple into proprietory OS and devices. He is a big fan of JUGs, OSS communities and beer. He blogs at dow.ngra.de, tweets from @toomasr and also runs the non-profit chesspastebin.com website. In his spare time he crashes Lexuses while test driving them, plays chess, Go and Starcraft. Looks can fool you; he will probably beat you in Squash. You can connect with Toomas on LinkedIn.
Automatically building Eclipse plug-ins has been sort of difficult for quite a while.
Running the build manually from PDE works, but it’s pretty much a black box and you can’t always get what you want from that. It can sign plug-ins when choosing Export… -> Deployable plug-ins…, but it can’t do this when building a whole update site. If you are used to Maven, Ant or another command line build tool, then things like this are truly annoying.
There are, of course, some tools provided by the Eclipse Foundation for headless building of plug-ins, but they don’t seem easy to set up or convenient to use. Tycho for Maven 3 aims to change that, making it possible to build OSGi bundles / Eclipse plug-ins in an environment familiar to most developers and with minimal additional configuration.
Background
Tycho still doesn’t have an 1.0 release, but seems pretty stable, if lacking a few features. It doesn’t yet have a lot of updated or detailed documentation, but I found help in blog posts about building with Tycho. Mattias Holmqvist’s posts, for example, are recommendedreading.
The information I found was sometimes outdated, though, or didn’t go into the things that we needed to make a headless build for JRebel for Eclipse, which has had over 800 downloads in February alone and continues to climb the charts on the Eclipse Marketplace. I figured that since others may have similar needs to ours at ZeroTurnaround, it would be cool to share this experience with everyone (*note: this post assumes some experience with Maven and PDE).
First, I’ll describe what we needed from Tycho. JRebel for Eclipse consists of 6 Eclipse plug-ins, some of which depend on each other. One plug-in provides general JRebel/Eclipse integration, another embeds JRebel itself, and others provide debugger, WTP and RAD integration. We needed to be able to:
use existing meta-data (manifest-first model), so that we can still use PDE for development
build the whole set of plug-ins at once when doing a new JRebel release
sign all our plug-ins and features
build single plug-ins separately to release bug fixes quickly
It was actually quite easy to get the first three requirements met by a Tycho build, but it turned out the fourth one was harder to achieve (more on that later).
At first I just added a pom.xml file to each plug-in and feature, specifying the artifact name, version and packaging type for each. Tycho can even generate a basic pom.xml for you. A parent pom.xml was added to define some common Maven plug-in settings. I also created a new update site project, which only has the site.xml that says which versions of what features to add to the site.
Sample project: Achievements for Eclipse
To make things easier to demonstrate, let’s create a sample project that mimics the setup I used. And to make it more fun (or ridiculous, take your pick), the sample project will add a couple of achievements to Eclipse, similar to Steam, Xbox or Playstation achievements. I got the idea for that from this post. The project structure will be like this:
After publishing Java Bytecode Fundamentals I received some valuable feedback from the community. The topic turned out to be quite popular and it seems that Java developers just miss the old days of programming in assembly language and fitting the program into 64k of memory :) Now it would be a good idea to revise the post a little bit and touch some of aspects that were left uncovered the first time.
The Java Bytecode Fundamentals post covered the very fundamental aspects related to Java bytecode – how to obtain the listings, how to read the mnemonics, the constant table, frame structure, local variable table, etc. After compiling Java source code with javac you obtain Java executables – the *.class files. Looking at the contents of those files you can actually recognize some of the opcodes and even full frames, like on the screenshot below.
javap is the standard disassembler from JDK tools which can be used to view the mnemonical representation of the compiled Java class. You cannot do much with the results that javap provides, but you can read and understand it fairly well.
DISCLAIMER: if you haven’t read the first article, it would probably be a good idea to take a look at that one first, and then return to the text below as at some point I assume that you’ve read the my previous post.
Now let’s take a dive into more specific aspects of Java bytecode: using classes, calling methods, and how the stack is involved in the whole process of passing the parameters to the methods.
Using objects, calling methods
Creating class instances, calling methods, obtaining field values – all these operations reserve a dedicated opcode in the Java bytecode instruction set. Our aim is to reveal the code constructs that produce the desired bytecode instructions. Let’s create a simple example: a class Scheduler calls a method on another class JobImpl via its interface Job. JobImpl then implements some logic to produce the result.
//Scheduler.java
public class Scheduler {
Job job = new JobImpl();
public void main() {
String result = (String) job.execute();
print(result);
}
private static void print(String message) {
System.out.println(message);
}
}
//Job.java
public interface Job {
Object execute();
}
// JobImpl.java
import java.util.Random;
public class JobImpl implements Job {
public Object execute(){
Integer value = createRandomValue();
return incValue(value);
}
private Integer createRandomValue(){
return new Random().nextInt(42);
}
private Integer incValue(Integer value){
return value + 1;
}
}
To see the bytecode listings for Scheduler and JobImpl we’ll use javap as follows:
javap -c -private Scheduler
javap -c -private JobImpl
The -private option is required as the source code includes some private methods for which bytecode listings will not be printed otherwise. We’re not using -verbose for brevity.
Let’s start our review from Scheduler‘s constructor that was generated by the compiler. Some may have expected the generated constructor to be empty, but there’s the Job field to be initialized. The first few lines for the constructor are the same as if we had an empty class without any fields:
Next, we can see part of the initializer included in the constructor. First, the reference to the Scheduler instance is loaded with aload_0 again as it was previously removed during the invokespecial call. On the next line, we can now see the use of the new instruction that creates a new object of type identified by the class reference in the constant pool. Indeed, the constant #2 refers to JobImpl. The newly created object reference will actually be pushed onto the stack. We can see that the instructions followed are invokespecial and putfield that will both pop the stack up. Therefore we’ll need to save the reference to JobImpl twice. This is done using dup instruction.
5: new #2; // create the instance of JobImpl
8: dup // duplicate the instance on the stack
9: invokespecial #3; // call "<init>" and pop the stack
12: putfield #4; // stores the object reference in Job field, and pop the stack
Opcode 0xBB: new
As you may have noticed the new opcode is only used to “create a reference” of the type, but in order to initialize the object it is still required to call <init> on that object reference. In fact, the four-instruction-sequence (new/dup/invokespecial/astore) is a common pattern, when an object is new’ed and stored into a local variable. You can read bytecode faster if you remember this rule :)
invokeinterface (0xB9) and invokestatic (0xB8)
If we proceed to reading the bytecode listing for the Scheduler class, in the main() method we can see a couple of instructions that are related to method calls – invokeinterface and invokestatic. The Scheduler‘s field job was declared using the Job interface, i.e. all the calls will actually be interface calls. Therefore we can see the execute() method being called using the invokeinterface instruction rather than invokevirtual, explained later.
invokestatic is used to call the class methods, i.e. if the target method is declared with the static keyword. The method is identified by a reference in the constant pool and therefore there’s no need to load the target object reference to the stack – it only requires the parameters to be passed in.
Further on, in the Scheduler class bytecode listing we find the print(..) method that includes one more instruction related to method invocation on an object reference – invokevirtual. If you see the invokevirtual opcode, you can be pretty sure that the method is being called directly on the class instance, without using an interface, and the method access is not private. In our example, we can see that invokevirtual is called on an instance of the java.io.PrintStream class:
In the example above you probably spotted the invokespecial instruction in use. The instruction is used to invoke instance method on object reference, and here’s is a good place for a question – what is the difference between invokespecial and invokevirtual?
The answer can be easily found if one reads the Java VM Spec carefully:
The difference between the invokespecial and the invokevirtual instructions is that invokevirtual invokes a method based on the class of the object. The invokespecial instruction is used to invoke instance initialization methods as well as private methods and methods of a superclass of the current class.
In other words, invokespecial is used to call methods without concern for dynamic binding, in order to invoke the particular class’ version of a method.
Passing the parameters to methods, returning values
For the last topic on this post, let’s grasp how the parameters are passed to methods and how the result is returned. For this example we will use the JobImpl class introduced earlier in the article. Using javap -c -private JobImpl, the bytecode listing is printed as follows:
The incValue(..) method is the one we’re looking for – it takes a parameter in and returns a value. The incValue(..) method is called from execute() using the invokespecial instruction, obviously, because it is declared private. So how is the parameter being passed to incValue?
Let’s read the execute() method code:
0: aload_0 // load the reference to this
1: invokespecial #2; // call createRandomValue()
4: astore_1 // store the result to local variable #1
5: aload_0
6: aload_1 // load the value of local variable #1 to the stack
7: invokespecial #3; //Method incValue:(Ljava/lang/Integer;)Ljava/lang/Integer;
10: areturn
Before calling invokespecial, the program loads the value of the local variable number 1 to the stack. This is how the parameter is passed. invokespecial pops the stack as many times as the number of parameters it is about to consume, according to the method signature. That said, aload is the type of instruction that prepares the parameters for a method call.
To return a value the program calls, the areturn instruction means that it returns an object reference from a method. The instruction is prefixed with the ‘a‘ character to indicate that we deal with an object reference here. If we tried to return a value of int type, the instruction would have been ireturn. There are also lreturn, dreturn, freturn used for long, double and float accordingly. The mechanics of the instruction is as follows: the result is popped from the operand stack of the current frame and pushed onto the operand stack of the frame of the invoker. The interpreter returns control to the invoker afterwards.
The following slidecast visualizes the process described above:
Summary
In the two sections above we had a chance to observe how objects are created at the bytecode level, what the opcodes for method invocation are, how parameters are passed to the method invocations and how the return value is passed back. The important part to understand is how the stack is involved into the operations, along with the local variable table taking part in the game.
References
There are some good articles on the topic that could be found on the internets. I’d like to give credit to Peter Haggar’sarticle at developerWorks. That is a superb piece, though a little outdated by now. Also, there’s Ted Neward’s The Working Developers Guide to Java Bytecode that explains all the stuff above and even more. With this all said, even if such articles exist and you can find good coverage of the topic in the documentation of bytecode crunching utilities like ObjectWeb ASM, still it is worth it to refer to The Java Virtual Machine Specification in order to get the information “from the source”.
There has been a lot of discussion regarding the use of JavaRebel with Eclipse Web Tools Project (WTP). JavaRebel does work with WTP but the configuration is not that straightforward. In this article we’ll try to give step by step instructions on how to make WTP and JavaRebel get along.
The article is divided into two parts. If you have JavaRebel installed under WTP you can skip to the configuration section. If you are an old time WTP user just enable autopublishing and disable auto reloading for modules.
JavaRebel Installation under WTP
Lets get started by downloading the JavaRebel zip archive from the download page. Unzip the archive somewhere on your harddisk. Copy the javarebel.jar from the uncompressed folder to a location that you can use later on. We’ll assume on Windows that this is c:\javarebel.jar and on Linux /home/john/javarebel.jar.
We’ll configure the startup of the container next. I will be using Tomcat v6.0 version. Open up the “Run Configurations” dialog from the Eclipse menu Run » Run Configurations. You should see the following dialog.
Next open the (x)= Arguments tab in the dialog and edit the VM arguments text area as seen on the next screenshot. Add the following option to the end of the area.
Windows -noverify -javaagent:c:\javarebel.jar
Linux -noverify -javaagent:/home/john/javarebel.jar
Now apply the settings and run the configuration. You should see the following message in the console output.
You have installed JavaRebel under WTP now. Next you need to configure some WTP options so that WTP auto publish would not interfere with JavaRebel class reloading.
Automatic publishing should be enabled in the server configuration. Double click on your server name and a configuration page opens. Under the Publish section you should have the Automatically publish when resources change option selected. I’ve outlined the automatic publishing settings in the following screenshot.
All your modules should have Auto Reload disabled. You can achieve this by opening the Modules tab of the server configuration and editing each module to disable auto reloading.
This is it. Once you have these configurations in place and you have restarted the container you are ready to use JavaRebel with WTP.
Make changes to your Java source files and they will be reloaded by JavaRebel. Make changes to your static content under you WebContent and they will be copied by WTP to your deployment folder.
If you have any questions or problems about setting up WTP and JavaRebel leave a comment or send an email to support [at] zeroturnaround.com.
Writen by one of the first JavaRebel users, Nathan Hamblen, this JavaWorld article talks about building applications with a text editor, Buildr, Jetty and JavaRebel. Bringing examples from Wicket and Scala applications it is worth a read whether you plan to develop without an IDE or not.
Update: the Eclipse support has made it to the final 1.0 release of JavaRebel and development snapshots are not needed to use JavaRebel for Eclipse plugin development.
JavaRebel’s latest development snapshot includes support for the Eclipse Platform. The speedup that we can see with JEE servers when using JavaRebel applies also to other containers. In this case it is Eclipse. Developers can launch their plugins and as they change the source code they can see the results without restarting the new Eclipse instance.
We’ve prepared a small screencast (~5 min) that shows JavaRebel in action speeding up Eclipse plugin development.
The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.
Configuring JavaRebel for Eclipse is as easy as adding VM arguments -noverify and -javaagent:path/to/javarebel.jar and launch as usual as a Eclipse Application Configuration.