Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

From a command prompt or shell change directory to <brokerage_home> and run the ant command. This will build the war, har and ear files and place them in the <brokerage_home>\jboss-artefact directory. The war created by the ant build contains a JBoss specific deployment descriptor jboss-web.xml file in the WEB-INF directory of the WAR. The HAR contains a JBoss specific hibernate-service.xml file in the META-INF directory and the EAR contains a JBoss specific deployment descriptor jboss-app.xml. These files are shown below.

Code Block
xml
xml
borderStylesolid
titlejboss-web.xmlxml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <context-root>/brokerage</context-root>
  <resource-ref>
      <res-ref-name>jdbc/HibernateDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <jndi-name>jdbc/HibernateDS</jndi-name>
  </resource-ref>
</jboss-web>

The resource-ref element is used to map the resource referred to by the name jdbc/HibernateDB in the web.xml file to the resource with the JNDI name java:jdbc/ HibernateDS, for example MySQL datasource.

Code Block
xml
xml
borderStylesolid
titlehibernate-service.xmlxml
<?xml version="1.0" encoding="UTF-8"?>
<server>
    <mbean code="org.jboss.hibernate.jmx.Hibernate"
           name="jboss.har:service=Hibernate">
        <attribute name="DatasourceName">java:jdbc/HibernateDS</attribute>

        <attribute name="Dialect">
            org.hibernate.dialect.MySQLDialect
        </attribute>
        <attribute name="SessionFactoryName">
            java:/hibernate/BrokerageSessionFactory
        </attribute>
        <attribute name="CacheProviderClass">
            org.hibernate.cache.HashtableCacheProvider
        </attribute>
         <!-- <attribute name="ScanForMappingsEnabled">true</attribute> -->
        <attribute name="ShowSqlEnabled">true</attribute>
    </mbean>
</server>

...

The hibernate-service.xml file should be present in the META-INF directory of the EAR.

Code Block
xml
xml
borderStylesolid
titlejboss-app.xmlxml
<!DOCTYPE jboss-app PUBLIC "-//JBoss//DTD J2EE Application 1.4//EN" "http://www.jboss.org/j2ee/dtd/jboss-app_4_0.dtd">
<jboss-app>
    <module>
        <har>brokerage.har</har>
    </module>
</jboss-app>

...

The following example shows the deployment descriptor web.xml used in this application. The web.xml file located in the WEB-INF directory of brokerage.war is the deployment descriptor where you specify, among other things, the servlets name and default JSP for the application.

Code Block
xml
xml
borderStylesolid
titleweb.xmlxml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>brokerage</display-name>
    <servlet>
        <display-name>Trade-Dispatcher</display-name>
        <servlet-name>TradeDispatcher</servlet-name>
        <servlet-class>com.dev.trade.servlet.TradeDispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/stocks</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/userstocks</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/buy</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/sell</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>TradeDispatcher</servlet-name>
        <url-pattern>/register</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
  <welcome-file>/login.jsp</welcome-file>
    </welcome-file-list>
    <error-page>
     <exception-type>javax.servlet.ServletException</exception-type>
     <location>/error.jsp</location>
    </error-page>

    <resource-ref>
        <res-ref-name>jdbc/HibernateDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
</web-app>

...

Now, you need to define a data source deployment plan. For your convenience, the sample application already provides a deployment plan called mysql-geronimo-plan.xml located in the <brokerage_home>\plan directory. The following example shows the content of this deployment plan.

Code Block
xml
xml
borderStylesolid
titlemysql-geronimo-plan.xmlxml
<?xml version="1.0" encoding="UTF-8"?>
<connector xmlns="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2">
  <dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
    <dep:moduleId>
	  <dep:groupId>user</dep:groupId>
	  <dep:artifactId>database-pool-HibernateDB</dep:artifactId>
	  <dep:version>2.0</dep:version>
	  <dep:type>car</dep:type>
	</dep:moduleId>
	<dep:dependencies>
	  <dep:dependency
	    <dep:groupId>mysql</dep:groupId>
		<dep:artifactId>mysql-connector-java</dep:artifactId>
		<dep:version>3.1.14-bin</dep:version>
		<dep:type>jar</dep:type>
	  </dep:dependency>
	</dep:dependencies>
  </dep:environment>
  <resourceadapter>
    <outbound-resourceadapter>
      <connection-definition>
        <connectionfactory-interface>javax.sql.DataSource</connectionfactory-interface>
        <connectiondefinition-instance>
          <name>HibernateDS</name>
          <config-property-setting name="Password">password</config-property-setting>
          <config-property-setting name="CommitBeforeAutocommit">false</config-property-setting>
          <config-property-setting name="Driver">com.mysql.jdbc.Driver</config-property-setting>
          <config-property-setting name="ExceptionSorterClass">org.tranql.connector.AllExceptionsAreFatalSorter</config-property-setting>
          <config-property-setting name="UserName">root</config-property-setting>
          <config-property-setting name="ConnectionURL">jdbc:mysql://localhost:3306/adi</config-property-setting>
          <connectionmanager>
            <local-transaction/>
            <single-pool>
              <max-size>10</max-size>
              <min-size>0</min-size>
              <blocking-timeout-milliseconds>5000</blocking-timeout-milliseconds>
              <idle-timeout-minutes>30</idle-timeout-minutes>
              <match-one/>
            </single-pool>
          </connectionmanager>
        </connectiondefinition-instance>
      </connection-definition>
    </outbound-resourceadapter>
  </resourceadapter>
</connector>

...

TradeDAO.java is located in the <brokerage_home>/src/com/dev/trade/dao directory.

Code Block
java
java
borderStylesolid
titleExcerpt from TradeDAO.java for JBossjava
package com.dev.trade.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.dev.trade.bo.Stock;
import com.dev.trade.bo.User;
import com.dev.trade.bo.UserStock;
import com.dev.trade.exception.DBException;
import com.dev.trade.util.HibernateUtil;

public class TradeDAO {

	SessionFactory factory  = null;
	Session session = null;

	public TradeDAO() throws Exception {

		try {
			InitialContext ctx = new InitialContext();
		    factory  = (SessionFactory)ctx.lookup("java:hibernate/BrokerageSessionFactory");

		} catch (NamingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public User getUserByUserId(String userId) throws DBException {

		session = factory.getCurrentSession();
		Query q = session.createQuery("from User u where u.userId=:userId");
		q.setString("userId", userId);
		return (User) q.uniqueResult();

	}
	...

...

Modify the first part of TradeDAO.java to match the changes in the following excerpt.

Code Block
java
java
borderStylesolid
titleExcerpt from TradeDAO.java for Geronimojava
package com.dev.trade.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dev.trade.bo.Stock;
import com.dev.trade.bo.User;
import com.dev.trade.bo.UserStock;
import com.dev.trade.exception.DBException;
import com.dev.trade.util.HibernateUtil;

public class TradeDAO {


      Session session = null;

       public TradeDAO() throws Exception {

        }

       public User getUserByUserId(String userId) throws DBException {

            session = HibernateUtil.getCurrentSession();
                Query q = session.createQuery("from User u where u.userId=:userId");
                q.setString("userId", userId);
              return (User) q.uniqueResult();

       }
       ...

...

As mentioned above we will use this class to create the SessionFactory and provide the application with Hibernate sessions. The source code for the class is given below

Code Block
java
java
borderStylesolid
titleHibernateUtil.java for Geronimojava
package com.dev.trade.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html}.
 */
public class HibernateUtil {

    /** location of the Hibernate Configuration File */
    private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";

    /** Holds a single instance of Session */
    private static final ThreadLocal threadLocal = new ThreadLocal();

    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();

    /** The single instance of hibernate SessionFactory */
    private static org.hibernate.SessionFactory sessionFactory;

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getCurrentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null || ! session.isConnected()) {
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%");
                    e.printStackTrace();
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();


        if (session != null) {
            session.close();
        }
    }



}

...

In this class there will also be a difference in getting the SessionFactory. In JBoss we get it from the JNDI Context but in Geronimo we will get it through the utility class.

Code Block
java
java
borderStylesolid
titledoGet method for JBossjava
protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

   Session hsession = null;
   try {
         InitialContext ctx = new InitialContext();
         SessionFactory factory  =  (SessionFactory)ctx.lookup("java:hibernate/BrokerageSessionFactory");
         hsession = factory.openSession();
       } catch (NamingException e1) {
            e1.printStackTrace();
       }

    Transaction tr = hsession.beginTransaction();

TradeDispatcherServlet.java is located in the <brokerage_home>/src/com/dev/trade/servlet directory. Replace the doGet method for the one shown in the following example.

Code Block
java
java
borderStylesolid
titledoGet method for Geronimojava
protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {

    Transaction tr = HibernateUtil.getCurrentSession().getTransaction();
    tr.begin();

Hibernate comes with transaction manager lookup classes for many application servers. Unfortunately Hibernate 3.2 does not have a lookup class specific for Apache Geronimo, so we need to write our own. The code for the Geronimo specific transaction manager lookup is shown in the following example.

Code Block
java
java
borderStylesolid
titleGeronimoTransactionManagerLookupjava
package org.hibernate.transaction;

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import javax.transaction.TransactionManager;
import org.hibernate.HibernateException;
import org.hibernate.transaction.TransactionManagerLookup;

import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.KernelRegistry;
import org.apache.geronimo.kernel.proxy.ProxyManager;

public class GeronimoTransactionManagerLookup implements
        TransactionManagerLookup {

    public static final String UserTransactionName = "java:comp/UserTransaction";

    public Object getTransactionIdentifier(Transaction arg0) {
		return null;
    }

    public TransactionManager getTransactionManager(Properties props) throws HibernateException {
       /*
         * try { Kernel kernel = KernelRegistry.getSingleKernel(); ProxyManager
         * proxyManager = kernel.getProxyManager(); AbstractNameQuery query =
         * new AbstractNameQuery(TransactionManager.class.getName()); Set names =
         * kernel.listGBeans(query); AbstractName name = null; for (Iterator it =
         * names.iterator(); it.hasNext();) name = (AbstractName) it.next();
         * Object transMg = (Object) proxyManager.createProxy(name,
         * TransactionManager.class); return (TransactionManager)transMg; }catch
         * (Exception e) { e.printStackTrace(); System.out.println(); throw new
         * HibernateException("Geronimo Transaction Manager Lookup Failed", e); }
         */
       try {
       Kernel kernel = KernelRegistry.getSingleKernel();
       AbstractNameQuery query = new AbstractNameQuery(TransactionManager.class.getName ());
       Set<AbstractName> names = kernel.listGBeans(query);
       if (names.size() != 1) {
           throw new IllegalStateException("Expected one transaction manager, not " + names.size());
       }
       AbstractName name = names.iterator().next();
       TransactionManager transMg = (TransactionManager)
       kernel.getGBean(name);
       return (TransactionManager)transMg;
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println();
           throw new HibernateException("Geronimo Transaction Manager Lookup Failed", e);
       }
   }

    public String getUserTransactionName() {
        return UserTransactionName;
    }
}

...

Now you need to create the hibernate configuration file hibernate-cfg.xml. Inside this file you will specify the required hibernate configuration attributes. Note that the hibernate-service.xml in JBoss is for doing the same thing. For your convenience this file is also provided with the sample application in the <brokerage_home>/hibrenate directory.

Code Block
xml
xml
borderStylesolid
titlehibernate-cfg.xmlxml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
 <!-- properties -->
 <property name="connection.datasource">java:comp/env/jdbc/HibernateDB</property>
 <property name="hibernate.transaction.manager_lookup_class">
    org.hibernate.transaction.GeronimoTransactionManagerLookup
 </property>

  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

 <!-- Disable the second-level cache  -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.JTASessionContext</property>
 <!-- Echo all executed SQL to stdout -->
 <property name="hibernate.show_sql">true</property>

 <!-- Drop and re-create the database schema on startup -->
<!--<property name="hibernate.hbm2ddl.auto">create</property> -->

 <!-- mapping files -->
 <mapping resource="Stock.hbm.xml"/>
 <mapping resource="UserStock.hbm.xml"/>
 <mapping resource="User.hbm.xml"/>

 </session-factory>
</hibernate-configuration>

...

One last step before building is to create a geronimo-web.xml file which is the Geronimo specific deployment descriptor as illustrated in the following example. Once again, for your convenience this file is also provided with the sample application in the <brokerage_home>/web/descriptors/geronimo directory.

Code Block
xml
xml
borderStylesolid
titlegeronimo-web.xmlxml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-1.1" xmlns:naming="http://geronimo.apache.org/xml/ns/naming-1.1">
    <dep:environment xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.1">
	    <dep:moduleId>
		    <dep:groupId>BrokerageApp</dep:groupId>
			<dep:artifactId>MySqlDS</dep:artifactId>
			<dep:version>2.0</dep:version>
			<dep:type>car</dep:type>
		</dep:moduleId>

		<dep:dependencies>
		    <dep:dependency>
		        <dep:groupId>user</dep:groupId>
			    <dep:artifactId>database-pool-HibernateDB</dep:artifactId>
			    <dep:version>2.0</dep:version>
			    <dep:type>car</dep:type>
			</dep:dependency>
		</dep:dependencies>

		<dep:hidden-classes>
		    <dep:filter>org.springframework</dep:filter>
			<dep:filter>META-INF/spring</dep:filter>
			<!--dep:filter>antlr</dep:filter-->
		</dep:hidden-classes>
	</dep:environment>

	<context-root>/brokerage</context-root>

    <resource-ref>
        <ref-name>jdbc/HibernateDB</ref-name>
        <resource-link>HibernateDS</resource-link>
    </resource-ref>
</web-app>

...