Jbossj 2 Ee
Jbossj 2 Ee
© JBoss inc, 2004, all rights reserved. The license given with the downloaded version of the book is
a single user license. Redistribution of this document is explicitely forbiden without the prior
written consent of JBoss inc.
Contents
Preface v
: Foreword - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - v
: Target Audience - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - v
: What this Book Covers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - vi
: About the Authors- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - vi
ii
Preparing the Files - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -19
Compiling the Java Source - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -19
Package the EJBs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -20
Package the WAR File. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -20
Package the Java Client - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -20
Assembling the EAR - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -20
The Database - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -21
Enabling the HSQL MBean and TCP/IP Connections - - - - - - - - - - - - - - - - - - - - - 21
Creating the Database Schema - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 22
The HSQL Database Manager Tool- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 23
Deploying the Application - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -24
4.2: JNDI and Java Clients - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -25
The jndi.properties File - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -25
4.3: Security - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -26
Configuring a Security Domain - - - - - - - - - - - - - - - - - - - - - - - - - - - - -26
UsersRolesLoginModule Files- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -27
The J2EE Security Model - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -28
Authentication- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 28
Access Control (Authorization)- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 29
Application JNDI Information in the JMX Console - - - - - - - - - - - - - - - - - - - -29
iii
CHAPTER 7 Web Services with JBoss.Net 42
7.1: JBoss.net - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -42
7.2: Duke’s Bank as a Web Service - - - - - - - - - - - - - - - - - - - - - - - - - - - - -43
The Web Service Archive (WSR) File - - - - - - - - - - - - - - - - - - - - - - - - - -43
Building and Deploying the WSR File - - - - - - - - - - - - - - - - - - - - - - - - - -44
Running the Client - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -45
Net Traffic Analysis - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -45
iv
Preface
Foreword
JBoss started out as an EJB container and has evolved over several years into a
fully fledged application server. While the architecture has grown to support
many new software technologies and additional features, there has always been
an emphasis on the implementation of the J2EE standards, regardless of whether
official certification has been achieved or not.
For the foreseeable future, JBoss will continue to be – first and foremost – a
J2EE application server.
Target Audience
The main aim of this book is to get you up and running with JBoss as quickly as
possible. We will use Sun’s J2EE 1.3 tutorial examples where possible to illus-
trate the deployment and configuration of J2EE applications in JBoss. While the
book is not intended to teach you J2EE, we will be covering the subject from
quite a basic standpoint so it will still be useful if you are new to J2EE. If you
would like to use JBoss to run the standard Sun J2EE tutorials then this is the
book for you. It should ideally be read in parallel with the tutorial texts.
We will cover downloading and installation and see how to start JBoss. Then we’ll have a quick tour of
the server directory structure and layout, the key configuration files and services.
Moving on to the examples, we’ll look at how to deploy the “Duke’s Bank” application from the Sun
J2EE Tutorial. This will let you see JBoss in action as quickly as possible and also gives you a chance to
get some practical experience of simple configuration and deployment issues. Further chapters cover
other J2EE topics which aren’t used in Duke’s Bank – JMS Messaging (and Message-Driven Beans)
and container-managed persistence (CMP). These also make use of the J2EE tutorial examples.
There is a separate chapter on web services. We work through how to expose EJB methods from the
Duke’s Bank application through web servies and then call them with a Java SOAP client.
Configuration of databases is an important issue and this is covered in “Using other Databases” on
page 48. We also work through some step-by-step examples.
In “Security Configuration” on page 56 we look at some more advanced security configuration options.
http://www.jboss.org
At the time of writing, the latest stable release is version 3.2.3. The binary ver-
sions are available as either zip or tar.gz files – the contents are the same so grab
whichever one is most convenient for the platform you’re running on. Once it's
downloaded, unpack the archive to a suitable location on your machine. It should
all unpack into a single directory named “jboss-” with a version-number suffix.
Make sure you don't use a directory which has any spaces in the name (such as
the “Program Files” directory on Windows) as this may cause problems. There
are no additional installation steps needed before you can get started.
Now try running the server: you'll find a bin directory inside the main JBoss directory which contains
various scripts. Execute the “run” script (run.bat if you're on Windows, run.sh if you're on Linux or
another Unix-like system). You should then see the log messages from all the JBoss components as they
are deployed and started up. The last message (obviously with different values for the time and start-up
speed) should be:
00:23:38,718 INFO [Server] JBoss (MX MicroKernel) [3.2.3 (build: CVSTag=JBoss_3_2_3
date=200311301445)] Started in 26s:593ms
To get a live view of the running server, point your browser at the URL
http://localhost:8080/jmx-console2.
You should see something similar to Figure 1.1. This is the JBoss Management Console which provides
a raw view of the JMX MBeans which make up the server3. You don't really need to know much about
these to begin with, but they can provide a lot of information about the running server and allow you to
modify its configuration, start and stop components and so on.
For example, find the “service=JNDIView” link and click on this. This particular MBean provides a
service to allow you to view the structure of the JNDI namespaces within the server. Now find the oper-
ation called “list” near the bottom of the MBean view page and click the “invoke”. The operation
1. This is required so that the tools.jar file, which contains the javac compiler classes, can be located. Javac is
needed for compiling JSPs.
2. Note that by default the web container runs on port 8080, so make sure you don't have anything else already on
your machine using that port. Also, there won’t be a default web application deployed at the root context, so
browsing to http://localhost:8080 will produce a “HTTP Status 500” error from Tomcat. On some
machines, the name “localhost” won’t resolve properly and you should use the local loopback address
“127.0.0.1” instead.
3. The Java Management Extensions (JMX) framework is a key part of the JBoss architecture. The instrumentable
components it defines are called MBeans (“Managed Beans”).
returns a view of the current names bound into the JNDI tree – very useful when you start deploying
your own applications and want to know why you can’t resolve a particular EJB name.
Have a look at some of the other MBeans and their listed operations, and try changing some of the con-
figuration attributes and see what happens. None of the changes made through the console are persist-
ent; the original configuration will be reloaded when you restart JBoss so you can experiment freely and
shouldn’t be able to do any permanent damage.
To stop the server, you can type Ctrl-C or you can run the shutdown script from the bin directory. Alter-
natively, you can use the management console (look for “type=Server” under the section “jboss.system”
and invoke the “shutdown” operation).
On Linux or other Unix-like systems, you will have to install a startup script (or get your system admin-
istrator to do it). There is an example in the JBoss bin directory called jboss_init_redhat.sh which you
can modify and use.
On a Windows system, you can use a utility like Javaservice which is freely available from
http://www.alexandriasc.com/software/JavaService/index.html.
• client – stores configuration and jar files which may be needed by a Java client application or an
external web container. You can select archives as required or use jbossall-client.jar.
• docs – contains the XML DTDs used in JBoss for reference (these are also a useful source of docu-
mentation on JBoss configuration specifics). There are also example JCA1 configuration files for
setting up datasources for different databases (such as MySQL, Oracle, Postgres)2.
• lib – jar files which are needed to run the JBoss microkernel. You should never add any of your own
jar files here.
• server – each of the subdirectories in here is a different server configuration. The configuration is
selected by passing the option “-c <config name>” to the run script. We’ll look at these next.
1. J2EE Connector Architecture – provides a standard for providing connectivity between application servers and
existing Enterprise Information Systems (EIS).
2. JBoss comes with an embedded instance of the free Hypersonic database and there is a corresponding data-
source set up in the default configuration. If you want to use another database then you have to add the appropri-
ate JCA configuration information. We’ll see how to do this later.
Server Structure 6
The JBoss Server – A Quick Tour
Within the server directory, there are three example configurations: all, default and minimal, each of
which installs a different set of services. Not surprisingly, the default configuration is used if you don’t
pass any parameters to the run script, so that’s the one we were running in the previous chapter. It con-
tains everything you need to run a stand-alone J2EE server. The other two are
• minimal – the bare minimum required to start JBoss. It starts the logging service, a JNDI server and
a URL deployment scanner to find new deployments. This is what you would use if you want to use
JMX/JBoss to start your own services without anything else from J2EE. This is just the bare server
– there is no web container, no EJB or JMS.
• all – starts all the available services. This includes the RMI/IIOP and clustering services and the
web-services deployer which aren’t loaded in the default configuration.
You can add your own configurations too. The best way to do this is to copy an existing one that is clos-
est to your needs and modify the contents. For example, if you weren’t interested in using messaging,
you could copy the “default” directory, renaming it as “myconfig”, remove the jms subdirectory and
then start JBoss with the command
run -c myconfig
Whichever server configuration you’re using, the corresponding directory effectively is the server while
JBoss is running. It contains all the code and configuration information for the MBeans, it’s where the
log output goes and it’s where you deploy your applications. Let’s take a look at the contents of the
default directory. If you haven’t tried running the server yet, then do so now, as some of the sub-directo-
ries are only created if JBoss has previously been started. The full directory structure is shown in
Figure 2.1 . The sub-directories are:
• conf – contains the jboss-service.xml file which specifies the core services. Also used for additional
configuration files for these services.
• data – this is where the embedded Hypersonic database instance stores its data. It is also used by
JBossMQ (the JBoss implementation of JMS) to store messages on disk.
Server Structure 7
The JBoss Server – A Quick Tour
• deploy – you deploy your application code (jar, war and ear files) by dropping them in here. It is also
used for hot-deployable services (those which can be added to or removed from the running server)
and for deploying JCA resource adapters3. That’s why there’s a lot of stuff in there already – in par-
ticular you’ll notice the jmx-console application (an unpacked war file) which we were using earlier.
The directory is constantly scanned for updates and any modified components will be re-deployed
automatically. We’ll look at deployment in more detail later.
• lib – jar files needed by this server configuration. You can add required library files here for JDBC
drivers etc.
• log – this is where the logging information goes. JBoss uses the Jakarta log4j package for logging
and you can also use it directly in your own applications from within the server.
• tmp – used by the deployer for temporary storage of unpacked applications etc.
• work – used by Tomcat for compilation of JSPs.
The data, log, tmp and work directories are created by JBoss so won’t exist until you’ve run the server
at least once.
We’ve touched briefly on the issue of hot-deployment of services in JBoss so let’s have a look at a prac-
tical example of this before we go on to look at server configuration issues in more detail. Start JBoss if
it isn’t already running and take a look in the deploy directory again (make sure you’re looking at the
one in the default configuration directory). Remove the mail-service.xml file and watch the output from
the server:
18:20:51,312 INFO [MainDeployer] Undeploying file:/F:/servers/jboss-3.2.2/server/default/deploy/
mail-service.xml
18:20:51,312 INFO [MailService] Stopping18:20:51,312 INFO [MailService] Mail service 'java:/Mail'
removed from JNDI
18:20:51,312 INFO [MailService] Stopped
18:20:51,312 INFO [MailService] Destroying
18:20:51,312 INFO [MailService] Destroyed
18:20:51,312 INFO [DeploymentInfo] Cleaned Deployment: file:/F:/servers/jboss-3.2.2/server/
default/tmp/deploy/tmp32144mail-service.xml
18:20:51,328 INFO [MainDeployer] Undeployed file:/F:/servers/jboss-3.2.2/server/default/deploy/
mail-service.xml
Then replace the file and watch the JBoss re-install the service: hot-deployment in action.
3. The J2EE Connector Architecture defines the Resource Adapter Archive (RAR) file – used for storing JCA
implementations for a particular resource.
Server Structure 8
The JBoss Server – A Quick Tour
If you then restart JBoss, you’ll see that the JNDIView service no longer appears in the management
console listing. In practice, you should rarely, if ever, need to modify this file, though there is nothing to
stop you adding extra MBean entries in here if you want to. The alternative is to use a separate file in
the deploy directory and your service will then also be hot-deployable.
We mentioned already that log4j is used for logging. If you're not familiar with this package and would
like to use it in your applications, you should read more about it on the Jakarta web site. JBoss uses an
XML configuration file to set up log4j. You can find this file in the conf directory. It defines a set of
“appenders” for logging4. By default, JBoss produces output to both the console and a log file (stored in
the log directory). The logging level on the console is INFO whereas the file contains all logging. So if
things are going wrong and there doesn’t seem to be any useful information in the console, always
check the log file to see if there are any debug messages which might help you track down the problem.
You may also have to boost the logging limits set for individual categories. For example you will see
further down the log4j.xml file you may see the entry
<!-- Limit JBoss categories to INFO -->
<category name="org.jboss">
<priority value="INFO"/>
</category>
4. “appender” is a log4j term. It specifies a particular output logging destination, what categories of messages
should go there, the message format and the level of filtering (DEBUG, WARN, INFO etc.) which should be
applied.
which limits the level to INFO for all JBoss classes (apart from those which have more specific over-
rides provided). If you change this to DEBUG it will produce a lot more logging output.
The file appender is set up to produce a new log file every day, so it doesn’t produce a one every time
you restart the server and it won’t write to a single file indefinitely. The current log file is called
server.log. Older files have the date they were written added to the name. You will notice that the log
directory also contains HTTP request logs which are produced by the web container.
As another example, let’s say you wanted to set the output from the container-managed persistence
engine to DEBUG level and to redirect it to a separate file, called cmp.log, in order to analyze the gen-
erated SQL commands. You would add the following code to the log4j.xml file:
<appender name="CMP" class="org.jboss.logging.appender.RollingFileAppender">
<errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
<param name="File" value="${jboss.server.home.dir}/log/cmp.log"/>
<param name="Append" value="false"/>
<param name="MaxFileSize" value="500KB"/>
<param name="MaxBackupIndex" value="1"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
</layout>
</appender>
<category name="org.jboss.ejb.plugins.cmp">
<priority value="DEBUG" />
<appender-ref ref="CMP"/>
</category>
which creates a new file appender and specifies that it should be used by the logger (or “category”) for
the package org.jboss.ejb.plugins.cmp. This will be useful when we come to look at CMP (See “Con-
tainer-Managed Persistence” on page 36.). Full documentation on using log4j can be found at
http://jakarta.apache.org/log4j.
5. The Java Authentication and Authorization Service. JBoss uses JAAS to provide pluggable authentication mod-
ules. You can use the ones that are provided or write your own if have more specific requirements.
We’ll go through the deploy directory in the default configuration and identify the contents. This is
really just for the sake of completeness, so you can skip this section unless you’d like to know more
about the what the existing MBean components are for. In the default configuration deploy directory,
you’ll find the following files and sub-directories:
• http-invoker.sar – provides RMI/HTTP access for MBeans and EJBs.
• jbossweb-tomcat41.sar – an expanded SAR file containing the embedded Tomcat service. This pro-
vides the standard web container within JBoss.
• jms – JMS-specific services grouped together in a subdirectory.
• jmx-console.war – the management console web application which we used in the previous chapter.
• jmx-invoker-adaptor-server.sar – provide remote access to the JMX MBean server.
• management – sub-directory containing alternative management services, including an improved
web console. Currently still in development.
• cache-invalidation-service.xml – allows customized control of the EJB cache via JMS.
• hsqldb-ds.xml – sets up the embedded Hypersonic database service and the default data source.
• jboss-jca.sar – the JBoss JCA implementation. Allows the deployment of JCA resource adaptors
within JBoss.
• jboss-local-jdbc.rar and jboss-xa-jdbc.rar – these are JCA resource adapters to integrate JDBC
drivers which support DataSource and XADataSource respectively but for which there is no propri-
etary JCA implementation.
• mail-service.xml – allows applications and services to use JavaMail from within JBoss. Must be
configured with relevant mail server information.
• properties-service.xml – amongst other things, allows the setting of global system properties (as
returned by System.getProperties).
• schedule-manager-service.xml and scheduler-service.xml – task scheduling service.
• snmp-adaptor.sar – JMX to SNMP adaptor.
• sqlexception-service.xml – provides a means of identifying non-fatal SQL exceptions for a given
JDBC driver.
• transaction-service.xml – together with the MBeans in conf/jboss-service.xml, sets up the JBoss
transaction manager and associated services.
The files in the jms subdirectory are all specific to JMS messaging. Many of them are “invocation lay-
ers” which define the transport protocols over which the message transfer takes place. Additional files
are:
• hsqldb-jdbc2-service.xml – implements caching and persistence using the embedded HSQL data-
base. Also contains the DestinationManager MBean which is the core service for the JMS imple-
mentation.
• jbossmq-destinations-service.xml – sets up standard JMS Topics and Queues which are used by the
JBoss test suite.
• jbossmq-service.xml – additional services for JMS, including the interceptor configuration.
• jms-ra.rar – resource adapter to allow JMS connection factories to be handled by JCA.
• jms-ds.xml – sets up JBoss Messaging as the default JMS provider and supplies JCA configuration
information to integrate the JMS resource adapter with JBoss JCA6.
More detailed information on all these services can be found in “JBoss Administration and Develop-
ment” which also provides comprehensive information on server internals and the implementation of
services such as JTA and the J2EE Connector Architecture (JCA).
which contains a subset of the standard Tomcat format configuration information. As it stands, this
includes setting up the HTTP connector on the default port 8080, an AJP connector on port 8009 (can
be used if you want to connect via a web server such as Apache) and an example of how to configure an
SSL connector (commented out by default).
6. Although the “-ds” suffix is used, it doesn’t apply only to DataSource configuration but can be used to config-
ure any resource adapter for use with JBoss JCA. The <adapter-display-name> element links the information
in the JBoss descriptor to a specific resource adapter.
You shouldn’t need to modify any of this other than for advanced use. If you’ve used Tomcat before as
a stand-alone server you should be aware that things are a bit different when using the embedded serv-
ice. JBoss is in charge and you shouldn’t need to access the Tomcat directory at all – web applications
are deployed by putting them in the JBoss deploy directory and logging output from Tomcat (both inter-
nal and access logs) can be found in the JBoss log directory.
http://java.sun.com/j2ee/tutorial/1_3-fcs/index.html
You should read the getting started information there and download the example
code from
http://java.sun.com/j2ee/1.3/download.html#tutorial
Duke’s Bank also makes some use of the Jakarta “Struts” framework which you
can get from http://jakarta.apache.org/struts.
We will look at how to run the code in JBoss, supplementing the tutorial where
necessary with JBoss-specific configuration information and deployment
descriptors. While you’re online, make sure you’ve downloaded the additional
code that comes with this document – the file should be a zip archive called
jbossj2ee-src.zip. You should be able to get it from
http://www.jboss.org/docs/jbossj2ee-src.zip
The tutorial uses the Apache “ant” build tool, which you should download and install1. Ant is almost
universally used in Java projects these days so if you aren’t already familiar with its use then we recom-
mend you spend some time reading the documentation that comes with it and learning the basics of Ant
build files. The default file name is build.xml ant it contains a set of “targets” which you can use to per-
form automated tasks in your project. Usually all you will have to do is run the “ant” command in the
directory which contains the build file. The default target in the file will perform the necessary work.
The tutorial explains how to run the applications with the J2EE SDK Reference Implementation server.
Our aim will be to deploy them in JBoss.
Container-specific information is usually contained in extra XML descriptors which map logical infor-
mation used in the application (such as JNDI names and security role names) to actual values which are
used in the server. JBoss uses separate files for the EJB and web modules of an application, called
jboss.xml and jboss-web.xml, respectively. There is also a client version of these files which fulfils the
same role in a Java client, in combination with the J2EE application-client.xml descriptor2. If container-
managed persistence (CMP) is being used for entity EJBs, it is also possible to configure the JBoss per-
sistence engine through the jbosscmp-jdbc.xml file.
The J2EE SDK refers to these as “runtime descriptors” and defines all the information under one XML
DTD. The files are all called sun-j2ee-ri.xml once they have been added to the packaged archives by the
build process.
1. You can get an up-to-date copy of Ant from http://ant.apache.org/. Make sure you are using version 1.5.4 or
later.
2. Support for the J2EE application client framework was introduced in JBoss 3.2.3
We’ll look at how to configure JBoss to use a different database in “Using other Databases” on page 48.
Similarly we wouldn’t necessarily recommend that you set up your projects using the same structure as
the examples. We’ve stuck to the simple layout of the originals but in practice you may want to do
things differently. For a start you’ll need to include test code which will often mean writing tests using
the JUnit test framework or one of its close relations. You’ll also need a means of running it as part of
your build. Ant can help you here as it has tasks which are used to run JUnit tests.
If you’re starting out, your best bet is probably to look at some existing open-source projects and see
how they are structured, and then pick something appropriate for your project. Alternatively you might
want to look at a tool like Maven
http://maven.apache.org
which attempts to go beyond Ant and provide a standardized framework for building and testing
projects.
Finally, we hope you’ll realise that there’s a lot more depth to JBoss than we can hope to cover here and
once you’ve worked your way through this basic introduction, we hope you’ll be eager to learn more.
JBoss is also a continually evolving project with lots of plans for the future. So keep an eye on the
bleeding-edge version, even if you’re running all your production applications on the stable 3.2.x series.
One of the first thing you’ll want to do once you’ve got a copy of JBoss is find
out how to get an application up and running and see what’s involved. So we’ll
do just that with the Duke’s Bank example from the J2EE tutorial.
Duke’s Bank demonstrates a selection of J2EE technologies working together to
implement a simple on-line banking application. It uses EJBs, web components
(JSPs and servlets) and uses a database to store the information. The persistence
is bean-managed, with the entity beans containing the SQL statements which are
used to manipulate the data.
The application also makes use of the Struts web framework so you must download this too. You can
get it from
http://jakarta.apache.org/struts.
If you are following the tutorial instructions to build it for the reference implementation, these were
written for Struts 1.0 which is now out of date. It will work with version 1.1 but you must also add the
extra jar files supplied with Struts to the application, along with the struts.jar file.
We’ll go through building and deploying the application first and then look at things in a bit more detail.
Download the struts distribution, as above, and copy the struts.jar, struts-logic.tld and the supporting
jakarta-commons jars (all those prefixed with “commons-”) to bank/jar.
In the j2eetutorial directory you should find a file called “build.properties”. Edit this to set the
jboss.home property to the full path to your JBoss 3.2.x installation2. The build process makes use of
the jar files and utilities that come with JBoss so it needs to know where to find them. If you’ve
unpacked JBoss 3.2.3 to the “C:” drive on a windows machine, you would set it to
# Set the path to the JBoss directory containing the JBoss application server
# (This is the one containing directories like "bin", "client" etc.)
jboss.home=C:/jboss-3.2.3
1. Rather than just overrating the existing build.xml file, we’ve used a different name from the default. This means
that ant must now be run as “ant -f jboss-build.xml”.
2. i.e. the JBOSS_DIST directory (See “Main Directories” on page 5.)
which runs the “compile” target in the build script. If there aren’t any errors, you should find a newly
created build directory with the class files in it.
It contains the application-client.xml and jboss-client.xml descriptors as well as the client jndi.proper-
ties file. The client jar will also be included as an additional module in the EAR file and the server.
and that any other examples are commented out. So you should have something like:
<!-- The jndi name of the DataSource, it is prefixed with java:/ -->
<!-- Datasources are not available outside the virtual machine -->
<jndi-name>DefaultDS</jndi-name>
<!-- for tcp connection, allowing other processes to use the hsqldb
database. This requires the org.jboss.jdbc.HypersonicDatabase mbean. -->
<connection-url>jdbc:hsqldb:hsql://localhost:1701</connection-url>
<!-- for totally in-memory db, not saved when jboss stops.
The org.jboss.jdbc.HypersonicDatabase mbean is unnecessary
<connection-url>jdbc:hsqldb:.</connection-url>
-->
<!-- for in-process db with file store, saved when jboss stops. The
org.jboss.jdbc.HypersonicDatabase is unnecessary
<connection-url>jdbc:hsqldb:${jboss.server.data.dir}/hypersonic/localDB
</connection-url>
-->
Now scroll down to the bottom of the file and you should find the MBean declaration for the Hyper-
sonic service:
<mbean code="org.jboss.jdbc.HypersonicDatabase" name="jboss:service=Hypersonic">
<attribute name="Port">1701</attribute>
<attribute name="Silent">true</attribute>
<attribute name="Database">default</attribute>
<attribute name="Trace">false</attribute>
<attribute name="No_system_exit">true</attribute>
</mbean>
Make sure this is also uncommented. This is also needed if you want to be able to run the HSQL Data-
base Manager tool which we’ll be looking at shortly.
Where necessary, we have supplied modified scripts to run with HSQL and you’ll find them in the sql
directory3. The main differences are in the SQL syntax for applying constraints in the table creation
script hsql-create-table.sql. Apart from that the changes are trivial.
We’ve modified the corresponding tasks in the build file to call the appropriate HSQL tool for running
the script. If JBoss isn’t already running, you should start it now, so that the HSQL database is availa-
ble. First we need to create the necessary tables by running the command
ant -f jboss-build.xml db-create-table
Then run the following command to populate them with the required data
ant -f jboss-build.xml db-insert
and finally, if everything has gone according to plan, you should be able to view some of the data using
ant -f jboss-build.xml db-list
3. Those prefixed with “hsql-” have been altered. The others are identical to the originals.
This will take you to the information for the Hypersonic service MBean4. Scroll down to the bottom of
the page and click the “invoke” button for the startDatabaseManager() operation. This starts up the
HSQL Manager – a Java GUI application which you can use to manipulate the database directly.
4. If you can’t find this, make sure the service is enabled as described in “Enabling the HSQL MBean and TCP/IP
Connections” on page 21.
and this will assemble the EAR file and deploy it. You should see something close to the following out-
put from the server (reduced for brevity):
19:30:32,966 INFO [MainDeployer] Starting deployment of package: file:/F:/servers/
jboss-3.2.3/server/default/deploy/JBossDukesBank.ear
19:30:32,997 INFO [EARDeployer] Init J2EE application: file:/F:/servers/jboss-3.2.3/
server/default/deploy/JBossDukesBank.ear
19:30:34,513 INFO [EjbModule] Deploying AccountEJB
...
19:30:45,356 INFO [Engine] StandardManager[/bank]: Seeding random number generator
class java.security.SecureRandom
19:30:45,356 INFO [Engine] StandardManager[/bank]: Seeding of random number generator
has been completed
19:30:45,356 INFO [Engine] StandardWrapper[/bank:default]: Loading container servlet
default
19:30:45,356 INFO [Engine] StandardWrapper[/bank:invoker]: Loading container servlet
invoker
19:30:45,685 INFO [EARDeployer] Started J2EE application: file:/F:/servers/jboss-
3.2.3/server/default/deploy/JBossDukesBank.ear
19:30:45,685 INFO [MainDeployer] Deployed package: file:/F:/servers/jboss-3.2.3/
server/default/deploy/JBossDukesBank.ear
If there are any errors or exceptions, make a note of the error message and at what point it occurs (e.g.
during the deployment of a particular EJB, the web application or whatever). Check that the EAR is
complete and inspect the WAR file and each of the EJB jar files produced by the build to make sure they
contain all the necessary components (classes, descriptors etc.).
You can safely redeploy the application if it is already deployed. To undeploy it you just have to remove
the archive from the deploy directory. There’s no need to restart the server in either case. If everything
seems to have gone OK, then point your browser at the application URL
http://localhost:8080/bank/main
You should be forwarded to the application login page. As explained in the tutorial, you can login with
a customer Id of 200 and the password “j2ee”5.
5. If you get an error at this point, check again that you have set up the database correctly as described in “Enabling
the HSQL MBean and TCP/IP Connections” on page 21. In particular, check that the connection-url is right.
Then make sure that you have populated the database with data.
You should also be able to run the standalone client application using the command
ant -f jboss-build.xml run-client
This is a Swing GUI client which allows you to administer the customers and accounts.
The first three are standad properties, which are set up to use the JBoss JNDI implementation. The
fourth “j2ee.clientName” is a custom property which identifies the client deployment information on
the server side. The name must match the jndi-name specified in the jboss-client.xml descriptor:
<jboss-client>
<jndi-name>bank-client</jndi-name>
<ejb-ref>
<ejb-ref-name>ejb/customerController</ejb-ref-name>
<jndi-name>MyCustomerController</jndi-name>
</ejb-ref>
<ejb-ref>
<ejb-ref-name>ejb/accountController</ejb-ref-name>
<jndi-name>MyAccountController</jndi-name>
</ejb-ref>
</jboss-client>
You don’t need to worry about any of this if you’re building web applications.
4.3. Security
You may have noticed that we haven’t done anything so far to set up any security configuration for the
application. In fact there isn’t any security to speak of and you can login with any password and gain
access to the account – not much use for an on-line bank. Logging in with an invalid Id will cause the
application to crash when the first JSP tries to access the (non-existent) user’s accounts – not exactly
ideal either.
If a web application doesn’t have a “security domain” specified7, JBoss assigns it a “NullSecurityMan-
ager” instance by default. This will allow any login to succeed, explaining the above behaviour.
If you also want access controls to be applied at the EJB layer, you should add an identical element to
the jboss.xml file too:
<jboss>
<security-domain>java:/jaas/dukesbank</security-domain>
<enterprise-beans>
...
</jboss>
7. The term “security domain” is widely used in security parlance, not always with the same meaning. It generally
refers to a set of users (or components) operating under a common set of authentication and access-control
mechanisms. In JBoss this is seen in the mapping of a security domain name to a particular set of login modules
in the login-config.xml file. The term is often used interchangeably with “realm”.
Security 26
The Duke’s Bank Application
What this means is that JBoss will bind a security manager instance for our application under the JNDI
name java:/jaas/dukesbank. The security domain for our application is named “dukesbank” and you
can configure it in the conf/login-config.xml file which we first saw in “Security Service” on page 10. If
you take a look at that file, you’ll see how each security domain has an application-policy element. The
name attribute is the security domain name, so to add a login configuration for our application, we would
insert an extra entry of the form
<application-policy name = "dukesbank">
<authentication>
<login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
flag = "required" />
</authentication>
</application-policy>
where the authentication element contains a sequence of login-module child elements, each of which
specifies a JAAS login module implementation which will be used to authenticate users. The “required”
flag means that login under this module must succeed for the user to be authenticated. The UsersRoles-
LoginModule which we’ve specified here is a simple login module which stores valid user names, pass-
words and roles in properties files. Any security domains which don’t have a login configuration entry
will default to the policy named “other” which you will find at the bottom of the login-config.xml file.
By default it uses this same login module, so we don’t really need to add a specific entry for our appli-
cation. However it’s a good idea for completeness sake and you may want to experiment with adding
different login modules later.
To recap, here are the steps you need to follow to secure Duke’s Bank:
1. Add the security-domain element to each of the jboss.xml and jboss-web.xml descriptors in the dd
directory. It should already be there, commented out.
2. Add an entry to the conf/login.xml file for the “dukesbank” security domain as above (optional).
3. Create the users.properties and roles.properties files which contain the security information for the
information for the application and include these in the EAR file (this has already been done for
you).
4. Follow through the build steps to re-package the EJBs and the web application (to make sure the
modified descriptors are included).
5. Assemble the EAR file and re-deploy it to JBoss.
Again make sure that the application deploys OK without any errors and exceptions and try accessing it
with your browser as before. This time you should not be able to login without the correct username and
password combination.
Security 27
The Duke’s Bank Application
username=password. The roles.properties entries are the user name and a comma-separated list of roles
for that user.
username=role1,role2...
In Duke’s Bank, the user “200” must be given the role “BankCustomer” to be able to access the web
application and the EJB methods which it calls.
In a real project you will want to use a more sophisticated approach. You can find out more about using
JAAS login modules in the JBoss “JAAS Howto” document which you can download from http://
sourceforge.net/docman/?group_id=22866. We’ll also look at security in more detail in “Security Config-
uration” on page 56.
4.3.3.1 Authentication
The servlet spec. defines a standard means of configuring the login process for web applications. You
will find an example in the element login-config in the web.xml file for Duke’s Bank:
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Default</realm-name>
<form-login-config>
<form-login-page>/logon</form-login-page>
<form-error-page>/logonError</form-error-page>
</form-login-config>
</login-config>
This is specifying that a form-based login should be used to obtain a username and password (as
opposed to HTTP basic authentication for example, where the browser pops up a login dialog). It also
specifies the URL that should be used for the login (/logon) and the URL which the user is forwarded to
on a login error, such as a bad password. The format of the login form – the URL to submit to and the
field names for username and password are defined in the spec. You can see an example in the file
logon.jsp which is used in the application8.
You should keep in mind that the authentication logic which decides whether a login succeeds or fails is
outside the scope of the spec. The actual authentication mechanism is contained in the login modules
that a security domain uses. So by adding the security-domain tag to your application, and thus linking
Security 28
The Duke’s Bank Application
it to an entry in login-config.xml, you are effectively specifying what authentication logic will be used,
be it a database, LDAP or whatever.
If you have a look at in web.xml you will find the access controls under the security-constraint ele-
ment. You can see the list of restricted URLs there under web-resource-collection and the role which is
allowed to access them (BankCustomer) under the auth-constraint element. In the ejb-jar.xml file,
method access is controlled using a series of method-permission elements which contain lists of method
definitions and the roles that can call them (or <unchecked/> for any role).
8. Note that the URL for form logins “j_security_check” is implemented by the web container (Tomcat)
and your code doesn’t play any part in the login process. In practice it isn’t too hard to break the example appli-
cation login (especially when it’s running in Tomcat 4) and you will get exceptions if you do things like brows-
ing directly to the login page or attempting to login twice in the same session. These are issues with the servlet
specification and Tomcat and you can find a lot of discussion of them online, e.g. in the Tomcat bugs database:
http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6279.
The example code just assumes that the standard model will be followed and doesn’t provide any workarounds.
So don’t push it too hard.
Security 29
The Duke’s Bank Application
from Duke’s Bank listed near the top and the contents of their private environment naming contexts as
well as the names the entries are linked to in the server.
which is a list of the active security managers, bound under their security-domain names. Note that
these objects are created on demand, so the dukesbank entry will only appear if you have tried to log in to
the application.
9. The java: namespace is for names which can only be resolved within the VM. Remote clients can’t resolve
them, unlike those in the global namespace.
Security 30
CHAPTER 5 JMS and Message-
Driven Beans
One thing that’s missing from the Duke’s Bank application is any use of JMS
messaging, so we’ll work through the tutorial example on Message Driven Beans
(MDB) to see how to use messaging in JBoss. We’ll assume you’re already
familiar with general JMS and MDB concepts. The J2EE tutorial code for the
MDB is in j2eetutorial/examples/src/ejb/simplemessage. We’ve supplied a build
file in the examples directory which will allow you to build the example from
scratch and run it in JBoss. We’ve also added the ejb-jar.xml file and the
jboss.xml file.
The example code is very simple. There are only two classes, one for the client
and one for the bean (unlike normal EJBs, MDBs don’t need any interfaces). The
client publishes messages to a JMS Queue and the MDB handles them via its
standard onMessage method. The messages are all of type javax.jms.TextMessage
and the bean simply prints out the text contained in each message.
The only container-specific tasks required are setting up the Queue in JBoss, and
configuring the MDB to accept messages from it.
Which will produce archives for the bean and the client and a combined EAR file in the jars directory.
We’ve retained the same layout as the Duke’s Bank build – with a dd directory containing the deploy-
ment descriptors and the jars directory containing the archives produced by the build. The examples
come with a set of pre-built EAR files in the ears directory but we won’t use these.
So the MDB will receive messages from the queue with JNDI name queue/MyQueue.
If you look more closely at this, you will see warnings that the message queue specified in the deploy-
ment doesn’t exist. In this case JBoss will create a temporary one for the application and bind it under
the supplied name. You can check it exists using the JNDIView MBean again – look under the “global”
JNDI namespace. We’ll look at how to explicitly create JMS destinations below.
and you should see output in both the client and server windows as they send and receive the messages
respectively.
can create them dynamically using the jmx-console application. If you use the latter method, they won’t
survive a server restart.
As an excercise, you can try temporarily stopping the delivery of messages to the MDB. Locate the sec-
tion called “jboss.j2ee” in the JMX console and you should find an MBean listed there which is respon-
sible for invoking your MDB. The name should be something like
binding=message-driven-bean,jndiName=local/SimpleMessageEJB,plugin=invoker,service=EJB
1. We’ve adopted the standard JBoss convention of binding queues under the JNDI name “queue” and topics under
“topic” but this isn’t necessary. You can use any name.
and you can start and stop the delivery of messages using the corresponding MBean operations which it
supports.
Then run the client a few times and monitor the queue depth as the messages accumulate. If you re-start
message delivery you should see all the messages arriving at once.
needed to build the database schema is included in the standard descriptor. We’ll look at JBoss-specific
customization later.
Both jar files will be created in the jar directory. Build the client jar using
ant -f jboss-build.xml package-roster-client
There are a few things worth noting here. In the Duke’s Bank application, we specified the JNDI name
we wanted a particular EJBHome reference to be bound under in the jboss.xml file. Without that infor-
mation JBoss will default to using the EJB name. So the session bean is bound under “RosterEJB” and
so on. You can check these in the jmx-console as before. You will also see that the database tables have
been automatically created – there is one for each entity bean and an additional join table to handle the
many-to-many relationship between players and teams. There is no standard naming convention for
either table names or columns but if you take a look at the database schema as we did before (See “The
HSQL Database Manager Tool” on page 23.), you can see that the columns are named after the corre-
sponding fields. This behaviour can be customized (to match an existing schema, for example) by sup-
plying a jbosscmp-jdbc.xml file.
Note that if you increase the logging level for the org.jboss.ejb.plugins.cmp package (See “Logging
Service” on page 9.) to DEBUG, the engine will log the SQL commands which it is executing. This can
be useful in understanding how the engine works and how the various tuning parameters affect the load-
ing of data (see below).
The client performs some data creation and retrieval operations via the session bean interface. It creates
leagues, teams and players which will be inserted into the database (check with the HSQL manager
tool). The session bean methods it calls to retrieve data are mainly wrappers for EJB finder methods.
The command to run the client and the expected output are shown below:
$ ant -f jboss-build.xml run-cmp
Buildfile: jboss-build.xml
run-cmp:
[java] P10 Terry Smithson midfielder 100.0
[java] P6 Ian Carlyle goalkeeper 555.0
[java] P7 Rebecca Struthers midfielder 777.0
[java] P8 Anne Anderson forward 65.0
[java] P9 Jan Wesley defender 100.0
Note that the client doesn’t remove the data, so if you run it twice it will fail because it tries to create
entities which already exist! If you want to run it again you’ll have to remove the data. The easiest way
to do this (if you’re using HSQL) is to delete the contents of the data/hypersonic directory in the server
configuration you are using (assuming you don’t have any other important data in there!) and restart the
server. We’ve also provided a simple delete SQL script which you can run with the command
ant -f jboss-build.xml db-delete
You could also use SQL commands directly through the HSQL Manager tool to delete the data.
CMP Customization 39
Container-Managed Persistence
etc.) and whether the database tables should be automatically created on deployment and deleted on
shutdown. You can customize the names of database tables and columns which the EJBs are mapped to
and you can also tune the way in which the engine loads the data depending on how you expect it to be
used. For example, by using the “read-ahead” element you can get it to read and cache blocks of data
for multiple EJBs with a single SQL call, anticipating further access. “Eager-loading” groups can be
specified, meaning that only some fields are loaded initially with the entity; the others are “lazy-loaded”
if and when they are required. The accessing of relationships between EJBs can be tuned using similar
mechanisms. This flexibility is impossible to achieve if you are using BMP where each bean must be
loaded with a single SQL call. If on top of that you include having to write all your SQL and relation-
ship management code by hand then the choice should be obvious. You should rarely, if ever, have to
use BMP in your applications.
The details of tuning the CMP engine are beyond the scope of this document but you can get an idea of
what’s available by examining the DTD (docs/dtd/jbosscmp-jdbc_3_2.dtd) which is well commented.
There is also a standard setup in the conf directory called standardjbosscmp-jdbc.xml which contains
values for the “default” settings and a list of type-mappings for common databases. The beginning of
the file is shown below:
<jbosscmp-jdbc>
<defaults>
<datasource>java:/DefaultDS</datasource>
<datasource-mapping>Hypersonic SQL</datasource-mapping>
<create-table>true</create-table>
<remove-table>false</remove-table>
<read-only>false</read-only>
<read-time-out>300000</read-time-out>
<row-locking>false</row-locking>
<pk-constraint>true</pk-constraint>
<fk-constraint>false</fk-constraint>
<preferred-relation-mapping>foreign-key</preferred-relation-mapping>
<read-ahead>
<strategy>on-load</strategy>
<page-size>1000</page-size>
<eager-load-group>*</eager-load-group>
</read-ahead>
<list-cache-max>1000</list-cache-max>
...
You can see that, among other things, this sets the datasource and mapping for use with the embedded
Hypersonic database and sets table-creation to “true” and removal to “false” (so the schema will be cre-
ated if it doesn’t already exist). The “read-only” and “read-time-out” elements specify whether data
should be read-only and the time in milliseconds it is valid for. Note that many of these elements can be
used at different granularities such as per-entity or even on a field-by-field basis (consult the DTD for
details). The read-ahead element uses an “on-load” strategy which means that the EJB data will be
loaded when it is accessed (rather than when the finder method is called) and the “page-size” setting
means that the data for up to 1000 entities will be loaded with one SQL command. You can override this
either in your own jbosscmp-jdbc.xml file’s list of default settings or by adding the information to a spe-
cific query configuration in the file.
CMP Customization 40
Container-Managed Persistence
A comprehensive explanation of the CMP engine and its various loading strategies can be found in the
full JBoss Admin. and Development Guide (See Table 1 on page 17).
6.3.1. XDoclet
Writing and maintaining deployment descriptors is a labour-intensive and error-prone job at the best of
times and detailed customization of the CMP engine can lead to some large and complex files. If you
are using CMP (or indeed EJBs) in anger then it is worth getting to grips with the XDoclet code gener-
ation engine (http://xdoclet.sourceforge.net). Using Javadoc-style attribute tags in your code it will gen-
erate the deployment descriptors for you as well as the EJB interfaces and other artifacts if required. It
fully supports JBoss CMP and though the learning curve is quite steep and a bit much when you’re try-
ing to get to grips with the basics, its use is thoroughly recommended (almost essential in fact) for real
projects.
CMP Customization 41
CHAPTER 7 Web Services with
JBoss.Net
Web services are all the rage these days. By transmitting XML data using plat-
form and language-independent protocols (e.g. SOAP over HTTP), the aim is to
achieve genuine interoperability, based on clearly-defined standards. Web serv-
ices are a required part of the J2EE 1.4 specification. There is a lot to learn (start-
ing with a whole pile of new acronyms) so if you’re not already familiar with the
subject, we would recommend you do some reading in advance. A good place to
start would be the JBoss.Net documentation on the JBoss web site, which provides
an excellent overview and links to other sources of information. Another good
source of reference material is the Apache Web Services Project web site at
http://ws.apache.org.
7.1. JBoss.net
JBoss.Net is the JBoss module responsible for providing web services. It is built
around the Apache Axis SOAP implementation (http://ws.apache.org/axis) and is
intended to provide integration with J2EE and JMX. It introduces a new archive
type – the web service archive (WSR) – which allows you to package and deploy
your web services in a similar fashion to standard J2EE modules, taking advan-
tage of the JBoss hot-deployment mechanism.
The JBoss.Net service is included in the “all” server configuration, not the “default” one which we’ve
been using up until now. It’s implemented by the expanded JBoss service archive, jboss-net.sar, in the
deploy directory. To make it available, you have to start JBoss with the command
run -c all
Alternatively you can move the whole SAR into the default configuration or create your own custom
configuration (See “Server Configurations” on page 7.).
With JBoss.Net it is easy to can expose an EJB as a web service, so we’ll do this, using one of the ses-
sion beans from Duke’s Bank as an example. Make sure you have the latest version of Ant, as some ver-
sions of the version of the Xerces parser which come with it can cause problems. We used Ant 1.5.4
(which contains Xerces 2.5) without any problems.
</deployment>
From the listing, you can see how the <service> tag is used to expose the bean is exposed as the web
service “AccountController”. This obviously doesn’t have to be the same as the bean name – the bean is
specified by the beanJndiName parameter. The org.jboss.net.axis.server.EJBProvider class, which is an
extension of the corresponding Axis EJBProvider, is responsible for handling the details. The allowed-
Methods parameter defines which EJB methods should be exposed by the service.
The final beanMapping element specifies that the AccountDetails object should be treated as a Java bean
which means that the (de)serialization to and from SOAP messages will be handled by the Axis bean
serialization classes. An alternative is to use the typeMapping element to set up custom serialization and
deserialization.
To make com.sun.ebank.util.AccountDetails into a valid Javabean class, we have to add a default con-
structor:
public AccountDetails() { }
or it won’t be possible for the client to create the return object from the SOAP message. So you should
do this and then recompile and deploy Duke’s Bank before proceeding. Make sure you deploy it into the
correct server configuration! For example, if you’ve been running the “default” configuration until now,
but have switched to “all” to enable Web Services, then you must obviously place the EAR file in the
JBOSS_DIST/server/all/deploy directory. You can do a sanity check by browsing to the web applica-
tion.
from the bank directory, this should produce the WSR file in the Jar directory. You can then copy the
file to the deploy directory (make sure you copy it to the server configuration you are running). You
should see a short message in the server console to say it has deployed the archive. Duke’s Bank must
be deployed prior to this or you’ll get a ClassNotFoundException for AccountDetails. An alternative
approach, which you would probably adopt in practice, would be to add the WSR file to the EAR and
deploy everything as a single unit.
Once the service is deployed you can view the WSDL (Web Service Description Language) for it by
browsing to to the URL http://localhost:8080/jboss-net/services/AccountController?wsdl
This description of the service interface is the web service equivalent of IDL in CORBA. In this exam-
ple it is generated for us but it is also possible to write the WSDL for the service and then compile code
for it using a tool such as wsdl2java (which comes with Axis).
The client uses the JAXRPC Call interface to invoke the service dynamically, rather than using stub
code compiled from the WSDL. It specifies the method to be invoked using call.setOperationName and
then uses call.registerTypeMapping to define how the returned object should be handled (the latter is an
Axis-specific method and we again use the Axis bean-(de)serialization facilities).
which will pop up the initial configuration window. You can check the Axis user guide for details on
using this but it just involves specifying a local port to listen on (we chose 7070) and the information for
the host and port to forward to (the defaults are “localhost” and “8080” respectively, so you shouldn’t
need to change them). You then have to modify the client to connect to the new port and recompile. You
can then run the client and view the output:
You can also make changes to the request message and resend it, making TCPMon a useful debugging
tool as well.
In the previous chapters, we’ve just been using the JBoss default datasource in
our applications. This is provided by the embedded HSQL database instance and
is bound to the JNDI name “java:/DefaultDS”. Having a database included with
JBoss is very convenient for running examples and HSQL is adequate for many
purposes. However, at some stage you will want to use another database, either to
replace the default datasource or to access multiple databases from within the
server.
If there is no proprietary adapter for the database in question then you can config-
ure it to use one of the two JDBC-wrapper resource adapters which we men-
tioned when we were looking at the various services deployed in JBoss (See
“Additional Services” on page 11). Obviously you need a JDBC driver for this to
work and the classes have to be made available (by copying the driver jar or zip file to the lib directory
of the server configuration you are working with). The main distinction between different datasource
configurations is whether they are set up to use the local or XA-transaction JDBC adapters. The latter
option is only available if the JDBC driver in question provides an implementation of javax.sql.XAData-
1
Source but you can still choose the local option even if an XADataSource implementation is available
(see the two oracle configuration files for example). There is also a “no-transaction” configuration but
you would rarely use this with a database.
Local-transaction datasources are configured using the <local-tx-datasource> element and XA-compli-
ant ones using <xa-tx-datasource>. The example file generic-ds.xml shows how to use both types and
also some of the other elements that are available for things like connection-pool configuration. Exam-
ples of both local and XA configurations are available for Oracle, DB2 and Informix.
If you look at the example files firebird-ds.xml, facets-ds.xml and sap3-ds.xml, you’ll notice that they
have a completely different format, with the root element being <connection-factories> rather than
<datasources>. These use an alternative, more generic JCA configuration syntax used with a pre-pack-
aged JCA resource adapter. As we mentioned in “Additional Services” on page 11, the syntax is not
specific to datasource configuration and is used, for example, in the jms-ds.xml file to configure the
JMS resource adapter.
8.2. Examples
We’ll work through some step-by-step examples to illustrate what’s involved.
1. The local and XA transaction contracts are discussed in chapter 7 of the JCA 1.5 Specification.
Examples 49
Using other Databases
example we’ve used MySQL 4.0.13 and Connector/J 3.0.9 on Windows XP. You can download them
both from http://www.mysql.com.
We’ll assume that you’ve already installed MySQL and that you have it running and are familiar with
the basics. Run the mysql client program from the command line so we can execute some administra-
tion commands. You should make sure that you are connected as a user with sufficient privileges (e.g.
by specifying the “-u root” option to run as the MySQL “root” user).
First create a database called “jboss” within MySQL for use by JBoss
mysql> CREATE DATABASE jboss;
Query OK, 1 row affected (0.05 sec)
Then create a user called “jboss” with password “password” to access the database
mysql> GRANT ALL PRIVILEGES ON jboss.* TO jboss@localhost IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.06 sec)
Examples 50
Using other Databases
which mirrors the database and user information we set up in the previous section. Our aim here is to
replace the default datasource in JBoss with a MySQL version, so you have to remove the existing
hsqldb-ds.xml from the deploy directory or there will be a conflict between the JNDI names of the two
datasources. Copy the new file in its place and start JBoss.
You may notice some exceptions during JMS startup and error messages about SQL syntax. This is
because the message persistence manager uses SQL subqueries (nested select statements) which have
been introduced in MySQL 4.1 (which is still in alpha release). There are alternative service files for
use with MySQL and other databases in the examples/jms directory2.
2. The file for MySQL is mysql-jdbc2-service.xml. Make sure you don’t use the “mssql” one by mistake. Replace
the occurrence of “MySqlDS” with “DefaultDS” and replace the file jms/hsql-jdbc2-service.xml in the deploy
directory with this one.
Examples 51
Using other Databases
After restarting JBoss, you should be able to deploy the application and see the tables being created as
we did in “Deploying and Running the Application” on page 37. The tables should be visible from the
MySQL client:
mysql> show tables;
+---------------------------------+
| Tables_in_jboss |
+---------------------------------+
| jms_messages |
| jms_transactions |
| leagueejb |
| playerejb |
| teamejb |
| teamejb_players_playerejb_teams |
+---------------------------------+
6 rows in set (0.00 sec)
You can see the JMS persistence tables in there too, since we’re using MySQL as the default data-
source.
http://www.oracle.com.
Installing and configuring Oracle is not for the faint of heart – it isn’t really just a simple database but is
heavy on extra features and technologies which you may not actually want (another Apache web server,
multiple JDKs, Orbs etc.) but which are usually installed anyway. So we’ll assume you already have an
Oracle installation available – for this example, we’ve used Oracle 9.2.0.1 for Linux3.
3. If you are installing on Linux and are using Redhat, you have to tweak the installation a bit as it won’t work out
of the box. Read the article linked to from Oracle’s web site and make sure you have plenty of spare time.
Examples 52
Using other Databases
The transaction service uses this to create XA transactions identifiers. The comment explains the situa-
tion: for use with Oracle you have to include the line which sets the attribute “Pad” to “true”. This acti-
vates padding the identifiers out to their maximum length of 64 bytes. Remember that you’ll have to
restart JBoss for this change to be put into effect, but wait until you’ve installed the JDBC driver classes
which we’ll talk about next.
The Oracle JDBC drivers can be found in the directory $ORACLE_HOME/jdbc/lib. Older versions,
which may be more familiar to some users, had rather uninformative names like “classes12.zip” but at
the time of writing the latest driver version can be found in the file ojdbc14.jar. There is also a debug
version of the classes with “_g” appended to the name which may be useful if you run into problems.
Again, you should copy one of these to the lib directory of the JBoss default configuration. The basic
driver class you would use for the non-XA setup is called oracle.jdbc.driver.OracleDriver. The XADa-
taSource class, which we’ll use here, is called oracle.jdbc.xa.client.OracleXADataSource.
For the configuration file, make a copy of the oracle-xa-ds.xml example file and edit it to set the correct
URL, username and password:
<datasources>
<xa-datasource>
<jndi-name>XAOracleDS</jndi-name>
<track-connection-by-tx>true</track-connection-by-tx>
<isSameRM-override-value>false</isSameRM-override-value>
<xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
<xa-datasource-property name="URL">jdbc:oracle:thin:@monkeymachine:1521:jboss
</xa-datasource-property>
<xa-datasource-property name="User">jboss</xa-datasource-property>
<xa-datasource-property name="Password">password</xa-datasource-property>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter
</exception-sorter-class-name>
<no-tx-separate-pools/>
</xa-datasource>
<mbean code="org.jboss.resource.adapter.jdbc.xa.oracle.OracleXAExceptionFormatter"
name="jboss.jca:service=OracleXAExceptionFormatter">
<depends
optional-attribute-name="TransactionManagerService">jboss:service=TransactionManager
</depends>
</mbean>
</datasources>
We’ve used the oracle thin (pure java) driver here and assumed the database is running on the host
“monkeymachine” and that the database name (or SID in Oracle terminology) is “jboss”. We’ve also
assumed that you’ve created a user “jboss” with all the sufficient privileges. You can just use “dba”
privileges for this example:
[oracle@monkeymachine oradata]$ sqlplus /nolog
SQL*Plus: Release 9.2.0.1.0 - Production on Sun Nov 9 23:11:25 2003
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Examples 53
Using other Databases
Now copy the file to the deploy directory. You should get the following output:
21:11:00,046 INFO [MainDeployer] Starting deployment of package: file:/F:/servers/
jboss-3.2.2/server/default/deploy/oracle-xa-ds.xml
21:11:00,171 INFO [RARDeployment] Started jboss.jca:service=ManagedConnectionFac-
tory,name=XAOracleDS
21:11:00,171 INFO [JBossManagedConnectionPool] Started jboss.jca:service=ManagedCon-
nectionPool,name=XAOracleDS
21:11:00,187 INFO [XAOracleDS] Bound connection factory for resource adapter for Con-
nectionManager
'jboss.jca:service=XATxCM,name=XAOracleDS to JNDI name 'java:/XAOracleDS'
21:11:00,187 INFO [TxConnectionManager] Started jboss.jca:service=XATxCM,name=XAOra-
cleDS
21:11:00,234 INFO [OracleXAExceptionFormatter] Started jboss.jca:service=OracleXAEx-
ceptionFormatter
21:11:00,234 INFO [MainDeployer] Deployed package: file:/F:/servers/jboss-3.2.2/
server/default/deploy/oracle-xa-ds.xml
and if you use the JNDIView service from the JMX console as before, you should see the name “java:/
XAOracleDS” listed.
There are other oracle type-mappings available too – if you’re using an earlier version, have a look in
the conf/standardjbosscmp-jdbc.xml file to find the names. As above, you can also modify the default
values directly in this file which will set them for all CMP deployments and also save you having to re-
package the EAR file.
Deploy the application as before, check the output for errors and then check that the tables have been
created using Oracle SQLPlus again from the command line:
Examples 54
Using other Databases
TABLE_NAME
------------------------------
LEAGUEEJB
PLAYEREJB
TEAMEJB
TEAMEJB_PLAYERS_PLAYE_1TKRO4S
Examples 55
CHAPTER 9 Security
Configuration
We’ve already seen how to set up simple security when we looked at the Duke’s
Bank application (See “Security” on page 26.). We looked at how to enable secu-
rity by adding a security domain element to the jboss-specific deployment
descriptors and thus linking your application to a configuration in the login-con-
fig.xml file. However we only used simple file based security in that chapter.
In this chapter, we’ll examine some more advanced configuration options and
find out how to use some of the other login modules that are available.
This gives you the flexibility to use an existing database schema. Let’s suppose that the security data-
base tables were created using the following SQL
CREATE TABLE Users(username VARCHAR(64) PRIMARY KEY, passwd VARCHAR(64))
CREATE TABLE UserRoles(username VARCHAR(64), userRoles VARCHAR(32))
then to use this as the security database for Duke’s Bank, you would modify the “dukesbank” entry in
the JBoss login-config.xml file as follows:
<application-policy name="dukesbank">
<authentication>
<login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule"
flag="required">
<module-option name="dsJndiName">java:/DefaultDS</module-option>
<module-option name="principalsQuery">
select passwd from Users where username=?
</module-option>
<module-option name="rolesQuery">
select userRoles,'Roles' from UserRoles where username=?
</module-option>
</login-module>
</authentication>
</application-policy>
The query to retrieve the password is straightforward. In the case of the roles query you will notice that
there is an additional field with value “Roles” which is the “role group”. This allows you to store addi-
tional roles (for whatever purpose) classified by the role group. The ones which will affect JBoss per-
missions are expected to have the value “Roles”. In this simple example we only have a single set of
roles in the database and no role group information1.
We’ve used the default DataSource here. If you’re using Hypersonic, then you can easily create the
tables and insert some data using the Database Manager tool which we also used in the Duke’s Bank
chapter. Just execute the two commands above and then the following ones to insert the information for
the user with customer Id “200” :
INSERT INTO Users VALUES(‘200’,’j2ee’)
INSERT INTO UserRoles VALUES(‘200’,’BankCustomer’)
1. You can also use the default schema which is to have a table called “Principals” with columns “PrincipalID” and
“Password” and a table called “Roles” with columns “PrincipalID”, “Role” and “RoleGroup”. In this case you
don’t have to specify the SQL queries for the login module. The RoleGroup entries for JBoss permissions
should be set to the value “Roles” as before.
<module-option name="hashAlgorithm">MD5</module-option>
<module-option name="hashEncoding">base64</module-option>
This indicates that we want to use MD5 hashes and use Base64 encoding to covert the binary hash value
to a string. JBoss will now calculate the hash of the supplied password using these options before
authenticating the user, so it’s important that we store the correctly hashed information in the database.
If you’re on a Unix system or have Cygwin installed on Windows you can use the following command:
$ echo -n "j2ee" | openssl dgst -md5 -binary | openssl base64
glcikLhvxq1BwPBZN0EGMQ==
and insert the string “glcikLhvxq1BwPBZN0EGMQ==” into the database in place of the password “j2ee”. If
you don’t have this option, you can use the class org.jboss.security.Base64Encoder which you’ll find in
the jbosssx.jar file.
$ java -classpath ./jbosssx.jar org.jboss.security.Base64Encoder j2ee MD5
[glcikLhvxq1BwPBZN0EGMQ==]
With a single argument it will just encode the given string but if you supply the name of a digest algo-
rithm as a second argument it will calculate the hash of the string first.
Throughout this book we have been referring to the JMX Console web applica-
tion which you can view by browsing to http://localhost:8080/jmx-console. How-
ever there is also a new management console application which extends the
functionality to include statistics on deployed J2EE components such as EJBs
and servlets.
The URL for the web console is http://localhost:8080/web-console. You will get
more out of it if you have some applications deployed and been running them to
accumulate some statistics. For example, with the Duke’s Bank application
deployed you’ll see something like Figure A.1, which shows the statistics for the
AccountController stateful session bean. The invocation statistics are self-
explanatory; you have a list of methods and the max, min, average time per invo-
cation as well as the total time spent in the method and the number of invoca-
tions. The number of concurrent invocations is shown underneath the table of
methods.
The information in the “Bean Statistics” section shows information on the bean
instance numbers. The details vary depending on the type of bean and the possi-
ble values are shown in Table 1 on page 60. For a complete description of the
bean states (“method-ready”, “pooled”, “ready” etc.) see the EJB specification.
60
TABLE 1. Bean Statistics Data
RemoveCount The number of beans that have been explicitly removeda.
PassiveCount The number of beans that have been passivated by the container.
Entity Bean
CreateCount Number of entities that have been created by calls to create
method.
RemoveCount Number of entities that have been removed (deleted) by calling
remove method.
ReadyCount Number of beans that are in the “ready” state - assigned an entity
object and ready to handle invocations.
PooledCount Number of beans in the “pooled” state. JBoss doesn’t use entity
instance pooling so this will be zero.
a. Note that RemoveCount may not equal CreateCount over time as the beans may be passivated
and then time-out without the remove method being called.
The web-console isn’t a pure web application but uses a Java applet for the tree view on the left-hand
side. So you’ll need to have the Java plugin installed and have Java enabled to make it work.
61