Showing posts with label Maven. Show all posts
Showing posts with label Maven. Show all posts

Friday, October 15, 2010

Maven, RAD and WebSphere: how to generate a set of RAD 7.5 projects for a J2EE application

This post continues the series on building RAD/WebSphere applications with Maven2.

 What we are trying to do here:
  • For a typical J2EE application, generate a set of RAD 7.5 projects using Maven's Eclipse plug-in (not to be confused with M2Eclipse, the Eclipse plug-in for Maven
  • Make sure the projects are usable "both ways": deploy on a local WebSphere server in the "normal" RAD way, and also build and deploy with Maven
  • Use Maven WAS6 plug-in to handle container-specific tasks: EJB stubs generation, bindings generation, application deployment

The main goal is to create a set-up that would not put any Eclipse/RAD-specific artefact (like .project, .classpath, .settings, etc.) in source control. Instead, the project in source control would be completely defined by the POM. The reason one would want to do that is that RAD projects -- in my humble opinion and experience -- are brittle, redundant and likely to contain settings that only make sense on a given workstation; this makes it hard to share. Another reason is that RAD is slow, rather bloated and an overkill for most tasks; if we don't standardize on RAD, people that don't use the advanced features would be able to use "vanilla" Eclipse, Net Beans, or any other IDE. Finally, making Maven POMs the single source of information about the project makes sure that this information is shared between the build script and the IDE.

Running Maven to generate RAD projects:

D:\apache-maven-2.2.1\bin\mvn.bat clean eclipse:clean eclipse:configure-workspace eclipse:eclipse -Declipse.workspace="${workspace_loc}


What follows is the Maven Eclipse plug-in configuration for the main POMs:

  • Common definitions factored out to parent POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.rbc.eca</groupId>
  <artifactId>J2EEProto</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>

  <modules>
    <module>../J2EEProto-EAR</module>
    <module>../J2EEProto-lib</module>
    <module>../J2EEProto-ejb</module>
    <module>../J2EEProto-web</module>
  </modules>
...
    <pluginManagement>
...
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-eclipse-plugin</artifactId>
          <version>2.8</version>
          <inherited>true</inherited>
          <configuration>

            <wtpdefaultserver>WebSphere Application Server v6.1</wtpdefaultserver>
            <wtpmanifest>false</wtpmanifest>
            <wtpapplicationxml>true</wtpapplicationxml>
            <wtpversion>1.5</wtpversion>

            <downloadSources>true</downloadSources>
            <downloadJavadocs>true</downloadJavadocs>

            <projectNameTemplate>[artifactId]</projectNameTemplate>
            <useProjectReferences>true</useProjectReferences>

            <additionalBuildcommands>
              <buildcommand>org.eclipse.wst.validation.validationbuilder</buildcommand>
              <buildcommand>org.eclipse.wst.common.project.facet.core.builder</buildcommand>
            </additionalBuildcommands>

            <additionalProjectnatures>
              <projectnature>org.eclipse.wst.common.project.facet.core.nature</projectnature>
              <projectnature>org.eclipse.wst.common.modulecore.ModuleCoreNature</projectnature>
            </additionalProjectnatures>

            <classpathContainers>
              <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/WebSphere v6.1 JRE</classpathContainer>
              <classpathContainer>org.eclipse.jst.server.core.container/com.ibm.ws.ast.st.runtime.runtimeTarget.v61/was.base.v61</classpathContainer>
              <classpathContainer>org.eclipse.jst.j2ee.internal.module.container</classpathContainer>
            </classpathContainers>

          </configuration>
        </plugin>
    </pluginManagement>
...
  </project>

  • EJB project

This project uses Eclipse plug-in definitions from the parent POM, and
also calls Maven's WAS6 plug-in to prepare the EJB for deployment
outside of RAD.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.rbc.eca</groupId>
    <artifactId>J2EEProto</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../J2EEProto/pom.xml</relativePath>
  </parent>
  <artifactId>J2EEProto-ejb</artifactId>
  <packaging>ejb</packaging>

...

  <properties>
    <was6-home>D:\IBM\SDP75\runtimes\base_v61</was6-home>
  </properties>


  <build>
...

   <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-ejb-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <ejbVersion>2.1</ejbVersion>
          <generateClient>true</generateClient>
          <archive>
            <manifest>
              <classpathPrefix>lib/</classpathPrefix>
              <addClasspath>true</addClasspath>
            </manifest>
          </archive>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>

          <additionalProjectFacets>
            <jst.ejb>2.1</jst.ejb>
            <com.ibm.websphere.extended.ejb>6.1</com.ibm.websphere.extended.ejb>
          </additionalProjectFacets>

        </configuration>
      </plugin>


    </plugins>
  </build>


  <profiles>
    <!-- Profile used for batch build, needs WebSphere's J2EE JARs -->
    <profile>
      <id>batch</id>
      <activation>
        <property>
          <name>batch</name>
          <value>true</value>
        </property>
      </activation>

      <dependencies>
        <dependency>
          <groupId>websphere</groupId>
          <artifactId>j2ee</artifactId>
          <version>6.1</version>
          <scope>system</scope>
          <systemPath>${was6-home}\lib\j2ee.jar</systemPath>
        </dependency>

        <dependency>
          <groupId>websphere</groupId>
          <artifactId>ejbruntime</artifactId>
          <version>6.1</version>
          <scope>system</scope>
          <systemPath>${was6-home}\plugins\com.ibm.ws.runtime_6.1.0.jar</systemPath>
        </dependency>

        <dependency>
          <groupId>websphere</groupId>
          <artifactId>ejbportable</artifactId>
          <version>6.1</version>
          <scope>system</scope>
          <systemPath>${was6-home}\plugins\com.ibm.ws.ejbportable_6.1.0.jar</systemPath>
        </dependency>

        <dependency>
          <groupId>websphere</groupId>
          <artifactId>iwsorbutil</artifactId>
          <version>6.1</version>
          <scope>system</scope>
          <systemPath>${was6-home}\java\jre\lib\ext\iwsorbutil.jar</systemPath>
        </dependency>

      </dependencies>

      <build>

        <plugins>

          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>was6-maven-plugin</artifactId>
            <executions>
              <execution>
                <id>integration-test</id>
                <phase>integration-test</phase>
                <goals>
                  <goal>ejbdeploy</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <legacyMode>true</legacyMode>
            </configuration>
          </plugin>

        </plugins>
      </build>
    </profile>
  </profiles>
</project>

  • EAR project

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.rbc.eca</groupId>
    <artifactId>J2EEProto</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../J2EEProto/pom.xml</relativePath>
  </parent>
  <artifactId>J2EEProto-EAR</artifactId>
  <packaging>ear</packaging>

  <properties>
    <was6-home>D:\IBM\SDP75\runtimes\base_v61</was6-home>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-ear-plugin</artifactId>
        <version>2.4.2</version>
        <configuration>
          <filtering>true</filtering>
          <earSourceIncludes>**/ibmconfig/**</earSourceIncludes>
          <earSourceExcludes>**/target/**</earSourceExcludes>
          <version>1.4</version>
<!-- Generating it is the simplest solution if we don't have any extra
     settings; we could use an existing one otherwise, and use Maven
     resource filtering to get correct artifact versions in it -->
          <generateApplicationXml>true</generateApplicationXml>
<!--          <applicationXml>${basedir}/src/main/application/META-INF/application.xml</applicationXml>-->
          <modules>
            <webModule>
              <groupId>${project.groupId}</groupId>
              <artifactId>J2EEProto-web</artifactId>
              <contextRoot>/J2EEProto-web</contextRoot>
            </webModule>

            <jarModule>
              <groupId>${project.groupId}</groupId>
              <artifactId>J2EEProto-lib</artifactId>
            </jarModule>
            <ejbModule>
              <groupId>${project.groupId}</groupId>
              <artifactId>J2EEProto-ejb</artifactId>
            </ejbModule>
            <ejbClientModule>
              <groupId>${project.groupId}</groupId>
              <artifactId>J2EEProto-ejb</artifactId>
            </ejbClientModule>
          </modules>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>was6-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>integration-test</id>
            <phase>integration-test</phase>
            <goals>
              <goal>wsStopServer</goal>
              <goal>wsUninstallApp</goal>
              <goal>wsDefaultBindings</goal>
              <goal>installApp</goal>
              <goal>wsStartServer</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <applicationName>${project.artifactId}</applicationName>
          <updateExisting>false</updateExisting>
          <earFile>${dest-ear}</earFile>
          <verbose>true</verbose>
        </configuration>
      </plugin>

    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>J2EEProto-web</artifactId>
      <version>${project.version}</version>
      <type>war</type>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>J2EEProto-test</artifactId>
      <version>${project.version}</version>
      <type>war</type>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>J2EEProto-ejb</artifactId>
      <version>${project.version}</version>
      <type>ejb</type>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>J2EEProto-ejb</artifactId>
      <version>${project.version}</version>
      <type>ejb-client</type>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>J2EEProto-lib</artifactId>
      <version>${project.version}</version>
    </dependency>

...

  </dependencies>


  <profiles>

    <!-- 
    If building for integration testing, deploy J2EEProto-test.war
     -->
    <profile>
      <id>integration-build</id>
      <activation>
        <property>
          <name>it-build</name>
          <value>true</value>
        </property>
      </activation>
      <properties>
        <exclude-integration>false</exclude-integration>
      </properties>
      <build>
      </build>
    </profile>

  </profiles>

</project>

  • Web Project

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.rbc.eca</groupId>
    <artifactId>J2EEProto</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../J2EEProto/pom.xml</relativePath>
  </parent>

  <artifactId>J2EEProto-web</artifactId>
  <packaging>war</packaging>

...

  <properties>
    <was6-home>D:\IBM\SDP75\runtimes\base_v61</was6-home>
  </properties>

  <build>

    <plugins>
...
       <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>

          <warContextRoot>J2EEProto-web</warContextRoot>

          <additionalProjectFacets>
            <jst.web>2.4</jst.web>
            <com.ibm.websphere.extended.web>6.1</com.ibm.websphere.extended.web>
            <com.ibm.websphere.coexistence.web>6.1</com.ibm.websphere.coexistence.web>
          </additionalProjectFacets>

        </configuration>
      </plugin>

    </plugins>
  </build>

  <profiles>
...
</project>

  • Library project

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.rbc.eca</groupId>
    <artifactId>J2EEProto</artifactId>
    <version>1.0-SNAPSHOT</version>
    <relativePath>../J2EEProto/pom.xml</relativePath>
  </parent>
  <artifactId>J2EEProto-lib</artifactId>

...

  <build>
    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
          <additionalProjectFacets>
            <jst.utility>1.0</jst.utility>
          </additionalProjectFacets>
        </configuration>
      </plugin>


    </plugins>
  </build>
  
   <reporting>    
   
    <plugins>  
    </plugins>      
  </reporting>  
 
</project>

Thursday, October 14, 2010

J2EE application on RAD/WebSphere with Maven: Integration testing and other problems

Integration testing of a J2EE application with Maven was unexpectedly hard to get right, although, having got there, the end result seems very logical and almost intuitive.

The reason is probably that (1) there is no single "right" solution, (2) the task is out of the tool's "comfort zone", and (3) doing it requires really wrapping one's head around Maven's life cycle. After having spent several years -- off and on -- using the tool, it turned out I still had some understanding to acquire with (3). But, after the fact, the whole thing seems very straightforward, because it really is.

So. Given: a typical J2EE application being built as an EAR to be deployed on WebSphere, consisting of a library JAR, an EJB JAR, a Web application (WAR), and a test web application with Cactus tests for the EJBs and servlets. The application is built with Maven 2.7 and needs to deploy on WebSphere 6.1.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.rbc.eca</groupId>
  <artifactId>J2eeProto</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>

  <modules>
    <module>../J2eeProto-EAR</module>
    <module>../J2eeProto-lib</module>
    <module>../J2eeProto-ejb</module>
    <module>../J2eeProto-web</module>
  </modules>
  ...

We need: the level of build automation that would allow for automatically building the application, deploying it on a WebSphere server, and running the integration tests. In real life the sequence would be run by a continuous integration server (e.g. Hudson).

The sequence of steps that need to happen is as follows:

(1) build
(2) run unit tests
(3) deploy on test server
(4) run integration tests

The problem: Maven life cycle is geared towards a project that falls short of J2EE 1.4 (EJB 2.1) and builds a WAR file that can be unit tested, bundled, deployed, integration tested inside a single project. However, building an EAR for WebSphere requires a modular J2EE project; Maven life cycle acts on a single project.


So we need to

(1) separate unit tests in all projects from integration tests

(2) build for integration testing (adding Cactus instrumentation where applicable)

(3) run unit tests in all projects (but not integration tests) when building (up to the "package" phase of Maven's life cycle), and apply coverage reporting and the rest

(4) if packaging succeeds, prepare the resulting artifacts for deployment (this needs running application server-specific tasks -- WebSphere-specific, in our case) and deploy them (since we are doing this for automated testing, we need to stop the server, un-deploy and deploy the EAR, and start the server to diminish the number of things that could break as the application changes)

(5) run the integration tests in all projects, with the appropriate test reporting

To be continued:

Saturday, October 3, 2009

JPA and Common Domain Objects

(belongs to this series)

The idea is to create a hierarchy of classes that all domain objects can derive from. These classes are the single point where we implement the following:

  • Methods for Collections: we need all domain objects to be comparable, hashable and to equal on ID (primary key)
  • Primary key: either auto-numbering or GUID
  • Optimistic concurrency

What could be added if needed:

  • Timestamp
  • Auditing: the user id of last update

All domain objects can extend these; we could also benefit from all domain objects following the same pattern (e.g. having a "getId()" method), when implementing the generic DAOs.

If we add entity classes, and configure the project as suggested below, then, at this stage, we would achieve the following:
  • The database schema will be generated by Hibernate using the entity classes that extend the generic domain object classes suggested here; the configuration suggested below actually provides for dropping and the tables and re-generating them each time the build runs.

  • Entity manager and transaction manager will be configured by Spring and ready for the next stage -- implementing the Data Access Objects

  • The unit tests can be implemented with the assumption that the database schema is up to date -- i.e. following the entity classes -- for every build (see "execution" clause in Hibernate plug-in configuration suggested below)

Libraries and Versions


... as expressed by Maven dependencies:

....

<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring</artifactid>
 <version>2.5.6</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring-core</artifactid>
 <version>2.5.6</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring-context</artifactid>
 <version>2.5.6</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring-test</artifactid>
 <version>2.5.6</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 <artifactid>spring-web</artifactid>
 <version>2.5.6</version>
</dependency>
...
  
<dependency>
 <groupid>javax.persistence</groupid>
 <artifactid>persistence-api</artifactid>
 <version>1.0</version>
</dependency>
<dependency>
 <groupid>org.hibernate</groupid>
 <artifactid>hibernate-entitymanager</artifactid>
 <version>3.3.2.GA</version>
</dependency>
<dependency>
 <groupid>javax.transaction</groupid>
 <artifactid>jta</artifactid>
 <version>1.1</version>
</dependency>
<dependency>
 <groupid>${jdbc.groupId}</groupid>
 <artifactid>${jdbc.artifactId}</artifactid>
 <version>${jdbc.version}</version>
</dependency>
...

Using Hibernate Maven Plugin to generate the schema


Let's start with the "build" section of the POM, where we define how the resources get filtered (in Maven parlance, this means resolving variables in them using property values from the POM):

...
  <resources>
   <resource>
    <directory>${project.basedir}/src/main/resources</directory>
    <filtering>true</filtering>
   </resource>
  </resources>
  <testresources>
   <testresource>
    <directory>${project.basedir}/src/test/resources</directory>
    <filtering>true</filtering>
   </testresource>
  </testresources>      


Where the resources we are filtering as shown above are used? It is mostly in the jdbc.properties file quoted below. This is the file that is referenced from the Hibernate section of the POM, and also in the Spring configuration quoted below. This way we are making sure that all the database properties are specified in the POM.

The reason we are choosing POM as the single place of specifying the parameters for the project is because Maven has the ability to implement logic switching sets of values depending on the environment where the build is performed (test, development, QA, production). The other possible places (.properties files, Spring configuration) lack this flexibility.

The idea was borrowed from this Maven archetype


#
# These properties are used at build time and run-time;
# they define the DB type and location; POM defines several
# sets of values for different environments (test, QA, ...)
#
jdbc.driverClassName=${jdbc.driverClassName}
jdbc.url=${jdbc.url}
jdbc.username=${jdbc.username}
jdbc.password=${jdbc.password}
jpa.database=${jpa.database}
jpa.showSql=${jpa.showSql}


# Needed by Hibernate3 Maven Plugin defined in pom.xml
hibernate.dialect=${hibernate.dialect}
hibernate.connection.username=${jdbc.username}
hibernate.connection.password=${jdbc.password}
hibernate.connection.url=${jdbc.url}
hibernate.connection.driver_class=${jdbc.driverClassName}


The property values that will be used at build time to resolve variables in the configuration file quoted above are specified in the POM -- in the "profiles" section -- as follows:

<properties>
  <dbunit.dialect>org.dbunit.ext.mysql.MySqlDataTypeFactory</dbunit.dialect>
  <hibernate.dialect>org.hibernate.dialect.MySQLDialect</hibernate.dialect>
  <jdbc.groupid>mysql</jdbc.groupid>
  <jdbc.artifactid>mysql-connector-java</jdbc.artifactid>
  <jdbc.version>5.1.6</jdbc.version>
  <jdbc.driverclassname>com.mysql.jdbc.Driver</jdbc.driverclassname>
  <jdbc.username>example</jdbc.username>
  <jdbc.password> </jdbc.password>
  <jpa.database>MYSQL</jpa.database>
  <jpa.showsql>true</jpa.showsql>
</properties>


Hibernate plug-in configuration references the jdbc.properties file that is getting receiving the values of properties specified in the POM as described above:

...
   <plugin>
    <groupid>org.codehaus.mojo</groupid>
    <artifactid>hibernate3-maven-plugin</artifactid>
    <version>2.2</version>
    <executions>
     <execution>
      <phase>process-classes</phase>
      <goals>
       <goal>hbm2ddl</goal>
      </goals>
     </execution>
    </executions>
    <configuration>
     <components>
      <component>
       <name>hbm2ddl</name>
       <implementation>jpaconfiguration</implementation>
      </component>
     </components>
     <componentproperties>
      <persistenceunit>example</persistenceunit>
      <outputfilename>schema.ddl</outputfilename>
      <propertyfile>target/classes/jdbc.properties</propertyfile>
      <drop>true</drop>
      <create>true</create>
      <export>true</export>
      <update>false</update>
      <format>true</format>
     </componentproperties>
    </configuration>
    <dependencies>
     <dependency>
      <groupid>${jdbc.groupId}</groupid>
      <artifactid>${jdbc.artifactId}</artifactid>
      <version>${jdbc.version}</version>
     </dependency>
    </dependencies>

   </plugin>
      ...


And persistence.xml is nearly empty (all mappings are handled by Hibernate, and entity manager is supplied by Spring):

<persistence version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/persistence" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
 <persistence-unit name="example" transaction-type="RESOURCE_LOCAL">
 </persistence-unit>
</persistence>

Finally, what binds together JPA and Hibernate is the Spring container; note the database parameters that reference the properties file:

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd ">

    <context:property-placeholder location="classpath:/jdbc.properties">
    </context:property-placeholder>
   
   
    <context:annotation-config>
    </context:annotation-config>

    <tx:annotation-driven>
    </tx:annotation-driven>

    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/Database">
    </jee:jndi-lookup>

   <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" p:datasource-ref="dataSource" p:jpavendoradapter-ref="jpaAdapter">
    <property name="loadTimeWeaver">
     <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
    </bean>
   </property>

   <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager" p:entitymanagerfactory-ref="entityManagerFactory">

      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" id="jpaAdapter" p:database="${jpa.database}" p:showsql="${jpa.showSql}">
      </bean>
    </bean>
  </bean>
  </beans>


Root class of reusable domain object hierarchy:


Implements comparison, equality and hash code, the primary key is left for the subclasses:

package com.example.domain;

import java.io.Serializable;

import javax.persistence.MappedSuperclass;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
import javax.persistence.Transient;
import javax.persistence.Version;

import org.apache.commons.lang.ObjectUtils;

/**
 * Root class for all entities; implements comparison and what goes with it.
 * Also has a "version" field for optimistic concurrency checking.
 * 
 * @author maxim
 *
 * @param <PK> primary key type
 * 
 * @see AutoNumberedDomainObject
 * @see SurrogateIdDomainObject
 */
@MappedSuperclass
abstract public class DomainObject<PK> implements
  Serializable, Comparable<DomainObject<PK>>, Cloneable {
 
 @Transient
 private boolean justCreated=true;
 
 @PostPersist
 @PostLoad
 public void saved(){
  justCreated=false;
 }
 
 static private  long serialVersionUID = 1L;
 
 @Version
 protected int version;

 @Override
 public String toString() {
  return "DomainObject ("+this.getClass().getSimpleName()+")";
 }

 
 @SuppressWarnings("unchecked")
 @Override
 public boolean equals(Object o) {
  if (o == this)
   return true;
  if (o == null)
   return false;
  return (o.getClass().isAssignableFrom(this.getClass()))
    && (this.getClass().isAssignableFrom(o.getClass()))
    && ObjectUtils.equals(((DomainObject<PK>) o).getId(), getId());
 }

 @Override
 public int hashCode() {
  if (getId() == null)
   return 0;
  return getId().hashCode();
 }

 /**
  * A simple stable ordering based on Id
  */
 @SuppressWarnings("unchecked")
 public int compareTo(DomainObject<PK> o) {
  if (getId() == null)
   return -1;
  if (o.getId() == null)
   return 1;
  return ((Comparable<PK>) getId()).compareTo(o.getId());
 }

 @Override
 public Object clone() {
  try {
   return super.clone();
  } catch (CloneNotSupportedException e) {
   throw new RuntimeException(e);
  }
 }
 
 /**
  * 
  * @return lable to display in selection lists; override in subclasses to produce something better
  */
 public String getSelectionLabel(){
  return getId().toString();
 }

 /**
  * @param id
  *            the id to set
  */
 public abstract void setId(PK id);

 /**
  * @return the id
  */
 public abstract PK getId();

 public int getVersion() {
  return version;
 }

 public void setVersion(int version) {
  this.version = version;
 }


 public void setJustCreated(boolean notSaved) {
  this.justCreated = notSaved;
 }


 public boolean isJustCreated() {
  return justCreated;
 }

}



Domain object with auto-numbered ID


This class extends DomainObject to add JPA auto-numbered ID fields.

package com.example.domain;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

/**
 * Extends {@link DomainObject} to support auto-numbered IDs via JPA
 * {@link GeneratedValue} with {@link GenerationType} =
 * {@link GenerationType#TABLE}
 * 
 * Does <b>not</b> force a unique constraint on the ID: add this in subclasses
 * if performance hit is accessible.
 * 
 * @param PK
 *            the primary key class for auto-numbering; the choice is usually
 *            between Long and Integer
 * 
 * @author maxim
 * 
 */
@MappedSuperclass
public abstract class AutoNumberedDomainObject<PK extends Number> extends
  DomainObject<PK> {

 private static  long serialVersionUID = 1L;

 @Override
 public String toString() {
  return "AutoNumberedDomainObject ("+this.getClass().getSimpleName()+") [id=" + id + "]";
 }
 
 @Id
 @GeneratedValue(strategy = GenerationType.TABLE)
 protected PK id;

 @Override
 public  PK getId() {
  return this.id;
 }

 @Override
 public  void setId(PK id) {
  this.id = id;
 }

}


Domain object with Surrogate Id


Another (and, arguably, more usable) flavour of DomainObject generates surrogate primary keys:

package com.example.domain;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

/**
 * DomainObject that has a surrogate ID calculated as a time-based GUID.
 * 
 * Does <b>NOT</b> force a unique constraint on the ID: add this in subclasses
 * if performance hit is acceptable.
 * 
 * @author maxim
 * 
 * @see UUID
 * 
 */
@MappedSuperclass
public class SurrogateIdDomainObject extends DomainObject<String> {

 @Override
 public String toString() {
  return "SurrogateIdDomainObject ("+this.getClass().getSimpleName()+") [id=" + id + "]";
 }

 /**
  * Default constructor; generates new ID
  */
 public SurrogateIdDomainObject() {
  super();
  this.id = newId();
 }

 /**
  * 
  * @param generateId specify false to <b>not</b> generate the ID
  */
 public SurrogateIdDomainObject(boolean generateId) {
  super();
  if (generateId) {
   this.id = newId();
  }
 }

 private static final long serialVersionUID = 1L;

 /**
  * "e5d302ed-0501-4a3e-abfc-a336124fe2b5" 
  */
 @Id
 @Column(name = "ID",length=36)
 private String id;

 /**
  * Creates new and assigns a surrogate ID
  */
 protected void initializeAsNew() {
  setId(newId());
 }

 public  void setId(String id) {
  this.id = id;
 }

 public  String getId() {
  return id;
 }

 /**
  * 
  * @return new UUID-based ID, e.g. "e5d302ed-0501-4a3e-abfc-a336124fe2b5" 

  * @see UUID
  */
 public static String newId() {
  return UUID.randomUUID().toString();
 }

}

Using the generic domain object classes


Having defined all of the above, we can benefit from it defining new domain objects as follows:

...
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
public class User extends SurrogateIdDomainObject {

 private String name;
...

The XML (actually, JAXB) annotations will come into play when we will be passing this object to and from Web Services.

Hibernate, JPA, JAX-WS, Spring AOP, JSF, Facelets, Transactions with Maven and Continuous Integration.

Starting what will hopefully become a series of articles showing how to use the widespread technologies in a web application started from scratch and intended to be deployed on a simple servlet container (Tomcat, Jetty,...) lacking support for advanced J2EE.

In other words, this is sharing simple home-made recipes and hoping to make them better by sharing.

The problem: create a slim and maintainable Java application including a lightweight framework that facilitates CRUD operations. This is a template that would be the starting point of many different projects, and eventually would lead to  creation of a Maven archetype.

What is known: performance is not critical; we should use free software (database and application servers), but not exclude a transition to other technologies in the future. The resulting project should lend itself easily to agile development and continuous integration (this is where things like DBUnit come into the picture).

The set of Java classes thus created can form the core of a lightweight framework that could be used to build different applications using modern Java technologies.

The content was a result of a recent design and development effort, and producing it involved a lot of googling, and very little original effort. Enjoy and comment!
Next articles (work in progress):


Some notes on the choice of technologies
... for those who need that.
  • JPA and Hibernate: first of all, JPA seemed to be the best for a project that starts from scratch as a Java application, because it's a Java-centric technology. It would allow to do domain modeling in terms of Java objects and make the database schema follow that model and the changes in it automatically; performance considerations were written off as "premature optimization", because the application is supposed to be small-scale -- in the best spirit of agile development we would care about scaling it up when we get to that point.
  • Spring: nothing better for wiring all the rest together; also, Spring's declarative transactions via AOP enable us to use this aspect of J2EE without placing extra requirements on the container (the target platform is Tomcat, representing the lowest common denominator among Java application servers)
  • JSF: as the CRUD-type functionality requires sophisticated editing forms with in-line fields for dependent records, JSF and Facelets seemed the best technology for creating the edit forms and making them maintainable through using Facelet compositions; another aspect of Facelets is that this technology provides for using compositions for reusable parts of views, and for giving all the pages a common structure.

  • Spring MVC is a good supplement to the rather heavy view technology that is JSF: one might -- and usually does -- want to provide a simple controller or two for some special screens or features (AJAX/JSON, PDF, etc.) and not jump through JSF hoops to do that, while using a general-purpose MVC framework; Spring MVC can also provide for JSF navigation definitions' lack of scalability.

  • Spring Web Flow  is really something that one is almost forced to use given the previous choices (Spring + Facelets). JSF on its own is, sadly,  disappointing in everything except view composition mechanics. JSF/Facelets do not seem to scale as a complete view technology: its view-centric approach means it is unnecessarily difficult to provide for initialization, its navigation definition syntax is too verbose to maintain without heavy tools, and, finally, the view needs a mechanism for saving state that makes objects survive longer, than a single request-response, but not for the whole duration of a user session; a shopping cart is a typical example. Spring Faces and Spring Web Flow (SWF) provide for these shortcomings and add a lot more. That SWF is really solving a real life problem, rather than providing yet another idiosyncratic way of creating a Java web application, is indirectly confirmed by the fact that other frameworks aiming at reasonable completeness also provide work-flow features (I am thinking of JBoss Seam), and also do it with JSF/Facelets.

  • JAX-WS is simply the most modern -- and widely supported -- way of exposing services for integration. See one of the later articles on how to best expose Spring beans as JAX-WS services when using a minimal Servlet container such as Tomcat.

  • Maven is almost a must given the above mix of products. I have seen projects that were using Ant or other build tools being compelled to almost re-invent Maven just to maintain a dependency list: the number of libraries coming from different projects needed to use what has been listed above is many dozens, and each library comes in many different versions, some of which are not compatible with the versions that are required by other libraries. Apart from this -- already compelling -- need to be able to maintain a list of all the dependencies and dependencies of dependencies, Maven provides for simpler build definitions if the project is using a standard layout (and nothing would stop it from using that when starting from scratch). On top of that Maven provides a cheap solution for maintaining a firm-wide repository of code artefacts where each artefact (.jar, .war, ...) could be stored with a version number (so that several versions could be maintained) and also associated with source code archives (so that a framework library could be used by developers with source code for browsing and de-bugging). This last is again something that at least one of the major companies that I had been working for in the past had created in-house just to solve internal software distribution problems; Maven's repositories provide minimal working solution out of the box.