« Posts under Jboss

Configuring Data Sources, JBoss 7

Yep it’s gonna be a big year for JBoss AS 7

This will be the first in a series I’ll be writing on JBoss’ new application server version 7. Lately I’ve been playing around with JBoss AS 7 recently, and all I can say is.. !@#%, NICE! I downloaded 7.0 with the expectation that it would honor a lot of the previous version’s overall approach and layout. I was in for a BIG surprise. It comes off as a total rewrite, leveraging a lot of the latest and greatest technologies and frameworks – things like Weld (an implementation of the context and dependency injection spec – JSR-299), OSGi (the Open Services Gateway initiative framework for the uninitiated), Hibernate, and RESTeasy.

I’ll say the guys over at JBoss certainly delivered. Before, server start up times could take a respectable 30 seconds to a minute or more depending on your deployment structure and dependencies. Now you ask? Less time than my 15 second ant build script! Right now I’m clocking 14 second from cold to deployed on my smaller sized application. With AS 5, the same deployment was taking something like a minute. Hat’s off guys, you all at JBoss really did some work!

The first thing and arguable the most difficult thing you’ll want to do is set up the data source for your deployment.

Configuring the Data Source

Before we had to configure out postgres-ds.xml file with all the data source metadata required to configure out application. The process now isn’t as straight forward – there are three ways to do it, two if you don’t count using the really nice console manager it ships with. I should mention that now there are 2 types of configuration setups 1) domain and 2) standalone. Standalone is the model we’re most familiar with – a single instance acting as a single server. Domain on the other hand is geared for a clustered style of deployment – although its way more flexible than that. More on this in another article. For the sake of simplicity, lets start with the standalone type.

Place the jdbc driver

There are 2 ways to do this. The first is really straight forwards – just stick your jdbc jar file in the deployment folder indicated in the configuration file:

jboss-7.0.0.GAstandaloneconfigurationstandalone.xml

Relevant contents:

<subsystem xmlns="urn:jboss:domain:deployment-scanner:1.0">

	<deployment-scanner name="default" 
		scan-enabled="true" scan-interval="5000" 
		deployment-timeout="60"
		relative-to="jboss.server.base.dir" 
		path="deployments" />

</subsystem>

Stick your jdbc jar file in here, and JBoss will automatically configure your standalone.xml file for you. BTW, this deployment-scanner entry maps the location of the deployments directory:

jboss-7.0.0.GAstandalonedeployments

Where jboss.server.base.dir points to the “standalone” directory and path maps the name of the deploy folder “deployments”.

The second way is a more complex and so requires a little bit more legwork. JBoss has completely changed its class loading strategy, and if you’ve ever worked with Maven repositories it might feel very familiar. Essentially jboss’ modules folder is where all the jars that are used by the jboss server live. By separating them into a separate classpath, you won’t run into weird classpath errors when there are competing jar files/versions deployed by your application. This problem exposed itself in earlier versions of jboss – in particular with the xml jars. If you had a mixed case of xml libraries, jboss might have been using an older version that could override your application’s newer version – hard to track down if you don’t know where to look. Anyway, these jar files are organized by psuedo packages – just like maven repositories except the final folder is called main. Each module jar file must be placed there and be paired with corresponding a module.xml file. For example you’d want to create a folder in your install like this:

jboss-7.0.0.GAmodulesorgpostgresqlmain

Here is an example of module.xml:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="org.postgresql">
  <resources>
    <resource-root path="postgresql-9.0-801.jdbc4.jar"/>
  </resources>
  <dependencies>
    <module name="javax.api"/>
    <module name="javax.transaction.api"/>
  </dependencies>
</module>

You’ll want to map the name of the jdbc driver, as well as the name of the module name here – we’re going to map it to the configuration next. Once this is squared away, we’ll want to configure the standalone.xml file:

jboss-7.0.0.GAstandaloneconfiguration

Map and Configure

In standalone.xml, you’ll want to look for the <subsystem xmlns=”urn:jboss:domain:datasources:1.0″> node and add a shiny new configuration like this:

<subsystem xmlns="urn:jboss:domain:datasources:1.0">
	<datasources>
			<datasource jndi-name="java:jboss/DefaultDS" enabled="true" 
				jta="true" use-java-context="true" use-ccm="true"
				pool-name="postgresDS" >
			<connection-url>
				jdbc:postgresql://localhost:5432/database?charSet=UTF-8
			</connection-url>
			<driver>
				org.postgresql
			</driver>
			<transaction-isolation>
				TRANSACTION_READ_COMMITTED
			</transaction-isolation>
			<pool>
				<min-pool-size>
					10
				</min-pool-size>
				<max-pool-size>
					100
				</max-pool-size>
				<prefill>
					true
				</prefill>
				<use-strict-min>
					false
				</use-strict-min>
				<flush-strategy>
					FailingConnectionOnly
				</flush-strategy>
			</pool>
			<security>
				<user-name>
					username
				</user-name>
				<password>
					password
				</password>
				</security>
			<statement>
				<prepared-statement-cache-size>
					32
				</prepared-statement-cache-size>
			</statement>
		</datasource>
		<drivers>
			<driver name="org.postgresql" module="org.postgresql">
				<datasource-class>
					org.postgresql.Driver
				</datasource-class>
			</driver>
		</drivers>
	</datasources>
</subsystem>

Pay attention to:

	<driver>
		org.postgresql
	</driver>

Note: you can set this to the jdbc driver file name if you’re using the deploy approach. In fact, jboss will be more than happy to write the driver configuration for you if you deploy the driver from the deploy directory.

This entry maps to the driver configured directly below to the driver name configured by :

	<driver name="org.postgresql" module="org.postgresql">
		<xa-datasource-class>
			org.postgresql.Driver
		</xa-datasource-class>
	</driver>

The name property maps the driver to the configuration, and the module property maps to the module we laid out in the first step. I’ll point out that it seems that you need to use a transaction aware data source. I think you’re supposed to be able to use the node </datasource-class> with the regular driver class but when I tried this, I got xml parsing errors – it doesn’t seem to think “datasource-class” is a legal element.

You can call on the data source file through the jndi handle configured on the datasource node: jndi-name=”java:jboss/DefaultDS”. The rest of the properties and nodes configure various settings for your datasource, and if you’ve worked with them before you will probably be familiar with them already. If you need a refresher (like me) you can also look through all the JBoss user guide documentation.

References:
JBoss Wiki on Datasource configuration
JBoss user guide documentation
JBoss Wiki Getting Started Guide
JBoss Getting Started Admin Guide

The conf directory, JBoss v5.x

Configure what you need

So you’re ready to configure some JBoss files? Great, lets have a look at the conf directory. The jboss/server/<configured instance>/conf directory is where you’ll find the majority of the configuration files for your jboss instance. For most deployments, the majority of these folders and files will remain untouched as they default to usable configurations. In this article we’ll go over the more practical configurable files, while leaving the really low level configurations alone.

`-- conf
    |-- bootstrap/
    |--|-- bindingservice.bean
    |   `-- META-INF
    |   |    `-- bindings-jboss-beans.xml *
    |   |-- aop.xml
    |   |-- classloader.xml
    |   |-- deployers.xml
    |   |-- jmx.xml
    |   |-- logging.xml
    |   |-- profile.xml *
    |   `-- vfs.xml
    |-- props
    |   |-- jbossws-roles.properties
    |   |-- jbossws-users.properties
    |   |-- jmx-console-roles.properties
    |   `-- jmx-console-users.properties
    |-- xmdesc
    |   |-- AttributePersistenceService-xmbean.xml
    |   |-- ClientUserTransaction-xmbean.xml
    |   |-- JNDIView-xmbean.xml
    |   |-- Log4jService-xmbean.xml
    |   |-- NamingBean-xmbean.xml
    |   |-- NamingProviderURLWriter-xmbean.xml
    |   `-- NamingService-xmbean.xml
    |-- bootstrap.xml
    |-- jacorb.properties
    |-- java.policy
    |-- jax-ws-catalog.xml
    |-- jboss-log4j.xml
    |-- jboss-service.xml
    |-- jbossjta-properties.xml
    |-- jndi.properties
    |-- login-config.xml
    |-- standardjboss.xml
    `-- standardjbosscmp-jdbc.xml

For starters, the bootstrap.xml file lets you configure which microcontainer deployments are loaded on boot. The ones we want to pay special attention to are profile.xml and conf/bindingservice.beans’s bindings-jboss-beans.xml (marked with an asterisk in the layout diagram) The other files are geared for low level configurations. For example – aop.xml configured how aop is implemented in jboss, deployers.xml configures jboss’ classloaders, and vfs.xml tells jboss what lib folders to load jars from.

External deployments

If you open up profile.xml, you’ll see a set of configurations that describe what kind of deployers are used for the profile object management service. Most of the contents deal with Jboss’ innards, but worthy of reviewing is the “applicationURIs” property. It’s actually a list of java.net.URI urls, and you can add elements to this list in order to configure Jboss so that it looks in to external deployment directories in addition to the defauls deploy directory. More detail is described in the related article “External deploy directories in JBoss 5.1”.

Port Bindings

Before Jboss 5, you would have to manually go in and change each port into its own numberspace. There were a bunch of places where these ports would need to be updated (for things like the naming and rmi services) across a slew of files scattered all over the place. In Jboss 5, if you open up bindings-jboss-beans.xml, you’ll find a means of binding multiple jboss instances across different ports in a single centralized location. Out of the box, Jboss ships with 4 sets of port configurations. Each configuration set reserves a set of ports for JBoss’ use. If you trail through each of these port configurations, you’ll notice the sets are offset by increments of 100. So for example the first configuration reserves 1099 for the NamingServer, while the second set reserves 1199, and the third set uses 1299 and so on. This functionality is particularly useful when you want Jboss to run on a single IP address. Given a choice though, I would opt for using a single IP per Jboss instance. It’s nice to have this option though, in case multiple IPs is not an option.

We can get an idea of how JBoss configures these binding sets from the snippets below – both are straight out of the bindings-jboss-beans.xml file:

<!-- Provides management tools -->
<bean name="ServiceBindingManagementObject" 
  class="org.jboss.services.binding.managed.ServiceBindingManagementObject">

  <constructor>
     <!-- The name of the set of bindings to use for this server -->
     <parameter>${jboss.service.binding.set:ports-default}</parameter>

     <!--  The binding sets -->
     <parameter>
	 <set>
	    <inject bean="PortsDefaultBindings"/>
	    <inject bean="Ports01Bindings"/>
	    <inject bean="Ports02Bindings"/>
	    <inject bean="Ports03Bindings"/>
	 </set>
     </parameter>

     <!-- Base binding metadata used to create bindings for each set -->
     <parameter><inject bean="StandardBindings"/></parameter>

  </constructor>
</bean>

...

<!-- bindings are obtained by taking the base bindings and adding offsets  -->
<bean name="Ports01Bindings"  
	class="org.jboss.services.binding.impl.ServiceBindingSet">
	<constructor>
	<!--  The name of the set -->
		<parameter>ports-01</parameter>
	<!-- Default host name -->
		<parameter>${jboss.bind.address}</parameter>
	<!-- The port offset -->
		<parameter>100</parameter>
	<!-- Bindings to which the "offset by X" approach can't be applied -->
		<parameter><null/></parameter>
	</constructor>
</bean>

If you run Jboss without a ports configuration, it will use the default port settings. If you want to use a specific port configuration, all you need to do is add the startup param to the run.sh script used to invoke jboss: “-Djboss.service.binding.set=ports-01”. This param selects which port config to use, and likewise can be used to use any of the available port bindings found in bindings-jboss-beans.xml.

The props folder – default UsersRolesLoginModule properties for jmx-console security

If you make use of jmx-console’s default UsersRolesLoginModule JAAS security domain configuration, you’ll find that the user and role properties are stored in this “props” folder. More on securing the jmx console can be found here. You can also opt to use a different security module, by defining a different login module in login-config.xml. More on this in a few paragraphs.

The xmdesc folder – mbean descriptors

This folder contains all the descriptors used for the major mbeans described in the jboss-service.xml. Not all the possible mbeans have been converted over to the new bootstrapping style format, so these legacy descriptors close the gap to allow existing mbean services to continue to work.

Logging with jboss-log4j.xml

This piece allows you to configure the logging for the entire instance. If you’re familiar with log4j, you’ll know right off the bat how to configure the logging. Out of the box Jboss ships with console output enabled. For production level environments though, we’ll want that disabled as console logging always takes up unnecessary system resources. You are able to control smtp, console, file, jms, and file based logging with levels (DEBUG, INFO, WARN, ERROR, FATAL etc) and by category (com.yourpackage.class or com.yourpackage). Asynchronous appenders allow you to configure logging that gets piped to more than one target. Learn mroe about how to configure this from Apache’s Log4J’s project website. A basic log4j configuration can be found in the example below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" 
      debug="false">
   <!-- A time/date based rolling appender -->
      <appender class="org.jboss.logging.appender.DailyRollingFileAppender"
        name="FILE">
      <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
      <param name="File" value="${jboss.server.log.dir}/server.log"/>
      <param name="Append" value="true"/>
       
      <!-- Rollover at midnight each day -->
      <param name="DatePattern" value="'.'yyyy-MM-dd"/>

      <layout class="org.apache.log4j.PatternLayout">
         <!-- Default pattern: Date Priority [Category] (Thread) Messagen -->
         <param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n"/>
      </layout>
   </appender>

   <root>
	<priority value="${jboss.server.log.threshold}"/>
	<appender-ref ref="FILE"/>
   </root>
</log>

JAAS/Security Domains with login-config.xml

This file allows you to configure security domain with JAAS for your applications. You have a number of login modules to choose from, notably the DatabaseServerLoginModule. This module allows you to hook in a set of users and roles query into a datasource to validate authentication credentials and allow access to your application. In a default install, Jboss will have example configurations where users and roles are also stored in the props directory and accessed via the UsersRolesLoginModule.

An example JAAS database login module configuration in login-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="urn:jboss:bean-deployer:2.0">
  <application-policy xmlns="urn:jboss:security-beans:1.0" name="loginForm">
    <authentication>
      <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule"
        flag="required">
        <!--  BASE64 also possible -->
        <module-option name="hashAlgorithm">MD5</module-option> 
        <module-option name="unauthenticatedIdentity">guest</module-option>
        <module-option name="dsJndiName">java:/DefaultDS</module-option>
        <module-option name="principalsQuery">
        	SELECT password FROM User WHERE username=?
        </module-option>
        <module-option name="rolesQuery">
        	SELECT role, 'Roles' 
        	FROM UserRoles, User 
        	WHERE User.username=? 
        		AND User.id = UserRoles.user_id
        </module-option>
      </login-module>
    </authentication>
  </application-policy>
</deployment>

In order for this configuration to work we’ll need to also add security domains to our web application’s web.xml as well as a the Jboss only jboss-web.xml deployment descriptor. More on how to configure this can be fond in Jboss’ server manual, section 9.6.4.

The remaining files

The last remaining files cover various integration configurations, and delve into Jboss’ low level implementation. One example is the java.policy file which configures your instance’s security policy on the jvm level. You may constrain permissions to allow strictly reading across the board or some custom mix of read and write, and by class. More information can be found on Jboss Web’s security manager page. For the uninitiated, Jboss Web is the integrated version of Tomcat 6 that deploys with JBoss as a deployable service.

The jbossjta-properties.xml file configures the Jboss transaction server’s default behavior. The jax-ws-catalog.xml maps xml metadata for use with jax-ws webservices, as specified by the Oasis XML Catalog spec. The jndi.properties file maps classes used by Jboss’ naming server. The jacorb.properties file configures JacORB (Java implementation of OMG’s Corba standard) for use with Jboss.

Finally, the standardjbosscmp.xml config defines how various types of enterprise java beans are configured during regular use, while standardjbosscmp-jdbc.xml configures specific persistence dialects relating to type mappings so that datasource files can communicate correctly with different database vendors. In your datasource file you can add a type element to specify which of these defined types jboss should use:

<?xml version="1.0" encoding="UTF-8"?>  
<datasources>   
     <local-tx-datasource> 
        <jndi-name>DefaultDS</jndi-name> 
        <connection-url>jdbc:postgresql://localhost:5432/db</connection-url> 
        <driver-class>org.postgresql.Driver</driver-class> 
         <user-name>user</user-name>   
         <password>password</password> 
          <metadata> 
               <type-mapping>PostgreSQL</type-mapping> 
          </metadata>          
     </local-tx-datasource> 
</datasources>

The recap

Once you’ve gone over these configuration files, you’ll have seen with some depth part of what Jboss is capable of. As mentioned earlier, you wont want to muck around with most of these configurations unless you’re working on Jboss server code itself or unless you want to tweak the server’s behavior. The most commonly edited files end up being bindings-jboss-beans.xml (multiple port bindings), profile.xml (external deploy directories), jboss-log4j.xml (logging), login-config.xml (security domains) and java.policy (jvm level security permissions). With these basics you can be well off into configuring Jboss for whatever needs you need to fill.

Resources:
Securing the JMX Console
JBoss App server Quick Tour
JBoss Web manual
Oasis XML Catalog project

The Deploy vs Deployers directory, JBoss v5.x

Tae Bo for JBoss!

JBoss ships with a few configurations that are meant to provide examples of how JBoss can be configured for your environment. It’s recommend you take the “default” configuration (or “all” if you require clustering), and then slim it down by removing the various mbean components found in the “jboss/server/<configured instance>/deployers” and “jboss/server/<configured instance>/deploy” folders until only your minimum requirements are met. If you deploy JBoss with everything as it is, you’re going to end up wasting system resources on services that your application is going to use. For example, if your application doesn’t make any use of ejb2, then theres no reason to enable ejb2 implementation services or deployers in your instance. By removing these unnecessary pieces you’ll end up with a more optimized configuration, and you’ll end up getting the most bang for the buck from your installation. You’ll want to become familiar with each of the items in the deploy and deployers folders so that you can remove the services that would otherwise eat your cpu cycles while not providing any benefit.

The deploy directory

This deploy folder houses deployable services or applications meant to be run by the JBoss instance. To squeeze absolutely the most out of your installation you’ll want to be picky when deciding which services you end up leaving in. It should be noted that even though the JBoss instance is capable of hot deployments, its generally a bad idea to use Hot deploy in a production environment, its bound to cause wierd problems over time – items in memory might not be completely unallocated and may end up causing unexpected behavior in the long run. It’s also a good idea NOT to use HypersonicSQL as the defaultDS provider for your application. You probably do NOT want to queue up a massive 300k message queue into HSQL via the defaultDS, you might want to use something a little more enterprise level. Replace the defaultDS provider with your own vendor.

Here is an breif explanation of the items found in those directories:

  • deploy/admin-console.war – this is a useful utility you can use to inspect jboss and start/stop and administer your application and/or services. Not required to run your application but if you run into trouble, it can be handy for debugging or performance tuning
  • deploy/http-invoker.sar – this service allows you to invoke ejbs and make jndi calls through the http protocol. Calls are made in a similar way to: http://<hostname>:8080/invoker/EJBInvokerServlet. If you dont use this service, you can take this out.
  • deploy/jbossweb.sar – this is the tomcat integration service. If your application doesn’t have a web interface, then you can remove this safely.
  • deploy/jbossws.sar – this is the web service implementation. If your application does not use web services, or you choose to implement your own, you can safely remove this.
  • deploy/jmx-console – this is an application similar to the admin-console.war where you can go and inspect the server’s individual mbeans, view the jndi namespace (bound services, ejbs etc) view stack traces for active threads and other useful things like that. This is not required to run your app in a production environment but it can be extremely useful for debugging or performance tuning.
  • deploy/jmx-remoting.sar – this allows rmi access to jmx in jboss. Even if you remove this you’ll still have access to jmx if you haven’t removed jmx-console.war.
  • deploy/management/console-mgr.sar – this is supposed to provide a gui interface for managing the jboss application server. Haven’t used it much, so I cant say if its any good or not. This can be safely removed if you don’t intend to administer the server via a web gui.
  • deploy/messaging – the set of files in this directory are used for jms. Out of the box, its wired to use the hsql db that jboss comes with. If your application uses jms, you’ll want to remove hsqldb-persistence-service.xml and use the proper service.xml file that goes with your vendor. The right file can be found here: jboss-5.1.0.GA/docs/examples/jms. So if you use postgres you would use postgresql-persistence-service instead of hsqldb-persistence-service.xml. There are other places where you would need to update to completely remove the hsql dependency, but this particular fileset speaks to the jms implementation
  • deploy/profileservice-secured.jar – documentation says it allows web access to the profile service. I think this section allows you to administer the individual profiles, but I’m not completely sure it saves the configurations to disk, although I could be wrong.
  • deploy/ROOT.war – this is the default context application that comes with JBoss. I usually remove this completely so that I’m free to use the root context for my own application since there can be only one is use.
  • deploy/security – this is used for configuring security policies for the server
  • deploy/uuid-key-generator.sar – this service is a uuid generators, it is used by things like entity primary key sequence generators in ejb3 etc. If you change the DefaultDS name to something else, theres the META-INF/jboss-service.xml file has a reference you’ll need to change.
  • deploy/xnio-provider.jar – default configuration for some kind of remote jboss connector
  • deploy/cache-invalidation-service.xml – this is a service that allows you to invalide the ejb cache through jms, this is disabled by default so it can safely be removed without problem
  • deploy/ejb2-container-jboss-beans.xml, deploy/ejb2-timer-service.xml – these are used to support ejb 2.x in jboss. Remove if yor app doesn’t use ejb 2.x
  • deploy/ejb3-connectors-jboss-beans.xml, deploy/ejb3-container-jboss-beans.xml, deploy/ejb3-interceptors-aop.xml, deploy/ejb3-timerservice-jboss-beans.xml – these descriptors directly support ejb3 functionality in jboss, remove if your application doesn’t use ejb3
  • deploy/hdscanner-jboss-beans.xml – hot deploy support for jboss. Hot deployments are usually a bad idea for production environments, so take this out and save yourself the trouble
  • deploy/hsqldb-ds.xml – the hsql ds file, remove this and wire the DefaultDS jndi resource to your one production environment database
  • deploy/jboss-local-jdbc.rar – this is the JCA adaptor that implements the jboss datasource. Remove this if your application doesn’t use the DS files. Use
  • deploy/jboss-xa-jdbc.rar – this is the JCA adaptor that is required to support distributed transaction management (XA) datasource
  • deploy/jca-jboss-beans.xml – the jboss JCA spec implementation, this allows JCA adaptors like jboss-xa-jdbc.rar to function (enabling transaction aware jdbc calls)
  • deploy/jms-ra.rar – jms resource adaptor
  • deploy/jmx-invoker-service.xml – mbean service that configures remote access to jmx via rmi. You probably don’t need this unless your application requires remote jmx management
  • deploy/jsr88-service.xml – mbean descriptor for the jsr-88 remote deploy spec. This can be safely removed if your application does not use any jsr-88 spec deployments. More info on the spec can be found here.
  • deploy/legacy-invokers-service.xml – mbean descriptors for legacy remote jms invokers
  • deploy/mail-ra.rar – resource adapters for javamail. You can safely remove this if your app doesn’t make use of javamail.
  • deploy/mail-service.xml – mbean dessriptor for the localized jboss javamail configuration. Use this file to configure the mail server settings for receiving, sending, etc
  • deploy/monitoring-service.xml – mbean descriptors for jmx based server monitoring services, like the jmx-console.
  • deploy/profileservice-jboss-beans.xml – mbean descriptor that supports the jboss profile service. You probably don’t want to get rid of this since this piece should help configure your instance’s bootstrap and port settings.
  • deploy/properties-service.xml – mbean descriptors for the jboss properties services, allowing system properties to be loaded externally or remotely. You should be able to remove this safely if you don’t use the profile service in your application and don’t mind the default system properties
  • deploy/quartz-ra.rar – the quartz resource adapter. Remove if your application doesn’t make any use of quartz
  • deploy/remoting-jboss-beans.xml – mbean descriptors that support the jboss remoting project. More on this can be found here. You can remove this if your application doesn’t make use of any jboss remoting code.
  • deploy/schedule-manager-service.xml – mbean descriptors for the Java5 scheduler services. This can be configured for older pooled jmx based timers. I think this might be required for ejb3 timer support.
  • deploy/scheduler-service.xml – additional mbean descriptors for Java5 timers. I’m not convinced ejb3 timers require this to work, but if you’re not using ejb3 timer or the scheduling service you can safely remove this.
  • deploy/sqlexception-service.xml – mbean descriptor for handling vendor specific sql exceptions.
  • deploy/transaction-jboss-beans.xml – mbean descriptors enabling JTA transactions. This is required for ejbs transaction management. More info on the JTA spec can be found here.
  • deploy/transaction-service.xml – mbean descriptors for a jmx service that handles the jboss UserTransaction implementation for client applications
  • deploy/vfs-jboss-beans.xml – mbean descriptors for virtual file caching, used by the server for deployments. Probably a good idea to leave this in.

The deployers directory

The items in the deployers directory are used to aid jboss in its deploy capability. The ear, ejb, and seam deployers are examples of the types of artifacts jboss can deploy, and each one of these types need deployer descriptors configurations to enable their deployment capabilities. Remove some of these, and jboss will not deploy artifacts of the corresponding type. Chances are it’s OK with leaving most of these in. You’ll want to remove and leave the obvious ones and experiment with the ones you’re not sure about if you want to achieve the most bare boned and streamlined JBoss configuration. Here’s a brief rundown of these deployers:

  • deployers/bsh.deployer – enables bean shell script deployments. Remove if your application does not use beanshell scripts
  • deployers/ejb3.deployer – enables ejb3 deployers, remove if your application doesn’t use any ejb3.
  • deployers/jboss-aop-jboss5.deployer – enables the jboss 5 base aspects.
  • deployers/jboss-jca.deployer – enables JCA deployments. Keep this if your app makes use of JCA adapters like jboss-local-jdbc.rar
  • deployers/jbossweb.deployer – deploys web components like servlets and jsps
  • deployers/jbossws.deployer – deploys web service related endpoint components
  • deployers/seam.deployer – provides integration support for jboss seam
  • deployers/alias-deployers-jboss-beans.xml – supports alias deployment descriptors that install once the original is deployed
  • deployers/clustering-deployer-jboss-beans.xml – supports deployments for jboss clusters, you don’t need this if you’re not running in a clustered environment
  • deployers/dependency-deployers-jboss-beans.xml – adds support for dependency deployments like aliases
  • deployers/directory-deployer-jboss-beans.xml – legacy support for embedded deployable artifacts in folder deployments like embedded lib directories
  • deployers/ear-deployer-jboss-beans.xml – adds support for ear deployments
  • deployers/ejb-deployer-jboss-beans.xml – supports java 1.4 ejb deployments
  • deployers/hibernate-deployer-jboss-beans.xml – adds support for hibernate deployment descriptors and artifacts
  • deployers/jsr77-deployers-jboss-beans.xml – support for the JSR 77 spec, standard j2ee deployments. See more here
  • deployers/metadata-deployer-jboss-beans.xml – add support for reading in and deploying metadata in the form of annotations or xml metadata
  • deployers/security-deployer-jboss-beans.xml – supports deployment of security related configuration

Feeling 10 lbs lighter!

As you can see, JBoss is highly configurable and is therefore extremely flexible – try to leave in only what you need to get the most out of your install. Sure, you can just use the default install as it is out of the box, but you’ll be bloating your server with unnecessary services as well as possibly providing security holes that the savvy intruder might be able to exploit. Specifically, the admin-console/jmx-console store usernames and password defaults in a properties file – if you leave those alone, and don’t update or change them, you’ll be vulnerable to anyone who happens to be familiar with these defaults and how to access either console.

Resources:
Jboss documentation on the “Default” configuration
JBoss 5.x Tuning/Slimming

Jars and Class Loading, Jboss v5.x

So where do I put all my jars?

As you write your applications you’re bound to leverage third party libraries to cut down on the amount of work; lets face it no one wants to reinvent the wheel. A downside is sometimes these third party libraries might not be the most mature or stable releases to date. As your product grows and matures, or you expand your client base or number of implementations, you’re bound to come across multiple third party library dependencies, even ones across the same library but different versions, what a headache! How can we organize these libraries in JBoss? Luckly we are provided with a few directories where you can stick library jars for use in your own application, here is a quick rundown:

  • jboss/client – this folder contains all the jar files used by any client application for jboss, for example a swing application that needs to commnicarte with a remote JBoss instance would need to have the jar files in this directory in its classpath or it will not be able to communicate correctly. Generally, you don’t stick third party libraries used by your application here unless you’re writing some kind of jboss client application and you’re extending the server’s functionality in some way.
  • jboss/common/lib – this folder is meant to hold jar files that should be made available to all JBoss instances. Jar files global to all applications go here.
  • jboss/lib – this folder holds all the jar files used in order for the server to run correctly. You don’t stick your libraries in this directory unless you’re extending or adding functionality to the JBoss server itself.
  • jboss/lib/endorsed – this folder holds all the endorsed libs that jboss uses where other implementations can be used to override. Xalan implementations other than the default go here if you want to override with a newer version. Since JBoss relies on these libraries also, be mindful that you might find xml parsing issues if you use an older xalan library (jboss uses many xml files for configuration)
  • jboss/server/<configured instance>/lib – this is where you put any instance specific jar files

So for the most part, unless you’re going to be tinkering with extending or modifying the JBoss server itself, you’ll want to stick to one of thee locations, the server global lib, the instance global lib, or the lib in your deployable artifact.

Possible scenarios

Ultimately, you’re going to need to make a decision on how you’re manage your third party libraries, and its all based on your particular setup and installed application base. The JBoss loaders can do teasingly mysterious things, as the order of precedence might not be completely obvious. The most easy pitfalls include more than one library being loaded, but of a different version. Which one gets loaded if there is more than one? The answer depends on the strategy you used in your setup, and figuring out the best strategy for your particular application(s) is paramount to minimizing this risk. First, lets look at the viable options:

If you want to make your application portable and completely self contained – you’ll want to package all your third party libraries in the right lib directory for your war or ear file. The benefits include more complete portability by becoming completely self contained deployable artifacts, and therefore minimizing immediate class loading problems. The downside to packaging everything into your deployable artifact is that your instance startup times inflate. A full complement of third party libraries in a huge ear file containing multiple war files could end up taking minutes to deploy because each artifact deploys its own libraries; and if there are common libraries throughout, each one can be loaded separately if they’re not organized to minimize this inefficiency.

The converse of removing all the third party libraries and sticking them into the instance library (jboss/server/<configured instance>/lib). The instance libraries load up orders of magnitude more quickly than the prepackaged third party library strategy, but the downside is your deployable artifact is no longer completely self contained. This might not necessarily be a bad thing at the end of the day however, as long as your third party libraries can be easily managed in whatever application server you use. JBoss allows you to use an instance specific library folder, and it turns out to be a neat alternative to self contained libraries, especially when there is more than one deployed application, and they share a few common libraries.

If you want to go a step more global than an instance specific common library, you could use the jboss/common/lib directory. This location will be loaded before the instance specific library and provides a baseline for all available instances. Any libraries that are super global should be placed here.

What the.. ?

So what happens if you have more than one library, say one in your war file, and another one in the instance lib, which one gets used by your code? It turns out that the order in which the classes are loaded matters and is the determining factor. The server global directory loads before the instance specific lib, and the instance specific lib loads before your deployable artifacts and their libraries. So basically, the more global libraries will outweigh the artifact local libraries.

Now what if you want your deployable artifact to override global libraries? Luckily, JBoss provides a way to scope the deployment. Scoping the deployment here means you’re making the libraries used by your deployment localized, superseding the global libraries with whats packaged in the artifact.

For War files you will need to add an entry to your jboss-web.xml file:

<jboss-web>
   <class-loading java2ClassLoadingCompliance="false">
      <loader-repository>
         com.example:archive=name-of-your-deployable-artifact.war
         <loader-repository-config>
            java2ParentDelegation=false
         </loader-repository-config>
      </loader-repository>
   </class-loading>
</jboss-web>

and for Ear files you’ll need to make your jboss-app.xml look like this:

<jboss-app>
  <loader-repository> 
  com.example:archive=name-of-your-deployable-artifact.ear
     <loader-repository-config> 
     java2ParentDelegation=false 
     </loader-repository-config> 
  </loader-repository>
</jboss-app>

Where com.example is the package name for the specific class package (third party library) you want to override, and unique-archive-name.xxx is the name of the deployable artifact for which you want to localize the classes loading. Note that these descriptors only work for jboss and will not be honored by other vendors. Also worthy of mention is that for your deployable artifacts, the most global artifact’s deployment scope will be honored, so if you have an ear file, the jboss-app.xml in the ear file will override and cause any jboss-web.xml scoping configurations in any embedded war files to be ignored. java2ParentDelegation is supposed to be disabled by default, but its a good idea to explicitly set it to false anyway just to be on the safe side – enabling it to true will cause the classes referenced in this scope configuration to be loaded by the next most global scope (moving the loaded classes to the instance/lib if its in an ear or war, and to the most global jboss/common/lib if its in the instance specific lib).

It’s also a good practice to make sure your war files don’t start with the same first few letters as other deployed war files in the same instance. In JBoss 4.x it was possible to collide class loading when 2 or more war files started with the first few letters and the packaged class files in the WEB-INF directory shared a similar code base (ex: my_war.war vs my_warfile.war). The fix was to change the names of the war files so they were totally different. Whoever loaded first would be linked in the JBoss class loaders. If you run into a situation where old code keeps getting reloaded, keep this in mind.

Resources:
JBoss wiki on Class Loading
Jboss Wiki on Class Loading use cases

Ejb3 Basics: Deploying Message Driven Beans

Farewell to lazy auto queue generation in JBoss 5

MDB’s were never so easy to deploy and manage when ejb3 first came out. In Jboss 4, all you have to do was annotate a class with @MessageDriven, sprinkle some meta data here and there, stick it in the oven and wham! Instant “I cant believe I made an MDB!?!” In Jboss AS 5 however, MDB queues are no longer automatically created for your application anymore on boot. An inspection of the MDB llifecycle illustrates why:

  1. MDB deploys
  2. No existing Topic/Queue
  3. Topic/Queue is automatically created
  4. MDB is undeployed
  5. There’s no callback/hook to remove the created Topic/Queue. And if there was, should undeploying the MDB even be allowed to trigger this action?

blatantly stolen from JBAS-5114, 5th comment down – thanks Andy, and DeCoste by proxy

SO to reiterate… whereas JBoss AS 4.0 would have auto-created and MDB queues for you on boot, in 5.0 this no longer holds true. Consider the following MDB:

package com.examples.mdb;

import javax.ejb.*;
import javax.jms.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@MessageDriven(name = "MyQueue", activationConfig = {
        @ActivationConfigProperty(
        		propertyName = "destinationType", 
        		propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(
        		propertyName = "destination", 
        		propertyValue = "queue/MyQueue"),
        @ActivationConfigProperty(
        		propertyName="DLQMaxResent", 
        		propertyValue="1")
})
public class MyQueue implements MessageListener {
	
	private static final Log log = LogFactory.getLog(MyQueue.class);
	
	public void onMessage (Message msg) {
		try {
			
			log.debug("Processing MyQueue queue...");
			ObjectMessage oMsg = (ObjectMessage) msg;
			
			SomeObject result = (SomeObject ) oMsg.getObject();

			/**
			 * do stuff with the object
			 */

		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

In jboss 4 you could leave your MDB class like this, and the app server would automatically handle everything for you. If you plan on using jboss 5.+ however, you will have to choose one of the following..

Wire it yourself in destinations-service.xml

In /deploy/messaging/destinations-service.xml, you can add the MDB destination yourself, letting jboss know to create your queue on boot. Here’s an example configuration:

<?xml version="1.0" encoding="UTF-8"?>
<!--
	Messaging Destinations deployment descriptor.
 -->
<server>

	<mbean 
		code="org.jboss.jms.server.destination.QueueService"
		name="jboss.messaging.destination:service=Queue,name=MyQueue"
		xmbean-dd="xmdesc/Queue-xmbean.xml">
		<depends optional-attribute-name="ServerPeer">
			jboss.messaging:service=ServerPeer
		</depends>
		<depends>
			jboss.messaging:service=PostOffice
		</depends>      
	</mbean>

</server>

The only thing this configuration needs to change is the queue name – make sure it matches the name of the queue annotated in your MDB class. This by itself is the closest you can get to being lazy. You will need to make sure however that you add one destination for each of the MDB queues your application uses. Option two requires a little bit more work but you don’t have to muck around with the jboss environment…

Add deployment descriptors to auto create the queue via jboss.xml

You can instead deploy the optional jboss.xml file in your ejb jar file’s META-INF folder (in addition to your persistence.xml file if you’re using entities). Your ejb jar structure should then look like this:

ejb-jar.jar
	- / ejb classes and cool stuff here
	- / META-INF
		- MANIFEST.MF
		- persistence.xml
		- jboss.xml

And this is what jboss.xml would look like:

<?xml version="1.0" encoding="UTF-8"?>
<jboss xmlns="http://www.jboss.com/xml/ns/javaee" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee 
                           http://www.jboss.org/j2ee/schema/jboss_5_0.xsd" 
       version="3.0"> 
	<enterprise-beans>
		<message-driven>
			<ejb-name>MyQueue</ejb-name>
			<destination-jndi-name>queue/MyQueue</destination-jndi-name>
			<create-destination>true</create-destination>
		</message-driven>
	</enterprise-beans>
</jboss>

The key command in this file here being: <create-destination>true</create-destination>. This will flag jboss to create the queue for you if it doesn’t already exist. This approach would probably be better suited for jboss only deployments since the flag to auto create the queue is configured within a jboss exclusive deployment descriptor – jboss.xml.

Once either of these has been implemented, your MDB should be deployed, initialized and ready to fire up. Oh, and fist pumps to ALR for pointing me in the right direction – cheers buddy!

XML, Xalan, Endorsed dirs and &..

So recently, we’ve been working on a project that makes use of OpenSAML. As it turns out OpenSAML required newer Xalan libraries (2.7.1 to be precise), the kind that don’t ship with the older incarnation of jboss we are using for the project – version 4.02. Some of you might be more familiar with the jboss system properties and will know there’s a property jboss used specifically to override the standard xml libraries that ship with the jdk/jre (entry in the console output bolded and marked with a *). Jboss will allow you to pass in as a parameter the location for a variable known as “java.endorsed.dirs.” The purpose of this property is to map the file path to the Xalan libraries you would like for jboss to use as the Xalan implementation during runtime.

-Djava.endorsed.dirs=file://path/to/your/xalan/libraries

So if you have other installed applications running in different instances, you wont have to upgrade every instance you’re running concurrently, instead you can override a specific instance’s use of Xalan libraries by using this parameter in the run script. I’m not quite sure what version of Xalan ships with jboss 4.02, but when we upgraded the first thing we noticed was that any xml text in like “&amp;” rendered as “&amp;amp;” post xslt instead of rendering as “&” (presumably a fix set forth as Xalan matured):

<xsl:param name="url">
	http://www.some-url.com/path.do?parameter=value&otherParameter=otherValue
</xsl:param>

turned into

http://www.some-url.com/path.do?parameter=value&amp;amp;otherParameter=otherValue

If you intend to upgrade your Xalan libraries I would think that you might need to do some type of regression testing to make sure upgrading these xml centric libraries doesn’t inadvertently wind up breaking xml dependent sections of your application. It should be noted if you randomly toss upgraded xalan jars into your application you’re bound to run into all kinds of crazy exceptions. I’ve seen jboss complain about login-conf.xml, missing class libraries, weird servlet allocation exceptions, class not founds – all kinds of misleading problems that seem unrelated to xalan jar collisions or wierded out dependancies.

Bottom line is if you need to upgrade Xalan, stick to using java.endorsed.dirs, and pass in the -Djava.endorsed.dirs param into the jboss run script if you want to override a specific instance.

War deployment file structure

What’s a war deployment, do I need my own army?

When it comes to deploying an web based application we have a few options on the table. Well only one really if you stick to J2EE standards, not counting Ear deployments which also deploy web apps via wars. Outside the world of J2EE though, it becomes a crap shoot based on the web framework you’re using. Maybe you ftp your files manually, edit html directly on the server, or upload all your files and rename the folders so the new code is live and the old code is no longer accessible. In the J2EE world, we use deployable artifacts like war files. A war file is basically a collection of files structured in a certain way, that is zipped up. A war file can also be exploded, which means it’s simply not zipped up. So what’s a war look like?

webapp.war
	|-- images/
	|   `-- banner.jpg
	|-- index.html
	`-- WEB-INF/
		|-- jsps/
		|   |-- public/
		|   |   `-- login.jsp
		|   `-- private/
		|       |-- application.jsp
		|       `-- settings.jsp
	    |-- lib/
	    |   `-- some-library.jar
	    |-- classes/
	    |   `-- compiled.class
	    `-- web.xml

There are 2 sections which pretty much divide up the entire archive. All the stuff directly inside the root / of the war file, and then everything that’s inside the WEB-INF directory. The key difference between the two is one is publicly accessible while the other one has protected access; it’s a violation of the spec for an application server to allow public exposure to anything in the WEB-INF folder of your application.

Context

Your war file has an application context. An application context is the reserved namespace your web application has in relation to the application server’s qualified domain name. For example, if on startup you bound jboss to the localhost domain your server’s fully qualified url would be:

http://localhost:8080/

This represents the root of your application server. If you are deploying a single war/a single web application, by default your application will take on the context name of the war file. So in our example above, if we wanted to access webapp.war’s deployed application we would need to call it this way:

http://localhost:8080/webapp

Jboss only!

Out of the box, jboss comes with a default ROOT.war application in the deploy directory that links to other jboss web applications. One great thing about jboss is you can set up your configuration instance to deploy whatever components you want, meaning you can remove this ROOT.war file and use your own as the context root. You would need to replace the default ROOT.war file with the contents of your war file to make your application use the same context. This is kind of messy though, so I would recommend just removing the ROOT.war file and instead stick a jboss-web.xml file in your war’s WEB-INF directory configured like this:

 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 2.3//EN" 
    "http://www.jboss.org/j2ee/dtd/jboss-web_3_0.dtd">

<jboss-web>

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

</jboss-web>

The context-root element here basically tells jboss to load up the war file into the root context of the application server, so calls to “http://localhost:8080/” will be processed by your war file. There’s also a way to map virtual hosts in jboss, discussed in another article, Virtual hosting with Jboss.

Compiled Resources

The other 2 things that need to go into the WEB-INF directory are the WEB-INF/lib and WEB-INF/classes directories. The /lib directory is a place where you put all of your web application’s third party jar files, as well as any jar’d up version of your custom code and resources. If you choose not to jar up all your custom code and resources you can then stick all your .class files and application resources in the WEB-INF/classes directory. From my point of view, its cleaner to just jar everything up and stickem in the /lib directory. Naked class files and resources are so.. messy.. But that’s just my opinion. It’s important to note, if you have empty /lib or /class directories you don’t need to include them in your deployment, they are only required if you are going to stick resources in there.

Static Resources

Now that you’ve figured out all your application resources, you can then then stick all your static resources in the root of your war file. I should point out that there are two sides of the fence about how you should proceed about this though; purists think everything but the basics need to be obscured from the user to prevent them from hacking urls/jsps (by sticking jsps in the WEB-INF, hiding them from exposure) while other folks don’t really care. I think the folks don’t really care that much because they’re using a web framework that hides the true jsp paths and file names. If you’re not using a web framework, it better be for a good reason. You then might want to consider obscuring the jsps in the WEB-INF.

That’s pretty much all there is to a war’s file structure. When it comes time to deploy, most of the time the war file is deployed as a zipped up archive. Jboss also supports the notion of exploded wars, which is basically just an unzipped war file. Exploded wars are like a double edges sword though – if you deploy as an exploded war you get the benefit of not having to redeploy the entire application if you want to fix something like text on a page. Be wary though, circumventing a build process is never a good idea. Build process is there for a reason, its purpose is to track code, updates and and make sure only tested code is released.

Using Jboss Datasource files, JBoss 5.1

If you’re using jboss and you’re storing database connection info in a properties file, you might be doing something wrong. Specifically, you’re probably not using the data source files jboss ships with to configure all that plumbing.

What’s a Datasource file?

Simply put, its a file that contains all the connection properties an application needs in order to connect to a database in xml format. Here’s an example:

<datasources>  
	<local-tx-datasource>
        <jndi-name>DefaultDS</jndi-name>
        <connection-url>jdbc:postgres://dbUrl:5432/schema</connection-url>
        <driver-class>org.postgresql.Driver</driver-class>
	    <user-name>username</user-name>  
	    <password>password</password>
		<metadata>
			<type-mapping>PostgreSQL</type-mapping>
		</metadata>	    
	</local-tx-datasource>
</datasources>

So, the “jndi-name” node gives this datasource configuration the jndi name it will be bound to while the server is running. We’ll need this later since we’ll be using jndi to fetch the datasource configuration. The “connection-url” is the jdbc connection string used to connect to the database; the “driver-class” sets the java driver used to load the database connectors; and the username/password nodes are self explanatory. The “metadata” node is optional, but its good to specify which mapping type jboss should use for this datasource; its job is to set which sql dialect constructs are used to map sql and data during an actual jdbc call. This file itself can be named anything, with the only limitation being that it needs to end with “-ds.xml”. The suffix pretty much flags jboss and lets it know to process the contents of the file as a datasource type. This file needs to be in the deploy directory for it to be loaded up.

Great, now we have a datasource file set up, how do we access it?

If you’re using ejb3, your persistence.xml file references the ds configuration by jndi-name. I’m pretty sure the hibernate configuration files do the same. If you’re using jdbc in your own homegrown persistence layer – gah, read on. Remember how we mapped the ds connection info with a jndi-name? We now get to use the InitialContext object to fetch the ds configuration by name via a jndi lookup:

/*
 *	Returns a java.sql.Connection object, given the ds name to lookup
 *
*/
private Connection getDatasourceConnection(String jndiName) throws Exception { 

	// load the driver first
	Class.forName("org.postgresql.Driver"); 
	String dsFile = "java:/DefaultDS"; 

	// sloppy, but just to show it can be done
	if(jndiName != null) {
		dsFile = jndiName;
	}

	InitialContext ic = new InitialContext(); 
	DataSource ds = (DataSource) ic.lookup(dsFile); 

	// returns an object of java.sql.Connection
	return ds.getConnection(); 
}

What’s powerful about this is because you’re using a jndi name to lookup the datasource, you can set up multiple datasources and just call them by name when you need them. Send in the name of your ds config, and you get back a fully loaded java.sql.Connection object, ready to fire up jdbc calls. But.. jdbc was so.. Y2004…

TANGENT!

If you’re using a legacy jdbc system (hard coded connection strings, ugly bundled properties files to hold connection settings, etc), porting your application to use datasource files could prove to be a worthwhile refactor, its so much cleaner. If you’re building an entirely new application though, take a look at ejb3 persistence, hibernate, they’re mature persistence frameworks that do a lot of the heavy lifting for you. There are others but these two stand out.

Virtual hosting with Jboss 5.1

How do I map a web application to a url in jboss?

If you have multiple web apps deployed in a single jboss instance, you’ll probably want to figure out an effective way to tell them apart when you try to access them from a browser. On startup jboss can be configured to bind to a single url which will act as the default host for all the deployed applications. You can then set up a separate context for each web app you are running. If they’re totally separate applications though, it might not make sense to use a single url and break them out by context. In Jboss you can set up virtual hosts to solve this dilemma. Here’s how to set this up:

WEB-INF/jboss-web.xml

In your web application you’ll want to add an xml file named “jboss-web.xml” to your WEB-INF folder. This is the file that’s going to map both the web application’s context and host in jboss.

<jboss-web>
    <context-root>/</context-root>
    <virtual-host>www.first-application.com</virtual-host>
</jboss-web>

This configuration sets the application’s context to “/” (essentially the root of the default domain), and it also maps the virtual host configuration to “www.first-application.com”. Note that it wont matter if you deploy this configuration from within an ear (embedded war file) or as a standalone war file, as only wars are meant to respond to web requests. Let’s also add the second configuration to the other war file’s WEB-INF/jboss-web.xml:

<jboss-web>
    <context-root>/</context-root>
    <virtual-host>www.second-application.com</virtual-host>
</jboss-web>

Next, we’ll need to add the virtual host configurations to jboss’ server.xml.

jbossweb.sar/server.xml

Now we need to edit jboss’ server.xml file, adding the virtual host mappings:

<Server>
   <Service name="jboss.web"
      className="org.jboss.web.tomcat.tc5.StandardService">
       
      <!-- A HTTP/1.1 Connector on port 8080 -->
      <Connector port="8080" address="${jboss.bind.address}"
                 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
                 enableLookups="false" redirectPort="8443" acceptCount="100"
                 connectionTimeout="20000" disableUploadTimeout="true"/>

      <Engine name="jboss.web" defaultHost="www.first-application.com">
         <Realm className="org.jboss.web.tomcat.security.JBossSecurityMgrRealm"
          certificatePrincipal="org.jboss.security.auth.certs.SubjectDNMapping"
            />
         <Logger className="org.jboss.web.tomcat.Log4jLogger"
                 verbosityLevel="WARNING"
                 category="org.jboss.web.localhost.Engine"/>

            <Host name="www.first-application.com" autoDeploy="false"
                  deployOnStartup="false" deployXML="false">
                <Alias>dev.first-application.com</Alias>
                <Alias>qa.first-application.com</Alias>   
                <Alias>test.first-application.com</Alias>    
                <Valve className="org.apache.catalina.valves.AccessLogValve"
					   prefix="localhost_access_log." 
					   suffix=".log"
					   pattern="common" 
					   directory="${jboss.server.log.dir}" 
					   resolveHosts="false" />
            </Host>   

            <Host name="www.second-application.com" autoDeploy="false" 
                  deployOnStartup="false" deployXML="false">
                <Alias>dev.second-application.com</Alias>
                <Alias>qa.second-application.com</Alias>   
                <Alias>test.second-application.com</Alias>    

                <Valve className="org.apache.catalina.valves.AccessLogValve"
					   prefix="localhost_access_log." 
					   suffix=".log"
					   pattern="common" 
					   directory="${jboss.server.log.dir}" 
					   resolveHosts="false" />
            </Host>

      </Engine>
   </Service>
</Server>

Note the alias map other optional domains that jboss would listen for as aliases of the keyed domains “www.first-application.com” and “www.second-application.com”. All this means is jboss will redirect requests for processing to the respective web application’s whose virtual-host config maps to this host configs.

In order for all of this to work however, we need to make sure dns is set up to handle these domain requests. On a local development machine, you’ll want to edit your hosts file (on windows: c:/WINDOWS/System32/drivers/etc/hosts, on linux: /etc/hosts) and add these entries:

127.0.0.1		www.first-application.com
127.0.0.1		www.second-application.com

This way when you type in one of the domains into your browser, it’ll forward the request to jboss’ bound IP. likewise, if you have jboss bound to a specific domain name/IP on boot, you would have to map that domain/ip in your hosts file just like in the example above.

Now you should be able to fire up jboss, type in either domain into the browser, and have jboss redirect those requests to the corresponding deployed war file.

Ejb3 Basics: Bean Managed Transactions

I’m Lazy, why would I want to do my own transaction management?

While its true that the ejb3 container is usually pretty smart about persisting and handling transactions, its also not as smart as a real human being and probably isn’t able to handle complex database transactions and rollbacks. This is where bean managed transactions come in. By handling your own transactions you can avoid some major pitfalls.

The first problem with Container Managed Transactions (CMT) is there’s a time limit imposed by the container (although it’s a configurable timeout). If you are performing a lengthy task and are persisting the results (like FTPing files over to a third party vendor, persisting the results of a jms queue distribution, or committing across two different data sources – What the heck is a datasource?) then you will want to have control over when the bean commits the transactions. This frees you from a time constraint and also allows you to decide when you want to commit and what rollback strategy you want to use for error management. If you stick to using CMT during these kinds of database transactions, the container will invariably end up flipping out and start throwing all kinds of errors because out of the box the container is usually set to handle short duration transactions (like 5 minutes). Likewise, if a transaction is taking upwards of say, 30 seconds, it might be a sign that the application’s relationship with the database might not be as efficient as possible.

In a perfect world, CMT management streamlines the process for quick and easy transactions like selects, inserts and updates; the type that have all the data ready to insert and don’t have any weird secondary transaction dependencies that need to be completed before committing or inserting. For other weird transaction management handling, user Bean Managed Transactions like this:

/**
 * set up the transaction maangement style for this class
 *
 */
@TransactionManagement(TransactionManagementType.BEAN)
public class MyClass... {


	// set the session context reference, we're going to use it soon
	@Resource private SessionContext sessionContext;

	public void setReminder(ReminderForm reminder) {

		UserTransaction utx = sessionContext.getUserTransaction();  
		try {  

			// begin the transaction
			utx.begin();  

			/**
			 * persist your object
			 * 
			 */
			em.persist(something);

			// attempt to commit the transaction
			utx.commit();

		} catch(Exception e) {

			// something went wrong, lets try to rollback the transaction
			utx.setRollbackOnly();
			log.error("problem with the database transaction: " + 
				e.getMessage());

		}
	}

}

Using those SessionContext objects with this type of construct you can create as many transactions as you want. The container’s transaction management is hands off during the entire body of this class, but you can override individual method with the CMT flag if you must.