Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP Open Source Middleware Stacks Blueprint: J2EE Application Server on HP ProLiant Servers with JBoss, MySQL or Oracle, and SLES10

Installing and Configuring the J2EE Application Server Middleware Stack Components

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

This section explains how to install and configure the J2EE Application Server Middleware Stack components and other related components. After installing the Linux distribution, proceed with the installation of the J2EE Application Server stack components. All components are distributed as RPM packages or binaries, therefore, you can install and remove all the components separately. The installation processes are described in the following sections.

Installing and Configuring Sun JDK

The following procedure provides the steps for installing and configuring a Sun Java Development Kit (JDK), as appropriate for your hardware environment.

  1. Download the hardware appropriate Sun JDK from the Java website and install as follows (see Table 1 for the correct version and website link):

    Change to the Sun JDK install package directory, as appropriate for your system, and install the package by entering the following:

    # chmod 755 jdk-1_5_0_10-linux-amd64-rpm.bin

    # ./jdk-1_5_0_10-linux-amd64-rpm.bin

  2. Create symbolic links for the Sun JDK by entering the following command:

    # ln -s /usr/java/jdk1.5.0_10 /usr/local/jdk

  3. The JAVA_HOME environment variable must be properly set before stack components, such as JBoss and Tomcat, can begin executing.

    Both bash and cshell use a different syntax for setting environment variables. To export the JAVA_HOME environment variable, modify the system file that is appropriate for your shell, java.sh or java.csh, located in the /etc/profile.d directory.

    To export the JAVA_HOME environment variable, modify the system file that is appropriate for your shell (/etc/profile.d/java.sh or /etc/profile.d/java.csh):

    For the java.sh file add the following contents:
    export JAVA_HOME=/usr/local/jdk
    export PATH=$JAVA_HOME/bin:$PATH
    For the java.csh file add the following contents:
    setenv JAVA_HOME /usr/local/jdk
    setenv PATH $JAVA_HOME/bin:$PATH
  4. Log out of the system, and then log back in to invoke the revised profile.

  5. Verify the Sun JDK installation was successful by entering the following command:

    # java –version

    The following messages appear:

    java version "1.5.0_10"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_10-b03)
    Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_10-b03, mixed mode)

Installing and Configuring JBoss

Installing JBoss

The following procedure provides the steps for installing and configuring JBoss:

  1. Verify that a JDK is installed before attempting to install JBoss and the JAVA_HOME environment variable is set to JDK, not JRE.

  2. Verify that Tomcat is not already installed on the system, and if it is, remove it.

    The JBoss Enterprise Application Server Platform contains an embedded Tomcat Server, which interferes with the standalone version.

  3. Download the JBoss Enterprise Application Platform package. See Table 1 for the correct version and Web link.

  4. Follow the JBoss instructions, provided at the JBoss website, to install and configure the JBoss Application Server.

NOTE: The remainder of this blueprint assumes the JBoss Enterprise Application Server is installed in the /usr/local/jboss directory. If it is installed in a different location, modify all commands as appropriate.

Configuring JBoss

After installing the JBoss Application Server, perform the following steps:

  1. Set the environment variable $JBOSS_HOME to the JBoss installation directory, the default is /usr/local/jboss, and modify the system file you previously created (jboss.sh or jboss.csh) to export the following environment variable:

    PATH=$JAVA_HOME/bin:$PATH

    • For the jboss.sh file include the following line:

      export JBOSS_HOME=/usr/local/jboss

    • For the jboss.csh file include the following line:

      setenv JBOSS_HOME /usr/local/jboss

    NOTE: You can edit the $JBOSS_HOME/bin/run.conf file to modify the JBoss run time parameters, which include Java Virtual Machine (VM) options. For example, to increase the memory consumed by JBoss from the default of 128MB to 1024MB, set the following line in the run.conf file:

    JAVA_OPTS="-server -Xms1024m -Xmx1024m"

    Choose a value appropriate for your system configuration. For detailed information, see the JBoss Application Server documentation.

  2. Start the JBoss Application Server using a non-root user and create a user and a group both called jboss, by entering the following:

    # groupadd -r jboss

    # useradd -r -m -g <JBOSS_GROUP_ID> -d /home/jboss jboss

  3. Change the user and group ownership for the $JBOSS_HOME/server directory by entering the following:

    # chown -R jboss:jboss $JBOSS_HOME/server

  4. Test the JBoss installation by entering the following:

    # su -l –m jboss -c '$JBOSS_HOME/bin/run.sh -c default -b 0.0.0.0'

  5. Check the standard output and verify that no error messages appear.

    The output should be similar to the following sample log:

    23:18:10,415 INFO  [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=.../deploy/jmx-console.war/
    23:18:10,556 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-0.0.0.0-8080
    23:18:10,568 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-0.0.0.0-8009
    23:18:10,574 INFO  [Server] JBoss (MX MicroKernel) [4.2.0.GA (build: SVNTag=JBPAPP_4_2_0_GA date=200706281411)] Started in 13s:147ms
  6. Verify the JBoss installation by opening a browser and entering the following URL:

    http://<YOUR_HOSTNAME>:8080/

    Figure 4 JBoss Test Page

    JBoss Test Page
  7. Verify the installation of the JBoss-embedded Hibernate package by changing to the $JBOSS_HOME/server/default/lib directory and checking for the hibernate3.jar file.

    # ls ./$JBOSS_HOME/server/default/lib

  8. Shutdown the server by entering the following:

    # $JBOSS_HOME/bin/shutdown.sh -u<USER_NAME> -p<PASSWORD> -S

    NOTE: Set the user name and password in $JBOSS_HOME/server/<YOUR_CONFIG>/conf/props/jmx-console-users.properties before running the shutdown script.

Monitor JBoss

JBoss provides two Web applications for monitoring runtime status, the Java Management Extensions (JMX) console and the Web console. The Web Console includes monitoring enhancements in addition to the JMX Console tree view. For more information, see the JBoss Web Console page located at:

http://jboss.org/wiki/Wiki.jsp?page=WebConsole

Using the JBoss JMX Console

The JBoss JMX console provides a basic view of the JMX MBeans and allows you to perform operations such as starting and stopping components and changing component configurations.

You can open the JMX Web console application by opening a browser and navigating to the following URL:

http://<YOUR_HOSTNAME>:8080/jmx-console

The JMX Agent View is displayed as in Figure 5.

Figure 5 JMX Agent View

JMX Agent View

For example, display the JNDI tree of the current namespaces by performing the following steps:

  1. From the JMX Agent View console, select service=JNDIView.

  2. Locate the list operation and click invoke.

    The JNDI Tree View is displayed as in Figure 6.

    This operation can be helpful in determining why a particular EJB name did not resolve.

Figure 6 JNDI Tree View

JNDI Tree View

Once it is restarted, the JBoss server loads the original configurations. Any changes that were made are not persistent.

Using the JBoss Web Console

The JBoss Web console, as displayed in Figure 7, allows you to monitor any string or numeric JMX attribute by performing the following steps:

NOTE: Before using the web console, set the user name and password in the web-console-users.properties file located in the $JBOSS_HOME/server/<YOUR_CONFIG>/deploy/management/console-mgr.sar/ web-console.war/WEB-INF/classes/ directory.

Figure 7 JBoss Web Console

JBoss Web Console
  1. Expand the system tree, located in the left-hand pane, and scroll down to the JMX MBeans view.

  2. Select a particular MBean and double-click it to open and view its attribute list.

  3. Right-click on an attribute to display the pop-up menu and select Graph.

  4. Select Create Monitor to display the creation view.

    After a monitor is created, it appears under the Monitoring tree in the JBoss Management console pane, as displayed in Figure 8.

    Figure 8 JBoss Web Console — Monitor Status

    JBoss Web Console — Monitor Status

    When a threshold is reached, the monitor sends out a JMX notification to the console. For example, the notification should look similar to the following:

    11:18:31,293 INFO  [Server] JBoss (MX MicroKernel) 
    [4.2.0.GA (build: SVNTag=JBPAPP_4_2_0_GA date=200706281411
    11:19:18,263 INFO  [ConsoleAlertListener] zyc-free-memory was 
    triggered for attribute FreeMemory.

    For more information, see the Web Console Monitoring Web page located at:

    http://wiki.jboss.org/wiki/Wiki.jsp?page=WebConsoleMonitoring

Deploy OSMS Components in JBoss

Hot deployment

JBoss provides the hot deployment feature which allows you to deploy or undeploy a package without restarting the server. To hot deploy application packages such as a Java Archive (JAR), Web Service Archive (WAR), and Enterprise Archive (EAR) files, you must move the files to the deploy directory. Once a package has been deployed, you can safely deploy the package again. To undeploy a package, delete the archive file from the deploy directory.

The JBoss server continuously scans the deploy directory for updates, all updated or undeployed components are deployed again automatically. The default deploy directory is server/<CONFIGURATION_FOLDER_NAME>/deploy.

For example, after deploying an EAR file successfully, the related server's standard output should look similar to the following:

22:05:53,125 INFO  [EARDeployer] Init J2EE application: file:/usr/local/jboss-4.2.0.GA/server/default/deploy/CountPortal.ear
22:05:53,285 INFO  [EjbModule] Deploying CounterModule1
22:05:53,335 INFO  [EjbModule] Deploying CounterModule2
22:05:53,388 INFO  [ProxyFactory] Bound EJB Home 'CounterModule1' to jndi 'CounterModule1'
22:05:53,394 INFO  [ProxyFactory] Bound EJB Home 'CounterModule2' to jndi 'CounterModule2'
22:05:53,395 INFO  [EJBDeployer] Deployed: file:/usr/local/jboss-4.2.0.GA/server/default/tmp/deploy/tmp48873CountPortal.ear-contents/CountPortalBeans.jar
22:05:53,420 INFO  [TomcatDeployer] deploy, ctxPath=/countportal, warUrl=.../tmp/deploy/tmp48873CountPortal.ear-contents/countportal-exp.war/
22:05:53,491 INFO  [EARDeployer] Started J2EE application: file:/usr/local/jboss-4.2.0.GA/server/default/deploy/CountPortal.ear

Hot Deploying a WAR file is also supported by JBoss. When the following messages appear, the WAR file is available on the JBoss Enterprise Application Server:

0:42:49,094 INFO  [TomcatDeployer] deploy, ctxPath=/counter-servlet, 
warUrl=.../tmp/deploy/tmp57264counter-servlet-exp.war/
20:42:49,189 INFO  [WSDLFilePublisher] WSDL published to: 
file:/usr/local/JBoss-4.2.0.GA/server/default/data/wsdl/counter-servlet.war/
CounterService.wsdl
20:42:49,208 INFO  [ServiceEndpointManager] WebService started: 
http://10.101.1.68:8080/counter-servlet/Counter

This log displays information about the deployment including the temporary location of the generated Web Service Description Language (WSDL) files. JBoss also displays the URL for the Web service. Displayed in the web service list are all the deployed Web services, the name of the deployment unit, and a link to the WSDL file for that service.

For example, navigate to the Web services site by opening a browser and entering the following URL:

http://<YOUR_HOSTNAME>:8080/jbossws/services

The website displays the following Registered Service endpoints:

ServiceEndpointID

JBoss.ws:context=counter-servlet,endpoint=CounterWS

ServiceEndpointAddress

http://10.101.1.68:8080/counter-servlet/Counter?wsdl

Service Dependencies

To define an MBean as a dependency on another MBean, you must specify the dependency in the element of the service descriptor by using the two elements; depends-list and depends. The following example shows a service descriptor fragment that uses the dependency related elements:

<server>
  <mbean code="com.mbean.SampleService"
    name="trace:service=Sample2">
    <attribute name="Number">9</attribute>
    <depends>trace:service=Sample1</depends>
  </mbean>
</server>

Integrating the J2EE Application Server Stack Components

This section describes the commonly used configurations for the J2EE Application Server stack components.

Configuring the Apache Web Server and Tomcat Connector

The following section explains how to use the mod_jk module from the Apache Jakarta project to connect the Apache Web Server and the Tomcat Web Container.

The Apache Web Server uses URL pattern rules that are defined in the Apache Web Server configuration file, to determine which requests to handle and which to forward. Apache handles content such as static HTML pages, images, and CGI scripts, while the Apache-Tomcat connector (mod_jk) uses the AJP protocol to forward all requests for JSPs, Servlets, and J2EE functionality to JBoss and Tomcat as depicted in Figure 9.

Figure 9 Connecting the Apache Web Server and JBoss Embedded Tomcat

Connecting the Apache Web Server and JBoss Embedded Tomcat

The following example provides the steps to configure Apache Web Server routing requests under the DOCUMENT_ROOT/jsp-examples/ directory to the Tomcat Server:

  1. Download mod_jk from the Apache Software Foundation (see Table 1 for the correct version and website link), and follow the instructions provided to build the mod_jk.so shared library. If necessary, copy the mod_jk.so file into the /usr/lib64/apache2/ directory.

  2. Edit the Apache Web Server configuration file, /etc/apache2/conf/httpd.conf, and then add the following contents:

    #Load mod_jk
    LoadModule jk_module /usr/lib64/apache2/mod_jk.so
    #Configure mod_jk
    JkShmFile /var/log/apache2/memory.shm
    JkWorkersFile /etc/apache2/workers.properties
    JkLogFile /var/log/apache2/mod_jk.log
    JkLogLevel info
    
  3. Insert the following contents below the DocumentRoot line:

    JkMount /jmx-console/* worker1
  4. Create a file named /etc/apache2/workers.properties and add the following contents:

    # Define 1 real worker using ajp13 
    worker.list=worker1 
    # Set properties for worker1 (ajp13) 
    worker.worker1.type=ajp13 
    worker.worker1.host=localhost 
    worker.worker1.port=8009 
    worker.worker1.lbfactor=50 
    worker.worker1.cachesize=10 
    worker.worker1.cache_timeout=600 
    worker.worker1.socket_keepalive=1 
    worker.worker1.socket_timeout=300
  5. To use the JMX console for testing, you must configure it using the following steps:

    1. Go to the $JBOSS_HOME/server/default/conf/props directory and open the jmx-console-users.properties file

    2. Uncomment the following line:

      # admin=admin

  6. If JBoss is not running, start it by entering the following:

    # /usr/local/jboss/run.sh -c default -b 0.0.0.0

  7. Restart Apache by entering the following:

    # /etc/init.d/apache2 restart

  8. Verify that you can connect to JBoss through the standard HTTP port served by Apache by navigating to the website located at:

    http://<YOUR_HOSTNAME>/jmx-console/

  9. At the JMX console security dialog box, enter admin for the username and admin for the password.

    The JMX Agent View is shown in Figure 10.

    Figure 10 JMX Agent View

    JMX Agent View

If there are any errors, check the log files /var/log/apache2/error_log , access_log and /var/log/apache2/mod_jk.log for additional information.

Integrating the Apache Web Server and PHP

To test the installation, perform the following steps:

NOTE: The Apache Web Server that is shipped with SLES10 already includes a built-in PHP module. Therefore, no extra configuration is required for Apache.
  1. Verify that php is installed by entering the following:

    # rpm -q apache2–mod_php5

  2. Create a test file named /srv/www/htdocs/test.php and add the following contents:

    <? 
    ## sample php file 
    phpinfo(); 
    ?>
  3. Verify that PHP works by opening a browser and navigating to the website located at:

    http://<YOUR_HOSTNAME>/test.php

    A Web page containing the PHP version and license numbers is displayed.

Integrating the Apache Web Server and Perl

The mod_perl module integrates a Perl interpreter into the Apache Web Server, allowing you to use Perl when creating Web applications. Use the mod_perl module provided by the Linux distribution.

To test the installation, perform the following steps:

  1. Verify that the mod_perl module is installed by entering the following:

    # rpm -q apache2–mod_perl

  2. Create a sample test file named /srv/www/cgi-bin/test.pl and add the following contents:

    #!/usr/bin/perl 
    print "Content-type: text/plain\n\n"; 
    print "mod_perl rocks!\n";
  3. Assign execute permissions to the file by entering the following:

    # chmod +x /srv/www/cgi-bin/test.pl

  4. Edit the file /etc/sysconfig/apache2 by adding mod_perl to the APACHE_MODULE definition.

  5. Change the DocumentRoot to /srv/www/cgi-bin in the /etc/apache2/default-server.conf file.

  6. Restart Apache by entering the following:

    # /etc/init.d/apache2 restart

  7. Verify that Perl works by opening a browser and navigating to the following URL:

    http://<YOUR_HOSTNAME>/perl/test.pl

    The Web page displays the following message:

    mod_perl rocks!

If there are any errors, check the log files, /var/log/apache2/error.log and /var/log/apache2/access.log for additional information.

Integrating Apache Web Server and Python

The mod_python module embeds the Python environment into the Apache Web Server. Embedding this environment avoids the run-time overhead of invoking the Python environment externally. Use the mod_python module provided by the Linux distribution.

To test the installation, perform the following steps:

  1. Verify the mod_python module is installed by entering the following:

    # rpm -q apache2–mod_python

  2. Create a test file named /srv/www/htdocs/test.py and insert the following contents:

    from mod_python import apache
    def handler(req):
            req.write("mod_python rocks!")
            return apache.OK
  3. Edit the file /etc/apache2/conf.d/python.conf and add the following contents:

    <Directory /srv/www/htdocs>
         AddHandler mod_python .py
         PythonHandler test
         PythonDebug On 
    </Directory>
  4. Add mod_python to the APACHE_MODULE definition in the file /etc/sysconfig/apache2

    NOTE: Check the file /etc/apache2/mime.types. If the line text/x-python py is included in this file, comment out this line by adding # to the beginning of the line.
  5. Restart Apache by entering the following:

    # /etc/init.d/apache2 restart

  6. Verify that Python works by opening a browser and navigating to the following URL:

    http://<YOUR_HOSTNAME>/test.py

    The Web page displays the following message:

    mod_python rocks!

If there are any errors, check the log files /var/log/apache2/error_log and /var/log/apache2/access_log for additional information.

JBoss Database Connectivity

To connect JBoss to a database, a JDBC driver for that particular database is needed. The driver is responsible for translating calls from Java programs to the native protocol that is understood by the database, as depicted in Figure 11.

Figure 11 JBoss JDBC Connection

JBoss JDBC Connection

JBoss uses the data source concept to create database connections. A data source is an XML configuration file that contains details about the target database, such as the database server IP address and login credentials. The JDBC driver connects to the database and the username/password combination is used to log in to the database. Because obtaining a database connection is an expensive operation, JBoss uses ConnectionPools to create a pool of active connections and automatically manage the lifecycle of the individual connections. The size of the pool is configurable in the data source file.

Connecting JBoss and MySQL

The MySQL Database (MySQL) is the leading open source database, and is a widely used and robust data store for J2EE Application Server Middleware environments. MySQL stores relational data and allows fast, simple access and updates to stored data through the standard Java Database Connector (JDBC) APIs that are supplied by MySQL in the form of the Connector/J software. This section provides the steps to connect JBoss to MySQL.

Acquiring the JDBC Drivers

To obtain the JDBC driver, perform the following steps on the JBoss Enterprise Application Server:

  1. Download the MySQL JDBC driver 5.0 located at:

    http://dev.mysql.com/downloads/connector/j/5.0.html

  2. Unzip the downloaded packages by entering the following:

    # tar zxf mysql-connector-java-<VERSION>.bin.tar.gz

    where:

    <VERSION> is the MySQL Java JDBC version.

    For example, mysql-connector-java-5.0.4.tar.gz

  3. Install the JDBC driver for JBoss by entering the following:

    # cp mysql-connector-java-<VERSION>-bin.jar \

    $JBOSS_HOME/server/default/lib

Creating a New Data Source

Create a data source binding for a JDBC driver by performing the following on the JBoss Enterprise Application Server:

  1. Create a data source descriptor file named $JBOSS_HOME/server/default/deploy/mysql-ds.xml and add the following contents:

    <datasources>
      <local-tx-datasource>
        <jndi-name>MysqlDS</jndi-name>
        <connection-url>
        jdbc:mysql://IP_OR_NAME_OF_THE_DB_SERVER:3306/DATABASE_NAME \
        ?autoReconnect=true
        </connection-url>
        <driver-class> com.mysql.jdbc.Driver</driver-class>
        <user-name>USERNAME</user-name>
        <password>PASSWORD</password>
        <max-pool-size>50</max-pool-size>
        <min-pool-size>20</min-pool-size>
        <idle-timeout-minutes>0</idle-timeout-minutes>
        <track-statements>true</track-statements>
      </local-tx-datasource>
    </datasources>

    where:

    <jndi-name> is the logical name by which Java programs running inside JBoss refer to for the connection to the MySQL database.

  2. Replace the variables <DATABASE_NAME>, <IP_OR_NAME_OF_DB_SERVER>, <USERNAME>, and <PASSWORD > with the appropriate values.

    For example:

    <datasources>
      <local-tx-datasource>
        <jndi-name>MysqlDS</jndi-name>
        <connection-url>
        jdbc:mysql://192.168.1.100:3306/mytestdb\
        ?autoReconnect=true
        </connection-url>
        <driver-class> com.mysql.jdbc.Driver</driver-class>
        <user-name>jboss</user-name>
        <password>jboss</password>
        <max-pool-size>50</max-pool-size>
        <min-pool-size>20</min-pool-size>
        <idle-timeout-minutes>0</idle-timeout-minutes>
        <track-statements>true</track-statements>
      </local-tx-datasource>
    </datasources>
Configuring the MySQL Server

Configure the MySQL Server by performing the following steps:

  1. Verify that the MySQL Server is running by entering the following:

    # ps -ef|grep mysqld

    If the MySQL Server is running, a process named mysqld displays in the output; otherwise, enter the following command:

    # /etc/init.d/mysql start

  2. If the database used in the JBoss data source does not exist, create the mytestdb database by entering the following:

    # mysqladmin -u root -p create mytestdb

  3. If the database user in the JBoss data source does not exist, create the user and grant the appropriate privileges by entering the following from the MySQL prompt:

    mysql> grant all on mytestdb.* to jboss@'%.%.%.%' identified by \

    'jboss'; flush privileges;

    The user named jboss with the password jboss is created and granted all operation privileges on the database mytestdb.

Testing MySQL Database Connectivity

To test the connectivity between JBoss and MySQL, perform the following steps on the JBoss Enterprise Application Server:

  1. Create a JSP file named $JBOSS_HOME/server/default/deploy/jmx-console.war/mysqltest.jsp and add the following contents:

    <%@page contentType="text/html" import="java.net.*,java.util.*,org.jboss.jmx.adaptor.model.*,
    java.io.*,java.sql.*,javax.sql.*,javax.naming.*"%>
    <html>
    	<head>
    		<title>JBoss->MySQL Test </title>
    		<link rel="stylesheet" href="style_master.css" type="text/css">
    		<meta http-equiv="cache-control" content="no-cache">
    	</head>
    	<body>
    		<%
    		InitialContext ctx = new InitialContext();
    		DatabaseMetaData dm = null;
    		DataSource ds = (DataSource)
    		ctx.lookup("java:/MysqlDS");
    		Connection conn = null;
    		Statement stmt = null;
    		try {
    		conn = ds.getConnection();
    		dm =conn.getMetaData();
    		out.println("Connected to-> database version "+dm.getDatabaseProductVersion());
    		}catch (Exception sqlex) {
    		out.println(sqlex.getMessage());
    		}finally{
    		conn.close();
    		}
    		%>
    	</body>
    </html>
  2. Edit the $JBOSS_HOME/server/default/conf/props/jmx-console-users.properties file and uncomment the following line:

    #admin=admin

  3. Launch JBoss by entering the following:

    # $JBOSS_HOME/bin/run.sh -b 0.0.0.0 -c default

  4. Verify that JBoss is connecting to MySQL by opening a browser and navigating to the following:

    http://<YOUR_HOSTNAME>:8080/jmx-console/mysqltest.jsp

    The JBoss Connection test page is displayed as in Figure 12.

    Figure 12 JBoss Connecting MySQL Test Page

    JBoss Connecting MySQL Test Page
  5. When prompted for the username and password, enter admin as the value for each.

Connecting JBoss and the Oracle Database

Oracle database (Oracle) is the leading commercial relational database. It is generally used to store and manage sensitive and mission-critical data. As with the MySQL, Oracle can also be used as the persistence layer for J2EE objects created and manipulated by J2EE applications. A JDBC connector for Oracle is needed to integrate an external Oracle Database Server with the JBoss Enterprise Application Server. This section describes the steps for connecting the JBoss Enterprise Application Server to an Oracle 10g Release 2 database.

Acquiring the Oracle JDBC Driver

Perform the following steps on the JBoss Enterprise Application Server:

  1. Download the JDBC driver for Oracle 10g Release 2 located at:

    http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html

    For the Oracle JDBC driver with JDK 1.4 and 1.5, use the ojdbc14.jar file.

  2. Copy the JDBC driver to the JBoss environment by entering the following:

    # cp ojdbc14.jar $JBOSS_HOME/server/default/lib

Creating an Oracle Data Source

To create a data source binding for the Oracle JDBC driver data source, perform the following on the JBoss Enterprise Application Server:

  1. Create a file named $JBOSS_HOME/server/default/deploy/oracle-ds.xml and add the following contents:

    <datasources>
      <local-tx-datasource>
        <jndi-name>OracleDS</jndi-name>
    	   <connection-url>jdbc:oracle:thin:@IP_OR_HOSTNAME_OF _ORACLE_DB_ SERVER:1521:ORACLE_SID
        </connection-url>
    	   <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
        <user-name>USERNAME</user-name>
        <password>PASSWORD</password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
    	   </exception-sorter-class-name>
        <metadata>
    			<type-mapping>Oracle9i</type-mapping>
        </metadata>
      </local-tx-datasource>
    </datasources>
  2. Replace the variables <IP_OR_HOSTNAME_OF _ORACLE_DB_ SERVER>, <ORACLE_ SID>, <USERNAME>, <PASSWORD > with appropriate values, for example:

    <datasources>
      <local-tx-datasource>
        <jndi-name>OracleDS</jndi-name>
    	   <connection-url>jdbc:oracle:thin:@192.168.1.100:1521:1521:OSMS</connection-url>
    	   <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
        <user-name>jboss</user-name>
        <password>jboss</password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
    	   </exception-sorter-class-name>
        <metadata>
    			<type-mapping>Oracle9i</type-mapping>
        </metadata>
      </local-tx-datasource>
    </datasources>
Configuring the Oracle Database Server

Perform the following steps on the Oracle Database Server:

  1. Verify that the Oracle Database Server and the listener are running by entering the following:

    # lsnrctl status

  2. Create a database user and grant similar privileges to those granted to the user in the oracle-ds.xml file, by entering the following:

    # sqlplus / as sysdba

    SQL> create user jboss identified by jboss;

    SQL> grant connect,resource to jboss;

Testing the Oracle Database Connectivity

Test the connectivity between JBoss and Oracle by performing the following steps on the JBoss Enterprise Application Server:

  1. Create a JSP file named $JBOSS_HOME/server/default/deploy/jmx-console.war/oracletest.jsp and add the following contents:

    <%@page contentType="text/html" import="java.net.*,java.util.*,org.jboss.jmx.adaptor.model.*,
    java.io.*,java.sql.*,javax.sql.*,javax.naming.*"%>
    <html>
    	<head>
    		<title>JBoss->Oracle Test </title>
    		<link rel="stylesheet" href="style_master.css" type="text/css">
    		<meta http-equiv="cache-control" content="no-cache">
    	</head>
    	<body>
    		<%
    		InitialContext ctx = new InitialContext();
    		DatabaseMetaData dm = null;
    		DataSource ds = (DataSource)
    		ctx.lookup("java:/OracleDS");
    		Connection conn = null;
    		Statement stmt = null;
    		try {
    		conn = ds.getConnection();
    		dm =conn.getMetaData();
    		out.println("Connected to-> database version "+dm.getDatabaseProductVersion());
    		}catch (Exception sqlex) {
    		out.println(sqlex.getMessage());
    		}finally{
    		conn.close();
    		}
    		%>
    	</body>
    </html>
  2. Edit the $JBOSS_HOME/server/default/conf/props/jmx-console-users.properties file and uncomment the following line

    #admin=admin

  3. Start JBoss by entering the following:

    # $JBOSS_HOME/bin/run.sh -b 0.0.0.0 -c default

  4. Verify that the Oracle test page is displayed as in Figure 13, by opening a browser and navigating to the following:

    http://<YOUR_HOSTNAME>:8080/jmx-console/oracletest.jsp

    Figure 13 Oracle Database Test

    Oracle Database Test
  5. When prompted for the username and password, enter admin as the value for each.

Deploy a JBoss Application Using Hibernate

Hibernate is designed to run in a managed environment, such as the environment of the JBoss Enterprise Application Server Platform. With Hibernate, you only need to configure a small part of the environment. Hibernate inherits database connections from the application server. Therefore, it is easy to create an enterprise application that uses Hibernate capabilities in the same way as other capabilities available in the application server. You can obtain Hibernate and Hibernate tools from the product website, see Table 1 for the appropriate links.

As depicted in Figure 14, the following sections provide an example that demonstrates the use of Hibernate in a Web application with a MySQL or Oracle database.

Figure 14 JBoss Hibernate Connection

JBoss Hibernate Connection

Generating Mapping Files

The following section provides information for generating mapping files for use in the Hibernate example and configuring Hibernate for the MySQL and Oracle databases.

To generate mapping files, perform the following steps:

  1. Create the following in both the MySQL and Oracle databases:

    • A database named osmsdb.

    • A database user named osmsusr with the password osmspass. For the MySQL database, grant the user osmsusr all privileges.

    For information on creating users, databases, and tables, see the following:

    For MySQL, see the MySQL 5.0 Reference Manual located at:

    http://dev.mysql.com/doc/refman/5.0/en/index.html

    For Oracle, see the Oracle Database SQL Reference guide located at:

    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/toc.htm

  2. Create the USERS table with the osmsusr user in the MySQL database, by entering the following:

    mysql> use osmsdb;

    mysql> CREATE TABLE USERS

    (USER_ID INT(10) AUTO_INCREMENT NOT NULL PRIMARY KEY,

    FIRST_NAME VARCHAR(30) NOT NULL,

    LAST_NAME VARCHAR(30) NOT NULL );

  3. Create the USERS table with the user osmsusr in the Oracle database by entering the following:

    SQL> CREATE TABLE USERS

    (USER_ID NUMBER(10) NOT NULL,

    FIRST_NAME VARCHAR2(30) NOT NULL,

    LAST_NAME VARCHAR2(30) NOT NULL, );

    SQL> ALTER TABLE USERS ADD CONSTRAINT USER_PRIMARY_KEY PRIMARY KEY(USER_ID) USING INDEX;

  4. Create the Oracle sequence HIBERNATE_SEQUENCE to generate the primary key for the USERS table by entering the following:

    SQL> CREATE SEQUENCE  HIBERNATE_SEQUENCE
    START WITH 10
    INCREMENT BY 1
    MINVALUE 10
    MAXVALUE 999999999999;
    
  5. Create the directories SimpleDemo/src and SimpleDemo/WebRoot in the location of your choice.

  6. Create a Hibernate mapping file named SimpleDemo/src/Users.hbm.xml, according to the definition of the table USERS, and add the following contents:

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="com.hp.osms.hibernate.Users" table="USERS">
        	<id name="userId" type="java.lang.Long">
        		<column name="USER_ID" precision="10" scale="0" />
        		<generator class="native">
    	   		<param name="sequence"> HIBERNATE_SEQUENCE</param>
        		</generator>
        	</id>
          <property name="firstName" type="java.lang.String">
          		<column name="FIRST_NAME" length="30" />
          </property>
          <property name="lastName" type="java.lang.String">
          		<column name="LAST_NAME" length="30" />
          </property>
        </class>
    </hibernate-mapping>

Creating the Hibernate POJO file

Hibernate uses Plain Old Java Objects (POJO) to pass values between applications and the persistent tier.

Create a Hibernate POJO file named SimpleDemo/src/com/hp/osms/hibernate/Users.java, according to the mapping file for your application and insert the following contents:

package com.hp.osms.hibernate;

public class Users  implements java.io.Serializable {
    private Long userId;
    private String firstName;
    private String lastName;

    public Users() {
    }
    public Users(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public Long getUserId() {
        return this.userId;
    }
    public void setUserId(Long userId) {
        this.userId = userId;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getFirstName() {
        return this.firstName;
    }
    public String getLastName() {
        return this.lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;}}

Configuring Hibernate

Hibernate uses a configuration file named hibernate.cfg.xml to obtain the database connection and mapping file information. Use the following steps to create the database appropriate configuration, using the container’s datasource:

  • For an Oracle database, create the hibernate.cfg.xml file and add the following contents:

    <?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>
    	<property name="show_sql">true</property>
    	<property name="connection.datasource">
    java:/OracleDS
    </property>
    	<property name="dialect">
    org.hibernate.dialect.Oracle9Dialect
    </property>
    	<mapping resource="com/hp/osms/hibernate/Users.hbm.xml" />
    </session-factory>
    
    </hibernate-configuration>
  • For a MySQL database, create the hibernate.cfg.xml file and add the following contents:

    <?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>
    	<property name="show_sql">true</property>
    	<property name="connection.datasource">
    java:/MySqlDS
    </property>
    	<property name="dialect">
    		org.hibernate.dialect.MySQLDialect
    </property>
    	<mapping resource="com/hp/osms/hibernate/Users.hbm.xml" />
    </session-factory>
    
    </hibernate-configuration>
NOTE: The datasource name java:/OracleDS is assigned to both configuration file examples. The following sections describe how to configure this datasource in the JBoss Enterprise Application Server.

In Hibernate, a unit of work is called a session which is managed by a <session-factory>. For the application to interact with Hibernate correctly, you must create a utility class to retrieve the session named HibernateSessionFactory. The code for creating the HibernateSessionFactory is located in “Appendix C: Hibernate Test Application Source Code”.

Creating a Test JSP for Hibernate

To test Hibernate functionality such as inserting, updating, deleting, and retrieving data from the database, you must create a sample JSP file named SimpleDemo/WebRoot/hibernate.jsp. The entire directory structure for the Web application SimpleDemo should display as in Figure 15.

Figure 15 Directory Structure for SimpleDemo

Directory Structure for SimpleDemo

The following code fragment from hibernate.jsp shows how to use Hibernate to insert data into the database. For the complete hibernate.jsp file code, see “Appendix C: Hibernate Test Application Source Code”.

org.hibernate.Session hbsession = HibernateSessionFactory.getSession();
try{
	Transaction tx = hbsession.beginTransaction();
	Users users= new Users();
	users.setFirstName("Smith");
	users.setLastName("Barney");
	hbsession.save(users);
	hbsession.flush();
	tx.commit();
}catch(HibernateException he){
	he.printStackTrace();
}finally
{
	if(hbsession!=null)
	HibernateSessionFactory.closeSession();
}

Archiving the Web Application to a WAR File

For future deployment of the Web application, use Apache Ant to compile and archive the Web application SimpleDemo to a Web archive (WAR) file named SimpleDemo.war. For information on using Apache Ant, see the Apache Ant Project website located at:

http://ant.apache.org

Deploying a Test Web Application to JBoss

To deploy a test Web application to JBoss, perform the following steps:

  1. Copy the example JBoss datasource files by entering the following:

    For a MySQL database:

    # cp $JBOSS_HOME/docs/examples/jca/mysql-ds.xml \

    $JBOSS_HOME/server/default/deploy/

    For an Oracle database:

    # cp $JBOSS_HOME/docs/examples/jca/oracle-ds.xml \

    $JBOSS_HOME/server/default/deploy/

  2. Configure the JBoss connection to MySQL by editing the mysql-ds.xml file and adding the following contents:

    <?xml version="1.0" encoding="UTF-8"?>
    <datasources>
      <local-tx-datasource>
        <jndi-name>MySqlDS</jndi-name>
        <connection-url>jdbc:mysql://IP_OR_HOSTNAME_OF_THE_DB_SERVER:3306/osmsdb
        </connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name> osmsusr </user-name>
        <password> osmspass </password>
        <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter
    		</exception-sorter-class-name>
        <metadata>
        <type-mapping>mySQL</type-mapping>
        </metadata>
      </local-tx-datasource>
    </datasources>
  3. Configure the JBoss connection to Oracle by editing the oracle-ds.xml file and adding the following contents:

    <?xml version="1.0" encoding="UTF-8"?>
    	<datasources>
    		<local-tx-datasource>
    			<jndi-name>OracleDS</jndi-name>
    			<connection-url>jdbc:oracle:thin:@IP_OR_HOSTNAME_OF_THE_DB_SERVER:1521:osmsdb</connection-url>
    			<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
    			<user-name> osmsusr </user-name>
    			<password> osmspass </password>
    			<exception-sorter-classname>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
    			</exception-sorter-class-name>
    			<metadata>
    			<type-mapping>Oracle9i</type-mapping>
    			</metadata>
    	</local-tx-datasource>
    </datasources>
    
  4. Download the JDBC driver, as appropriate for the database, from one of the following websites:

  5. Copy the JDBC driver to the $JBOSS_HOME/server/default/lib directory.

  6. Deploy the archive file SimpleDemo.war to JBoss by entering the following:

    # cp SimpleDemo.war $JBOSS_HOME/server/default/deploy/

  7. Start the JBoss Enterprise Application Server by entering the following:

    # $JBOSS_HOME/bin/run.sh -c default -b 0.0.0.0

  8. Verify the Hibernate test page is displayed as in Figure 16 by opening a browser and navigating to:

    http://JBOSS_HOSTNAME:8080/SimpleDemo/hibernate.jsp

    Figure 16 Hibernate Test Page

    Hibernate Test Page
Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© 2007 Hewlett-Packard Development Company, L.P.