Friday, December 19, 2008

A very basic JBPM tutorial - Hello World

According to the documentation
a minimal deployment of JBPM needs the following jars:
  • jbpm-jpdl-3.3.0.GA.jar
  • commons-logging.jar
  • dom4j.jar
To start off we create the process definition. It consists of a start and end state and an additional intermediate state.

<process-definition xmlns="urn:jbpm.org:jpdl-3.2" name="simple">

<start-state name="Start">
<transition name="trHelloWorld" to="HelloWorld"></transition>
</start-state>

<state name="HelloWorld">
<event type="node-enter">
<action class="HelloWorldActionHandler" name="recharge"></action>
</event>
<transition name="trEnd" to="End"></transition>
</state>

<end-state name="End"></end-state>

</process-definition>


The state with name HelloWorld executes an action when the node-enter event is fired by the process executuion engine. The Action is implemented as Java code:

import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

public class HelloWorldActionHandler implements ActionHandler {
private static final long serialVersionUID = 1L;

public void execute(ExecutionContext context) throws Exception {
System.out.println("Hello World!");
}
}


For the definition of the process nothing more is needed. It can be run outside of containers and does not need a database for non persistent processes. To start the process you have to load the definition and create a concrete ProcessInstance:

import org.jbpm.graph.def.ProcessDefinition;
import org.jbpm.graph.exe.ProcessInstance;

public class SimpleProcess {
public static void main(String[] args) {
ProcessDefinition processDefinition = ProcessDefinition.parseXmlResource("process-def.xml");
ProcessInstance instance = new ProcessInstance(processDefinition);
displayStatus(instance);
instance.signal();
displayStatus(instance);
instance.signal();
displayStatus(instance);
}

private static void displayStatus(ProcessInstance instance) {
String nodeName = instance.getRootToken().getNode().getName();
System.out.println("You are now in node: " + nodeName);
}
}


To trigger a transition the method signal() is called on the process instance. An action handler can leave the state by calling context.leaveNode().

Sunday, May 25, 2008

Avoiding Java generics verbosity

public class GenericsTest { 
static class Model<T> {
public Model(T value) {
}
}

static class TextField<T> {
public TextField(Model<T> model) {
}
}

static <T> TextField<T> createTextField(Model<T> model) {
return new TextField<T>(model);
}

static <T> Model<T> createModel(T value) {
return new Model<T>(value);
}

public static void main(String[] args) {
TextField<String> tf1 = createTextField(createModel("tf1"));
TextField<String> tf2 = createTextField(new Model<String>("tf1"));
TextField<String> tf3 = new TextField<String>(new Model<String>("tf2"));
}
}

Wednesday, March 12, 2008

Update: Inter-type declarations with implicit conversions

With some closure magic it's possible to shorten the code to build a class extension aka. to add some inter type members.
class ClassExtension[S, T](createExtendedObject: => T) {

val extendedObjects = new HashMap[S, T]

implicit def extendObject(o : S) : T = {
if (!extendedObjects.contains(o)) {
extendedObjects += o -> createExtendedObject;
}
extendedObjects(o);
}
}

Instead of making the class abstract and using a factory method on the concrete class, we can use a closure for the construction of the extended / alternative object.

The class can be used like this:
def main(args : Array[String]) : Unit = {
object PositionVertexExtension extends ClassExtension[Vertex, Position](new Position);
import PositionVertexExtension._;
val v = new Vertex("v1");
v.x = 2.3;
println(v.x)
}

This code shows another nice feature of scala. It is possible to have imports scoped to blocks. So in this case the extension is only visible in this local context. This is comparable to Groovy where categories are applied by the use controll structure.

Monday, March 10, 2008

Inter-type declarations with implicit conversions

AspectJ has a feature called inter-type declarations. With this feature you can add methods to an existing class without touching the class itself. (Similar to categories in Groovy) Actually it is even possible to add fields to classes with AspectJ. This is especially useful if you don't want to add the field to the class itself because it is used only by a small subset of all users.

I missed such a feature in Scala. But in fact it is possible to add methods and fields on a class with Scalas implicit conversions. Debasish Ghosh explains how to add methods on existing classes.

But how do we add new fields to a class? E.g. we have a class Vertex. This class is used in severall packages. Now we want to layout some vertices in an euclidean plane. In the context of the layouting algortihm every vertex has a position.
def main(args : Array[String]) : Unit = {
val v = new Vertex();
v.x = 2.3;
println(v.x)
}

It would be nice to use a vertex like this without the need to access a map manually to get the additional fields. In this piece of code object creation is in our control, but we assume that the layouting algorithm does not have control over the vertex creation.

The extension Position would look like this:
class Position {
var x = 0.0;
var y = 0.0;
}

The last missing piece is how to delegate the call to x.
object EuclideanExtension {  
val extendedVertices = new HashMap[Vertex, Position]

implicit def extendVertex(v : Vertex) : Position = {
if (!extendedVertices.contains(v)) {
extendedVertices += v -> new Position;
}
extendedVertices(v);
}
}

The implicit conversion enables us to use all methods and fields of Position whenever we import the EuclideanExtension. (import graph.EuclideanExtension._;)

It is possible to extract most of the code to an abstract, generic class. So you can reuse this extension mechanism.
abstract class ClassExtension[S, T] {  
val extendedObjects = new HashMap[S, T]

implicit def extendObject(o : S) : T = {
if (!extendedObjects.contains(o)) {
extendedObjects += o -> createExtendedObject;
}
extendedObjects(o);
}

def createExtendedObject : T;
}

Using the abstract class reduces the code:
object EuclideanExtension extends ClassExtension[Vertex, Position] {  
def createExtendedObject = new Position;
}

Monday, March 3, 2008

2 or more, use a for

I want to start this post with a citation. Dijkstra coined the phrase "2 or more, use a for". In common use a for loop is an abstraction for iterating through a collection.

In scalax the for keyword is used to build something like the "using" keyword in C#. As expected the following code to copy a file line by line contains three nested iterations:
def createReader = ManagedResource(new BufferedReader(new FileReader("test.txt")))
def createWriter = ManagedResource(new BufferedWriter(new FileWriter("test_copy.txt")))

//copy a file, line by line
for(reader <- createReader; writer <- createWriter) {
var line = reader.readLine
while (line != null) {
writer.write(line)
writer.newLine
line = reader.readLine
}
}

You can find more on how to build an Automatic Ressource Management feature for Scala on Chris Hansen's Blog: Polyglot Window: Chris Hansen's Blog: ARM Blocks in Scala, Part 3: The Concession

Wednesday, February 27, 2008

An Assertions-DSL in Scala

As I am currently working on some Java code, I am writing unit tests in JUnit and using the quite helpful Assertions and Matchers library Hamcrest. Hamcrest improves assertions by providing matcher to check, whether a current results matches an expectation. It allows the construction of complex logical statements, that are actually not regular Java expressions, but rather runtime expression trees. A benefit of this matchers over conventional assertions is, that they can provide much better error messages. Visit the Hamcrest project website to get more insights in this helpful and slim framework.

Unfortunately Java restricts the design of matcher libraries by not allowing operator overloading and new infix operators. In Scala it is possible to improve the readability of assertions a lot. The following code shows some assertions in Scala:
import matcher.Assertion._;

object MatcherTest {
def main(args : Array[String]) : Unit = {
val x = 5;
val varX = variable("x", x);
assertThat(varX.==(5));
assertThat((varX == 6).or(varX == 5));
assertThat((varX == 6) or (varX == 7) or (varX == 8));
val s = "test";
val varS = variable("s", s);
assertThat(varS.==("t"));
assertThat((varS == "tz") or (varS == "rd"));
assertThat((varS == "t") or ((varX == 5) and (varX == 8)));
}
}

This is all valid Scala code. In Scala it is allowed to use regular methods as infix operators.

Actually instead of raising an exception assertThat just prints the error message:
Expected that (((x == 6) or (x == 7)) or (x == 8))
Expected that (s == t)
Expected that ((s == tz) or (s == rd))
Expected that ((s == t) or ((x == 5) and (x == 8)))


The following code block is a basic implementation. Every expression subclass implements a method to pretty print itself and a method to evaluate whether the expectation is met.
object Assertion {
def assertThat(expression : Expression) = {
if (!expression.evaluate) {
println("Expected that "+expression.text);
}
}

def variable[T](name : String, x : T) = new Variable[T](name, x)

protected abstract class Expression {
def evaluate : boolean
def text : String = "("+textInternal+")"
def textInternal : String
def or(expression : Expression) = new Or(this, expression);
}

protected class Variable[T](name : String, x : T) {
def ==(y:T) = new Equals(this, y);
def getX = x;
def text = name;
}

protected class Equals[T](v : Variable[T], x : T) extends Expression {
def evaluate = v.getX == x;
def textInternal = v.text + " == " + x;
}

protected class Or(e1 : Expression, e2 : Expression) extends Expression {
def evaluate = e1.evaluate || e2.evaluate;
def textInternal = e1.text + " or " + e2.text;
}
}

There is still a piece of RY (Repeat Yourself) in the code. In fact I had no idea how to avoid the construction of the named variable. Perhaps some Scala gurus can give me a hint.

Update: Context-free in Scala

After reviewing my implementation in Scala I discovered, that both Scala and Java implementation allow method chains like a().a().b().a().b().b(). In fact the presented grammar only allows words starting with n calls of a() and ending with n calls of b().

Here is a patched version of the code:
object AbLanguage {  
def a = new AfterABase

protected class AfterBBase {
def b = {}
}

protected class AfterABase extends AfterBBase {
def a = new AfterA[AfterBBase](this)
}

protected class AfterB[T](sourroundingExpression : T) {
def b = sourroundingExpression
}

protected class AfterA[T](sourroundingExpression : T) extends AfterB[T](sourroundingExpression) {
def a = new AfterA[AfterB[T]](this)
}

def main(args : Array[String]) : Unit = {
a b;
((a a) b) b;
a.a.b.b;
}
}

The return type of method a() itself allows a further call of a(), instead of that the enclosed type does not have a method a().

Tuesday, February 26, 2008

Context-free in Scala

With less code than in Java the AbLanguage in Scala:
object AbLanguage {  
def a = new AOpenedBase()

protected class AOpenedBase {
def a = new AOpened[AOpenedBase](this)
def b = {}
}

protected class AOpened[T](surroundingExpression : T) {
def a = new AOpened[AOpened[T]](this)
def b = surroundingExpression
}

def main(args : Array[String]) : Unit = {
a b;
((a a) b) b;
a.a.b.b;
}
}

Monday, February 25, 2008

More than regular

This post discusses, whether it is possible to build more than regular languages with method chaining in Java.

Ray Myers suggested in his post Fluent Interface Grammars: Part II (Chaining), that the use of pure method chaining restricts you to regular languages. In fact this seems to be right for Java without generic types. He considered a simple non-regular language:

S ::= a B
S ::= a S B
B ::= b
The compiler should check, whether a sentence corresponds to the language or not. E.g. it should be possible to compile the following:
AbLanguage.a().a().b().b();

This should raise an error:
AbLanguage.a().a().b().b().b();

So we need at least a static method a(). It should return a type, that provides methods a() and b().
public static AbLanguage.AOpenedBase a() {
return new AOpenedBase();
}

public static class AOpenedBase {
public AOpened<AOpenedBase> a() {
return new AOpened<AOpenedBase>(this);
}

public void b() {
}
}

The implementation and return type of method b() are self explaining. It just finishes the sentence. Method a() shows how to (ab)use the generic type system to count its calls on compiler level.
public static class AOpened<T> {
public final T surroundingExpression;

public AOpened(T se) {
surroundingExpression = se;
}

public AOpened<AOpened<T>> a() {
return new AOpened<AOpened<T>>(this);
}

public T b() {
return surroundingExpression;
}
}

Every call of a() surrounds the given type with a further layer. In the opposite way b() unwraps one layer.

This technique enables us to build bracketed expressions with free depth on top of method chaining . By the way it is fairly complex to build even simple grammars and the code is not really obvious.