Site Navigation
Tech Feeds

 

Chariot TechCast

The Chariot TechCast is a unique podcast geared toward the IT developer.  I interview open source and Java committers and leaders, and shed light on upcoming and important trends in the community.

Private Previews
Thursday
02Jul

Chariot TechCast summer vacation about to end

For those of you who listen to my Chariot TechCast, I've been busy with other things lately, including launching Chariot's training practice, which now features official Spring Framework Training.  So, the TechCast has been on a bit of a vacation.  I feel like Click and Clack putting the puzzler to bed.

Lucky for me, I'm not on a scheduled 1-hour radio program that has to deliver every week.  Nevertheless, I've been getting antsy to do more recordings, so coming up in July and August (subject to change):

  • A discussion with James Ward on Flex 4.0 and other topics
  • A 'beer night' recording with Chariot's Integration and SOA team about the state of Open Source Integration
  • Potentially a discussion about SpringSource Roo (speakers TBD)
  • Discussion with members of The Open Source Alliance
  • A discussion on CouchDB
  • Talk with a very influential consultant and blogger on Java Concurrency.

Whet your appetite?  If you haven't listened to the archives, we have lots of interesting topics to choose from, including discussions on Spring, Seam, JSR-299 and 303 (yes, JSRs are interesting too!) Mule, Flex, Grails, Rails, The Google Map Reduce Process and Hadoop, and much more.

As usual, you can subscribe via iTunes or RSS.

Happy early summer,

Ken

 

Thursday
18Jun

SpringSource Roo 1.0.0.M2 released, great blog post by Ben Alex on internals...

SpringSource just released Milestone 1.0.0.M2 of Roo, their developer productivity tool. It's 'getting better all the time', to quote a Beatles tune.

I was about to set aside some time to go over the internals of SpringSource's Roo and blog about it, but the creator, Ben Alex, beat me to the punch. Read his article on the SpringSource blog.

One interesting part of Roo for me is how you can start by scaffolding the UI pages, and then stop and manually customize things. There is an annotation on the Controller like this:

@RooWebScaffold(automaticallyMaintainView = true
   formBackingObject = Conference.class)

The key item here is the automaticallyMaintainView entry.  If set to false, Roo no longer generates and replaces the jsp code.  Which means that you can start by scaffolding the view, and then stop and customize it to your heart's content.

Also the Eclipse AJDT plugin apparently has a 'push generation' feature that will turn all aspect-driven code into actual classes, and remove your dependency on Roo altogether.  This is important, as you can use Roo to get started, get work done, and eventually part with it if need be.

Interesting stuff to watch going forward.

 

Friday
12Jun

SpringSource Roo - What is it?

Overview

I just did a talk with our development team at Chariot on SpringSource's latest application platform builder, Roo. As with most new projects, I approached it with some skepticism--why do we need another convention over configuration framework?  Re: Spring, I was happy working in Grails! After spending a couple of days with it, I now realize that it was a very smart move to create this project.  This series of posts will outline what I'm learning, and hopefully will get you off to a good start in your own experiments.

Much of what I'm saying was written up very well by Ben Alex himself in this blog post. I suggest reading his post as well.

They're using Maven?

Roo is headed up by Ben Alex, and it was refreshing to see that his approach is centered around using Maven as the build system.  Essentially, the roo platform gives you a command line (named, aptly, 'roo'), which lets you issue commands to build and modify your platform.

For example, to build a new project, you issue:

roo> create project -topLevelPackage com.chariot.demo.roodemo

This builds a new Maven project. Under the covers, the team has installed the following features:

  • Spring Framework 3.0.0 beta
  • Spring MVC, annotation driven
  • A Web application plus the mvc context
  • Spring context loaders in web.xml
  • Jetty and Tomcat runner support
  • Eclipse and SpringSource Tool Suite project natures, including ADJT, Spring, STS

JPA Support

This is a fully functional application from the get-go. What's more, you can add features to the project easily. Since it's a convention-over-configuration, domain-driven application platform, let's create a JPA domain class. First, we have to install JPA:

roo> install jpa -provider HIBERNATE -database MYSQL

This installs JPA support. You could also pick ECLIPSELINK or OpenJPA as providers. The Maven build is configured to add the relevant libraries, and the applicationContext.xml file reflects the installation of JPA as a platform. In addition, roo sets up the transaction management platform, including annotation-driven transactions, and gives you a database.properties file.

One thing to note: right now Roo gives you a DriverManagerDataSource, which doesn't do connection pooling, but you are free to modify that and add the relevant support for DBCP or C3P0 instead. In fact, roo has an "add dependency" command to add Maven Artifacts, if you'd like to use their command line.

Creating a JPA Domain Object

Normally Spring developers are used to building JPA entities, wrapping them with Repository objects, and then coordinating access to these data layer repositories with Service-level beans. Ben and his team seem to have realized that one of the key features of Grails is GORM, a domain-driven object relational modeling system. In GORM, you can define and add constraints to an object, and have it persist itself.

The clever way that the Roo team solved this challenge was to add special annotations and some AOP magic to weave in validation and persistence code using Aspects. For example, if I define a simple JPA bean using 'new persistent class jpa' and edit it like this:


// the roo command to generate the class skeleton:
roo> new persistent class jpa -name Conference

// (without imports) the code:
@Entity
@RooEntity
@RooJavaBean
@RooPlural("conferences")
@RooToString
public class Conference {
@Column(nullable=false)
@Size(min = 5, max = 30,
message = "Please enter a name between {min}
and {max} characters.")
private String name;

@Size(min = 10, max=512,
message = "{description.required}")
private String description;

@Temporal(TemporalType.TIMESTAMP)
@Column(insertable=true, updatable=false)
@NotNull
private Date created;
}

You are getting the following functionality:

  • You get an id and version column automatically by default
  • You can use JSR-303 annotations like @NotNull, @Size, and others. These will modify the UI pages and generate error messages using Spring MVC's errors object.
  • Roo will automatically generate getters and setters and helper methods for your domain objects, and do it by watching your @Entity classes and sensing that they are changed
  • Hint:  If you place a ValidationMessages.properties file in the root of the src/main/resources directory you can externalize the error messages as in the {description.required} message above.  Roo doesn't look for these in the MessageSources as this is a JSR-303 spec requirement.

Roo will also write persistence mechanisms and attach them to the Entity's class. For example, you get:

  • persist() - saves your entity for the first time
  • remove() - deletes the entity
  • findAllConferences() - does a jpa entity manager query to get the all conferences
  • findConferenceById() - does a get by the primary key
  • flush() - flushes to the persistent storage mechanism (Hibernate in this case)
  • countAllConferences() - does a select count(*) query to count the rows

How does it do that?

How Roo does that ;-)

(Ok, I couldn't resist.) Here's how it works: Roo uses AspectJ to install .aj files to shadow all of the key objects (Domain Classes, Controllers, etc). It also installs certain AOP features that look for key annotations such as @RooEntity and @RooJavaBean to generate and synchronize those .aj files.

The Conference file generates (as of today) the following AJ files:

  • Conference_Roo_Entity.aj - wires in the id and version fields, as well as flush(), merge(), countConferences(), findAllConferences(), findConference() and findConferenceEntries()
  • Conference_Roo_JavaBean.aj - generates getters and setters for fields in the domain class
  • Conference_Roo_Plural.aj - looks like it determines how to ask for multiples of the object. So, for example, Entity would be defaulted to Entitys. Apparently there is an @RooPlural annotation that lets you modify what gets generated here.
  • Conference_Roo_ToString.aj - automatically creates an Apache ToStringBuilder on the fields including the id and version. Nice touch.
  • Conference_Roo_Configurable.aj - adds the @Configurable annotation to the entity. This is where my spring-fu needs a little dusting off ;)

So, now roo can issue calls to the Conference object as if it is a domain class.  

Update, I was attempting to do this in IntelliJ Maia within a controller, and I couldn't issue the code. It looks like if you want to edit the code yourself you need to further configure Maia and on Eclipse you really need SpringSource Tool Suite with the Roo plugin.  I'm testing this with the 2.1.0.M2 release of STS.  

Conference c = Conference.findConference(2L);
c.setName("BasketWeaving 101");
c.update();

The Story So Far...

So, in a few steps, we've created a project and configured it with JPA, then written a fully domain-driven database model object that can be persisted using this platform. If it wasn't obvious, I keep a roo command line open all the time, run SpringSource Tool Suite (or IntelliJ Idea Maia beta, which has support for Aspects), and run the app using 'mvn jetty:run' or 'mvn tomcat:run'. That's pretty nifty.

IDE Support

To use Roo under STS / Eclipse, just use 'mvn eclipse:eclipse' and import the existing project into your workspace. To use it under Idea, you'll have to download the Maia beta (it works pretty well and can view aspect files without screwing up your project). I've also tested this from NetBeans and it opened and let me view the aspects as text files. You should NOT edit the .aj files directly, as they are re-generated and you'll lose code.

One word of warning: On STS / Eclipse, you'll have to refresh the project if you add support for any feature that updates the maven pom. To build the eclipse project, do 'mvn eclipse:eclipse' and then go and refresh (F5) the project tree. Also, I've seen where I have to manually referesh contents of files because Eclipse doesn't watch them very well. IntelliJ or NetBeans 6.7 RC2 do fine re-reading the POM automatically.

Why not Groovy/Grails?

That's a good question.  Rod/Ben answered this somewhere in the blog post comments with the comment that many Spring developers can't or won't move to Groovy and/or another persistence framework like GORM.  If your company insists on doing Spring development in Java, or wants you to use the Spring APIs directly rather than wrap them in something like Grails, this is a great alternative.  Also, I can't think of a better way to kick the tires of features like Spring Security, JMS Templating, Spring IoC 3.0, Bean Validation annotations, JPA, and others from within Spring itself.

I'm still a huge Groovy on Grails fan, and see this as one of two ways to build applications on top of the Spring core.  The fact that regular Spring developers can take advantage of domain-driven application persistence is a huge bonus for our industry.

Early Days

This product still has a way to go, and was released as a milestone build recently (1.0.0.M1).  I've asked questions in the forum and posted JIRA issues, and the team has been absolutely responsive.  They will take your input and are welcoming contributors.

Resources

Coming up...

Over the next series of posts, I'll dig deeper into the JPA configuration, talk about scripting roo, outline the web framework, and show you how you can use Roo to automatically scaffold your web application and interact with the domain-driven Entities, using annotations and aspects.

Tuesday
02Jun

Gettin' all Testy - The Spring TestContext, Hibernate, and you...

I'm getting some materials ready around a project using the Hibernate Annotations API in Spring 2.5.6.  The client is using Hibernate rather than straight JPA, likely due to wanting to get features such as Filters, Criteria, etc...

I've been used to JUnit 3.x for a while, but as I'm testing my Hibernate knowledge, I came across the newer Spring Test Context framework.  If you install JUnit 4.4 (I'm using Maven, so I just added it as a test-time dependency) and also the spring test-context library, you'll have the ability to define tests that ramp up a Spring Context using the @ContextConfiguration annotation and coupled with extending a specific Spring abstract class, AbstractJUnit4SpringContextTests.

This is similar to the Junit 3.8 context configuration, but uses JUnit 4 semantics.  Also you can use TestNG, just use a different abstract class.  Here is a fragment:

@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class HibernateModelTest 
   extends AbstractJUnit4SpringContextTests {
...
}

 

Ok, that's cool.  You get an applicationContext member in the test class too. So, what if you wanted to interact with the Hibernate API directly?  I've mounted my Hibernate configuration using the Spring Hibernate AnnotationSessionFactoryBean, scanning for entities in the org.rimple.example.domain package as in this example:

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.
AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="org.rimple.example.domain"/>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
        hibernate.hbm2ddl.auto=create
        hibernate.cache.provider_class=org.hibernate.cache.NoCacheProvider
        hibernate.show_sql=true
        hibernate.current_session_context_class=thread
        hibernate.connection.pool_size=15
      </value>
    </property>
</bean>
       

Now I can just create a @Before and @After method to setup and tear down the session context.  I can get fancy and begin a transaction and end it, just like the transactional tests provided for Repository tests, but then I can open and close and interact with the session myself.

    private Session session;
    @Before
    public void setupSession() {
        SessionFactory sessionFactory = (SessionFactory) applicationContext.
getBean("mySessionFactory");
        session = sessionFactory.openSession();
        session.getTransaction().begin();
    }

    @After
    public void tearDownSession() {
        session.getTransaction().rollback();
        session.close();
    }

Now, all I have to do is just interact with Hibernate directly. Given this Entity:


@Entity
@Table(name="employees")
public class Employee {

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(nullable=false, length=30)
    private String firstName;

    @Column(nullable=false, length=30)
    private String lastName;

    @Column(nullable=false)
    private Boolean active;

    @Column(nullable=false)
    @Temporal(TemporalType.DATE)
    private Date hireDate;

    @Column(nullable=true)
    private String comments;
    ...
}

We can use this test:

    @Test
    public void createEmployee() {
        Employee e = new Employee();
        e.setActive(true);
        e.setFirstName("Joe");
        e.setLastName("Smith");
        e.setComments("A new employee");
        e.setHireDate(new Date());

        session.save(e);
        assertNotNull(e);
    }

QED!  I am partial to the JPA Entity Manager and putting Hibernate behind a facade, but this works if your team decides they are using the Hibernate annotation and API instead.

Wednesday
13May

New Chariot TechCast posted on JSR-299 and WebBeans

Thanks to Dan Allen, who set up the interview, I skyped with Pete Muir on the JSR-299 spec last week, which is the spec that used to be called 'WebBeans', and is now 'Java Context and Dependency Injection', or JCDI. Pete was a great interview, and we hopefully demystified a few things about the spec and the JBoss-led Reference Implementation, which now has the name WebBeans.

You can listen to the episode by clicking on the link below.

Episode 33 - JSR-299 and WebBeans with Pete Muir of JBoss