BUY THIS BOOK
Add to Cart

Print Book $29.95


Add to Cart

Print+PDF $38.94

Add to Cart

PDF $23.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £20.95

What is this?

Looking to Reprint or License this content?


JBoss: A Developer's Notebook
JBoss: A Developer's Notebook By Norman Richards, Sam Griffith
June 2005
Pages: 172

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Installing and Running JBoss
In this chapter:
  • Installing the Server
  • Starting Up JBoss
  • Examining the Server (JMX Console)
  • Shutting Down the Server
  • Specifying a Server Configuration
  • Creating a New Configuration
We will start by installing JBoss and getting the server up and running. You'll be surprised by how easy it is to work with JBoss. It doesn't matter whether you're on Linux, Mac, or Windows; you can get the full JBoss application server running in just a few minutes. So, let's get going.
Installing JBoss is so easy that new users often think they are missing something. But don't mistake this simplicity for lack of power or configurability. Before we get started, you'll need to make sure you have either Java 1.4 or Java 1.5 installed on your machine. That's the only prerequisite for JBoss 4, so if you are all set we'll get started.
You can download the latest JBoss version, currently 4.0.2, from the JBoss download page at http://www.jboss.org/downloads/index. Once you choose the version of the JBoss application server you want, you'll be taken to the SourceForge.net page to do the actual download. When you get there select one of the prebuilt binary distributions. For JBoss 4.0.2 look for a file named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing the Server
Installing JBoss is so easy that new users often think they are missing something. But don't mistake this simplicity for lack of power or configurability. Before we get started, you'll need to make sure you have either Java 1.4 or Java 1.5 installed on your machine. That's the only prerequisite for JBoss 4, so if you are all set we'll get started.
You can download the latest JBoss version, currently 4.0.2, from the JBoss download page at http://www.jboss.org/downloads/index. Once you choose the version of the JBoss application server you want, you'll be taken to the SourceForge.net page to do the actual download. When you get there select one of the prebuilt binary distributions. For JBoss 4.0.2 look for a file named jboss-4.0.2.zip. You'll also see jboss-.4.0.2.tar.gz and jboss-4.0.2.tar.bz2 archives. If either of those formats works better for your platform, feel free to use it instead.
We use Java 1.4 in most examples, but there should be no differences if you use Java 1.5. JRE install.
Before JBoss 4.0.2, JBoss required a full JDK installation to compile JSP files. As of Version 4.0.2, Tomcat ships with its own Java compiler, so JBoss only requires a JRE install.
Many of the releases have service packs, which are marked with the sp designation. Always choose the latest service pack release for the version you are downloading. You might also see source code releases marked with the -src suffix, as well as RC (release candidate) and DR (developer release) versions of the server. Ignore those for now and stick to the production binaries. In this book we will work from the jboss-4.0.2.tar.gz release.
If you are on a Unix machine, we suggest sticking with the .tar.gz release to make sure file permissions are preserved accurately.
Uncompress the download into the directory where you want JBoss installed, using the appropriate tool for your platform. We put the server into
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Starting Up JBoss
You might expect it to be complicated and time consuming to configure the server and get it running for the first time. JBoss is indeed a complex server, but it's simple to run, configure, and maintain. Later in the book we will see the different kinds of configuration and maintenance options, but for now let's just get JBoss up and running.
To start JBoss, you'll need to use the run script in the bin directory of the server. There is a run.sh script for use on Unix machines and a run.bat file for Windows. When you run the script, you'll see something like the following output:
If your run.sh file isn't executable, you should chmod the script or invoke it using the sh run.sh command.
    [bin]$ ./run.sh
    ========================================================= 

      JBoss Bootstrap Environment

      JBOSS_HOME: /Users/samjr/jboss-4.0.2RC1

      JAVA: java

      JAVA_OPTS: -server -Xms128m -Xmx128m -Dprogram.name=run.sh

      CLASSPATH: /Users/samjr/jboss-4.0.2RC1/bin/run.jar:/lib/tools.jar

    =========================================================  

    05:02:58,197 INFO  [Server] Starting JBoss (MX MicroKernel)...
    05:02:58,230 INFO  [Server] Release ID: JBoss [Zion] 4.0.2RC1 (build:
    CVSTag=JBoss_4_0_2_RC1 date=200503140913)
    05:02:58,232 INFO  [Server] Home Dir: /Users/samjr/jboss-4.0.2RC1
    05:02:58,233 INFO  [Server] Home URL: file:/Users/samjr/jboss-4.0.2RC1/
    05:02:58,235 INFO  [Server] Library URL: file:/Users/samjr/jboss-4.0.2RC1/lib/
    05:02:58,238 INFO  [Server] Patch URL: null
    05:02:58,256 INFO  [Server] Server Name: default
    05:02:58,258 INFO  [Server] Server Home Dir: /Users/samjr/jboss-4.0.2RC1/
    server/default
    05:02:58,259 INFO  [Server] Server Home URL: file:/Users/samjr/jboss-4.0.
    2RC1/server/default/
    05:02:58,261 INFO  [Server] Server Data Dir: /Users/samjr/jboss-4.0.2RC1/
    server/default/data
    05:02:58,262 INFO  [Server] Server Temp Dir: /Users/samjr/jboss-4.0.2RC1/
    server/default/tmp
    05:02:58,264 INFO  [Server] Server Config URL: file:/Users/samjr/jboss-4.0.
    2RC1/server/default/conf/
    05:02:58,265 INFO  [Server] Server Library URL: file:/Users/samjr/jboss-4.0.
    2RC1/server/default/lib/
    05:02:58,267 INFO  [Server] Root Deployment Filename: jboss-service.xml
    05:02:58,324 INFO  [Server] Starting General Purpose Architecture (GPA)...
   
        [Lots of startup output removed for brevity]
   
    05:04:05,834 INFO  [TomcatDeployer] deploy, ctxPath=/quote, warUrl=file:/
    Users/samjr/jboss-4.0.2RC1/server/default/tmp/deploy/tmp14739quote.war/
    05:04:06,348 INFO  [Http11Protocol] Starting Coyote HTTP/1.1 on http-0.0.0.0-8080
    05:04:06,868 INFO  [ChannelSocket] JK2: ajp13 listening on /0.0.0.0:8009
    05:04:06,956 INFO  [JkMain] Jk running ID=0 time=0/199  config=null
    05:04:07,092 INFO  [Server] JBoss (MX MicroKernel) [4.0.2RC1 (build:
    CVSTag=JBoss_4_0_2_RC1 date=200503140913)] Started in 1m:7s:977ms
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examining the Server (JMX ConsoleJMX Console
The JBoss application server provides a management application that lets you see and manage the services that are deployed and running inside the server. JBoss itself is implemented as a microkernel composed of managed beans (MBeans). The MBeans that are visible provide you a way to manage the resources and applications that are deployed on your application server. This allows you to monitor and modify applications and their usage. You can see what MBeans you have through the JMX Console. The JMX Console organizes the MBeans by the domain, as well by type (service, database, etc.). When you select an MBean you are taken to a page where you can view and edit attributes or invoke the operations of that MBean.
You can manage all the JBoss services through the JMX Console. If you provide MBeans for your own services, you will see them here too.
You can get to the JBoss JMX Console by going to the main web page (http://localhost:8080) and choosing the JMX Console link. This will take you to the jmx-console web application at http://localhost:8080/jmx-console. When you're there, you'll see something like Figure 1-2.
Figure 1-2: JMX Console
JBoss provides an MBean that allows you to look at your server information. To do that now, scroll down in your browser until you get to the section for the jboss.system domain. You should see a link for this: type=ServerInfo. Choose that link and you'll see the ServerInfo MBean page. It will look something like Figure 1-3.
Figure 1-3: JMX Console view of ServerInfo
You can see what JVM JBoss is running on top of, what operating system it is running on, etc. That's useful information, especially if you are doing remote monitoring.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Shutting Down the Server
Now that you know how to start the server and look at it using the JMX Console, you need to know how to shut it down properly. It's really pretty simple, so let's get to it.
You can shut down the server in three ways:
  • Use the JMX Console to go to the jboss.system domain and choose the type=Server MBean link. On the MBean page, scroll down to the operations section and click the "Invoke" button for the shutdown() operation.
  • Run the shutdown script for your platform in the same directory where you found the run script.
  • Type Ctrl-c in the same console window where you started JBoss.
When JBoss is stopped, you'll see the following message:
    03:50:02,412 INFO  [Server] Shutdown complete
You can verify that JBoss has stopped by trying to access the server in your web browser. You won't be able to connect because the server is not running anymore.
Just as you would expect, the application server shut down. You also learned three different ways to stop JBoss, and you got to see another useful MBean. Of those three ways, when should you use one or the other?
The shutdown script is in the bin directory with the startup script! The twiddle script is a program for "twiddling" with a remote JBoss server.
In development, the Ctrl-c option is the easiest because you will likely have an open terminal window running JBoss. However, if JBoss is running as a service, especially on a remote machine, you'll need to use one of the other options. If you have shell access to the machine, the shutdown script will work fine. You can also use the shutdown command to shut down a remote JBoss instance, but this requires a local JBoss installation and a few extra command-line arguments. For remote machines, it's often more convenient to just use the JMX Console. If you keep a bookmark set to the ServerInfo MBean, it can be a very quick process. In the end, each option serves the needs of different types of users, so just choose whatever is most convenient for you.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Specifying a Server Configuration
JBoss is not only powerful, it's also very configurable. At the center of JBoss is a JMX microkernel that manages the MBeans that control the various services in the server. The JBoss documentation describes the microkernel as a spine, and the analogy fits well. JBoss in its minimum configuration is like the brainstem sitting at the top of the spine. It provides all the core autonomic features (to steal some thunder from IBM's autonomic computing initiative). The spinal column is the attachment point for all the MBeans that want to talk to the brainstem and to each other over the spinal cord. This architecture provides a strong backbone to build on, but at the same time it can work at its most minimal state and still do amazing things. It makes JBoss useful for everything from very small, embedded applications all the way up to full-blown enterprise server applications, all on the same spinal column.
Having a flexible architecture is pointless unless you can make use of that flexibility. JBoss provides several different configurations that range from a barebones server with no J2EE capabilities to a superserver with more services than any single application could possibly use. Figure 1-4 shows the three standard server configurations.
Figure 1-4: Server configurations
Here are descriptions of the server configurations:
There is a huge difference in the size of these configurations. The minimal configuration can start up in just a few seconds, whereas it can take nearly a minute for the all configuration to completely start on a typical developer machine.
minimal
This configuration provides the bare services you might need in the simplest application: logging, JNDI naming services, and URL deployment scanning. You'd use this setup in tight memory situations, or when you want to use JMX to control exactly which MBeans are loaded, and when and how they are loaded. This configuration doesn't provide support for EJBs, web applications, JMS, or any other high-level services. It's just a raw microkernel waiting to be molded.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a New Configuration
You aren't limited to the three configurations JBoss provides. In fact, instead of having unneeded services loaded, wasting memory and CPU space, you can create your own JBoss configuration that has exactly what you need. It's actually quite easy to create a custom configuration.
The easiest way to create your own configuration is to copy an existing one and then rename the folder to something that describes your configuration options. Once you've done that you can add any new JARs and resources to that new server configuration folder.
Let's say you want to create a new configuration based on minimal that you can add other services to later. You can copy the minimal server configuration folder to a new folder in the server folder and call it my_server_config. On Unix this would be cp -R minimal my_server_config.
You can run your new configuration like this:
    [bin]$ ./run.sh -c my_server_config
            
The server will start up using your new configuration, and you'll see console output that looks like this:
    =========================================================

      JBoss Bootstrap Environment

      JBOSS_HOME: /Users/samjr/jboss-4.0.2RC1

      JAVA: java

      JAVA_OPTS: -server -Xms128m -Xmx128m -Dprogram.name=run.sh

      CLASSPATH: /Users/samjr/jboss-4.0.2RC1/bin/run.jar:/lib/tools.jar

    =========================================================
   
    05:49:22,213 INFO  [Server] Starting JBoss (MX MicroKernel)...
    05:49:22,217 INFO  [Server] Release ID: JBoss [Zion] 4.0.2RC1 (build:
    CVSTag=JBoss_4_0_2_RC1 date=200503140913)
    05:49:22,220 INFO  [Server] Home Dir: /Users/samjr/jboss-4.0.2RC1
    05:49:22,221 INFO  [Server] Home URL: file:/Users/samjr/jboss-4.0.2RC1/
    05:49:22,223 INFO  [Server] Library URL: file:/Users/samjr/jboss-4.0.2RC1/lib/
    05:49:22,226 INFO  [Server] Patch URL: null
    05:49:22,244 INFO  [Server] Server Name: my_server_config
    05:49:22,246 INFO  [Server] Server Home Dir: /Users/samjr/jboss-4.0.
    2RC1/server/my_server_config
    05:49:22,247 INFO  [Server] Server Home URL: file:/Users/samjr/jboss-4.0.
    2RC1/server/my_server_config/
    05:49:22,249 INFO  [Server] Server Data Dir: /Users/samjr/jboss-4.0.2RC1/server/my_
    server_config/data
    05:49:22,250 INFO  [Server] Server Temp Dir: /Users/samjr/jboss-4.0.2RC1/
    server/my_server_config/tmp
    05:49:22,251 INFO  [Server] Server Config URL: file:/Users/samjr/jboss-4.0.
    2RC1/server/my_server_config/conf/
    05:49:22,285 INFO  [Server] Server Library URL: file:/Users/samjr/jboss-4.0.
    2RC1/server/my_server_config/lib/
    05:49:22,287 INFO  [Server] Root Deployment Filename: jboss-service.xml
    05:49:22,294 INFO  [Server] Starting General Purpose Architecture (GPA)...

        [More startup information]

    05:50:44,641 INFO  [Server] JBoss (MX MicroKernel) [4.0.2RC1 (build:
    CVSTag=JBoss_4_0_2_RC1 date=200503140913)] Started in 1m:21s:849ms
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Deploying an Application on JBoss
In this chapter:
  • Getting Ant
  • Creating and Packaging the Application
  • Running the Application
  • Modifying the Deployed Application
  • Exploding Deployments
  • Viewing the Application on the Management Console
  • Uninstalling the Application
In the last chapter we focused on getting the application server up and running. Now we will see how to build a simple web application, get it running on the server, and then monitor it. The pattern of build-install-test-monitor is standard in engineering; in this chapter, we'll see how to do those things in JBoss. The application titled "The Great Albert Einstein Quote Machine" demonstrates the deployment of a web application on JBoss while dispensing interesting quotes.
Ant is a build tool made with Java in mind, allowing Java developers to have a tool that fits with the Java environment and mentality. It is an expandable, open source tool that is constantly being upgraded and extended to support the latest Java standards. One specific standard that we use in this chapter is the WAR file, which will allow us to package up our application. We'll learn more about what a WAR file is, and why it's important, in a little bit.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Ant
Ant is a build tool made with Java in mind, allowing Java developers to have a tool that fits with the Java environment and mentality. It is an expandable, open source tool that is constantly being upgraded and extended to support the latest Java standards. One specific standard that we use in this chapter is the WAR file, which will allow us to package up our application. We'll learn more about what a WAR file is, and why it's important, in a little bit.
WAR stands for Web Application Archive.
Ant has an active community of supporters who have helped make Ant the preferred build tool in the Java community (pun intended). With that in mind, we've chosen to use Ant for the examples in this book. At the end of this book, you too might be one of those supporters or contributors. So...
Ant is provided in both source and binary form. For the examples and work we are doing in this book you'll only need the binaries . To get the binaries, go to http://ant.apache.org/bindownload.cgi and download a binary distribution. Choose a binary format that is appropriate for your system.
If you are on a Unix-based system, you might want to choose the /usr/local/ directory. On a PC you might want to install Ant in a top-level directory off of the C:\ drive.
For more about Ant, check out Ant: The Definitive Guide (O'Reilly).
Once you've unpacked the download, you'll need to set the ANT_HOME environment variable to point at the directory in which you unpacked Ant, which is /Users/samjr/apache-ant-1.6.2 in this example. You also need to add Ant's bin directory to your command path. In this example it is /Users/samjr/apache-ant-1.6.2/bin. You can find more information about configuring and installing Ant in the Ant manual, available online at http://ant.apache.org/manual/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating and Packaging the Application
The application is the soon-to-be-classic "The Great Albert Einstein Quote Machine." The application is simple; it consists of five files, including the build file.
To save yourself some typing, you can download the example code for this book from the O'Reilly web site, http://www.oreilly.com. You'll be able to find it on the same page as this book's listing.
In this section we look at the required files for a simple JBoss web application, and the build file to package them up so that JBoss can run them.
Since our application is a web application, it is packaged as a WAR file for deployment on the server. The WAR file has places for JSPs, HTML, libraries, and metadata (see Figure 2-1).
Let's look at the files that go into a WAR file; as we talk about each file we'll identify where it goes in the WAR file.
Figure 2-1: Standard WAR file structure
The first file is the core of our application, quote.jsp:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page import="java.util.Random" %>
    
    <%
      //List of sayings
      String[  ] quotes = {
        "Before God we are all equally wise - and equally foolish",
        "I never think of the future - it comes soon enough",
         "Imagination is more important than knowledge...",
         "Reality is merely an illusion, albeit a very persistent one",
         "The important thing is not to stop questioning",
         "The secret to creativity is knowing how to hide your sources",
         "Science without religion is lame, religion without science is blind",
         "Everything that is really great and inspiring is created by" +
            "the individual who can labor in freedom"
      };
      ArrayList list = new ArrayList(Arrays.asList(quotes)); 
      Random r = new Random();
      int x = r.nextInt(list.size());
      String saying = (String)list.get(x); 
      saying = saying + " -- Albert Einstein";
      pageContext.setAttribute("saying", saying);
    %>
    
    <html>
      <head>
          <title>JBoss Notebook Chapter 2 Demo 1</title>
      </head>
      <body>
        <br>
        <c:set var="sessionCount" scope="session"
                value="${sessionCount + 1}" />
        <c:set var="applicationCount" scope="application"
                value="${applicationCount + 1}" />
        <h1>
            <font color="#1230cb">The Great Albert Einstein Quote Machine</font>
        </h1>
        <h3>
            <spacer size="32" type="horizontal">
            <font color="#a6a6a6">
                ${saying}
            </font>
        </h3>
        <br><br>
        You've visited this application ${sessionCount}
        times in this session
        <br>
        and the application has been visited ${applicationCount}
        times by you and others.
        </body>
    </html>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running the Application
To run the application, first we need to know what the URL is to access the application. You can figure this out by looking at the web.xml and build.xml files. The path to use in the URL is based on the WAR file's name and the url-pattern from the servlet-mapping section in the web.xmlfile. In our case the WAR file is named quote.war and the servlet mapping is quote. This gives us the path /quote/quote, which we put together with the host and port portion of a URL.
Open your web browser and go to http://localhost:8080/quote/quote. You should see something like Figure 2-3.
Leave the web browser open, as you'll probably want to use it in the next lab. You might want to click the browser's refresh button to see the counts on the page go up. After you've done that a few times, do another build. Once that build is done and deployed, click the browser's refresh button a few more times. Now you should see that the counts are different (see Figure 2-4). The application count gets reset each time the servlet is reloaded, which happens whenever you deploy the application. However, the session state doesn't get reset. So, the server is maintaining state; and you're not losing it when you do a redeploy. Hot deploy makes this possible.
Figure 2-3: Einstein quote server
Figure 2-4: Count changes
When you went to the URL for the application, the application compiled and created a servlet based on what is specified in the servlet section of the web.xml file. Then JBoss deployed that servlet and created a mapping based on the servlet-mapping section of the web.xmlfile. Again, the URL is based on the WAR filename created by the build (look in build.xml) and the URL pattern mapping in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Modifying the Deployed Application
Hot deployment allows you to rapidly deploy an application in JBoss by simply placing the application in the deploy directory. JBoss quickly sees the application and deploys it, but ideally you would like to be able to make changes to a live application without deployment delays, no matter how small.
JBoss unpacks those pesky J2EE archives into the tmp/deploy directory. The names are slightly mangled, but you should see a directory whose name ends in quote.war. This directory contains the fully expanded contents of quote.war. Each time you redeploy your application JBoss removes the current temporary directory and replaces it with one of a slightly different name.
If you need to check which version of your application is deployed, check the tmp/deploy directory. Whatever you see there is what JBoss currently has deployed.
You will see a temporary copy of everything you see in the lib and deploy directories. JBoss doesn't keep an open handle on any of the files in those directories. This is very important if your operating system keeps a lock on files while they are being read.
If you edit the quote.jsp file in the expanded quote.war directory, you will see the changes reflected the next time you access the application. That's all you have to do to test out a minor change to a live web application.
You can update JSPs and static web content, but unfortunately you can't update the deployment descriptors. You'll have to redeploy the entire application to pick up a change to them.
...the compiled JSPs?
If you run into a problem where you need to see the compiled JSPs, look in the work/jboss.web/localhost/ directory. The generated Java code is available in a subdirectory named after the context the web application serves.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exploding Deployments
We're sure you can see the power of being able to access the temporary directory JBoss uses to hold expanded archives. If you find yourself wanting to use this feature a lot, JBoss supports the notion of an exploded deployment. Instead of deploying your application in its normal archived form, you can deploy it as a fully expanded directory and save JBoss the trouble of copying it out to the temporary directory.
The exploded WAR directory has the exact same structure as a regular WAR file. Our build file could easily be modified to build to a WAR directory, but since we have a WAR file already made, we'll just use that.
From the deploy directory, we'll expand quote.war into a new WAR directory using the jar command:
    [deploy]$ mkdir quote2.war
    [deploy]$ cd quote2.war/
    [quote2.war]$ jar xvf ../quote.war
      created: META-INF/
    extracted: META-INF/MANIFEST.MF
    extracted: quote.jsp
      created: WEB-INF/
      created: WEB-INF/lib/
    extracted: WEB-INF/lib/jstl.jar
    extracted: WEB-INF/lib/standard.jar
    extracted: WEB-INF/web.xml
    [quote2.war]$ ls
    META-INF        WEB-INF         quote.jsp
You won't find a copy of the application in tmp/deploy when you deploy an exploded archive. It's just not needed.
If you check the console log, you'll see the application has been deployed. Since the new application is deployed as quote2.war, you'll access it at a slightly different URL than before: http://localhost:8080/quote2/quote.
You can edit quote.jsp in the live application, just as you did in the last lab. What is more interesting is that you can edit the deployment descriptors now. When JBoss detects a change to the web.xml file, it will redeploy the whole application. Try adding an additional servlet mapping for quote.jsp and watch the application redeploy.
We discovered how to deploy applications on JBoss in exploded form. This isn't limited to WAR files. Any J2EE archive can be deployed in exploded form. A nested archive, such as a WAR file inside of an EAR file, for example, can be deployed as nested directories. JBoss will always monitor the topmost J2EE deployment descriptor (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Viewing the Application on the Management Console
Now that we've deployed the application and run it, let's see what it looks like in the JBoss Console. We'll take just a quick look at the console for now, but later in the book we will cover it in much more depth.
To see the application in the JBoss Console, you need to open your web browser and go to http://localhost:8080/web-console/. You'll see a screen like Figure 2-5.
Figure 2-5: Web console open to quote.war
You can see quote.war under the JBoss server. You can see that it has QuoteServlet in it, which is what we told it to create from the quote.jsp file in web.xml. If you choose QuoteServlet, you will see servlet statistics about it, including the number of times it has been invoked (see Figure 2-6).
Figure 2-6: Servlet statistics
If you have not closed your web browser, you can reload the application at http://localhost:8080/quote/quote and then click QuoteServlet again to cause the web console application to refresh, at which point you should see the "# Invocations" count go up (see Figure 2-7).
You just saw the JBoss web console and your application deployed onto the server. You also saw that when you ran your application again, the web console could show you those changes. We will spend quite a bit more time on the web console later in the book, but for now we just wanted to give you a quick view of it and show you the possibilities.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Uninstalling the Application
Now, like all good things, our application's time in the limelight has to come to an end. It has served its purpose of entertaining and informing us and now we are ready to undeploy it. Let's see how to do that on JBoss.
Figure 2-7: Going up, up, up
If you deploy an application by placing it into the deploy directory, it stands to reason that undeploying should happen when you remove it from the deploy directory. Sure enough, that holds true. If you delete the quote.war file, JBoss notices this change and undeploys the application. You should get a notice such as this in the log:
    08:56:13,629 INFO  [TomcatDeployer] undeploy, ctxPath=/quote, warUrl=file:/
    Users/samjr/jboss-4.0.2/server/default/tmp/deploy/tmp12813quote.war/
We've also provided an undeploy target that accomplishes this. As you can see, the build file is just deleting the file from the deploy directory:
    [quote]$ ant undeploy
    Buildfile: build.xml

    undeploy:
         [echo] In undeploy
       [delete] Deleting 1 files from /users/samjr/jboss-4.0.2/server/default/deploy

    BUILD SUCCESSFUL
And that's it; the application is gone! This was just a simple web application; we'll move on to a more complete J2EE application in the next chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Creating a Complete Application
In this chapter:
  • Building the EJB Tier
  • Using XDoclet to Build the Web Tier
  • Defining Users
  • Deploying the Application
  • Examining the Database
We're going to take a big step, from a simple web application to a complete J2EE application with both a web and an EJB component. J2EE has a reputation for being complex and requiring a lot of configuration to make it work. That reputation is not entirely undeserved, but it is possible to work with J2EE and avoid much of the complexity.
We'll use two tools to do this. The first is XDoclet. XDoclet is a code-generation tool that allows a developer to work with a single bean class instead of worrying about the myriad related classes that need to be developed. This model resembles the simplified EJB development model that will be introduced in EJB3, except that the metadata is stored in untyped Javadoc-style comments rather than proper language-level metadata. XDoclet also manages the generation of both J2EE and application server-specific deployment descriptors.
The second tool is JBoss itself. JBoss is extremely developer friendly in that you can quickly deploy an application on JBoss without worrying about database integration, security configuration, or any of the other details that can slow down your application development. That is exactly the approach we will take here. We won't ignore those topics forever, but we will skip over them initially and let JBoss fill in the blanks.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building the EJB Tier
The ToDo application looks like any other J2EE application. It consists of an EJB JAR file that contains the EJBs, and a WAR file that provides the web application code. Both of these are wrapped up in an EAR file that comprises the entire enterprise application. Since the web tier depends on the EJB tier , we'll start there.
The EJB tier consists of two local CMP entity beans, TaskBean and CommentBean , and one local session bean, TaskMasterBean. You can find the source code for all the beans in the src/com/oreilly/jbossnotebook/todo/ejb directory.
Notice that there are only three source files for the three enterprise beans, instead of the dozen or so you might normally expect to write. XDoclet will do the heavy lifting and generate all the required J2EE interfaces, as well as a host of other supporting classes.
See the build.xml file for the taskdef operations required to load the XDoclet tasks.
XDoclet isn't just a great tool for developing EJB applications. It's used to develop the JBoss server itself. You'll find XDoclet attributes throughout the JBoss code tree.
The build.xml file contains the ejbdoclet target, which is responsible for invoking the XDoclet-provided ejbdoclet task. This code-generation step needs to take place right before the compile step.
    <target name="ejbdoclet" depends="init">
        <mkdir dir="dd/ejb" />

        <ejbdoclet destdir="${gen.src.dir}" ejbSpec="2.1">
            <fileset dir="${src.dir}">
                <include name="**/*Bean.java"/>
            </fileset>

            <deploymentdescriptor destdir="dd/ejb"/>
            <homeinterface/>
            <remoteinterface/>
            <localinterface/>
            <localhomeinterface/>

            <utilobject includeGUID="true" cacheHomes="true" />
            <valueobject pattern="{0}"/>
            <entitycmp/>
            <session/>
        </ejbdoclet>
    </target>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using XDoclet to Build the Web Tier
The web tier of the application builds on the EJB tier. It provides a simple web interface for a user to manage ToDo items. The application uses JavaServer Faces as the controller. The application needs to provide a few simple backing beans to provide an interface to our back-end EJBs and the JSP pages that make up the view. The JSPs are very standard, so we won't look at them in detail. Instead, we'll look at how we are building and deploying the web tier.
The deployment-descriptor subtask generates the web.xml file.
Once again, XDoclet will come to our aid to make sure we can get the application up and running as fast as possible. While XDoclet isn't quite the hero on the web tier that it is on the EJB tier, it will help us to generate a good deployment descriptor. The webdoclet task invokes XDoclet for us:
    <target name="webdoclet" depends="init">
        <mkdir dir="dd/web" />
        <webdoclet destdir="${gen.src.dir}" mergedir="${merge.dir}">
            <fileset dir="${src.dir}">
                <include name="**/*Servlet.java"/>
                <include name="**/*Filter.java"/>
            </fileset>

            <deploymentdescriptor servletspec="2.4"
                                  destdir="dd/web"
                                  distributable="false"/>
        </webdoclet>
    </target>
Think of merge files as metadata that isn't associated with any particular Java class.
In the ToDo application, we primarily make use of XDoclet merge files to break up the individual configurable elements. Merge files are small code or deployment descriptor fragments that can be inserted into the generated document. The merge files are loaded from the merge directory.
The servlet.xml file provides the servlet definition for the JSF controller servlet:
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining Users
Security is the one exception to the rule for which JBoss provides useful defaults. JBoss needs to know how to check the usernames and passwords required to access the application. At first glance it might seem that JBoss could provide a global repository of names and passwords. That would work fine if all that were required were a username and password, but J2EE applications have a notion of role-based authorization. A username needs not only to be valid, but also to be assigned to a specific role named in the deployment descriptor. There's no generic way to map users onto arbitrary roles, so it is necessary to provide that configuration with the application.
The role name has meaning only to the application. JBoss has no notion of users, administrators, or other such roles.
The default security domain in JBoss looks for user information in properties files inside the application. The first of the properties files is users.properties. It provides usernames and passwords. You can find the file in the web/WEB-INF/classes/ directory:
    pinky=duh
    brain=conquest
The property name (on the lefthand side of the equals sign) is the username, and the property value is the password. Go ahead and add your own user to the file.
The other important file is roles.properties, which maps users onto roles. We declared the application to require the User role in the web-security.xml merge file. We need to make sure that the application users have that role:
    pinky=User
    brain=User
The property name is the username, and the property value is the role assigned to the user. The ToDo application uses only one role, but if we had more than one, we would separate them with commas:
We will configure application security in Chapter 5.
    brain=User,Admin
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying the Application
Both the web and EJB sides of the application are ready. It is possible to deploy the WAR and EJB JAR files created directly to JBoss, but that would require a few more additional configuration steps to link the two parts of the application together. Instead, we'll assemble the application into an EAR file for deployment . It's not only better design, it's also easier.
When you build the application, a todo.ear file is created in the build/jars directory. The EAR file combines the todo.jar and todo.war archives into one larger package. The structure is simple:
    [todo]$ jar tf build/jars/todo.ear
    META-INF/
    META-INF/application.xml
    todo.jar
    todo.war
All that is required is a J2EE application.xml deployment descriptor. XDoclet doesn't generate it, but it is easy enough to produce by hand:
    <application xmlns="http://java.sun.com/xml/ns/j2ee" version="1.4"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                            http://java.sun.com/xml/ns/j2ee/application_1_4.xsd">
        <display-name>JBoss Notebook ToDo Application</display-name>
        <description>JBoss Notebook ToDo Application</description>
        <module>
            <ejb>todo.jar</ejb>
        </module>
        <module>
            <web>
                <web-uri>todo.war</web-uri>
                <context-root>todo</context-root>
            </web>
        </module>
    </application>
In the absence of explicit configuration, JBoss uses the base name of the WAR file as the context root.
The deployment descriptor lists the archives, and in the case of the WAR file it adds the context root of the application telling JBoss what URL space the application serves. The context root is set to todo, which is what JBoss would have used had we deployed the todo.war file separately.
To deploy the application, copy the EAR file to the JBoss
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examining the Database
JBoss provides an embedded relational database called Hypersonic, and it automatically links CMP entity beans to that database in the absence of any other configuration. Using Hypersonic was a big help in getting an application up quickly. But instead of treating it like a big black box, we'll take a little time to dig into it a bit and understand exactly what JBoss is doing with the database.
The Hypersonic database instance is completely embedded in JBoss and offers no connectivity to the world outside of the JBoss server, at least not by default. That means there is no convenient way to access the database from outside of JBoss. It does offer a simple management console, but we will need some co-operation from JBoss to get it running.
The console is at http://localhost:8080/jmx-console, if you forgot.
Fortunately for everyone, all services in JBoss are represented by managed beans (MBeans). The MBean for Hypersonic is responsible for interfacing with the database. You can get to the Hypersonic MBean using the JMX Console. You can load the JMX Console and then locate the database=localDB,service=Hypersonic MBean in the jboss domain.
Following the link provides the list of attributes and operations available. If you look around a bit, you will notice a startDatabaseManager operation. Invoking this operation launches the HSQL Database Manager, shown in Figure 3-2.
Figure 3-2: The HSQL Database Manager
The database manager is not an applet. It is a swing-based tool that is launched from within the JBoss instance. Even if you invoke the operation on a remote machine, the database manager runs on the machine that is actually running JBoss. This can be confusing if you are developing on a remote machine or if you are trying to run JBoss under a different user on the same machine, but it won't cause a problem for a typical development scenario.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Connecting to a Real Database
In this chapter:
  • Setting Up MySQL
  • Adding the JDBC Driver
  • Creating a Datasource
  • Linking the Datasource to Our Application
  • Monitoring the Connection Pool
Modern enterprise applications revolve around relational databases, and our application is no exception. However, up to this point we have barely paid any attention to configuring the all-important database tier. We've been using the embedded Hypersonic database and delegating all the schema management to JBoss. This has allowed us to focus on making our application work first, without needing to bother with the added complexity of a database.
Developing an application with this approach makes a lot of sense, but now that our application is up and running, it's time to turn our attention toward the database, and have our application access a more robust, production-friendly database. We'll use MySQL for the application.
MySQL is a free download that is available from http://dev.mysql.com for every major computing platform. You'll want to download and install the most current MySQL distribution available for your platform. We'll be working from the MySQL Standard 4.1.8 GA version.
We'll assume you can follow the instructions for installing MySQL on your platform. Once you have MySQL running, you'll need to create a database to be used by JBoss. You'll also need to create a database user that has access to the JBoss database for JBoss to use.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting Up MySQL
MySQL is a free download that is available from http://dev.mysql.com for every major computing platform. You'll want to download and install the most current MySQL distribution available for your platform. We'll be working from the MySQL Standard 4.1.8 GA version.
We'll assume you can follow the instructions for installing MySQL on your platform. Once you have MySQL running, you'll need to create a database to be used by JBoss. You'll also need to create a database user that has access to the JBoss database for JBoss to use.
MySQL is administered using the