Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Connect a Java Swing application to a Geronimo server

Create a stand-alone client that can talk to a Geronimo EJB application

Neal Sanche (neal@nsdev.org), Java Developer, Pure Technologies
Author photo
Neal Sanche is a Java developer recently beached in the Microsoft® .NET world and fighting for any ties back to his old, comfortable roots. His experience includes development of several commercial J2EE applications, as well as several stand-alone Java applications. In his spare time, he writes music, takes photographs, and writes technical articles. Visit his Web site to see several examples of each.

Summary:  In two previous developerWorks articles (see Resources), author Neal Sanche used a simple phonebook application to demonstrate how to connect the Apache Geronimo application server to a database and how to use Geronimo to create a Struts-based Web application with an Enterprise Java™Beans (EJB) back end. This article takes the phonebook application one step further to demonstrate how you can create a stand-alone client application to manipulate the phone-number database. You'll also learn how to configure Geronimo to allow secure access from specific clients.

Date:  26 Jul 2005
Level:  Introductory
Also available in:   Russian

Activity:  15393 views
Comments:  

Introduction

This article will show you how to develop a stand-alone (fat) client that can communicate with an EJB application running inside the Geronimo application server. Building on my two previous articles -- "Three ways to connect a database to a Geronimo application server" (developerWorks, June 2005) and "Dive into EJB Web applications with Geronimo" (developerWorks, July 2005) -- this shows you a Swing client that connects to a small phonebook database built using a Geronimo EJB application. You'll read a brief design description, followed by information on the client libraries you need to run the application. Next I'll explain the methodology for contacting the server and performing operations on a remote stateless session bean on the server. Finally you'll learn how to develop, compile, and run the client application and how to configure the server to allow secure access from specific clients on your network.

To get the most out of this article, you need to be familiar with the Java Swing API for building Java desktop applications and with the Apache Maven build system (see Resources for a link to the Maven Web site).


A design overview

Start by taking a look at the overview of the sample application design -- a Unified Modeling Language (UML) deployment diagram describing the phonebook client application -- shown in Figure 1. The client application connects to Geronimo through its EJB port and talks to the PhoneBook Session EJB to manipulate the data in the database through the PhoneBook Entry Container-Managed Persistence (CMP) Bean.


Figure 1. Phonebook client deployment diagram
Phonebook client deployment diagram

Default distributions of Geronimo have a limitation on the EJB port. You can connect to that port only if your client application is running on the same machine and is connecting through the loopback address (localhost or 127.0.0.1). The Configuring Geronimo's EJB port section later in this article provides details on how to let clients on other machines access the server.


Client libraries for connecting to Geronimo

For your client application to be able to connect to Geronimo's EJB port and communicate with the EJB layer, these Java libraries must be in your client's classpath:

  • geronimo-spec-j2ee-1.4-rc4.jar
  • geronimo-kernel-1.0-SNAPSHOT.jar
  • geronimo-j2ee-1.0-SNAPSHOT.jar
  • geronimo-security-1.0-SNAPSHOT.jar
  • cglib-nodep-2.1.jar
  • openejb-core-2.0-SNAPSHOT.jar

A note on the build structure

Some small modifications were made to the build structure of the code from the previous articles, so the code included with this article contains both the phonebook application and the phonebook client application. The download includes detailed instructions on how to build both using Maven.

When you compile Geronimo from source, these libraries are placed into your local Maven repository and are accessible when you use the Maven build scripts to compile the phonebook client application. You can look at the dependencies section of the project.xml file to see where all of these libraries are located within the Maven repository.

Some of these libraries have important parts to play in the communication between the client and the server. Geronimo uses the CGLib library to perform dynamic proxy generation. This lets the server generate code that calls the server-side components remotely on the fly. If you're in a debugger and examine one of the objects returned from the lookup() method of an InitialContext object on the client, you can see that the dynamically generated objects' class names include CGLib. The geronimo-spec-j2ee.jar file contains all of the Sun Java 2 Platform, Enterprise Edition (J2EE) interfaces and classes. Without this file, the client would not be able to understand any of the dynamic-proxy instances. The openejb-core.jar file is required to talk to the server's EJB port. The Java Naming and Directory Interface (JNDI) classes for performing remote directory lookups within the Geronimo server are in this .jar file. The final three .jar files provide other supporting classes, such as security principals, for talking with Geronimo.


Performing a remote session home lookup

The implementation of the client's communication portion is straightforward. Geronimo is no different from any other J2EE server when it comes to connecting a client to a server, following the well-established standards of communication through JNDI lookups and remote method invocation (RMI). JNDI lookups are the standard way to obtain references to remote objects. To make the connection through JNDI, you must use a number of Geronimo-specific properties to create the InitialContext instance, which is then used to perform lookups. Listing 1 shows an example of how to create a session.


Listing 1. Creating a remote session to a Geronimo-hosted session bean
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public void Connect() {
      String hostName = getHostName();
      String port = getPort();

      Properties props = new Properties();

      props.setProperty("java.naming.factory.initial",
                  "org.openejb.client.RemoteInitialContextFactory");
      props.setProperty("java.naming.provider.url", hostName+":"+port);
      props.setProperty("java.naming.security.principal", "username");
      props.setProperty("java.naming.security.credentials", "passwd");

      Context ic;
      try {
            ic = new InitialContext(props);
            PhoneBookSessionHome sessionHome = (PhoneBookSessionHome)
                  PortableRemoteObject.narrow(
                  ic.lookup(PhoneBookSessionHome.JNDI_NAME),
                  PhoneBookSessionHome.class);
            phoneBookSession = sessionHome.create();
      } catch (Throwable ex) {
            ex.printStackTrace();
      } finally {
            if (ic != null) {
                  ic.close();
            }
      }
}

As Listing 1 shows, you create a Properties object and set four properties. The first and most important is the java.naming.factory.initial property, which must be set to org.openejb.client.RemoteInitialContextFactory. The other properties specify the provider URL and the security principal and credentials. The provider URL is a hostname and port separated by a colon.

As mentioned earlier, the EJB port currently accepts only connections from clients connecting to 127.0.0.1 or localhost. The default port is 4201. The hostname and port can both be configured, however. See the Configuring Geronimo's EJB Port section for details.

Once you've created the properties, you're ready to create the InitialContext instance and use it. Do this by passing the properties to the constructor. After you have an instance, you can perform lookups. Listing 1 includes a complicated line performing the lookup and a PortableRemoteObject.narrow() on the result. This is necessary to hide many of the details about the protocol transport -- RMI or, perhaps, Internet Inter-ORB Protocol (IIOP) -- from the user. After that is done, the remote session is ready to be used. In Listing 1, that line simply creates a new PhoneBookSession and stores it in a field for later use.

After you have a reference to the remote session, it can be used for all of the operations of manipulating phonebook database information. All you need now is an application to exercise the remote session.


Design and development of the client

Now you're ready to dig into the design and development of a small Swing application for browsing, creating, deleting, and modifying phonebook database entries. I'll try to keep the Swing jargon to a minimum, in case you're more familiar with another GUI technology, such as the Standard Widget Toolkit (SWT). In fact, the application's architecture makes it easy to separate the display from the application's internal logic and hook things up to another GUI technology if you need to.

The application's architecture looks something like Figure 2, a UML class diagram showing the application's static structure in detail.


Figure 2. UML class diagram of client application
UML class diagram of client application

The green-shaded classes in Figure 2 are the main application classes. The Main class is a frame that contains a menu and a split pane whose left side is the PhoneNumberListPanel and whose right side is the PhoneBookEditorPanel. The menu also lets the user set preferences for which server to connect to, connect to the server, and exit the program. The Application class is a singleton class that acts as a controller for all of the application's operations. It is the only class where EJB operations are performed, and it holds the reference to the PhoneBookSession stateless session bean.

The two interfaces in orange define the main events in the system. The DataChangeEvent is fired whenever the Application decides the phone-number list needs to be updated. The PhoneNumberListModel registers for that event. Because it is the main data-model list view in the PhoneNumberListPanel, the list is updated by changes to the model. This is in tune with the way Swing applications should be designed.

Both the PhoneNumberListPanel and the PhoneBookEditorPanel classes implement the PhoneBookSelectionListener interfaces and register for events from the Application singleton. When they receive the event, they update their current selections accordingly. In the case of the PhoneBookEditorPanel, the current selection causes the Name and Number fields to be filled in with the data from the currently selected phonebook entry.

If you want to save time when writing user-interface code, you can always find high-quality, free tools on the Internet. Some excellent examples are JGoodies Forms 1.0.5 and a small tool for visually creating the forms called FormLayoutMaker (see Resources for links to these tools). The FormLayoutMaker tool generates XML files that represent the layout constraints for JGoodies forms. These tools helped me quickly create the forms for the Phone Number edit panel and the Preferences panel.


Building the application

There are two ways to compile the application. I developed the application in Eclipse using the Eclipse Visual Editor (VE) plug-in, Version 1.2. It generated much of the code framework for the application, but it does so in a noninvasive way (no code marking and untouchable code blocks), so you should have no trouble if you don't have the VE installed. You can simply load the project and try running it.

You might need to set up your MAVEN_REPO build variable to point to your local Maven repository. You also need to have built Geronimo and the PhoneBook server application included in the source code that is supplied with this article (see Download ). The reason for this is that to compile the client application, the .jar file that contains the EJB interfaces from the server application must be published into your local Maven repository. The Maven build script for PhoneBook does this through the following Maven build-script fragment:


Listing 2. Maven build-script fragment
<goal name="client" prereqs="java:compile">
      <ant:jar destfile="target/${pom.artifactId}-client.jar">
            <fileset dir="target/classes">
                  <include name="**/*.class"/>
            </fileset>
      </ant:jar>
      <artifact:install artifact="target/${pom.artifactId}-client.jar"
            type="jar" project="${pom}"/>
</goal>

The second way to build the application is simply to use Maven. Unpack the files and run the maven command in the PhoneBook directory. Then do the same in the PhoneBookClient directory. If all goes well, you will have created an UberJar -- a JAR file containing everything needed to run the client -- in the target subdirectory.

The two build approaches should work equally well. The advantage of using the Maven approach is that if you haven't downloaded the dependencies already, it automatically downloads them from the remote Maven repository on the ibiblio Web site (see Resources for a link). So if you're having problems with dependencies in Eclipse, try running Maven at least once on the project to rectify any missing libraries.


Running the application

Make sure the PhoneBook server application is deployed into your Geronimo server and running. Then type the following command:

java -jar phonebook-client-uber.jar

You'll see the application pop up, as in Figure 3.


Figure 3. Geronimo phonebook client application
Geronimo phonebook client application

First, from the File menu, select Connect. If you're connecting to the localhost:4201 port, you should get a connection; otherwise, errors will appear in your console window. You can change the server and port you connect to by selecting Edit > Preferences, changing the information, and attempting to connect again. Once connected, you can type a name and number into the phone-number editor and click Save to create a new record. It will appear in the name list. Delete an entry by selecting it and clicking Delete. Change an entry by selecting it, making modifications, and clicking Save.


Configuring Geronimo's EJB port

The methodology for configuring Geronimo's EJB port currently requires editing an XML file and then recompiling Geronimo. A small article on Tom McQueeney's great Geronimo Live blog spells out the details on how to change the Geronimo Jetty listen port using the openejb\modules\assembly\src\plan\j2ee-server-plan.xml file (see Resources for a link to the blog). The same file also contains the configuration information for the EJB port (see Listing 3).


Listing 3. Excerpt from the j2ee-server-plan.xml file
<gbean name="EJBNetworkService" 
class="org.openejb.server.StandardServiceStackGBean">
        <attribute name="name">EJB</attribute>
        <attribute name="port">4201</attribute>
        <attribute name="address">127.0.0.1</attribute>
        <attribute name="allowHosts">127.0.0.1</attribute>
        <attribute name="logOnSuccess">HOST,NAME,THREADID,USERID</attribute>
        <attribute name="logOnFailure">HOST,NAME</attribute>
        <reference name="Executor"><name>DefaultThreadPool</name></reference>
        <reference name="Server">
            <gbean-name>openejb.server:name=EJBServer,*</gbean-name>
        </reference>
</gbean>

You need to edit the j2ee-server-plan.xml file and change the allowHosts attribute. Geronimo supports a number of different types of addresses. You must enter a comma-separated list of addresses with one of the following patterns:

  • An IP address whose last quad is 0. For example, 192.168.10.0 allows any machines on the 192.168.10 network to communicate with the server.
  • Any fully specified IP address.
  • A factorized IP address. This is a special pattern that lets you specify the network part of the address and a list of host addresses in curly braces. For example, 192.168.10.{5,6,7} allows three machines to access the server: 192.168.10.5, 192.168.10.6, and 192.168.10.7.
  • A netmask IP address. This is a type of address that network administrators are familiar with. An IP address matches a netmask based on precise bit pattern matching rules (beyond the scope of this article). For example, 192.168.255.255 allows all addresses in the 192.168.* network to access the server.
  • An exact IPv6 address. When the future IP network comes, Geronimo will be ready to serve, allowing specific IP addresses to be listed.
  • A netmask IPv6 address.

For more details on the specific patterns accepted by the server, consult the source code file -- ServiceAccessController.java -- in the openejb\modules\core\src\java\org\openejb\server directory of the source. There you'll find explicit regular expressions that match each address type supported.

After making the modifications to the j2ee-server-plan.xml file, recompiling, and updating your server deployment, you'll have a server specifically secured to your needs. (You needn't do any of this if you just want to see the client running against a server on the same machine. By default the Geronimo is configured to do exactly that.)


Summary

This article has given you a concrete example of building a stand-alone (fat) client that can to talk to an EJB application running inside the Geronimo application server. The Geronimo team has been careful to implement the established standards, so the simple JNDI lookup method of obtaining a remote connection to a stateless session bean works as advertised. This is good news if you just want to get a simple application running, because it requires you to write only a small amount of code.

By following the pattern I've shown you, you'll be able to connect much larger databases to client applications running on the same machine as the Geronimo server. And with the instructions provided here, you'll also be able to configure your Geronimo server to allow access to the server's EJB port from other machines connected to your network or the Internet. Go ahead and give it a try.



Download

DescriptionNameSizeDownload method
Source code for the phonebook applicationPhonebookClient.zip227 KB HTTP

Information about download methods


Resources

Learn

Get products and technologies

Discuss

About the author

Author photo

Neal Sanche is a Java developer recently beached in the Microsoft® .NET world and fighting for any ties back to his old, comfortable roots. His experience includes development of several commercial J2EE applications, as well as several stand-alone Java applications. In his spare time, he writes music, takes photographs, and writes technical articles. Visit his Web site to see several examples of each.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Java technology, WebSphere
ArticleID=90238
ArticleTitle=Connect a Java Swing application to a Geronimo server
publish-date=07262005
author1-email=neal@nsdev.org
author1-email-cc=ruterbo@us.ibm.com