Saturday, January 16, 2010

Pick 'n' Choose Target Implementation

This article gives an overview of the options you have regarding the generated target implementation. We add new stuff all the time so this describes what is available at the time of this writing, i.e. in Sculptor 1.7.0.

The default target implementation is using:
  • JPA with Hibernate as provider
  • Spring with annotations, no EJBs
  • Web CRUD GUI client with JSF, Facelets, and Spring Web Flow
  • In-memory Hsqldb as database
  • Deployment as war in Jetty
The default choices gives a good starting environment with minimal requirements of installation of external software, such as database and application server.

For each of these areas there are alternative implementations that are supported by Sculptor out of the box. The features are selected with simple configuration.

















If you have a different reference architecture than what is provided by Sculptor out of the box you can rather easily customize the generator to fit your needs. It is possible to add your own code generator templates or redefine sections of existing templates. All that is described in the Developer's Guide.

Test Scaffold

I must admit that when I use Sculptor I often skip completing the JUnit tests for the ordinary CRUD operations. To my defense I would say that they are trivial and completely generated, but anyway I think that is a bad habit that should be changed. Therefore I wrote a small Eclipse template for them. Maybe useful for you also:


@${testType:newType(org.junit.Test)}
public void testFindById() throws Exception {
${DomainObject:localVar(org.fornax.cartridges.sculptor.framework.domain.AbstractDomainObject)} obj = ${service:field}.findById(getServiceContext(), 1L);
assertNotNull(obj);
}

@${testType:newType(org.junit.Test)}(expected=${DomainObject}NotFoundException.class)
public void testFindByIdWithNotFoundException() throws Exception {
${service}.findById(getServiceContext(), -1L);
}

@${testType:newType(org.junit.Test)}
public void testFindAll() throws Exception {
${listType:newType(java.util.List)}<${DomainObject}> found = ${service}.findAll(getServiceContext());
assertEquals(1, found.size());
}

@${testType:newType(org.junit.Test)}
public void testSave() throws Exception {
int countBefore = countRowsInTable(${DomainObject}.class);
${DomainObject} obj = new ${DomainObject}();
// TODO complete...
// obj.set${cursor}
${service}.save(getServiceContext(), obj);
assertEquals(countBefore + 1, countRowsInTable(${DomainObject}.class));
}

@${testType:newType(org.junit.Test)}
public void testDelete() throws Exception {
int countBefore = countRowsInTable(${DomainObject}.class);
${DomainObject} obj = ${service}.findById(getServiceContext(), 1L);
${service}.delete(getServiceContext(), obj);
assertEquals(countBefore - 1, countRowsInTable(${DomainObject}.class));
}


Add it in Eclipse > Preferences > Java > Editor > Templates
Name: testScaffold
Context: Java type members
Description: JUnit test methods for Sculptor CRUD operations

Tuesday, December 1, 2009

Internal DSL for Criteria - part 3:3

In previous 2 articles I have described the basics of the new internal DSL for JPA/Hibernate criteria. Let us dive in to an advanced topic. We would like to be able to specify conditional expressions with logical operators, and with grouping of nested conditions.

// A and (B or C)
criteriaFor(Person.class).withProperty(aaa()).eq("A").and().lbrace()
.withProperty(bbb()).eq("B").or().withProperty(ccc()).eq("C").rbrace()
.build();


That should build a syntax tree like:

and
/ \
A or
/ \
B C


This means that I need to hold state of current and previous not completed operators in the builder. I hold the current operator in a stack and give braces a special meaning. The expression builder looks like this:


public class ConditionalCriteriaBuilder<T> {

private enum ExpressionOperator {
Not, Or, And, LBrace
}

private ConditionalCriteriaBuilder() {
}

public static <T> ConditionRoot<T> criteriaFor(Class<T> clazz) {
return new ConditionalCriteriaBuilder<T>().new RootBuilderImpl();
}

public interface ConditionRoot<T> {
List<ConditionalCriteria> build();
CondditionProperty<T> withProperty(Property<T> property);
ConditionRoot<T> and();
ConditionRoot<T> or();
ConditionRoot<T> not();
ConditionRoot<T> lbrace();
ConditionRoot<T> rbrace();
}

public interface CondditionProperty<T> {
ConditionRoot<T> eq(Object value);
}

public class RootBuilderImpl implements ConditionRoot<T> {
private final SimpleStack<ConditionalCriteria> criteriaStack = new SimpleStack<ConditionalCriteria>();
private final SimpleStack<ExpressionOperator> operatorStack = new SimpleStack<ExpressionOperator>();

/**
* End the expression with this build
*/
public List<ConditionalCriteria> build() {
return criteriaStack.asList();
}

public CondditionProperty<T> withProperty(Property<T> property) {
return new PropBuilderImpl(property.getName());
}

public ConditionRoot<T> and() {
operatorStack.push(ExpressionOperator.And);
return this;
}

public ConditionRoot<T> or() {
operatorStack.push(ExpressionOperator.Or);
return this;
}

public ConditionRoot<T> not() {
operatorStack.push(ExpressionOperator.Not);
return this;
}

public ConditionRoot<T> lbrace() {
operatorStack.push(ExpressionOperator.LBrace);
return this;
}

public ConditionRoot<T> rbrace() {
operatorStack.pop();
if (criteriaStack.isEmpty()) {
return this;
}
ConditionalCriteria lastCriteria = popCriteria();
pushCriteria(lastCriteria);
return this;
}

private ConditionalCriteria popCriteria() {
return criteriaStack.pop();
}

private void pushCriteria(ConditionalCriteria criteria) {
ExpressionOperator currentOperator = operatorStack.peek();
if (currentOperator == ExpressionOperator.Or || currentOperator == ExpressionOperator.And) {
ConditionalCriteria compositeCriteria;
if (currentOperator == ExpressionOperator.Or) {
compositeCriteria = ConditionalCriteria.or(popCriteria(), criteria);
} else {
compositeCriteria = ConditionalCriteria.and(popCriteria(), criteria);
}
criteriaStack.push(compositeCriteria);
operatorStack.pop();
} else if (currentOperator == ExpressionOperator.Not) {
ConditionalCriteria notCriteria = ConditionalCriteria.not(criteria);
criteriaStack.push(notCriteria);
operatorStack.pop();
if (!operatorStack.isEmpty() && !criteriaStack.isEmpty()) {
pushCriteria(criteriaStack.pop());
}
} else if (currentOperator == ExpressionOperator.LBrace) {
criteriaStack.push(criteria);
} else {
criteriaStack.push(criteria);
}
}

private class PropBuilderImpl implements CondditionProperty<T> {
String propertyName;

PropBuilderImpl(String name) {
this.propertyName = name;
}

public ConditionRoot<T> eq(Object value) {
pushCriteria(ConditionalCriteria.equal(propertyName, value));
return RootBuilderImpl.this;
}
}

}
}


The magic is in pushCriteria, which is invoked at the end of a condition, such as eq(), and also when right brace is reached. It is not a trivial problem, but thanks to the stack metaphor the solution is not that complicated.

A final thought about the syntax. Look at the expression again:

// A and (B or C)
criteriaFor(Person.class).withProperty(aaa()).eq("A").and().lbrace()
.withProperty(bbb()).eq("B").or().withProperty(ccc()).eq("C").rbrace()
.build();


I use special keywords for left brace and right brace. Why not use grouping with an single method instead and write the nested expression as method parameter?

// A and (B or C)
criteriaFor(Person.class).withProperty(aaa()).eq("A").and().group(
criteriaFor(Person.class).withProperty(bbb()).eq("B").or().withProperty(ccc()).eq("C"))
.buildSingle();


That would be possible, and probably easier to implement, but I see a few problems from end user perspective:
  1. There are already much clutter of braces due to the methods and it is hard to see and write the end brace of the group operation.
  2. You loose context and have to start the nested expression from scratch, i.e. with static criteriaFor method.

That was all of this exercise. I hope you find it useful as a practical example of how to develop a small Internal DSL. You find the full source code in subversion, including JUnit test.

Monday, November 30, 2009

Internal DSL for Criteria - part 2:3

In previous article I introduced the new internal DSL for JPA/Hibernate criteria. Let us look at how to handle the property names.

criteria().prop("lastName").eq("Svensson").build();
The problem with the above expression is that the property lastName is a String. Refactoring of Person.lastName will not be automatically detected. Another issue is that you have to remember/lookup that the property name is "lastName" when writing this expression, the IDE will not help you.

We, who are using Sculptor, define the domain object in the design model like this:

Entity Person {
String firstName
String lastName
}
From this Sculptor generates the Person class. We can also easily generate meta data of the properties of Person, which makes it possible to write expressions like this:

List<ConditionalCriteria> conditionalCriteria = ConditionalCriteriaBuilder.criteriaFor(Person.class)
.withProperty(PersonProperties.lastName()).eq("Svensson").build();
PersonProperties is generated and it contains static methods for each property, returning a Property<Person> object, which internally defines the strings. The builder is also parameterized, using the class defined in the criteriaFor factory method. This means that the withProperty method only accepts properties of correct type, i.e. Property<Person>.

Static imports can be used to make the expression more compact and readable:

import static org.fornax.cartridges.sculptor.framework.accessapi.ConditionalCriteriaBuilder.criteriaFor;
import static org.library.person.domain.PersonProperties.lastName;

List<ConditionalCriteria> conditionalCriteria = criteriaFor(Person.class)
.withProperty(lastName()).eq("Svensson").build();

Note that the eclipse keyboard shortcut for static import is <ctrl+shift+m> (mac: <cmd+shift+m>).

The expression builder looks like this:

public class ConditionalCriteriaBuilder<T> {

private final List<ConditionalCriteria> criteriaList = new ArrayList<ConditionalCriteria>();

private ConditionalCriteriaBuilder() {
}

public static <T> ConditionalCriteriaBuilder<T> criteriaFor(Class<T> clazz) {
return new ConditionalCriteriaBuilder<T>();
}

public List<ConditionalCriteria> build() {
return criteriaList;
}

private void addCriteria(ConditionalCriteria criteria) {
criteriaList.add(criteria);
}

public CondditionProperty<T> withProperty(Property<T> property) {
return new PropBuilderImpl(property.getName());
}

public interface CondditionProperty<T> {
ConditionalCriteriaBuilder<T> eq(Object value);
}

private class PropBuilderImpl implements CondditionProperty<T> {
String propertyName;

PropBuilderImpl(String name) {
this.propertyName = name;
}

public ConditionalCriteriaBuilder<T> eq(Object value) {
addCriteria(ConditionalCriteria.equal(propertyName, value));
return ConditionalCriteriaBuilder.this;
}
}
}


Alright, let us refactor the model, and introduce a BasicType for the first and last name of the Person:


Entity Person {
- @PersonName name
}

BasicType PersonName {
String first
String last
}


Generate, and you will immediately detect compilation error in the criteria expression. Fix it and it looks like this:

List<ConditionalCriteria> conditionalCriteria = criteriaFor(Person.class)
.withProperty(name().last()).eq("Svensson").build();


The generated Properties classes defines refererences also, so it easy to navigate associations with full code completion support. Great, our goals of code completion and refactoring are fulfilled.

That is not the end of this series of articles. In next article I will illustrate some more advanced operators that requires some intellectual thoughts. See you tomorrow.

Sunday, November 29, 2009

Internal DSL for Criteria - part 1:3

Hibernate has support for criteria queries and that is an awaited feature in JPA 2.0. The criteria API is rather technical and doesn't read to well with your domain terms, your DDD Ubiquitous Language. Therefore I have developed a small internal DSL in Java to be able to express conditional criteria in human readable format. It is not intended to handle everything in the criteria API.

I use this to illustrate how to implement an internal DSL. It is not hard once you have learned the tools to play with. Java is not optimal for DSLs, but let us use it as good as possible.

The goal was to create a fluent api that supported code completion and refactoring in a good way. A simple criteria may look like:

criteriaFor(Person.class).withProperty(sex()).eq(Gender.FEMALE).build();

and a more advanced criteria:

criteriaFor(Person.class)
.withProperty(sex()).eq(Gender.FEMALE).and()
.withProperty(ssn().country()).eq(SWEDEN).and()
.lbrace().withProperty(name().first()).like("A%")
.or().withProperty(name().last()).like("A%").rbrace()
.orderBy(name().last())
.build();
I will show how a few pieces of the DSL was developed. I have mostly used Expression Builder and Method Chaining, but also a few other tricks.

The expression builder doesn't create the JPA/Hibernate criteria directly. It creates an intermediate structure of objects , which can be translated to criteria API. The main reason for that is decoupling and possibility to have vendor specific implementations.

First, let me state the obvious: When developing an internal DSL it is perfect to do it the TDD way. You will add more and more features and do a lot of refactoring until you are satisfied with the language.

Enough of the introductory talking, let us go hands on to a simple equals expression:

List<ConditionalCriteria> conditionalCriteria =   
ConditionalCriteriaBuilder.criteria().prop("name").eq("Svensson").build();
This can be implemented in the builder as:

public class ConditionalCriteriaBuilder {
private final List<ConditionalCriteria> criteriaList = new ArrayList<ConditionalCriteria>();
private String propertyName;

private ConditionalCriteriaBuilder() {
}

public static ConditionalCriteriaBuilder criteria() {
return new ConditionalCriteriaBuilder();
}

public List<ConditionalCriteria> build() {
return criteriaList;
}

public ConditionalCriteriaBuilder prop(String name) {
propertyName = name;
return this;
}

public ConditionalCriteriaBuilder eq(Object value) {
addCriteria(ConditionalCriteria.equal(propertyName, value));
return this;
}

private void addCriteria(ConditionalCriteria criteria) {
criteriaList.add(criteria);
}
}

But that is not very good because it allows invalid expressions, such criteria().eq("A").prop("aaa").eq("B").

Therefore I introduce an interface for the property level:



public PropBuilder prop(String name) {
return new PropBuilderImpl(name);
}

public interface PropBuilder {
ConditionalCriteriaBuilder eq(Object value);
}

private class PropBuilderImpl implements PropBuilder {
String propertyName;

PropBuilderImpl(String name) {
this.propertyName = name;
}

public ConditionalCriteriaBuilder eq(Object value) {
addCriteria(ConditionalCriteria.equal(propertyName, value));
return ConditionalCriteriaBuilder.this;
}
}

This also facilitates code completion (ctrl+space) in a good way, which was one of our goals.

In next post, tomorrow, I will take care of the string property names that are not very refactoring friendly.

Thursday, November 19, 2009

How we do automated regression testing with Selenium and Hudson

When developing a piece of software that has a lifecycle that spans over several years and periodically is released you have to do regression testing, i.e. making sure that previous features doesn't break because of new stuff.
And after a while when your software grows and you add new features, the amount of regression tests increases. To avoid drowning yourself with testing you need to automate as much as possible.

The Sculptor team is a bunch of guys that are driven by interest and are developing the software on there spare time during late nights. We doesn't have the time to do deep manual testing, hence automation is very attractive for us. And since we are geographically distributed and don't have a central CI environment we have to solve some practical problems locally.

What we do (amongst other things), involves having a local Hudson server running on our developing environment (i.e. my iMac) that (of course) builds all projects and runs unit tests.
But we also use Selenium to run automated functional tests to make sure that our example application works. I though I should show some more details about how we use Selenium.

As I said, we have an example application called Library. If you look in the source code for the library-web module you will find the directory:

src/main/webapp/selenium

In there you will find a bunch of tests. The root is the suite file:

___test-suite.xhtml

Selenium test can be written in various programming languages. We have chosen to keep it simple and implement the tests in html.

Having these tests enables us to run them as soon as the code base changes thanks to Hudson and Maven. In Hudson we just creates a new job that is triggered to run as soon as the Library projects is compiled and the unit tests passes. In the pom-file for the Library web project we have a profile that we can use to start a local instance of the Jetty server. Deploy the the application. Run our selenium tests. And finally stop the server. The Maven configuration for this is:
<profile>
<id>regression</id>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.11</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>selenium-maven-plugin</artifactId>
<version>1.0</version>
<configuration>
<suite>src/main/webapp/selenium/___test-suite.xhtml</suite>
<browser>*firefox</browser>
<results>${project.build.directory}/target/selenium.html</results>
<startURL>http://localhost:8080/${artifactId}</startURL>
</configuration>
<executions>
<execution>
<id>run-tests</id>
<phase>integration-test</phase>
<goals>
<goal>selenese</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
But, since the amount of tests keeps growing and the time it takes to run them all also grows, there is a need to be able to run just a single test or a few of them. For instance, it is very convenient to have that possibility when developing new features, fixing bugs, or just doing a refactoring. To enable this we use the very competent Firefox plugin called SeleniumIDE. Beside recording test case, you can also load already defined test cases (or suites) and run them.




Sunday, November 15, 2009

Promote Quality with Sculptor

We have written an article that has been published in the paper magazine JayView Issue 20.

Without a vision of how to design applications within an organization the development can be compared to lawless Wild West. Development guidelines are often used, but seldom successful over the long haul. We suggest taking the architectural decisions one step further by automating them using a tool such as Sculptor.

When using a general purpose language, such as Java, and its big toolbox of APIs and frameworks there is a huge freedom of choice. This is a double-edged sword. We meet a lot of companies that have realized that they must narrow down the choices so that each new project doesn't invent its own unique system architecture and product suite. The benefits of a homogeneous architecture is obvious when looking at the big picture.

The reference architecture is often accomplished by writing guidelines and maybe a sample reference application. There are several problems with a reference architecture that is only promoted by documentation. We suggest automating some pieces of the development by using a code generator tool, such as Sculptor, to enforce consistency in the architecture.

Read more in the full article.