Deploying BroadleafCommerce 2.0 on JBoss AS 7

First 2 steps are not really related to Broadleaf specific, but mentioned to make it easy to follow(copy/paste) the steps.

Step#1: Configure DataSources in JBoss AS.

<datasource jta="true" jndi-name="java:jboss/datasources/BroadleafDS" pool-name="BroadleafDS_Pool" enabled="true" use-java-context="true" use-ccm="true">
 <connection-url>jdbc:mysql://localhost:3306/broadleaf</connection-url>
 <driver>mysql</driver>
 <security>
  <user-name>root</user-name>
  <password>admin</password>
 </security>
 <timeout>
  <idle-timeout-minutes>0</idle-timeout-minutes>
  <query-timeout>600</query-timeout>
 </timeout>
</datasource>
<datasource jta="true" jndi-name="java:jboss/datasources/BroadleafSecureDS" pool-name="BroadleafSecureDS_Pool" enabled="true" use-java-context="true" use-ccm="true">
 <connection-url>jdbc:mysql://localhost:3306/broadleaf</connection-url>
 <driver>mysql</driver>
 <security>
  <user-name>root</user-name>
  <password>admin</password>
 </security>
 <timeout>
  <idle-timeout-minutes>0</idle-timeout-minutes>
  <query-timeout>600</query-timeout>
 </timeout>
</datasource>
<datasource jta="true" jndi-name="java:jboss/datasources/BroadleafCmsDS" pool-name="BroadleafCmsDS_Pool" enabled="true" use-java-context="true" use-ccm="true">
 <connection-url>jdbc:mysql://localhost:3306/broadleaf</connection-url>
 <driver>mysql</driver>
 <security>
  <user-name>root</user-name>
  <password>admin</password>
 </security>
 <timeout>
  <idle-timeout-minutes>0</idle-timeout-minutes>
  <query-timeout>600</query-timeout>
 </timeout>
</datasource>

Step#2: Update core/src/main/resources/META-INF/persistence.xml as follows to use DataSources configured in JBossAS7.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
             
    <persistence-unit name="blPU" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>java:jboss/datasources/BroadleafDS</non-jta-data-source>
        <exclude-unlisted-classes/>
    </persistence-unit>
    
    <persistence-unit name="blSecurePU" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>java:jboss/datasources/BroadleafSecureDS</non-jta-data-source>
        <exclude-unlisted-classes/>
    </persistence-unit>

    <persistence-unit name="blCMSStorage" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>java:jboss/datasources/BroadleafCmsDS</non-jta-data-source>
        <exclude-unlisted-classes/>
    </persistence-unit>
</persistence>

Step#3: Update site/src/main/webapp/WEB-INF/applicationContext.xml as follows:

<bean id="blMergedDataSources" class="org.springframework.beans.factory.config.MapFactoryBean">
 <property name="sourceMap">
  <map>
   <entry key="java:jboss/datasources/BroadleafDS" value-ref="webDS"/>
   <entry key="java:jboss/datasources/BroadleafSecureDS" value-ref="webSecureDS"/>
   <entry key="java:jboss/datasources/BroadleafCmsDS" value-ref="webStorageDS"/>
  </map>
 </property>
</bean>

Now if you deploy the app you will get the following error:

ERROR Error creating bean with name ‘blMergedDataSources’ defined in resource loaded from byte array: Cannot resolve reference to bean ‘webDS’ while setting bean property ‘sourceMap’ with key [TypedStringValue: value [java:jboss/datasources/BroadleafDS], target type [null]]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘webDS’: Post-processing of the FactoryBean’s object failed; nested exception is java.lang.IllegalArgumentException: warning no match for this type name: org.broadleafcommerce.profile.core.service.CustomerAddressService [Xlint:invalidAbsoluteTypeName]

 Step#4: Create jboss-deployment-structure.xml in site/src/main/webapp/WEB-INF/ folder.

<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0">
   <deployment>
      <dependencies>
         <module name="org.jboss.ironjacamar.jdbcadapters" />
      </dependencies>
      <exclusions>
            <module name="org.apache.commons.logging"/>
            <module name="org.apache.log4j"/>
            <module name="org.jboss.logging"/>
            <module name="org.jboss.logmanager"/>
            <module name="org.jboss.logmanager.log4j"/>
            <module name="org.slf4j"/>
      </exclusions>
   </deployment>
</jboss-deployment-structure>

Now if you try to deploy the app you will get the following error because JBossAS7 comes with Hibernate4 and application is using some hibernate3 features.

 @CollectionOfElements
 @JoinTable(name = "BLC_CATEGORY_IMAGE", joinColumns = @JoinColumn(name = "CATEGORY_ID"))
 @MapKey(columns = { @Column(name = "NAME", length = 5, nullable = false) })
 @Column(name = "URL")
 @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
 @BatchSize(size = 50)
 @Deprecated
 protected Map<String, String> categoryImages = new HashMap<String, String>(10);

org.hibernate.MappingException: Could not determine type for: java.util.Map, at table: BLC_CATEGORY, for columns: [org.hibernate.mapping.Column(URL)] 

So let us install hibernate3 module in JBossAS7 and use it.

Step#5: Install Hibernate 3 module in JBoss AS 7. 

Copy the following jars(you can get these from site.war file) into jboss-as-7.1.1.FINAL/modules/org/hibernate/3/ folder.

antlr-2.7.6.jar
 commons-collections-3.2.1.jar
 dom4j-1.6.1.jar
 hibernate-commons-annotations-3.2.0.Final.jar
 hibernate-core-3.6.10.Final.jar
 hibernate-entitymanager-3.6.10.Final.jar
 javassist-3.16.1-GA.jar

Create module.xml in jboss-as-7.1.1.FINAL/modules/org/hibernate/3/ folder.

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="org.hibernate" slot="3">
    <resources>
        <resource-root path="hibernate-core-3.6.10.Final.jar"/>  
        <resource-root path="javassist-3.16.1-GA.jar"/>
        <resource-root path="antlr-2.7.6.jar"/>  
        <resource-root path="commons-collections-3.2.1.jar"/>  
        <resource-root path="dom4j-1.6.1.jar"/>  
        <!-- Insert other Hibernate 3 jars to be used here -->
  <resource-root path="hibernate-commons-annotations-3.2.0.Final.jar"/>
  <resource-root path="hibernate-entitymanager-3.6.10.Final.jar"/>
    </resources>
    <dependencies>
        <module name="org.jboss.as.jpa.hibernate" slot="3"/>
        <module name="asm.asm"/>
        <module name="javax.api"/>
        <module name="javax.persistence.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.validation.api"/>
        <!-- <module name="org.apache.ant"/> -->
        <module name="org.infinispan" optional="true"/>
        <module name="org.javassist"/>
        <module name="org.slf4j"/>
    </dependencies>
</module>

Step#6: Tell JBoss to use hibernate 3 module. Update core/src/main/resources/META-INF/persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
 <persistence-unit name="blPU" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>java:jboss/datasources/BroadleafDS</non-jta-data-source>
        <exclude-unlisted-classes/>
        <properties>
         <property name="jboss.as.jpa.providerModule" value="org.hibernate:3" />
         <property name="jboss.as.jpa.managed" value="false" />
        </properties>
    </persistence-unit>
    
    <persistence-unit name="blSecurePU" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>java:jboss/datasources/BroadleafSecureDS</non-jta-data-source>
        <exclude-unlisted-classes/>
        <properties>
         <property name="jboss.as.jpa.providerModule" value="org.hibernate:3" />
         <property name="jboss.as.jpa.managed" value="false" />
        </properties>
    </persistence-unit>

    <persistence-unit name="blCMSStorage" transaction-type="RESOURCE_LOCAL">
        <non-jta-data-source>java:jboss/datasources/BroadleafCmsDS</non-jta-data-source>
        <exclude-unlisted-classes/>
        <properties>
         <property name="jboss.as.jpa.providerModule" value="org.hibernate:3" />
         <property name="jboss.as.jpa.managed" value="false" />
        </properties>
    </persistence-unit>
</persistence>

Enjoy 🙂

Spring3+JPA2+JavaEE6AppServer = Confusion Over Configuration

Spring is great, JavaEE6 is great and latest JavaEE6 Application servers are also great. This post is not a rant on Spring Vs JavaEE6, but my experience of porting a Spring3+JPA2(Hibernate) application on JBoss AS-7.1 App Server.

My application requirement is very simple: Developing a couple of SOAP based webservices using Spring3.1 and JPA2(Hibernate) and host it on JBoss AS 7.1.

So I started creating a multi-module maven project with one jar module containing the service implementations using Spring & JPA and another war module which exposes those services as SOAP based webservices. But the key part is services needs to talk to multiple databases for some of the service methods.

 I am aware of JPA2 integration support from Spring without persistence.xml and cool packagesToScan attribute which makes life a bit easier. I configured 2 dataSources, 2 LocalContainerEntityManagerFactoryBeans, registered 2 JpaTransactionManagers and enabled Annotation based Transaction Management Support.

	<tx:annotation-driven transaction-manager="txnManager1"/>
<tx:annotation-driven transaction-manager="txnManager2"/>

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/><!-- This will throw error because it found multiple EntityManagerFactory beans -->

<bean id="txnManager1"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="emf1"/>

<bean id="txnManager2"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="emf2"/>

<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sivalabs1PU"></property>
<property name="dataSource" ref="dataSource1"></property>
<property name="jpaVendorAdapter">
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${hibernate.show_sql}"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="packagesToScan" value="com.sivalabs.springdemo.entities"></property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>

</bean>

<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sivalabs2PU"></property>
<property name="dataSource" ref="dataSource2"></property>
<property name="jpaVendorAdapter">
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${hibernate.show_sql}"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="packagesToScan" value="com.sivalabs.springdemo.entities"></property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>

</bean>

<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${node1.jdbc.driverClassName}"></property>
<property name="url" value="${node1.jdbc.url}"></property>
<property name="username" value="${node1.jdbc.username}"></property>
<property name="password" value="${node1.jdbc.password}"></property>
</bean>

<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${node2.jdbc.driverClassName}"></property>
<property name="url" value="${node2.jdbc.url}"></property>
<property name="username" value="${node2.jdbc.username}"></property>
<property name="password" value="${node2.jdbc.password}"></property>
</bean>

After this I realized to bind Entitymanager with the correct PersistenceUnit I need to give persistenceUnitName to LocalContainerEntityManagerFactoryBean.

	
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits" >
<map>
<entry key="unit1" value="Sivalabs1PU"/>
<entry key="unit2" value="Sivalabs2PU"/>
</map>
</property>
</bean>

<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sivalabs1PU"></property>
<property name="dataSource" ref="dataSource1"></property>
....
....
</bean>

<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sivalabs2PU"></property>
<property name="dataSource" ref="dataSource2"></property>
....
....
</bean>

Then in my Service Bean EntityManagers and transaction managers are glued together as follows:

@Service
public class AdminUserService implements UserService
{
@PersistenceContext(unitName="Sivalabs1PU")
private EntityManager sivalabs1EM;
@PersistenceContext(unitName="Sivalabs2PU")
private EntityManager sivalabs2EM;

@Override
@Transactional("txnManager1")
public List<User> getAllUsersFromSivalabs1DB() {
return sivalabs1EM.createQuery("from User", User.class).getResultList();
}

@Override
@Transactional("txnManager2")
public List<User> getAllUsersFromSivalabs2DB() {
return sivalabs2EM.createQuery("from User", User.class).getResultList();
}

}

With this setup now I got the Exception saying “No persistence unit with name ‘Sivalabs1PU’ found“. Then after some googling I created META-INF/persistence.xml file as follows:

<persistence>

<persistence-unit name="Sivalabs1PU" transaction-type="RESOURCE_LOCAL">
</persistence-unit>

<persistence-unit name="Sivalabs2PU" transaction-type="RESOURCE_LOCAL">
</persistence-unit>

</persistence>

Now the persistence unit name error got resolved and got other Exception saying “User is not mapped [from User]“. The User class is annotated with @Entity and is in “com.sivalabs.springdemo.entities” package which I configured to “packagesToScan” attribute. I didn’t understand why “packagesToScan” attribute is not working which is working fine without persistence.xml. So for time being I configured entity classes in persistence.xml file.

<persistence>

<persistence-unit name="Sivalabs1PU" transaction-type="RESOURCE_LOCAL">
<class>com.sivalabs.springdemo.entities.User</class>
</persistence-unit>

<persistence-unit name="Sivalabs2PU" transaction-type="RESOURCE_LOCAL">
<class>com.sivalabs.springdemo.entities.User</class>
</persistence-unit>

</persistence>

Finally when I ran my JUnit Test which invokes AdminUserService methods everything looks good and working fine. Then I deployed the war file on JBoss AS 7.1 Server then again got a bunch of errors. JBoss is complaining that “Connection cannot be null when ‘hibernate.dialect’ not set” …. “[PersistenceUnit: Sivalabs1PU] Unable to build EntityManagerFactory”.

After thinking for a couple of minutes, I understood that JBoss server is trying to do what it is supposed to do with “Convention Over Configuration” rules. JBoss is trying to create EntityManagerFactory because it found META-INF/persistence.xml in classpath. But as it doesn’t contain jdbc connection details its throwing Error. 

Again after some googling I found we can rename persistence.xml to something else(spring-persistence.xml) and hook up this new name with Spring as follows:

	<bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sivalabs1PU"></property>
<property name="persistenceXmlLocation" value="classpath:META-INF/spring-persistence.xml"/>
<property name="dataSource" ref="dataSource1"></property>
....
....
</bean>

<bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sivalabs2PU"></property>
<property name="persistenceXmlLocation" value="classpath:META-INF/spring-persistence.xml"/>
<property name="dataSource" ref="dataSource2"></property>
....
....
</bean>

Finally I got this application working on my JBoss AS 7.1 successfully(Still I don’t know how many other holes are there that I haven’t yet found).

But here I didn’t understand few Spring concepts:
1. When I try to give persistenceUnitName why Spring is checking for that name to be existed in persistence.xml? Anyway that persistence.xml doesn’t contain anything exception the unit-name!!

2. Why packagesToScan mechanism is failing when used with persistence.xml? Is it a Spring Bug?

Everything seems to be working fine except one thing is missing, a smile on my face which usually I have when working with Spring and Tomcat 🙁

I like Spring framework very much and I am using it since 2006 and I do enjoy while writing Spring code. That doesn’t mean I don’t like CDI, EJB3, JAX-RS 🙂

 Anyway, with all the above exercise I feel like Spring3+JPA2+JavaEE6AppServer=Confusion Over Configuration and it is my(an average java developer) opinion only.

Again say one more time : Spring is great, JavaEE6 is great and latest JavaEE6 Application servers are also great :-).

RESTEasy Tutorial Part 3 – Exception Handling

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling

Exception Handling is an obvious requirement while developing software application. If any error occured while processing user request we should show the user an error page with details like brief exception message, error code(optional), hints to correct the input and retry(optional) and actual root cause(optional). This is applicable to RESTful web services also.

But putting try-catch-finally blocks all around the code is not a good practice. We should design/code in such a way that if there is any unrecoverable error occured then the code should throw that exception and there should an exception handler to catch those exceptions and extract the error details and give a proper error response to the client with all the error details.

RESTEasy provides such ExceptionHandler mechanism which simplifies the ExceptionHandling process.

In this part I will show you how we can use RESTEasy’s ExceptionHandlers to handle Exceptions.

Step#1: Create Application Specific Exceptions.

Step#2: Create ExceptionHandlers by implementing ExceptionMapper interface.

Step#3: Update UserResource.getUserXMLById() method to validate user input and throw respective exceptions.

Step#4: Test the UserResource.getUserXMLById() service method by issueing following requests.


Important things to note:
As Spring is creating the necessary objects we should let Spring know about @Provider classes to get them registered with RESTEasy. We can do this in two ways.

a)Annotate Provider classes with @Component

b)Using component-scan’s include-filter.

<context:component-scan base-package=”com.sivalabs.springdemo”>
         <context:include-filter expression=”javax.ws.rs.ext.Provider” type=”annotation”/>
</context:component-scan>

RESTEasy Tutorial Part-2: Spring Integration

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling
RESTEasy provides support for Spring integration which enables us to expose Spring beans as RESTful WebServices.

Step#1: Configure RESTEasy+Spring dependencies using Maven.

Step#2: Configure RESTEasy+Spring in web.xml


		
   
    org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
  
  
    org.jboss.resteasy.plugins.spring.SpringContextLoaderListener
  
  
    Resteasy
    org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
  
  
    Resteasy
    /rest/*
  
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
    resteasy.servlet.mapping.prefix
    /rest
  

  
        resteasy.scan
        false
    

Step#3: Create a Spring Service class UserService and update UserResource to use UserService bean.

Step#4: Same JUnit TestCase to test the REST Webservice described in Part-1.

Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.
2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*
3. While using Spring integration set resteasy.scan to false or don’t configure resteasy.scan parameter at all.
Otherwise you may get REST Resource instances(UserResource) from RestEasy instead of Spring container. While running JUnit Tests I observed this random behavior.

4. You should register REST Resource as Spring bean by annotating with @Component or @Service.

RESTEasy Tutorial Part-1: Basics

 

RESTEasy Tutorial Series

RESTEasy Tutorial Part-1: Basics

RESTEasy Tutorial Part-2: Spring Integration

RESTEasy Tutorial Part 3 – Exception Handling
RESTEasy is a JAX-RS implementation from JBoss/RedHat and is in-built in JBoss 6 onwards.
Here I am going to show you how to develop a Simple RESTful Web Services application using RESTEasy and JBossAS7.1.1.FINAL.

Step#1: Configure RESTEasy dependencies using Maven.

Step#2: Configure RESTEasy in web.xml

Step#3: Create User domain class, MockUserTable class to store User objects in-memory for testing purpose and UserResource class to expose CRUD operations on User as RESTful webservices.

Step#6: JUnit TestCase to test the REST Webservice.

Step#7: To test the REST service we can use the REST Client Tool. 
You can download REST Client Tool at http://code.google.com/a/eclipselabs.org/p/restclient-tool/

Important Things to Keep in mind:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Listener should be registered before any other listener.

2. You should configure resteasy.servlet.mapping.prefix <context-param> if the HttpServletDispatcher servlet url-pattern is anything other than /*


3. Keep visiting my blog 🙂