Adv BK
Adv BK
Platform
Preface
As an experienced developer on the Java™ platform, you undoubtedly know how fast mov-
ing and comprehensive the platform is. Its many application programming interfaces (APIs)
provide a wealth of functionality for all aspects of application and system-level program-
ming. While there are many good books and online documents that detail all the parameters
that an API has, finding a book that brings these APIs together and uses them to solve an
advanced business problem has always been a challenge.
This book fills that void by presenting the design, development, test, deployment and debug-
ging phases for an enterprise-worthy auction application. It is not purely a reference for the
Java APIs, but a practical, hands-on guide to building successful projects with the Java plat-
form. Like any good handbook on your car or house, it includes an entire section on what to
do if things do not go so well. You will find sections that detail everything from what steps to
take when troubleshooting bugs to tips on performance.
While the example application does not cover every possible programming scenario, it
explores many common situations and leaves you with a solid base of knowledge so you can
go on and use the Java platform to design, build, debug, and deploy your own solutions.
Developing one application throughout the book is a tool to help you fast-track learning new
features. For example, you gain a working knowledge of RMI in one section, and a follow-
ing section on CORBA explains the similarities and differences between the two.
You can get a download of the example application source code and explore more informa-
tion on any topic presented here by visiting the Java Developer ConnectionSM (JDC) web site
at http://developer.java.sun.com, or the main Java web site at http://java.sun.com.
The example for this book is an auction application because of the growing popularity of and
interest in web-based electronic commerce. The example runs on a real application server
using Enterprise JavaBeans™ technology, which is particularly well-suited to electronic
commerce applications. Later chapters expand the core example by adding advanced func-
tionality, improvements, and alternative solutions to do some of the things you get for free
when you use the Enterprise JavaBeans platform. Additional topics important to applications
development such as security, transaction management, and performance tuning are also pre-
sented.
This book is for developers with more than a beginning level of understanding of writing
programs in the Java programming language. The example application is written with the
4 PREFACE
Java 2 platform APIs and explained in terms of functional hows and whys, so if you need
help installing the Java platform, setting up your environment, or getting your first applica-
tion to work, you should first read a more introductory book such as Essentials of the Java
Programming Langauge: A Hands-On Guide or The Java Tutorial .
Acknowledgements
We would like to thank Tony Squier for writing the code for the Thread Pooling (page 342)
section, and the web session code for the Servlets (page 145) section. Tony also helped on
the initial design and content, and with Joe Sam Shirah, came up with the idea for a book
like this.
Special thanks to Isaac Elias, Daniel Liu, Mark Horwath, Satya Dodda, and Mary Dageforde
for their contributions to the advanced examples and all the Java Developer Connection
members who sent in suggestions and corrections. Also, the Printing Graphics in Project
Swing (page 259) and Writing a Security Manager (page 422) sections used code adapted
from The Java Tutorial and The Java Tutorial Continued by Kathy Walrath, Mary Campi-
one, and The Tutorial Team.
We would also like to thank the following for reviewing and checking the book for accuracy
Bob Bell, Rama Roberts, Erik Larsen, <<add A-W reviewers>>.
5
Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Acknowledgements 4
1: Matching Project Requirements with Technology . . . . . . . . . . . . . . 1
Project Requirements 2
Interview User Base 2
Auction House Requirements 2
User Requirements 2
Model the Project 2
Activity Diagram 6
Choosing the Software 7
Duke’s Auction Demonstration 7
Home Page 8
Registration Page 9
Items Closing Today 10
All Items 11
Search for Items 11
Sell Items 12
2: Auction House Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
A Multitiered Application with Enterprise Beans 14
Thin-Client Programs and Multitiered Architecture 14
Entity and Session Bean Differences 16
Auction House Workings 17
Developing and Running Applications 19
How Multitiered Applications Work 19
How Enterprise Beans are used in the Example 20
AuctionServlet 20
Entity Bean Classes 22
AuctionItem Entity Bean 22
Auction Items Table 23
Registration Entity Bean 24
Registration Table 24
Session Bean Classes 24
Bidder Session Bean 25
Seller Session Bean 25
Container Classes 25
6
Managing Transactions 59
Why Manage Transactions? 60
Session Synchronization 60
Container-Managed Example 61
Session Synchronization Code 61
Transaction Commit Mode 63
Bean-Managed finder Methods 68
AuctionServlet.searchItems 68
SearchBean 70
Database Connection 70
Get Matching Items List 70
Create Method 71
Code for this Chapter 72
RegistrationBean (SQL) 72
SellerBean (Session Synchronization) 75
searchItems Method 77
SearchBean 77
4: Distributed Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Lookup Services 82
Java Naming and Directory Interface (JNDI) 82
CORBA Naming Service 84
Interoperable Object References (IOR) 87
Remote Method Invocation (RMI) 88
RMI Over Internet Inter-ORB Protocol (IIOP) 89
Improving Lookup Performance 91
Remote Method Invocation 91
About RMI 92
RMI in the Auction Application 92
Establishing Remote Communications 97
RegistrationServer Class 98
Registration Interface 103
RegistrationHome Interface 104
ReturnResults Interface 104
SellerBean Class 105
8
java.io.File 450
java.io.FileInputStream 450
java.io.FileOutputStream 451
java.io.ObjectInputStream 451
java.io.ObjectOutputStream 451
java.io.RandomAccessFile 451
java.lang.Class 452
java.lang.ClassLoader 453
java.lang.Runtime 454
java.lang.SecurityManager 454
java.lang.System 454
java.lang.Thread 455
java.lang.ThreadGroup 456
java.lang.reflect.AccessibleObject 457
java.net.Authenticator 457
java.net.DatagramSocket 458
java.net.HttpURLConnection 459
java.net.InetAddress 459
java.net.MulticastSocket 459
java.net.ServerSocket 460
java.net.Socket 460
java.net.URL 460
java.net.URLConnection 461
java.net.URLClassLoader 461
java.rmi.activation.ActivationGroup 461
java.rmi.server.RMISocketFactory 461
java.security.Identity 461
java.security.IdentityScope 462
java.security.Permission 462
java.security.Policy 462
java.security.Provider 462
java.security.SecureClassLoader 463
java.security.Security 463
java.security.Signer 463
java.util.Locale 463
java.util.zip.ZipFile 464
C: Security Manager Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
D: API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
ActionListener Interface 469
WindowListener Interface 469
Graphics Class 469
15
1: Matching Project
Requirements with
Technology
One challenge in writing a book on advanced application development for the Java™ plat-
form is to find a project small enough to write about, while at the same time, complex
enough to warrant advanced programming techniques. The project presented in this book is
a web-based auction house. The application is initially written for the Enterprise Java-
Beans™ platform. Later chapters expand the core example by adding advanced functionality,
improvements, and alternative solutions to do some of the things you get for free when you
use the Enterprise JavaBeans platform.
To keep the discussion simple, the example application has only a basic set of transactions
for posting and bidding on auction items. However, the application scales to handle multiple
users, provides a three-tiered transaction-based environment, controls security, and inte-
grates legacy-based systems.
This chapter covers how to determine project requirements and model the important steps
that should always come before coding begins.
Project Requirements
The first step in determining project requirements is to interview the user base to find out
what they want in an online auction. This is an important step, and one that cannot be over-
rated because a solid base of user-oriented information helps you define your key application
capabilities.
2: Auction House Application (page 13) walks through the application code, explains how
the Enterprise JavaBeans platform works, and tells you how to run a live demonstration. If
you have never seen or used an online auction, Duke’s Auction Demonstration (page 7)
shows mock-ups of the example auction application HTML pages.
User Requirements
• Bid on or sell an item
• Search or view items for sale
• Notify buyer and seller of sale
tion. Not all actors are people, though. For example, the software is the actor that determines
when an item has closed, finds the highest bidder, and notifies the buyer and seller of a sale.
The Unified Modeling Language (UML) (http://www.rational.com/uml/resources/documen-
tation/notation/notation52.jtmpl) is the tool of choice for creating use case diagrams. The
Use Case diagram in Figure 1 uses UML to describe the buyer and seller use cases for the
online auction application. In UML, squares group systems, stick figures represent actors,
ovals denote use cases, and lines show how actors use the system.
Online Auction House
Search for
Item
View Item
Anyone
Lists
View Item
Details
Post Items
The following descriptions further define the project. These descriptions are not part of
UML, but are a helpful tool in project definition.
tions and to finalize the sale. So, to post or bid on an auction item, buyers and sellers are
required to register. Registration needs to get the following information from buyers and
sellers:
• User ID and password for buying and selling.
• Email address so highest bidder and seller can communicate when item closes.
• Credit card information so auction can charge sellers for listing their items.
Once registered, a user can post or bid on an item for sale.
Activity Diagram
The activity diagram in Figure 2 outlines the flow of tasks within the auction house as a
whole. The solid black circle on the left shows the beginning of activities, and the white cir-
cles with black dots in the center denote where activities end.
Not
Go to registered User
Web Page Registered? Registration
Registered
View Item
Details
Buyer Bids
on Item
registered
?
Home Page
The Home page introduces the auction and makes auction house features available to buyers
and sellers.
Registration Page
The Registration page gets information from new buyers and sellers so all individuals initiat-
ing transactions at the auction house can be identified..
All Items
The All Items page lets anyone view all items available for sale..
Sell Items
The Post Items page lets registered sellers post an item for sale.
The proliferation of internet- and intranet-based applications has created a great need for dis-
tributed transactional applications that leverage the speed, security, and reliability of server-
side technology. One way to meet this need is to use a multitiered model where a thin-client
application invokes business logic that executes on the server. Normally, thin-client multit-
iered applications are hard to write because they involve many lines of intricate code to han-
dle transaction and state management, multithreading, resource pooling, and other complex
low-level details. And to add to the difficulties, you have to rework this intricate code every
time you write a new application because the code is so low-level it cannot be reused.
If you could use prebuilt and pretested transaction management code or even reuse some of
your own code, you would save a lot of time and energy that you could better spend solving
the business problem. Well, Enterprise JavaBeans™ technology can give you the help you
need. Enterprise JavaBeans technology makes distributed transactional applications easy to
write because it separates the low-level details from the business logic. You concentrate on
creating the best business solution and leave the rest to the underlying architecture.
This chapter describes how to create the example auction with the services provided by the
Enterprise JavaBeans platform. Later chapters show how to customize these services.
Multitiered architecture or three-tier architecture extends the standard two-tier client and
server model by placing a multithreaded application server between the client and the data-
base. The application server is where the Enterprise JavaBeans reside and where the applica-
tion’s business logic executes.
Figure 11 shows that client programs (first tier) communicate with the database (third tier)
through the application server (second tier). The application server responds to the client
requests and makes database calls as needed into the underlying database.
Browser
Network
Thin-Client
Servlet 1st Tier
(Web Server)
Network
Enterprise
JavaBeans 2nd Tier
Server
Network
Note: In the Enterprise JavaBeans specification, Enterprise JavaBeans server support for ses-
sion Beans is mandatory. Enterprise JavaBeans server support for entity Beans was optional,
but is mandatory for version 2.0 of the specification.
Enterprise
JavaBeans Server
AuctionItem
Home
AuctionItem AuctionItem
Remote Entity Bean
Registration Database
Home
Registration Registration
Remote Entity Bean
Servlet Containers
Bidder
Home
Bidder
Bidder Session
Remote Bean
Seller
Home
Seller
Seller Session
Remote Bean
• An Enterprise Bean's remote interface describes the Bean's methods, or what the Bean
does. A client program or another Enterprise Bean calls the methods defined in the
remote interface to invoke the business logic implemented by the Bean.
• An Enterprise Bean's home interface describes how a client program or another Enter-
prise Bean creates, finds (entity Beans only), and removes that Enterprise Bean from
its container.
• The container provides the interface between the Enterprise Bean and the low-level
platform-specific functionality that supports the Enterprise Bean.
2: AUCTION HOUSE APPLICATION 19
Because everything is written to specification, all Enterprise Beans are interchangeable with
containers, deployment tools, and servers created by other vendors. In fact, you might or
might not write your own Enterprise Beans because it is possible, and sometimes desirable,
to use Enterprise Beans written by one or more providers that you assemble into an Enter-
prise JavaBeans application.
Lookup Service
To find remote server objects at runtime, the client program needs a way to look them up.
One way to look remote server objects up at runtime is to use the Java™ Naming and Direc-
tory Interface™ (JNDI) API. JNDI is a common interface to existing naming and directory
interfaces. The Enterprise JavaBeans containers use JNDI as an interface to the Remote
Method Invocation (RMI) naming service.
At deployment time, the JNDI service registers (binds) the remote interface with a name. As
long as the client program uses the same naming service and asks for the remote interface by
its registered name, it will be able to find it. The client program calls the lookup method on a
javax.naming.Context object to ask for the remote interface by its registered name. The
javax.naming.Context object is where the bindings are stored and is a different object from
the Enterprise JavaBeans context, which is covered later.
20 2: AUCTION HOUSE APPLICATION
Data Communication
Once the client program gets a reference to a remote server object, it makes calls on the
remote server object's methods. Because the client program has a reference to the remote
server object, a technique called data marshaling is used to make it appear as if the remote
server object is local to the client program.
Data marshaling is where methods called on the remote server object are wrapped with their
data and sent to the remote server object. The remote server object unwraps (unmarshals) the
methods and data, and calls the Enterprise Bean. The results of the call to the Enterprise
Bean are wrapped again, passed back to the client through the remote server object, and
unmarshaled.
The Enterprise JavaBeans containers use Remote Method Invocation (RMI) services to mar-
shal data. When the Bean is compiled, stub and skeleton files are created. The stub file pro-
vides the data wrapping and unwrapping configuration on the client, and the skeleton
provides the same information for the server. The data is passed between the client program
and the server using serialization. Serialization is a way to represent Java objects as bytes
that can be sent over the network as a stream and reconstructed on the other side in the same
state they were in when first sent.
AuctionServlet
AuctionServlet (page 44) is essentially the second tier in the application and the focal point
for auction activities. It accepts end user input from the browser by way of hypertext transfer
protocol (HTTP), passes the input to the appropriate Enterprise Bean for processing, and dis-
plays the processed results to the end user in the browser.
2: AUCTION HOUSE APPLICATION 21
Figure 13 presents a Unified Modeling Language (UML) class diagram for the AuctionServ-
let class.
Servlet
GenericServlet implements
ServletConfig
HTTPServlet
AuctionServlet
listAllItems(out)
listAllNewItems(out)
searchItems(out, request)
listClosingItems(out)
InsertItem(out, request)
itemDetails(out, request)
itemBid(out, request)
registerUser(out, request)
The AuctionServlet methods shown above invoke business logic that executes on the server
by looking up an Enterprise Bean and calling one or more of its methods. When the servlet
adds HTML codes to a page for display to the user, that logic executes on the client.
For example, the listAllItems(out) method executes code on the client to dynamically gener-
ate an HTML page to be viewed by the client in a browser. The HTML page is populated
with the results of a call to BidderBean that executes logic on the server to generate a list of
all auction items.
private void listAllItems(ServletOutputStream out) throws IOException{
if(enum != null) {
//Put retrieved items on servlet page.
displayitems(enum, out);
addLine("", out);
}
} catch (Exception e) {
//Print error on servlet page.
addLine("AuctionServlet List All Items error",out);
System.out.println("AuctionServlet <list>:"+e);
}
out.flush();
}
Registration Table
This is the schema for the REGISTRATION database table. Some application servers cre-
ate the table for you, but others require you to create it yourself. The BEA Weblogic appli-
cation server does not create the database table.
create table REGISTRATION (THEUSER VARCHAR(40) ,
PASSWORD VARCHAR(40) ,
EMAILADDRESS VARCHAR(80) ,
CREDITCARD VARCHAR(40) ,
BALANCE DOUBLE PRECISION )
Container Classes
The container needs classes to deploy an Enterprise Bean onto a particular Enterprise Java-
Beans server, and those classes are generated with a deployment tool. Container classes
include *_Stub.class and *_Skel.class classes that provide the RMI hooks on the client and
server sides for marshaling (moving) data between the client program and the Enterprise
JavaBeans server. In addition, implementation classes are created for the interfaces and
deployment rules defined for each Bean.
• The Stub object is installed on or downloaded to the client system and provides a local
proxy object for the client. It implements the remote interfaces and transparently del-
egates all method calls across the network to the remote object.
26 2: AUCTION HOUSE APPLICATION
• The Skel object is installed on or downloaded to the server system and provides a local
proxy object for the server. It unwraps data received over the network from the Stub
object for processing by the server.
Member Variables
A container-managed environment needs to know which variables are for persistent storage
and which are not. In the Java programming language, the transient keyword indicates vari-
ables to not include when data in an object is serialized and written to persistent storage. In
the RegistrationBean.java class, the EntityContext variable is marked transient to indicate
that its data not be written to the underlying storage medium.
EntityContext data is not written to persistent storage because its purpose is to provide infor-
mation on the container's runtime context. It, therefore, does not contain data on the regis-
tered user and should not be saved to the underlying storage medium. The other variables are
declared public so the container can use the Reflection API to discover them.
protected transient EntityContext ctx;
public String theuser, password, creditcard, emailaddress;
public double balance;
Create Method
The Bean's ejbCreate method is called by the container after the client program calls the cre-
ate method on the remote interface and passes in the registration data. This method assigns
the incoming values to the member variables that represent user data. The container handles
storing and loading the data, and creating new entries in the underlying storage medium.
public RegistrationPK ejbCreate(String theuser,String password,
String emailaddress,String creditcard)
throws CreateException, RemoteException {
this.theuser=theuser;
this.password=password;
this.emailaddress=emailaddress;
this.creditcard=creditcard;
this.balance=0;
2: AUCTION HOUSE APPLICATION 27
Load Method
The Bean's ejbLoad method is called by the container to load data from the underlying stor-
age medium. This would be necessary when BidderBean or SellerBean need to check a
user's ID or password against the stored values.
You do not implement the ejbLoad method because the Enterprise JavaBeans container
seamlessly loads the data from the underlying storage medium for you.
//API Ref :void ejbLoad()
public void ejbLoad() throws RemoteException {}
Store Method
The Bean's ejbStore method is called by the container to save user data. This method is not
implemented because the Enterprise JavaBeans container seamlessly stores the data to the
underlying storage medium.
//API Ref :void ejbStore()
public void ejbStore() throws RemoteException {}
Connection Pooling
Loading data from and storing data to a database can take a lot of time and reduce an appli-
cation's overall performance. To reduce database connection time, the BEA Weblogic server
uses a JDBC™ connection pool to cache database connections so connections are always
available when the application needs them.
However, you are not limited to the default JDBC connection pool. You can override the
Bean-managed connection pooling behavior and substitute your own. 8: Performance Tech-
niques (page 339) explains how.
28 2: AUCTION HOUSE APPLICATION
Deployment Descriptor
The remaining configuration for a container-managed persistent Bean occurs at deployment
time. The following is the text-based Deployment Descriptor used in a BEA Weblogic Enter-
prise JavaBeans server for deploying the Registration Bean.
Text Deployment Descriptor
(environmentProperties
(persistentStoreProperties
persistentStoreType jdbc
(jdbc
tableName registration
dbIsShared false
poolName ejbPool
(attributeMap
creditcard creditcard
emailaddress emailaddress
balance balance
password password
theuser theuser
); end attributeMap
); end jdbc
); end persistentStoreProperties
); end environmentProperties
The deployment descriptor indicates that storage is a database whose connection is held in a
JDBC™ connection pool called ejbPool. The attributeMap contains the Enterprise Bean vari-
able on the left and the associated database field on the right.
2: AUCTION HOUSE APPLICATION 29
Finder-Based Search
Figure 14 shows how the browser passes the search string to the AuctionServlet.searchItem
method, which then passes it to the BidderBean.getMatchingItemsList method. At this point,
BidderBean.getMatchingItemsList passes the search string to the findAllMatchingItems
method declared in the AuctionItemHome interface.
The findAllMatchingItems method is a finder method, and container implementations vary
in how they handle calls to finder methods. BEA Weblogic containers look in the Bean's
deployment descriptor for information on a Bean's finder methods. In the case of the search,
30 2: AUCTION HOUSE APPLICATION
AuctionItemServlet
searchItem()
BidderBean
getMatchingItemsList()
AuctionItemHome
findAllMatchingItems()
Deployment Descriptor
Search String -> Summary Field
AuctionItems Table
Summary Field
AuctionServlet.searchItems
The searchItems method retrieves the text string from the browser, creates an HTML page to
display the search results, and passes the search string to the BidderBean.getMatching-
ItemsList method. BidderBean is a session Bean that retrieves lists of auction items and
checks the user ID and password for end users seeking to bid on auction items. The search
results are returned to this method in an Enumeration variable.
private void searchItems(ServletOutputStream out, HttpServletRequest request)
throws IOException {
//Retrieve search string
String searchString=request.getParameter(“searchString");
//Create HTML page
String text = "Click Item number for description and to place bid.";
setTitle(out, "Search Results");
try {
addLine("<BR>"+text, out);
//Look up home interface for BidderBean
BidderHome bhome=(BidderHome) ctx.lookup("bidder");
//Create remote interface for BidderBean Bidder bid=bhome.create();
//Pass search string to BidderBean method
Enumeration enum=(Enumeration) bid.getMatchingItemsList(searchString);
if(enum != null) {
displayitems(enum, out);
addLine("", out);
}
} catch (Exception e) {
addLine("AuctionServlet Search Items error", out);
System.out.println("AuctionServlet <newlist>: "+e);
}
out.flush();
}
32 2: AUCTION HOUSE APPLICATION
BidderBean.getMatchingItemsList
The BidderBean.getMatchingItemsList method calls the AuctionItemHome.findAllMatch-
ingItems method and passes it the search string. AuctionItemBean is an entity Bean that han-
dles auction item updates and retrievals. The search results return an Enumeration.
public Enumeration getMatchingItemsList(String searchString)
throws RemoteException {
Enumeration enum=null;
try{
//Create Home interface for AuctionItemBean
AuctionItemHome home = (AuctionItemHome) ctx.lookup("auctionitems");
//Pass search string to Home interface method
enum=(Enumeration)home.findAllMatchingItems(searchString);
}catch (Exception e) {
System.out.println("getMatchingItemList: "+e);
return null;
}
return enum;
}
AuctionItemHome.findAllMatchingItems
The AuctionItemHome.findAllMatchingItems method is not implemented in AuctionItem-
Bean. Instead, the AuctionItemBean finder method implementations are defined in the Auc-
tionItemBean deployment descriptor when BEA Weblogic containers are used.
When using these containers, even if the Bean has finder method implementations, they are
ignored and the deployment descriptor settings are consulted instead.
//Declare method in Home interface
public Enumeration findAllMatchingItems(String searchString)
throws FinderException, RemoteException;
(finderDescriptors
"findAllItems()" "(= 1 1)"
"findAllNewItems(java.sql.Date newtoday)" "(= startdate $newtoday)"
"findAllClosedItems(java.sql.Date closedtoday)" "(= enddate $closedtoday)"
"findAllMatchingItems(String searchString)" "(like summary $searchString)"
); end finderDescriptors
AuctionItem
package auction;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
AuctionItemHome
package auction;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
AuctionItemBean
package auction;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
AuctionItemPK
package auction;
Registration
package registration;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
RegistrationHome
package registration;
38 2: AUCTION HOUSE APPLICATION
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
RegistrationBean
package registration;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
RegistrationPK
package registration;
Bidder
package bidder;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
BidderHome
package bidder;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
BidderBean
package bidder;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
public int placeBid(int item, String buyer, String password, double amount)
throws RemoteException {
double highbid, increment=0;
int bidcount=0;
try {
// Find bidder details from Registration database and
// verify that the password supplied for that bidder matches what
// is in the database
RegistrationHome rhome = (RegistrationHome) ctx.lookup(“registration”);
RegistrationPK rpk=new RegistrationPK();
rpk.theuser=buyer;
Registration newbidder=rhome.findByPrimaryKey(rpk);
2: AUCTION HOUSE APPLICATION 41
Calendar currenttime=Calendar.getInstance();
enum = (Enumeration)home.findAllNewItems(
new java.sql.Date((currenttime.getTime()).getTime()));
} catch (Exception e) {
System.out.println(“getNewItemList: “+e);
return null;
}
return enum;
}
public Enumeration getClosedItemList() throws RemoteException {
// Return list of all completed auction items in the auction database
Enumeration enum=null;
try {
AuctionItemHome home = (AuctionItemHome) ctx.lookup(“auctionitems”);
Calendar currenttime=Calendar.getInstance();
enum = (Enumeration)home.findAllClosedItems(
new java.sql.Date((currenttime.getTime()).getTime()));
} catch (Exception e) {
System.out.println(“getClosedItemList: “+e);
return null;
}
return enum;
}
public Enumeration getMatchingItemsList(String searchString)
throws RemoteException {
// Return list of all items matching searchString in the auction database
Enumeration enum=null;
try {
AuctionItemHome home = (AuctionItemHome) ctx.lookup(“auctionitems”);
enum=(Enumeration)home.findAllMatchingItems(searchString);
} catch (Exception e) {
System.out.println(“getMatchingItemList: “+e);
return null;
}
return enum;
}
public void ejbCreate() throws CreateException, RemoteException {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,
“weblogic.jndi.TengahInitialContextFactory”);
try {
ctx = new InitialContext(p);
} catch(Exception e) {
System.out.println(“create exception: “+e);
}
}
public void setSessionContext(SessionContext sctx) throws RemoteException {
this.sctx = sctx;
}
public void unsetSessionContext() throws RemoteException {
sctx = null;
}
public void ejbRemove() {}
2: AUCTION HOUSE APPLICATION 43
Seller
package seller;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
SellerHome
package seller;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
SellerBean
package seller;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
AuctionServlet
package auction;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.NumberFormat;
2: AUCTION HOUSE APPLICATION 45
import bidder.*;
import registration.*;
import seller.*;
import pool.*;
import search.*;
// The client side interface to EJB server is the AuctionServlet that
// displays results using HTML
}
out.flush();
}
private void listAllNewItems(ServletOutputStream out) throws IOException {
setTitle(out, “New Auction Items”);
try {
addLine(““, out);
String text = “Click Item number for description and to place bid.”;
addLine(text, out);
BidderHome bhome=(BidderHome) ctx.lookup(“bidder”);
Bidder bid=bhome.create();
Enumeration enum=(Enumeration)bid.getNewItemList();
if(enum != null) {
displayitems(enum, out);
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet List New Items error”, out);
System.out.println(“AuctionServlet <newlist>:”+e);
}
out.flush();
}
private void searchItems(ServletOutputStream out, HttpServletRequest request)
throws IOException {
// Return an HTML page with a list of auction items matching
// the search string posted in parameter searchString
String searchString=request.getParameter(“searchString”);
String text = “Click Item number for description and to place bid.”;
setTitle(out, “Search Results”);
try {
addLine(“<BR>”+text, out);
AuctionItemHome ahome = (AuctionItemHome) ctx.lookup(“auctionitems”);
SearchHome shome=(SearchHome) ctx.lookup(“search”);
Search search=shome.create();
Enumeration enum=(Enumeration)search.getMatchingItemsList(searchString);
addLine(“<TABLE BORDER=1 CELLPADDING=1 CELLSPACING=0><TR><TH>Item</TH>
<TH>Summary</TH><TH>Current High bid</TH><TH>Number of bids</TH>
<TH>Closing Date</TH></TR>”, out);
while ((enum != null) && (enum.hasMoreElements())) {
while(enum.hasMoreElements()) {
AuctionItem ai=ahome.findByPrimaryKey((
AuctionItemPK)enum.nextElement());
displayLineItem(ai, out);
}
}
addLine(“</TABLE>”, out);
} catch (Exception e) {
addLine(“AuctionServlet Search Items error”, out);
System.out.println(“AuctionServlet <searchItems>:”+e);
}
out.flush();
}
private void listClosingItems(ServletOutputStream out) throws IOException{
48 2: AUCTION HOUSE APPLICATION
if(result >0) {
addLine(“Inserted item “+summary, out);
addLine(“Details available
<A HREF=/ AuctionServlet?action=details&item=”+result+”>here</A>”,
out);
} else {
addLine(“Error inserting item”, out);
return;
}
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet Insert Item error”, out);
System.out.println(“AuctionServlet <insert>:”+e);
}
out.flush();
}
private void itemDetails(ServletOutputStream out, HttpServletRequest request)
throws IOException{
// Return an HTML page with details about the auction identified by
// the posted parameter item
setTitle(out, “Item Details”);
String item=request.getParameter(“item”);
int itemid=0;
try {
itemid=Integer.parseInt(item);
} catch (NumberFormatException e) {
System.out.println(“problem with item id “+itemid);
return;
}
try {
AuctionItemHome home = (AuctionItemHome) ctx.lookup(“auctionitems”);
AuctionItemPK pk=new AuctionItemPK();
pk.id=itemid;
AuctionItem ai=home.findByPrimaryKey(pk);
displayPageItem(ai, out);
addLine(“<BR><HR><P>Do you want to bid on this item?”, out);
addLine(“<FORM ACTION=\”/AuctionServlet\” METHOD=\”POST\”>”, out);
addLine(“<TR>Enter your user id:<INPUT TYPE=\”TEXT\”
SIZE=20 NAME=\”buyer\”> “, out);
addLine(“and password:<INPUT TYPE=\”PASSWORD\” SIZE=20 NAME=\”password\”>
</TR>”, out);
addLine(“<TR>Your bid amount:<INPUT TYPE=\”TEXT\”
SIZE=20 NAME=\”amount\”></TR>”, out);
addLine(“<INPUT TYPE=\”HIDDEN\” NAME=\”action\” VALUE=\”bid\”>”, out);
addLine(“<INPUT TYPE=\”HIDDEN\” NAME=\”item\” VALUE=\””+itemid+”\”>”,
out);
addLine(“<INPUT TYPE=\”SUBMIT\” VALUE=\”Place Bid\” NAME=\”Bid\”></FORM>”,
out);
} catch (Exception e) {
addLine(“AuctionServlet List Item error”, out);
System.out.println(“AuctionServlet <details>:”+e);
}
50 2: AUCTION HOUSE APPLICATION
out.flush();
}
private void itemBid(ServletOutputStream out, HttpServletRequest request)
throws IOException{
// Place a bid on the item specified in the item posted parameter
setTitle(out, “Item Bid”);
String item=request.getParameter(“item”);
String buyer=request.getParameter(“buyer”);
String password=request.getParameter(“password”);
String bid=request.getParameter(“amount”);
int itemid=0;
double bidamount=0;
try {
itemid=Integer.parseInt(item);
} catch (NumberFormatException e) {
System.out.println(“problem with item id “ +itemid);
return;
}
try {
bidamount=Double.valueOf(bid).doubleValue();
} catch (NumberFormatException e) {
System.out.println(“problem with bid” +bid);
return;
}
try {
BidderHome bhome = (BidderHome) ctx.lookup(“bidder”);
Bidder bidbean=bhome.create();
int result=bidbean.placeBid(itemid, buyer, password, bidamount);
switch(result) {
case Auction.OUT_BID:
addLine(“Your bid was not high enough”, out);
break;
case Auction.HIGH_BID:
addLine(“You are the high bidder”, out);
break;
case Auction.AUCTION_OVER:
addLine(“This auction has finished”, out);
break;
case Auction.INVALID_USER:
addLine(“Invalid user or password”, out);
break;
default:
addLine(“Problem submitting bid”, out);
}
} catch (Exception e) {
addLine(“AuctionServlet Bid error”, out);
System.out.println(“AuctionServlet <bid>:”+e);
}
out.flush();
}
private void registerUser(ServletOutputStream out, HttpServletRequest request)
throws IOException{
// Register a new user
2: AUCTION HOUSE APPLICATION 51
line.append(“<TD>”+bidcount+”</TD>”);
line.append(“<TD>”+auctionItem.getEndDate() +”</TD></TR>”);
addLine(line.toString(), out);
}
static private void displayPageItem(AuctionItem auctionItem,
ServletOutputStream out)
throws RemoteException, IOException {
// Return an HTML page with one auction item on it
int bidcount=auctionItem.getBidCount();
addLine(auctionItem.getSummary(), out);
addLine(“Auction Item Number: “+ auctionItem.getPrimaryKey(), out);
if(bidcount >0) {
addLine(“<P>Current price: “+NumberFormat.getCurrencyInstance().format(
auctionItem.getHighBid()), out);
addLine(“Minimum increment: “+NumberFormat.getCurrencyInstance().format(
auctionItem.getIncrement()), out);
} else {
addLine(“<P>Current price: “+NumberFormat.getCurrencyInstance().format(
auctionItem.getStartPrice()), out);
}
addLine(“# of bids: “+bidcount, out);
addLine(“<P>Auction Started: “+auctionItem.getStartDate(), out);
addLine(“Auction Ends: “+auctionItem.getEndDate(), out);
addLine(“<P>Seller: “+auctionItem.getSeller(), out);
if(bidcount >0) {
addLine(“High Bidder: “+auctionItem.getHighBidder(), out);
} else {
addLine(“High Bidder: “+”-”, out);
}
addLine(“<HR><P>”, out);
addLine(“Description: “+auctionItem.getDescription(), out);
}
private String readFile (String file) throws IOException {
// Convenience method to read a file into memory
if(file != null) {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader (new FileReader (file));
String line;
while( (line=reader.readLine()) != null ) {
buffer.append (line+’\n’);
}
reader.close();
return buffer.toString();
} else {
return null;
}
}
private void setTitle(ServletOutputStream out, String title) {
// Set the title on the html page
try {
out.println(“<HTML><HEAD><TITLE>”+title+”</TITLE></HEAD>”);
out.println(“<BODY BGCOLOR=\”WHITE\”>”);
} catch(IOException e) {
2: AUCTION HOUSE APPLICATION 53
When you use the Enterprise JavaBeans™ architecture, data is written to and read from the
database without your writing any SQL code to do it. But what if you want to write your own
SQL commands or manage transactions? You can override the built-in container-managed
persistence and implement Bean-managed persistence using your own data storage and
transaction management code.
Bean-managed persistence comes in handy when you want more control than the container-
managed persistence provides. For example you might want to override the default of most
containers to map the data in one Bean to one row in a table, implement your own finder
methods, or customize caching.
This chapter converts the RegistrationBean class from 2: Auction House Application (page
13) to provides its own SQL commands for reading from and writing to the database. It also
explains how you can write your own transaction management code and implement a more
complex search than you can get with the finder-based search described in 2: Auction House
Application (page 13).
multiple Beans to one row in a database table. This section shows you how to convert the
RegistrationBean.java class to access the database with the JDBC PreparedStatement
class.
Connect to Database
This version of the RegistrationBean (SQL) (page 72) class establishes a connection to the
database by instantiating a static Driver class and providing the getConnection method. The
getConnection method queries the static DriverManager class for a registered database
driver that matches the Uniform Resource Locator (URL). In this case, the URL is
weblogic.jdbc.jts.Driver.
//Create static instance of database driver
static {
new weblogic.jdbc.jts.Driver();
}
Create Method
The ejbCreate method assigns values to data member variables, gets a connection to the
database, and creates an instance of the java.sql.PreparedStatement class to execute the SQL
statement for writing the data to the registration table in the database.
A PreparedStatement object is created from a SQL statement which is sent to the database
and precompiled before any data is sent. You call the appropriate setXXX statements on the
PreparedStatement object to send the data. Keeping the PreparedStatement and Connection
objects as private instance variables greatly reduces overhead because the SQL statement
does not have to be compiled every time data is sent.
The last thing the ejbCreate method does is create a primary key class with the user ID, and
return it to the container.
public RegistrationPK ejbCreate(String theuser, String password,
String emailaddress, String creditcard)
throws CreateException, RemoteException {
this.theuser=theuser;
this.password=password;
this.emailaddress=emailaddress;
this.creditcard=creditcard;
this.balance=0;
try {
con=getConnection();
3: DATA AND TRANSACTION MANAGEMENT 57
Load Method
The ejbLoad method gets the primary key from the entity context and passes it to the refresh
method which loads the data.
public void ejbLoad() throws RemoteException {
try {
refresh((RegistrationPK) ctx.getPrimaryKey());
} catch (FinderException fe) {
throw new RemoteException (fe.getMessage());
}
}
Refresh Method
The refresh method is programmer-supplied code to load the data from the database. It
checks the primary key value, gets a connection to the database, and creates a PreparedState-
ment object for querying the database for the user specified in the primary key. Data is read
from the database into a ResultSet and assigned to the global member variables so the Regis-
trationBean has the most up-to-date information for the user.
58 3: DATA AND TRANSACTION MANAGEMENT
Store Method
This method gets a database connection and creates a PreparedStatement to update the data-
base.
public void ejbStore() throws RemoteException {
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
//API Ref :PrepareStatement prepareStatement(String sql)
ps = con.prepareStatement("update registration set password = ?,
emailaddress = ?, creditcard = ?, balance = ? where theuser = ?");
//API Ref :void setString(int index, String s)
3: DATA AND TRANSACTION MANAGEMENT 59
ps.setString(1, password);
ps.setString(2, emailaddress);
ps.setString(3, creditcard);
//API Ref :void setDouble(int index, double doublevalue)
ps.setDouble(4, balance);
ps.setString(5, theuser);
//API Ref :int executeUpdate()
int i = ps.executeUpdate();
if (i == 0) {
throw new RemoteException (
"ejbStore: Registration (" + theuser + ") not updated");
}
} catch (RemoteException re) {
throw re;
} catch (SQLException sqe) {
throw new RemoteException (sqe.getMessage());
} finally {
try {
ps.close();
} catch (Exception ignore) {}
try {
con.close();
} catch (Exception ignore) {}
}
}
Find Method
The ejbFindByPrimaryKey method matches the signature of the findByPrimaryKey method
in the RegistrationHome (page 37) interface. It calls the refresh method to get or refresh the
user data for the user specified by the primary key. The container-managed version of Regis-
trationBean (page 38) does not implement this method because the container handles getting
and refreshing the user data.
public RegistrationPK ejbFindByPrimaryKey(RegistrationPK pk)
throws FinderException, RemoteException {
if ((pk == null) || (pk.theuser == null)) {
throw new FinderException ("primary key cannot be null");
}
refresh(pk);
return pk;
}
Managing Transactions
Wouldn't it be great if every operation your application attempts succeeds? Unfortunately, in
the multithreaded world of distributed applications and shared resources, this is not always
60 3: DATA AND TRANSACTION MANAGEMENT
possible. Why? First of all, shared resources must maintain a consistent view of the data to
all users. This means reads and writes have to be managed so users do not overwrite each
other's changes, or transaction errors do not corrupt data integrity. Also, if you factor in
intermittent network delays or dropped connections, the potential for operations to fail in a
web-based application increases as the number of users increases.
If operation failures are unavoidable, the next best thing is to recover safely, and that is
where transaction management fits in. Modern databases and transaction managers let you
undo and restore the state of a failed sequence of operations to ensure the data is consistent
for access by multiple threads.
This section adds code to the container-managed SellerBean (page 43) so it can manage its
auction item insertion transaction beyond the default transaction management provided by
its container.
Session Synchronization
A container-managed session Bean can optionally include session synchronization code to
manage the default auto commit provided by the container. Session synchronization code
lets the container notify the Bean when important points in the transaction are reached. Upon
3: DATA AND TRANSACTION MANAGEMENT 61
receiving the notification, the Bean can take any needed actions before the transaction pro-
ceeds to the next point.
Note: A session Bean using Bean-managed transactions does not need session synchronization
because the Bean is in full control of the commit.
Container-Managed Example
SellerBean is a session Bean that uses RegistrationBean and AuctionItemBean in the follow-
ing ways:
• RegistrationBean checks the user ID and password when someone posts an auction
item and debit the seller's account for a listing.
• AuctionItemBean adds new auction items to the database.
The transaction begins in the SellerBean.insertItem method with the account debit and ends
when the entire transaction either commits or rolls back. The entire transaction including the
50 cents debit rolls back if the auction item is null (the insertion failed), or if an exception is
caught. If the auction item is not null and the insertion succeeds, the entire transaction
including the 50 cents debit commits.
afterBegin
The container calls the afterBegin method before the debit to notify the session Bean a new
transaction is about to begin. You can implement this method to do any preliminary database
62 3: DATA AND TRANSACTION MANAGEMENT
work that might be needed for the transaction. In this example, no preliminary database work
is needed so this method has no implementation.
beforeCompletion
The container calls the beforeCompletion method when it is ready to write the auction item
and debit to the database, but before it actually does (commits). You can implement this
method to write out any cached database updates or roll back the transaction. In this exam-
ple, the method calls the setRollbackOnly method on its session context in the event the suc-
cess variable is set to false during the transaction.
afterCompletion
The container calls the afterCompletion method when the transaction commits. A boolean
value of true means the data committed and false means the transaction rolled back. The
method uses the boolean value to determine if it needs to reset the Bean's state in the case of
a rollback. In this example, there is no need to reset the state in the event of a failure. The
insertItem method shown here has comments to indicate where SessionSynchronization
methods are called.
public int insertItem(String seller, String password, String description,
int auctiondays, double startprice, String summary) throws RemoteException {
try {
Context jndiCtx = new InitialContext(p);
RegistrationHome rhome = (RegistrationHome) sCtx.lookup("registration");
RegistrationPK rpk=new RegistrationPK();
rpk.theuser=seller;
Registration newseller=rhome.findByPrimaryKey(rpk);
if((newseller == null) || (!newseller.verifyPassword(password))) {
return(Auction.INVALID_USER);
}
//Call to afterBegin
newseller.adjustAccount(-0.50);
AuctionItemHome home = (AuctionItemHome) jndiCtx.lookup("auctionitems");
AuctionItem ai= home.create(seller, description, auctiondays,
startprice, summary);
if(ai == null) {
success=false;
return Auction.INVALID_ITEM;
} else {
return(ai.getId());
}
} catch(Exception e){
System.out.println("insert problem="+e);
success=false;
return Auction.INVALID_ITEM;
}
3: DATA AND TRANSACTION MANAGEMENT 63
//Call to beforeCompletion
//Call to afterCompletion
Server Configuration
Configuring the Enterprise JavaBeans server involves specifying the following settings in a
configuration file for each Bean:
• An isolation level to specify how exclusive a transaction's access to shared data is.
• A transaction attribute to specify how to handle Bean-managed or container-managed
transactions that continue in another Bean.
• A transaction type to specify whether the transaction is managed by the container or
the Bean.
For example, you would specify these settings for the BEA Weblogic server in a Deploy-
mentDescriptor.txt file for each Bean. Here is the part of the DeploymentDescriptor.txt for
SellerBean that specifies the isolation level and transaction attribute. A description of the
settings follows.
(controlDescriptors
(DEFAULT
isolationLevel TRANSACTION_SERIALIZABLE
transactionAttribute REQUIRED
runAsMode CLIENT_IDENTITY
runAsIdentity guest
); end DEFAULT
); end controlDescriptors
Here is the equivalent Enterprise JavaBeans 1.1 extended markup language (XML) descrip-
tion that specifies the transaction type. In this example SellerBean is container managed.
64 3: DATA AND TRANSACTION MANAGEMENT
<container-transaction>
<method>
<ejb-name>SellerBean</ejb-name>
<method-name>*</method-name>
</method>
<transaction-type>Container</transaction-type>
<trans-attribute>Required</trans-attribute>
</container-transaction>
REQUIRED TX_REQUIRED
Container-managed transaction. The server either starts and manages a new trans-
action on behalf of the user or continues using the transaction that was started by
the code that called this Bean.
REQUIRESNEW TX_REQUIRED_NEW
Container-managed transaction. The server starts and manages a new transaction.
If an existing transaction starts this transaction, it suspends until this transaction
completes.
Specified as Bean transaction-type in TX_BEAN_MANAGED
deployment descriptor
Bean-managed transaction. You access the transaction context to begin, commit,
or rollback the transaction as needed.
SUPPORTS TX_SUPPORTS
If the code calling this Bean has a transaction running, include this Bean in that
transaction.
NEVER TX_NOT_SUPPORTED
If the code calling a method in this Bean has a transaction running, suspend that
transaction until the method called in this Bean completes. No transaction context
is created for this Bean.
MANDATORY TX_MANDATORY
The transaction attribute for this Bean is set when another Bean calls one of its
methods. In this case, this Bean gets the transaction attribute of the calling Bean.
If the calling Bean has no transaction attribute, the method called in this Bean
throws a TransactionRequired exception.
66 3: DATA AND TRANSACTION MANAGEMENT
Note: Be sure to verify that your database can handle the level you choose. In the Enterprise
JavaBeans 1.1 specification, only Bean-managed persistence session Beans can set the isolation
level. If the database cannot handle the isolation level, the Enterprise JavaBeans server will get
a failure when it tries to call the setTransactionIsolation JDBC method.
Bean-Managed Example
SellerBean is a session Bean that uses RegistrationBean and AuctionItemBean in the follow-
ing ways:
3: DATA AND TRANSACTION MANAGEMENT 67
• RegistrationBean checks the user ID and password when someone posts an auction
item and debit the seller's account for a listing.
• AuctionItemBean adds new auction items to the database.
The transaction begins in the SellerBean.insertItem method with the account debit and ends
when the entire transaction either commits or rolls back. The entire transaction including the
50-cent debit rolls back if the auction item is null (the insertion failed), or if an exception is
caught. If the auction item is not null and the insertion succeeds, the entire transaction
including the 50 cents debit commits.
For this example, the isolation level is TRANSACTION_SERIALIZABLE, and the transac-
tion attribute is TX_BEAN_MANAGED. The other Beans in the transaction, Registration-
Bean and AuctionItemBean, have an isolation level of TRANSACTION_SERIALIZABLE
and a transaction attribute of REQUIRED. Changes to this version of SellerBean.insertItem
over the container-managed version are flagged with comments.
public int insertItem(String seller, String password, String description,
int auctiondays, double startprice, String summary)
throws RemoteException {
//Declare transaction context variable using the
//javax.transaction.UserTransaction class
UserTransaction uts= null;
try {
Context ectx = new InitialContext(p);
//Get the transaction context
uts=(UserTransaction)ctx.getUserTransaction();
RegistrationHome rhome = (RegistrationHome)ectx.lookup("registration");
RegistrationPK rpk=new RegistrationPK();
rpk.theuser=seller;
Registration newseller=rhome.findByPrimaryKey(rpk);
if((newseller == null)|| (!newseller.verifyPassword(password))) {
return(Auction.INVALID_USER);
}
//Start the transaction
//API Ref :void begin()
uts.begin();
//Deduct 50 cents from seller's account
newseller.adjustAccount(-0.50);
AuctionItemHome home = (AuctionItemHome) ectx.lookup("auctionitems");
AuctionItem ai= home.create(seller, description, auctiondays,
startprice, summary);
if(ai == null) {
//Roll transaction back
//API Ref :void rollback()
uts.rollback();
return Auction.INVALID_ITEM;
} else {
//Commit transaction
//API Ref :void commit()
68 3: DATA AND TRANSACTION MANAGEMENT
uts.commit();
return(ai.getId());
}
} catch(Exception e){
System.out.println("insert problem="+e);
//Roll transaction back if insert fails
uts.rollback();
return Auction.INVALID_ITEM;
}
}
AuctionServlet.searchItems
The search begins when the end user submits a search string to the search facility on the auc-
tion house home page and clicks the Submit button. This invokes AuctionServlet, which
retrieves the search string from the HTTP header and passes it to the searchItem method.
Note: The search logic for this example is fairly simple. The idea here is to show you how to
move the search logic into a separate Enterprise Bean so you can create a more complex search
on your own.
Figure 15 shows how the searchItem operation is in the following two parts: 1) Using the
search string to retrieve primary keys, and 2) Using primary keys to retrieve auction items.
Parts 1 and 2 are described in more detail below the figure.
3: DATA AND TRANSACTION MANAGEMENT 69
searchItem searchItem
method method
search IDs
string
AuctionItemBean
SearchBean Container-managed
Bean-managed search
search
auction
IDs items
IDs
Auction Items
Part 1: The first thing the searchItems Method (page 77) does is pass the search string sub-
mitted by the end user to the SearchBean session Bean. SearchBean (page 70) implements a
Bean-managed search that retrieves a list of primary keys for all auction items whose Sum-
mary fields contain characters matching the search string. This list is returned to the search-
Items method in an Enumeration variable.
Enumeration enum = (Enumeration)search.getMatchingItemsList(searchString);
Part 2: The searchItems method then uses the returned Enumeration list from Part 1 and
AuctionItemBean (page 34) to retrieve each Bean in turn by calling findByPrimaryKey on
each primary key in the list. This is a container-managed search based on the finder mecha-
nism described in 2: Auction House Application (page 13).
//Iterate through search results
while ((enum != null) && enum.hasMoreElements())) {
while(enum.hasMoreElements(in)) {
//Locate auction items
AuctionItem ai=ahome.findByPrimaryKey((
AuctionItemPK)enum.nextElement());
displayLineItem(ai, out);
}
}
70 3: DATA AND TRANSACTION MANAGEMENT
SearchBean
The SearchBean (page 70) class defines a Bean-managed search for the primary keys of auc-
tion items with summary fields that contain characters matching the search string. This Bean
establishes a database connection, and provides the getMatchingItemsList and EJBCreate
methods. A custom search Bean is written because the default finder rules supplied by the
EJB server do not allow a wild card SQL search string. This technique can also be used for
more complex queries or queries that could be better optimized by the developer than those
search queries generated by the EJB server.
Database Connection
Because this Bean manages its own database access and search, it has to establish its own
database connection. It cannot rely on the container to do this. The database connection is
established by instantiating a static Driver class and providing the getConnection method.
The getConnection method queries the static DriverManager class for a registered database
driver that matches the Uniform Resource Locator (URL). In this case, the URL is
weblogic.jdbc.jts.Driver.
//Establish database connection
static {
new weblogic.jdbc.jts.Driver();
}
public Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:weblogic:jts:ejbPool");
}
Create Method
The ejbCreate method creates an javax.naming.InitialContext object. This is a Java Naming
and Directory™ (JNDI) class that lets SearchBean access the database without relying on the
container.
public void ejbCreate() throws CreateException,
RemoteException {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.TengahInitialContextFactory");
try {
ctx = new InitialContext(p);
} catch(Exception e) {
System.out.println("create exception: "+e);
}
}
72 3: DATA AND TRANSACTION MANAGEMENT
RegistrationBean (SQL)
package registration;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.sql.*;
}
public RegistrationPK ejbCreate(String theuser, String password,
String emailaddress, String creditcard)
throws CreateException, RemoteException {
this.theuser=theuser;
this.password=password;
this.emailaddress=emailaddress;
this.creditcard=creditcard;
this.balance=0;
try {
con=getConnection();
// Create new registration entry into the database using JDBC
ps=con.prepareStatement(“insert into registration (theuser, password,
emailaddress, creditcard, balance)
values (?, ?, ?, ?, ?)”);
ps.setString(1, theuser);
ps.setString(2, password);
ps.setString(3, emailaddress);
ps.setString(4, creditcard);
ps.setDouble(5, balance);
if (ps.executeUpdate() != 1) {
throw new CreateException (“JDBC did not create any row”);
}
RegistrationPK primaryKey = new RegistrationPK();
primaryKey.theuser = theuser;
return primaryKey;
} catch (CreateException ce) {
throw ce;
} catch (SQLException sqe) {
throw new CreateException (sqe.getMessage());
} finally {
try {
ps.close();
} catch (Exception ignore) {}
try {
con.close();
} catch (Exception ignore) {}
}
}
public void ejbPostCreate(String theuser, String password, String emailaddress,
String creditcard) throws CreateException, RemoteException {
}
public void setEntityContext(javax.ejb.EntityContext ctx)
throws RemoteException {
this.ctx = ctx;
}
public void unsetEntityContext() throws RemoteException {
ctx = null;
}
public void ejbRemove() throws RemoteException, RemoveException { }
public void ejbActivate() throws RemoteException { }
public void ejbPassivate() throws RemoteException { }
public void ejbLoad() throws RemoteException {
74 3: DATA AND TRANSACTION MANAGEMENT
try {
refresh((RegistrationPK) ctx.getPrimaryKey());
} catch (FinderException fe) {
throw new RemoteException (fe.getMessage());
}
}
public void ejbStore() throws RemoteException {
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
// Write the Bean contents to the database
ps = con.prepareStatement(“update registration set password = ?,
emailaddress = ?, creditcard = ?, balance = ? where theuser = ?”);
ps.setString(1, password);
ps.setString(2, emailaddress);
ps.setString(3, creditcard);
ps.setDouble(4, balance);
ps.setString(5, theuser);
int i = ps.executeUpdate();
if(i == 0) {
throw new RemoteException(“ejbStore: Registration (“ +
theuser + “) not updated”);
}
} catch (RemoteException re) {
throw re;
} catch (SQLException sqe) {
throw new RemoteException (sqe.getMessage());
} finally {
try {
ps.close();
} catch (Exception ignore) {}
try {
con.close();
} catch (Exception ignore) {}
}
}
public RegistrationPK ejbFindByPrimaryKey(RegistrationPK pk)
throws FinderException, RemoteException {
// Find the Bean matching this primary key and read from database
if((pk == null) || (pk.theuser == null)) {
throw new FinderException (“primary key cannot be null”);
}
refresh(pk);
return pk;
}
private void refresh(RegistrationPK pk)
throws FinderException, RemoteException {
// Read the Bean contents from the database
if(pk == null) {
throw new RemoteException (“primary key cannot be null”);
}
Connection con = null;
3: DATA AND TRANSACTION MANAGEMENT 75
PreparedStatement ps = null;
try {
con=getConnection();
ps=con.prepareStatement(“select password, emailaddress, creditcard,
balance from registration where theuser = ?”);
ps.setString(1, pk.theuser);
ps.executeQuery();
ResultSet rs = ps.getResultSet();
if(rs.next()) {
theuser = pk.theuser;
password = rs.getString(1);
emailaddress = rs.getString(2);
creditcard = rs.getString(3);
balance = rs.getDouble(4);
} else {
throw new FinderException (“Refresh: Registration (“
+ pk.theuser + “) not found”);
}
} catch (SQLException sqe) {
throw new RemoteException (sqe.getMessage());
} finally {
try {
ps.close();
} catch (Exception ignore) {}
try {
con.close();
} catch (Exception ignore) {}
}
}
}
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import javax.jts.*;
import auction.*;
import registration.*;
if(!success ) {
ctx.setRollbackOnly();
}
}
public void afterCompletion(boolean state) {}
searchItems Method
private void searchItems(ServletOutputStream out, HttpServletRequest request)
throws IOException {
String searchString=request.getParameter(“searchString”);
String text = “Click Item number for description and to place bid.”;
setTitle(out, “Search Results”);
try {
addLine(“<BR>”+text, out);
//Look up Home interfaces
AuctionItemHome ahome = (
AuctionItemHome) ctx.lookup(“auctionitems”);
SearchHome shome=(SearchHome) ctx.lookup(“search”);
//Create remote interface for search Bean
Search search=shome.create();
//Call search method and pass the search string
Enumeration enum=(Enumeration) search.getMatchingItemsList(searchString);
addLine(“<TABLE BORDER=1 CELLPADDING=1 CELLSPACING=0>
<TR> <TH>Item<TH> <TH>Summary<TH><TH>Current High bid<TH>
<TH>Number of bids<TH><TH>Closing Date<TH><TR>”, out);
//Iterate through search results
while ((enum != null) && (enum.hasMoreElements())) {
while(enum.hasMoreElements(in)) {
//Locate auction items
AuctionItem ai=ahome.findByPrimaryKey((AuctionItemPK)enum.nextElement());
displayLineItem(ai, out);
}
}
addLine(“<TABLE>”, out);
} catch (Exception e) {
addLine(“AuctionServlet Search Items error”, out);
System.out.println(“AuctionServlet <searchItems>:”+e);
}
out.flush();
}
SearchBean
package search;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
import java.sql.*;
ResultSet rs = null;
PreparedStatement ps = null;
Vector v = new Vector();
Connection con = null;
try {
AuctionItemHome home = (AuctionItemHome)
ctx.lookup(“auctionitems”);
con = getConnection();
ps = con.prepareStatement(
“select id from auctionitems where summary like ?”);
ps.setString(1, “%”+searchString+”%”);
ps.executeQuery();
rs = ps.getResultSet();
AuctionItemPK pk;
while(rs.next()) {
pk = new AuctionItemPK();
pk.id = (int)rs.getInt(1);
v.addElement(pk);
}
return v.elements();
} catch (Exception e) {
System.out.println(“getMatchingItemsList: “+e);
return null;
} finally {
try {
if(rs != null) {
rs.close();
}
if(ps != null) {
ps.close();
}
if(con != null) {
con.close();
}
} catch (Exception ignore) {
// An exception was thrown trying to
// close the used connections. The exception is ignored
// because there is no further need for the used connection.
3: DATA AND TRANSACTION MANAGEMENT 79
}
}
}
public void ejbCreate() throws CreateException, RemoteException {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,
“weblogic.jndi.TengahInitialContextFactory”);
try {
ctx = new InitialContext(p);
} catch(Exception e) {
System.out.println(“create exception: “+e);
}
}
public void setSessionContext(SessionContext sctx) throws RemoteException {
this.sctx = sctx;
}
public void unsetSessionContext() throws RemoteException {
sctx = null;
}
//API Ref :void ejbRemove()
public void ejbRemove() {}
//API Ref :void ejbActivate()
public void ejbActivate() throws RemoteException { }
//API Ref :void ejbPassivate()
public void ejbPassivate() throws RemoteException { }
}
80 3: DATA AND TRANSACTION MANAGEMENT
4: DISTRIBUTED COMPUTING 81
4: Distributed Computing
As recently as ten years ago, distributed computing generally meant you had client PCs in
one room with a server in another room. The problem here is if the server machine is down,
the clients cannot update the payroll, sales, or whatever other distributed company databases.
To prevent this kind of down time, required different distributed models. One example is the
master and slave model where if the master fails, the slaves take over.
The problem with the different distributed network models is they all required some form of
manual intervention and are often tied to one operating system or language. And while these
approaches met some of the short-term requirements for decreasing down time, they do not
apply to heterogeneous distributed systems with mixed network protocols and machines.
The Java™ platform and other advances such as Common Object Request Broker Architec-
ture (CORBA), multi-tiered servers, and wireless networks have brought the realization of
fully distributed computing another step ahead of the traditional client and server approach.
Today, you can build applications that include service redundancy by default. If one server
connection fails, you can seamlessly use a service on another server. CORBA and Distrib-
uted Component Object Model (DCOM) bridges mean that objects can be transferred
between virtually all machines and languages. And with the new Jini™ System software, the
distributed computing environment can soon be part of everything in your home, office or
school. In short, distributed computing has never been as important as it is today.
The first part of this chapter shows you how to write lookup code using JNDI, CORBA, IOR,
and RMI-IIOP. The second part describes how to use lookup code with RMI and CORBA,
and concludes with a discussion of JDBC™ and servlet technologies.
Lookup Services
Lookup (naming) services enable communications over a network. A client program can use
a lookup protocol to get information on remote programs or machines and use that informa-
tion to establish a communication.
• One common lookup service you might already be familiar with is Directory Name
Service (DNS). It maps Internet Protocol (IP) addresses to machine names. Programs
use the DNS mapping to look up the IP address associated with a machine name and
use the IP address to establish a communication.
• In the same way, the AuctionServlet (page 44) presented in 2: Auction House Appli-
cation (page 13) uses the naming service built into the Enterprise JavaBeans™ archi-
tecture to look up and reference Enterprise Beans registered with the Enterprise
JavaBeans server.
In addition to naming services, some lookup protocols provide directory services. Directory
services such as Lightweight Directory Access Protocol (LDAP) and Sun's NIS+ provide
other information and services beyond what is available with simple naming services. For
example, NIS+ associates a workgroup attribute with a user account. This attribute can be
used to restrict access to a machine so only the users in the specified workgroup have access.
This chapter describes how the Java Naming and Directory Interface™ (JNDI) is used in the
auction application to look up Enterprise Beans. It also explains how to use some of the
many other lookup services that have become available over time. The code to use these
other services is not as simple as the lookup code in the auction application in 2: Auction
House Application (page 13), but the advantages to these other services can outweigh the
need for more complex code in some situations.
Once created, the JNDI context is used to look up Enterprise Bean home interfaces. In this
example, a reference to the Enterprise Bean bound to the name registration is retrieved and
used for further operations.
RegistrationHome rhome = (RegistrationHome) ctx.lookup("registration");
RegistrationPK rpk=new RegistrationPK();
rpk.theuser=buyer;
Registration newbidder = rhome.findByPrimaryKey(rpk);
On the server side, the deployment descriptor for the RegistrationBean has its beanhome-
name value set to registration. Enterprise JavaBeans tools generate the rest of the naming
code for the server.
The server calls ctx.bind to bind the name registration to the JNDI context. The this param-
eter references the _stub class that represents the RegistrationBean.
ctx.bind("registration", this);
JNDI is not the only way to look up remote objects. Lookup services are also available in the
RMI, JINI, and CORBA platforms. You can use these platform-specific lookup services
directly or from the JNDI API.
JNDI allows the application to change the name service with little effort. For example, here
are the code changes to have the BidderBean.ejbCreate method use the org.omb.CORBA
lookup services instead of the default BEA Weblogic lookup services.
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", “com.sun.jndi.cosnaming.CNCtxFactory");
Context ic = new InitialContext(env);
84 4: DISTRIBUTED COMPUTING
auction
RegistrationBean AuctionItemBean
In this example, the auction application has adapted SellerBean to a CORBA naming service
to look up the CORBA RegistrationBean. The following code is extracted from the Seller-
Bean class, which acts as the CORBA client, and the RegistrationServer CORBA server.
CORBA RegistrationServer
The RegistrationServer (lookup) (page 161) code creates a NameComponent object that uses
the auction and RegistrationBean strings as a full name indicating where to locate the Regis-
trationBean.
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent("auction", "");
fullname[1] = new NameComponent( "RegistrationBean", "");
This next code binds the fullname as a new name context. The first elements in the full name
(auction in this example) are placeholders for building the context naming tree. The last ele-
ment of the full name (RegistrationBean in this example) is the name submitted as the bind-
ing to the object.
public static void main(String args[]) {
String[] orbargs = { "-ORBInitialPort 1050"};
//API Ref :status ORB init(String[] args, Properties props)
ORB orb = ORB.init(orbargs, null)
RegistrationServer rs= new RegistrationServer();
try{
//API Ref :void connect(Object object)
orb.connect(rs);
org.omg.CORBA.Object nameServiceObj =
orb.resolve_initial_references("NameService");
NamingContext nctx = NamingContextHelper.narrow(nameServiceObj);
//API Ref :NameComponent(String nameid, String kind)
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent("auction", "");
fullname[1] = new NameComponent("RegistrationBean", "");
NameComponent[] tempComponent = new NameComponent[1];
for (int i=0; i < fullname.length-1; i++ ) {
tempComponent[0]= fullname[i];
try {
//API Ref :NamingContext bind_new_context(NameComponent[] nc)
nctx=nctx.bind_new_context(tempComponent);
} catch (org.omg.CosNaming.NamingContextPackage.AlreadyBound e){
//If this part of the tree is already bound then ignore this exception
}
}
tempComponent[0]=fullname[fullname.length-1];
// finally bind the object to the full context path
//API Ref :static void rebind(String rminame, Remote obj)
nctx.rebind(tempComponent, rs);
86 4: DISTRIBUTED COMPUTING
Once the RegistrationServer object is bound, it can be looked up with a JNDI lookup using a
CosNaming service provider as described in Java Naming and Directory Interface (JNDI)
(page 82) or using the CORBA name lookup service. Either way, the CORBA name server
must be started before any lookups can take place. In the Java 2 platform, the CORBA name
server is started as follows to start the CORBA RegistrationServer on the default TCP port
900:
tnameserv
If you need to use a different port, you can start the server like this:
CORBA SellerBean
On the client side, the CORBA lookup uses the NameComponent object to construct the
name. Start the object server like this:
java registration.RegistrationServer
The difference in the client is the name is passed to the resolve method which returns the
CORBA object. The following code from the SellerBean object illustrates this point.
public static void main(String args[]) {
java.util.Properties props=System.getProperties();
props.put("org.omg.CORBA.ORBInitialPort", "1050");
System.setProperties(props);
ORB orb = ORB.init(args, props);
The narrow method, from the Helper class, is generated by the IDL compiler, which pro-
vides a detailed mapping to translate each CORBA field into its respective Java program-
ming language field. For example, the SellerBean.insertItem method looks up a registration
CORBA object using the name RegistrationBean, and returns a RegistrationHome object.
With the RegistrationHome object, you can return a Registration record by calling its find-
ByPrimaryKey method.
4: DISTRIBUTED COMPUTING 87
IOR Server
To create an IOR all you do is call the object_to_string method from the ORB class and pass
it an instance of the object. For example, to convert the RegistrationServer object to an IOR,
you need to add the line String ref = orb.object_to_string(rs); to the main program:
String[] orbargs= {"-ORBInitialPort 1050"};
ORB orb = ORB.init(orbargs, null);
RegistrationServer rs = new RegistrationServer();
//Add this line
//API Ref :String object_to_String(Object object)
88 4: DISTRIBUTED COMPUTING
So, instead of retrieving this object information from a naming service, there is another way
for the server to send information to the client. You can register the returned String with a
substitute name server, which can be a simple HTTP web server because the object is
already in a transmittable format.
IOR Client
This example uses an HTTP connection to convert the IOR string back to an object. You call
the string_to_object method from the ORB class. This method requests the IOR from the
RegistrationServer and returns the IOR string. The String is passed to the ORB using the
ORB.string_to_object method, and the ORB returns the remote object reference:
URL iorserver = new URL("http://server.com/servlet?object=registration");
URLConnection con = ioserver.openConnection();
BufferedReader br = new BufferReader(new InputStreamReader(con.getInputStream));
String ref = br.readLine();
//API Ref :Object string_to_object(String stringvalue)
org.omg.CORBA.Object cobj = orb.string_to_object(ref);
RegistrationHome regHome = RegistrationHomeHelper.narrow(cobj);
The substitute name server can keep persistent IOR records that can survive a restart if
needed.
The above code returns the remote SellerHome reference _stub from the object bound to the
name seller on the machine called appserver. The rmi part of the URL is optional and you
may have seen RMI URLs without it, but if you are using JNDI or RMI-IIOP, including rmi
4: DISTRIBUTED COMPUTING 89
in the URL will save confusion later. Once you have a reference to SellerHome, you can call
its methods.
In contrast to the JNDI lookup performed by AuctionServlet.java (page 82), which requires a
two-stage lookup to create a context and then the actual lookup, RMI initializes the connec-
tion to the RMI name server, rmiregistry, and also gets the remote reference with one call.
This remote reference is leased to the client from the rmiregistry. The lease means that
unless the client informs the server it still needs a reference to the object, the lease expires
and the memory is reclaimed. This leasing operation is automatic and transparent to the user,
but can be tuned by setting the server property java.rmi.dgc.leaseValue value in milliseconds
when starting the server as follows:
You can find more information on leasing in Distributed Garbage Collection (page 99).
Note: The rmic compiler provides the -iiop option to generate the stub and the classes neces-
sary for RMI-IIOP.
IIOP Server
The RMI-IIOP protocol is implemented as a JNDI plug-in, so as before, you need to create
an InitialContext:
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.cosnaming.CNCtxFactory");
env.put("java.naming.provider.url","iiop://localhost:1091");
Context ic = new InitialContext(env);
The naming factory should look familiar as it is the same CORBA naming service used in
CORBA Naming Service (page 84). The main difference is the addition of a URL value
specifying the naming service to which to connect. The naming service used here is the
tnameserv program started on port 1091.
The other main change to the server side is to replace calls to Naming.rebind to use the JNDI
rebind method in the InitialContext instance. For example:
Old RMI lookup code:
SellerHome shome= new SellerHome("seller");
Naming.rebind("seller", shome);
IIOP Client
On the client side, the RMI lookup is changed to use an instance of the InitialContext in
place of RMI Naming.lookup. The return object is mapped to the requested object by using
the narrow method of the javax.rmi.PortableRemoteObject class. PortableRemoteObject
replaces UnicastRemoteObject that was previously available in the RMI server code.
Old RMI code:
//API Ref :static Remote lookup(String rminame)
SellerHome shome =
(SellerHome)Naming.lookup("rmi://appserver:1090/seller");
New RMI code:
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.cosnaming.CNCtxFactory");
env.put("java.naming.provider.url", iiop://localhost:1091");
Context ic = new InitialContext(env);
SellerHome shome =
//API Ref :static object narrow(Object narrowFrom, Class narrowTo
(SellerHome)PortableRemoteObject.narrow(ic.lookup("seller"), SellerHome)
Unix Systems
On Unix, the hosts file is usually /etc/hosts.
Windows
On Windows 95 or 98, the hosts file is c:\windows\hosts, (hosts.sam is a sample file). On
Windows NT, the hosts file is c:\winnt\system32\drivers\etc\hosts All you do is put these
lines in the hosts file. The myserver1 and myserver2 entries are the hosts running the remote
server and rmiregistry.
127.0.0.1 localhost
129.1.1.1 myserver1
129.1.1.2 myserver2
managed SellerBean (page 43) from Chapter 2 is also changed to call the new RMI registra-
tion server using a Java 2 RMI lookup call.
About RMI
The RMI API lets you access a remote server object from a client program by making simple
method calls on the server object. While other distributed architectures for accessing remote
server objects such as Distributed Component Object Model (DCOM) and Common Object
Request Broker Architecture (CORBA) return references to the remote object, the RMI API
not only returns references, but provides these additional benefits.
• The RMI API handles remote object references (call by reference) and can also return
a copy of the object (call by value).
• If the client program does not have local access to the class from which a local or
remote object was instantiated, RMI services can download the class file.
Note: Transferring code and data are key parts of the Jini™ System software specification. In
fact, adding a discovery and join service to the RMI services would create something very sim-
ilar to what you get in the Jini architecture.
Class Overview
The two main classes in the RMI-based auction implementation are SellerBean (RMI) (page
170) and RegistrationServer (RMI) (page 165). SellerBean is called from AuctionServlet
(RMI) (page 173) to insert an auction item into the database, and check for low account bal-
ances.
The example models the Enterprise JavaBeans architecture in that a user's registration details
are separate from the code to create and find the registration details. That is, the user's regis-
tration details provided by the Registration (RMI) (page 169) class are separate from the
code to create and find a Registration object, which is in the RegistrationHome (RMI) (page
169) class.
The remote interface implementation in RegistrationHome.java is bound to the rmiregistry.
When a client program wants to manipulate a user's registration details, it must first look up
the reference to the RegistrationHome.java object in the rmiregistry.
File Summary
All the source code files for the RMI-based example are described in the bullet list below.
• SellerBean (RMI) (page 170): Client program that calls the RegistrationServer.verify-
passwd and RegistrationServer.findLowCreditAccounts remote methods. SellerBean
also exports its updateResults method that RegistrationServer calls when it completes
its RegistrationServer.findLowCreditAccounts search.
• RegistrationServer (RMI) (page 165): Remote server object that implements the Reg-
istrationHome and Registration remote interfaces.
94 4: DISTRIBUTED COMPUTING
• Registration (RMI) (page 169): Remote interface that declares the getUser, verify-
passwd, and other remote methods for managing a user's registration details.
• RegistrationHome (RMI) (page 169): Remote interface that declares the create, find-
ByPrimaryKey, and findLowCreditAccounts remote methods that create or return
instances of registration details.
• RegistrationImpl.java: The RegistrationServer (RMI) (page 165) source file includes
the implementation for the Registration remote interface as class RegistrationImpl
• RegistrationPK (RMI) (page 170): Class that represents a user's registration details
using just the primary key of the database record.
• ReturnResults (RMI) (page 172): Remote interface that declares the updateResults
method the SellerBean class implements as a callback.
• AuctionServlet (RMI) (page 173): Modified version of the original AuctionServlet
class where registration accounts are created by calling the RMI RegistrationServer
directly. The auction servlet also calls the SellerBean.auditAccounts method, which
returns a list of users with a low account balance.
The auditAccounts method is called with the following Uniform Resource Locator
(URL), which does a simple check to verify the request came from the local host.
http://phoenix.eng.sun.com:7001/AuctionServlet?action=auditAccounts
You also need the following java.policy security policy file to grant the permissions needed
to run the example on the Java 2 platform.
grant {
permission java.net.SocketPermission "*:1024-65535", "connect,accept,resolve";
permission java.net.SocketPermission "*:80", "connect";
permission java.lang.RuntimePermission "modifyThreadGroup";
permission java.lang.RuntimePermission "modifyThread";
};
Most RMI applications need the two socket permissions for socket and HTTP access to the
specified ports. The two thread permissions, were listed in a stack trace as being needed for
the RegistrationImpl class to create a new inner thread.
In the Java 2 platform, when a program does not have all the permissions it needs, the Java
virtual machine generates a stack trace that lists the permissions that need to be added to the
security policy file. See 10: Signed Applets & Security Managers (page 417) for more infor-
mation on this and other security topics.
Unix:
javac registration/Registration.java
javac registration/RegistrationPK.java
javac registration/RegistrationServer.java
javac registration/ReturnResults.java
javac seller/SellerBean.java
rmic -d . registration.RegistrationServer
rmic -d . registration.RegistrationImpl
rmic -d . seller.SellerBean
Win32:
javac registration\Registration.java
javac registration\RegistrationPK.java
javac registration\RegistrationServer.java
javac registration\ReturnResults.java
javac seller\SellerBean.java
rmic -d . registration.RegistrationServer
rmic -d . registration.RegistrationImpl
rmic -d . seller.SellerBean
Win32:
unset CLASSPATH
start rmiregistry
Windows:
copy *_Stub.class \home\zelda\public_html\registration
copy RegistrationImpl.class \home\zelda\public_html\registration
cd \home\zelda\public_html\registration
java -Djava.server.hostname=phoenix.sun.com registration.RegistrationServer
The following key properties are used to configure RMI servers and clients. These properties
can be set inside the program or supplied as command line properties to the Java virtual
machine.
• The java.rmi.server.codebase property specifies where the publicly accessible classes
are located. On the server this can be a simple file URL to point to the directory or JAR
file that contains the classes. If the URL points to a directory, the URL must terminate
with a file separator character, “/”. If you are not using a file URL, you will either need
an HTTP server to download the remote classes or have to manually deliver the remote
client stub and remote interface classes in, for example, a JAR file.
• The java.rmi.server.hostname property is the complete host name of the server where
the publicly accessible classes reside. This is only needed if the server has problems
generating a fully qualified name by itself.
• The java.rmi.security.policy property specifies the policy file with the permissions
needed to run the remote server object and access the remote server classes for down-
load.
4: DISTRIBUTED COMPUTING 97
Note: In the Java 2 platform, the server side, _Skel.class file is not used.
Data Marshaling
An example of marshaling and unmarshaling data is when you call the Registra-
tionHome.create method from SellerBean, this call is forwarded to the
RegistrationServer_Stub.create method. The RegistrationServer_Stub.create method wraps
the method arguments and sends a serialized stream of bytes to the
RegistrationServer_Skel.create method.
As shown in Figure 17, the RegistrationServer_Skel.create method unwraps the serialized
bytestream, re-creates the arguments to the original RegistrationHome.create call, and
98 4: DISTRIBUTED COMPUTING
returns the result of calling the real RegistrationServer.create method back along the same
route, but this time wrapping the data on the server side.
Client Server
Program Program
Marshaling and unmarshaling data is not without its complications. The first issue is that
serialized objects might be incompatible across Java Development Kit (JDK™) releases. A
Serialized object has an identifier stored with the object that ties the serialized object to its
release. If the RMI client and server complain about incompatible serial IDs, you might need
to generate backward compatible stubs and skeletons using the -vcompat option to the rmic
compiler. Another issue is not all objects are serialized by default.
Fortunately, in the Java 2 platform the Collections API offers alternatives to previously
unmarshalable objects. In this example, an ArrayList from the Collections API replaces the
Vector. If the Collections API is not an option for you, you can create a wrapper class that
extends Serializable and provides readObject and writeObject method implementations to
convert the object into a bytestream.
RegistrationServer Class
The RegistrationServer (RMI) (page 165) class extends java.rmi.server.UnicastRemoteOb-
ject and implements the create, findByPrimaryKey and findLowCreditAccounts methods
declared in the RegistrationHome interface. The RegistrationServer.java source file also
includes the implementation for the Registration remote interface as class RegistrationImpl.
RegistrationImpl also extends UnicastRemoteObject.
The create and findByPrimaryKey methods are practically identical to the other versions of
the Registration Server. The main difference is that on the server side, the registration record
is referenced as RegistrationImpl, which is the implementation of Registration. On the client
side, Registration is used instead.
The findLowCreditAccounts method builds an ArrayList of serializable RegistrationImpl
objects and calls a remote method in the SellerBean class to pass the results back. The
100 4: DISTRIBUTED COMPUTING
results are generated by an inner Thread class so the method returns before the results are
complete. The SellerBean object waits for the updateAccounts method to be called before
displaying the HTML page. In a client written with the Java programming language, it
would not need to wait, but could display the update in real time.
public class RegistrationServer extends UnicastRemoteObject
implements RegistrationHome {
public registration.RegistrationPK create(String theuser,
String password, String emailaddress, String creditcard)
throws registration.CreateException{
double balance=0;
Connection con = null;
PreparedStatement ps = null;;
try {
con=getConnection();
ps=con.prepareStatement("insert into registration (theuser, password,
emailaddress, creditcard, balance) values (?, ?, ?, ?, ?)");
ps.setString(1, theuser);
ps.setString(2, password);
ps.setString(3, emailaddress);
ps.setString(4, creditcard);
ps.setDouble(5, balance);
if (ps.executeUpdate() != 1) {
throw new CreateException ();//JDBC did not create any row;
}
RegistrationPK primaryKey = new RegistrationPK();
primaryKey.setUser(theuser);
return primaryKey;
} catch (CreateException ce) {
throw ce;
} catch (SQLException sqe) {
throw new CreateException ();
} finally {
try {
ps.close();
con.close();
} catch (Exception ignore) {
// ignore the exception as we are no longer interested
// in this connection
}
}
}
public registration.Registration findByPrimaryKey(
registration.RegistrationPK pk)
throws registration.FinderException {
// return a Registration object that is created from reading
// values from the database by calling refresh()
if ((pk == null) || (pk.getUser() == null)) {
throw new FinderException ();
4: DISTRIBUTED COMPUTING 101
}
return(refresh(pk));
}
The main method loads the JDBC pool driver. This version uses the Postgres database,
installs the RMISecurityManager, and contacts the RMI registry to bind the Registra-
tionHome remote object to the name registration2. It does not need to bind the remote inter-
face, Registration, because that class is loaded when it is referenced by RegistrationHome.
4: DISTRIBUTED COMPUTING 103
By default, the server uses port 1099. If you want to use a different port number, you can add
it to the machine name with a colon as follows: phoenix:4321. If you change the port here,
you must start the RMI Registry with the same port number.
The main method also installs a RMIFailureHandler. If the server fails to create a server
socket then the failure handler returns true which instructs the RMI server to retry the opera-
tion.
public static void main(String[] args){
try {
new pool.JDCConnectionDriver("postgresql.Driver",
"jdbc:postgresql:ejbdemo","postgres", "pass");
} catch (Exception e){
System.out.println("error in loading JDBC driver");
System.exit(1);
}
try {
Properties env=System.getProperties();
env.put("java.rmi.server.codebase",
"http://phoenix.sun.com/registration");
RegistrationServer rs= new RegistrationServer();
//API Ref :static SecurityManager getSecurityManager()
if(System.getSecurityManager() == null ) {
//API Ref :static SecurityManager setSecurityManager(SecurityManager s)
System.setSecurityManager(new RMISecurityManager());
}
//API Ref :static void setFailureHandler(RMIFailureHandler fh)
RMISocketFactory.setFailureHandler(new RMIFailureHandlerImpl());
//API Ref :static void rebind(String rminame, Remote obj)
Naming.rebind("//phoenix.sun.com/registration2",rs);
} catch (Exception e) {
System.out.println("Exception thrown "+e);
}
} // End of Main
class RMIFailureHandlerImpl implements RMIFailureHandler {
public boolean failure(Exception ex ){
System.out.println("exception "+ex+" caught");
return true;
}
}
Registration Interface
The Registration (RMI) (page 169) interface declares the methods implemented by the Reg-
istrationImpl class in the RegistrationServer.java source file.
package registration;
import java.rmi.*;
import java.util.*;
104 4: DISTRIBUTED COMPUTING
RegistrationHome Interface
The RegistrationHome (RMI) (page 169) interface declares the methods implemented by the
RegistrationServer class. These methods mirror the Home interface defined in the Enterprise
JavaBeans example. The findLowCreditAccounts method takes a remote interface as its only
parameter.
package registration;
import java.rmi.*;
import java.util.*;
ReturnResults Interface
The ReturnResults (RMI) (page 172) interface declares the method implemented by the Sell-
erBean class. The updateResults method is called from RegistrationServer to return data and
frees the client from blocking while the results are generated.
package registration;
import java.rmi.*;
import java.util.*;
SellerBean Class
The SellerBean (RMI) (page 170) class includes the callback method implementation and
calls the RegistrationServer object using RMI. The updateResults method in the Seller-
Bean class is made accessible to other services in the auction application with a call to the
UnicastRemoteObject.exportObject method.
The call to UnicastRemoteObject in this example makes all public methods in the Seller-
Bean class available to other RMI clients. When the auction administrator wishes to retrieve
the list of accounts that have a low balance, the SellerBean.auditAccounts method is
called, which calls the remote RMI method findLowCreditAccounts from the Registra-
tionServer and waits on a Boolean object called ready.
When the remote findLowCreditAccounts method has finished processing the search
results, it calls the updateResults method from the RMI exported SellerBean. The updat-
eResults method updates ArrayList of Auction user IDs from the passed-in value and
notifies all methods waiting on the Boolean object ready that the results have been updated.
This enables the auditAccounts method to continue and forward the results to the Auction
administrator.
package seller;
import java.rmi.RemoteException;
import java.rmi.*;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
try {
RegistrationHome regRef = (RegistrationHome)Naming.lookup(
"//phoenix.sun.com/registration2");
RegistrationPK rpk= new RegistrationPK();
rpk.setUser(seller);
Registration newseller = (
Registration)regRef.findByPrimaryKey(rpk);
if ((newseller == null) || (!newseller.verifyPassword(password))) {
return(Auction.INVALID_USER);
}
AuctionItemHome home = (AuctionItemHome) ectx.lookup("auctionitems");
AuctionItem ai = home.create(seller, description, auctiondays,
startprice, summary);
if (ai == null) {
return Auction.INVALID_ITEM;
} else{
return(ai.getId());
}
} catch(Exception e){
System.out.println("insert problem="+e);
return Auction.INVALID_ITEM;
}
}
public void updateResults(java.util.ArrayList ar) throws RemoteException {
// Method called from remote rmi client as a callback
returned=ar;
synchronized(ready) {
ready.notifyAll();
}
}
understand objects, but as long as they can provide a mapping between the common IDL for-
mat and their own data representations, the applications can share data.
This section describes the Java language to IDL mapping scheme, and how to replace the
original container-managed RegistrationBean with its CORBA server equivalent. The Seller-
Bean.java and AuctionServlet.java programs are changed to interoperate with the CORBA
RegistrationServer program.
Quick Reference
Here is a quick reference table of the Java programming language to CORBA IDL data
types, and the runtime exceptions thrown when conversions fail. Data types in this table that
need explanation are covered below.
Table 1 Java Data Type Table 2 IDL Format Table 3 Runtime Exception
byte octet
boolean boolean
char char DATA_CONVERSION
char wchar
double double
float float
int long
int unsigned long
long long long
4: DISTRIBUTED COMPUTING 109
Table 1 Java Data Type Table 2 IDL Format Table 3 Runtime Exception
Unsigned Values
The primitive types byte, short, int, and long are represented by 8 bit, 16 bit, 32 bit and 64 bit
two's-complement integers. So, a Java short value represents the range -215 to 215- 1
or -32768 to 32767 inclusive. The equivalent signed IDL type for a short, matches that
range, but the unsigned IDL short type uses the range 0 to 216 or 0 to 65535.
This means that in the case of a short, if an unsigned short value greater than 32767 is passed
to a program written in the Java programming language, the short value is represented in the
Java programming language as a negative number. This can cause confusion in boundary
tests for a value greater than 32767 or less than 0.
Java packages and interfaces. Java package statements are equivalent to the module
type in IDL. The module types can be nested, which results in generated Java classes being
created in nested sub-directories. IDL is compiled and the compiler maps IDL interfaces to
Java interfaces.
For example, if a CORBA program contains this package statement:
package registration;
the mappings file would have this IDL module mapping for it:
module registration {
};
package registration.corba;
Distributed classes are defined as Java interfaces and map to the IDL interface type. IDL
does not define access such as public or private like you find in the Java programming lan-
guage. It does, however, allow inheritance from other interfaces. This example adds the Java
Registration interface to an IDL registration module.
module registration {
interface Registration {
};
}
This example adds the Java Registration interface to an IDL registration module, and indi-
cates the Registration interface inherits from the User interface.
module registration {
interface Registration: User {
4: DISTRIBUTED COMPUTING 111
};
}
Java methods. IDL operations map to Java methods. The IDL operation looks similar to
a Java method except there is no concept of access control. You also have to tell the IDL
compiler which parameters are in, inout or out. An inout parameter is marshaled 4 times, and
in and out parameters are marshaled 2 times. Because marshling takes time, you want to
specify the parameters exactly. Specifying parameters to be inout when they eally are not
will only generate a lot of time consuming code.
• in - parameter is passed into the method but not changed.
• inout - parameter is passed into the method and might be returned changed.
• out - parameter might be returned changed.
This IDL mapping includes the Registration and RegistrationHome interface methods to
IDL operations using one IDL module type.
module registration {
interface Registration {
boolean verifyPassword(in string password);
string getEmailAddress();
string getUser();
long adjustAccount(in double amount);
double getBalance();
};
interface RegistrationHome {
Registration findByPrimaryKey( in RegistrationPK theuser) raises (FinderExce
ption);
}
}
Java Arrays. Arrays in the Java programming language are mapped to the IDL array or
IDL sequence type using a type definition. This example maps the Java array double bal-
ances[10] to an IDL array type of the same size.
These examples map the Java array double balances[10] to an IDL sequence type. The first
typedef sequence is an example of an unbounded sequence, and the second typedef sequence
has the same size as the array.
typedef sequence<double> balances;
typedef sequence<double,10> balances;
Java Exception. Java exceptions are mapped to IDL exceptions. Operations use IDL
exceptions by including the raises keyword. This example maps the CreateException from
the auction application to the IDL exception type, and adds the IDL raises keyword to the
112 4: DISTRIBUTED COMPUTING
operation as follows. IDL exceptions follow C++ syntax, so instead of throwing an excep-
tion (as you would in the Java language), the operation raises an exception.
exception CreateException {
};
interface RegistrationHome {
RegistrationPK create(in string theuser, in string password,
in string emailaddress, in string creditcard) raises (CreateException);
}
IDL attribute
The required IDL attribute keyword is similar to the get and set methods used to access fields
in the JavaBeans software. In the case of a value declared as an IDL attribute, the IDL com-
piler generates two methods of the same name as the IDL attribute. One method returns the
field and the other method sets it. For example, this attribute definition:
interface RegistrationPK {
attribute string theuser;
};
IDL enum
The Java programming language has an Enumeration class for representing a collection of
data. The IDL enum type is different because it is declared as a data type and not a data col-
lection. The IDL enum type is a list of values that can be referenced by name instead of by
their position in the list. In the example, you can see that referring to an IDL enum status
code by name is more readable than referring to it by its number. This line maps static final
int values in the final class LoginError. You can reference the values as you would reference
a static field: LoginError.INVALID_USER.
Here is a version of the enum type that includes a preceding underscore that can be used in
switch statements:
switch (problem) {
case LoginError.INVALID_USER:
System.out.println("please login again");
break;
}
IDL struct
An IDL struct type can be compared to a Java class that has only fields, which is how it is
mapped by the IDL compiler. This example declares an IDL struct. Note that IDL types can
reference other IDL types. In this example LoginError is from the enum type declared above.
struct ErrorHandler {
LoginError errortype;
short retries;
};
IDL union
An IDL union can represent one type from a list of types defined for that union. The IDL
union maps to a Java class of the same name with a discriminator method used for determin-
ing the type of this union.
This example maps the GlobalErrors union to a Java class by the name of GlobalErrors. A
default case: DEFAULT could be added to handle any elements that might be in the Login-
Errors enum type, and not specified with a case statement here.
union GlobalErrors switch (LoginErrors) {
case: INVALID_USER: string message;
case: WRONG_PASSWORD: long attempts;
case: TIMEOUT: long timeout;
};
114 4: DISTRIBUTED COMPUTING
In a program written in the Java programming language, the GlobalErrors union class is cre-
ated as follows:
GlobalErrors ge = new GlobalErrors();
ge.message("please login again");
// The INVALID_USER value is retrieved like this:
switch (ge.discriminator().value()) {
case: LoginError.INVALID_USER
System.out.println(ge.message());
break;
}
Any type
If you do not know what type is going to be passed or returned to an operation, you can use
the Any type mapping, which can represent any IDL type. The following operation returns
and passes an unknown type:
interface RegistrationHome {
Any customSearch(Any searchField, out count);
};
To create a type of Any, first request the type from the Object Request Broker (ORB). To set
a value in a type of Any, use an insert_<type> method. To retrieve a value, use the
extract_<type> method. This example requests an object of type Any, and uses the
insert_type method to set a value.
Any sfield = orb.create_any();
sfield.insert_long(34);
The Any type has an assigned TypeCode value that you can query using type().kind().value()
on the object. The following example shows a test for the TypeCode double. This example
includes a reference to the IDL TypeCode to find out which type the Any object contains.
The TypeCode is used for all objects. You can analyze the type of a CORBA object using the
_type or type methods as shown here.
public Any customSearch(Any searchField, IntHolder count){
if(searchField.type().kind().value() == TCKind._tk_double){
//return number of balances greater than supplied amount
double findBalance=searchField.extract_double();
Principal
The Principal type identifies the owner of a CORBA object, for example, a user name. The
value can be interrogated from the request_principal field of the CORBA RequestHeader
class to make the identification. More comprehensive security and authorization is available
in the CORBA security service.
4: DISTRIBUTED COMPUTING 115
Object
The Object type is a CORBA object. If you need to send Java objects, you have to either
translate them into an IDL type or use a mechanism to serialize them when they are trans-
ferred.
interface RegistrationPK {
attribute string theuser;
};
enum LoginError {INVALIDUSER, WRONGPASSWORD, TIMEOUT};
exception CreateException {
};
exception FinderException {
};
typedef sequence<Registration> IDLArrayList;
interface ReturnResults {
void updateResults(in IDLArrayList results) raises (FinderException);
};
interface RegistrationHome {
RegistrationPK create(in string theuser, in string password,
in string emailaddress, in string creditcard)
raises (CreateException);
Registration findByPrimaryKey(in RegistrationPK theuser)
raises (FinderException);
void findLowCreditAccounts(in ReturnResults rr) raises (FinderException);
Any customSearch(in Any searchfield, out long count);
};
};
Other Java IDL compilers should also work, for example, jidl from ORBacus can generate
classes that can be used by the Java 2 ORB.
a _RegistrationHomeImplBase class (the skeleton or servant class) that the generated Regis-
trationServer class extends.
Client Server
Program Program
When requesting a remote CORBA object or calling a remote method, the client call passes
through the stub class before reaching the server. This proxy class invokes CORBA requests
for the client program. The following example is the code automatically generated for the
RegistrationHomeStub.java class.
org.omg.CORBA.Request r = _request("create");
r.set_return_type(registration.RegistrationPKHelper.type());
org.omg.CORBA.Any _theuser = r.add_in_arg();
In the RegistrationServer (CORBA) (page 181) program, the server object to be distributed
is bound to the ORB using the connect method:
RegistrationServer rs = new RegistrationServer();
//API Ref :void connect(Object object)
orb.connect(rs);
Once connected to a CORBA server object, the Java 2 ORB keeps the server alive and waits
for client requests to the CORBA server.
java.lang.Object sync = new java.lang.Object();
synchronized(sync) {
sync.wait();
}
The next lines from the main method in the RegistrationServer (CORBA) (page 181) class
show how this naming reference is created. The first step is to request the service called
NameService by calling the resolve_initial_references method from the Object Request Bro-
ker with the value NameService. This technique is used to find other services from the ORB,
not just the NameService.
The NamingContext is retrieved by narrowing the returned Object to the NameComponent
type. The name is built up and bound to the naming service as a list of NameComponent ele-
ments. The name in this example has a root called auction with this object being bound at the
next level of the name tree as RegistrationBean. The naming scheme could be used to mir-
ror the package and class that the object came from, in this example it could be used to
describe that the object was also the class auction.RegistrationBean.
4: DISTRIBUTED COMPUTING 119
In the Java 2 IDL, there is no distinct object adapter. As shown in the example code segment
below, using the Basic Object Adapter from ORBacus requires an explicit cast to the ORBa-
cus ORB. The Broker Object Architecture (BOA) is notified that the object is ready to be
distributed by calling the impl_is_ready(null) method.
120 4: DISTRIBUTED COMPUTING
Although both the ORBSingletonClass and ORBClass ORBs build the object name using
NameComponent, you have to use a different ORBacus Naming Service. The CosNam-
ing.Server service is started as follows where the -OAhost parameter is optional:
Once the naming service is started, the server and client programs find the naming service
using the IIOP protocol to the host and port named when starting the Naming service:
java registration.RegistrationServer -ORBservice NameService
iiop://localhost:1060/DefaultNamingContext
In the case of the ORBacus ORB, the clients also need a Basic Object Adapter if callbacks
are used as in the SellerBean.auditAccounts method. The naming context helper is also con-
figured differently for the ORBacus server started earlier:
Object obj = ((com.ooc.CORBA.ORB)orb).get_inet_object ("localhost",
1060, "DefaultNamingContext");
NamingContext nctx = NamingContextHelper.narrow(obj);
In the next example, the count of how many occurrences of the search term is held in a
instance of an int type Holder object. The Holder object, count is passed to the custom-
Search method where the field called value in the Holder object is changed on the remote
end. On return from the customSearch method, the count value is retrieved by accessing the
value field.
//API Ref :IntHolder()
IntHolder count= new IntHolder();
sfield=regRef.customSearch(sfield,count);
System.out.println("count now set to "+count.value);
Garbage Collection
Unlike RMI, CORBA does not have a distributed garbage collection mechanism. References
to an object are local to the client proxy and the server servant. This means each Java virtual
machine is free to reclaim that object and garbage collect it if there are no longer references
to it. If an object is no longer needed on the server, the orb.disconnect(object) needs to be
called to allow the object to be garbage collected.
CORBA Callbacks
The new findLowCreditAccounts method is called from the AuctionServlet when the
user uses the Uniform Resource Locator (URL) http://localhost:7001/AuctionServ-
let?action=auditAccounts. The AuctionServlet.auditAccounts method calls the Seller-
Bean.auditAccounts method, which returns an ArrayList of Registration records.
// From file AuctionServlet.java
private void auditAccounts(ServletOutputStream out,HttpServletRequest request)
throws IOException{
// ...
SellerHome home = (SellerHome) ctx.lookup("seller");
Seller si= home.create();
if(si != null) {
// Call the auditAccounts method in SellerBean and return
// an ArrayList of Registration records. Call the getUser
// and getBalance methods on each Registration Object.
ArrayList ar=si.auditAccounts();
//API Ref :Interator iterator()
//API Ref :boolean hasNext()
for(Iterator i=ar.iterator(); i.hasNext();) {
Registration user=(Registration)(i.next());
addLine("<TD>"+user.getUser() + "<TD><TD>"+user.getBalance() +
"<TD><TR>", out);
}
addLine("<TABLE>", out);
}
122 4: DISTRIBUTED COMPUTING
http://phoenix.sun.com:7001/
AuctionServlet?action=customSearch&searchfield=2
addLine("<BR>"+text, out);
SellerHome home = (SellerHome)ctx.lookup("seller");
Seller si= home.create();
if(si != null) {
// Call customFind method from SellerBean and display results
String displayMessage=si.customFind(searchField);
if(displayMessage != null ) {
addLine(displayMessage+"<BR>", out);
}
}
} catch (Exception e) {
addLine("AuctionServlet customFind error",out);
System.out.println("AuctionServlet " + "<customFind>:"+e);
}
out.flush();
}
The SellerBean.customFind method calls the RegistrationHome object implemented in
the RegistrationServer (CORBA) (page 181) class, and because the searchField might be a
number or a string, an object of the CORBA type Any is used to transfer the value.
The convenience of not needing to specify the type of the object incurs an extra cost because
special methods are required to set and retrieve values from an object of type Any. The Any
object is created by a call to the ORB, orb.create_any method.
The customFind method also uses an out parameter, count, of type int that returns the
number of records found. The number of records found is retrieved from count.value when
the customFind method returns. The return type of the customFind method also is type
String and is described after the code sample.
// From file SellerBean.java
public String customFind(String searchField)
throws javax.ejb.FinderException, RemoteException{
int total=-1;
IntHolder count= new IntHolder();
try {
//API Ref :NameComponent(String nameid, String kind)
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent("auction", "");
fullname[1] = new NameComponent(
"RegistrationBean", "");
RegistrationHome regRef =
RegistrationHomeHelper.narrow(nctx.resolve(fullname));
if(regRef == null ) {
System.out.println("cannot contact RegistrationHome");
throw new javax.ejb.FinderException();
}
//API Ref :Any create_any()
Any sfield=orb.create_any();
Double balance;
try {
// Treat the search value as an account balance. If it cannot
126 4: DISTRIBUTED COMPUTING
The return value from the call to customFind is extracted into an object of type Any, the
results of the search are then displayed to the user in the AuctionServlet. For simple types,
the extract_<type> method of the Any object can be used. However, for the Registration
type, the RegistrationHelper class is used.
Registration reg = RegistrationHelper.extract(
regRef.customSearch(sfield,count));
Finally, because the customSearch method returns an object of type Any, a call to
orb.create_any() is required. For simple types like double, the insert_<type> method is
used. For a Registration record, the RegistrationHelper class is used like this: Regis-
trationHelper.insert(returnResults, regarray[0]).
// From file RegistrationServer.java
public Any customSearch(Any searchField, IntHolder count){
Any returnResults= orb.create_any();
int tmpcount=count.value;
if(searchField.type().kind().value() == TCKind._tk_double){
// Search database for number of accounts where the balance is
// less than supplied amount
double findBalance=searchField.extract_double();
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
con=getConnection();
//API Ref :PrepareStatement prepareStatement(String sql)
ps=con.prepareStatement("select count(*) from
registration where balance < ?");
//API Ref :void setDouble(int index, double doublevalue)
ps.setDouble(1, findBalance);
//API Ref :ResultSet executeQuery()
ps.executeQuery();
rs = ps.getResultSet();
//API Ref :boolean next()
if(rs.next()) {
//API Ref :int getInt(String ColumnName)
tmpcount = rs.getInt(1);
}
count.value=tmpcount;
rs.close();
} catch (Exception e) {
System.out.println("custom search: "+e);
returnResults.insert_long(-1);
return(returnResults);
} finally {
try {
if(rs != null) { rs.close(); }
if(ps != null) { ps.close(); }
if(con != null) { con.close(); }
} catch (Exception ignore) {}
}
returnResults.insert_long(tmpcount);
return(returnResults);
} else if(searchField.type().kind().value() == TCKind._tk_string) {
// If the any value is of type string then the admin was
// looking for an email address so return the
128 4: DISTRIBUTED COMPUTING
In Conclusion
As you have seen, converting the application to use RMI or CORBA requires very little
change to core programs. The main difference has been the initialization and naming ser-
vice. By abstracting these two areas in your application away from the business logic you
ease migration between different distributed object architectures for the Java platform.
4: DISTRIBUTED COMPUTING 129
JDBC Technology
The Bean-managed Enterprise JavaBeans auction application with its Remote Method Invo-
cation (RMI) and Common Object Request Broker (CORBA) variants has used simple
JDBC calls to retrieve and update information from a database using a JDBC connection
pool. By default, JDBC database access involves opening a database connection, running
SQL commands in a statement, processing the returned results, and closing the database
connection.
Overall, the default approach works well for low volume database access, but how do you
manage a large number of requests that update many related tables at once and still ensure
data integrity? This section explains how.
JDBC Drivers
The connection to the database is handled by the JDBC Driver class. The Java SDK contains
only one JDBC driver, a jdbc-odbc bridge that can communicate with an existing Open
DataBase Connectivity (ODBC) driver. Other databases need a JDBC driver specific to that
database.
To get a general idea of what the JDBC driver does, you can examine the JDCConnection-
Driver (page 391) class. The JDCConnectionDriver class implements the java.sql.Driver
class and acts as a pass-through driver by forwarding JDBC requests to the real database
JDBC Driver. The JDBC driver class is loaded with a call to Class.forName(drivername).
These next code lines show how to load three different JDBC driver classes:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("postgresql.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
Each JDBC driver is configured to understand a specific URL so multiple JDBC drivers can
be loaded at any one time. When you specify a URL at connect time, the first matching
JDBC driver is selected.
The jdbc-odbc bridge accepts Uniform Resource Locators (URLs) starting with jdbc:odbc:
and uses the next field in that URL to specify the data source name. The data source name
identifies the particular database scheme you wish to access. The URL can also include more
details on how to contact the database and enter the account.
//access the ejbdemo tables
String url = "jdbc:odbc:ejbdemo";
This next example contains the Oracle SQL*net information on the particular database
called ejbdemo on machine dbmachine.
130 4: DISTRIBUTED COMPUTING
This next example uses mysql to connect to the ejbdemo database on the local machine. The
login user name and password details are also included.
String url = "jdbc:mysql://localhost/ejbdemo?user=user;
password=pass";
JDBC drivers are divided into four types. Drivers may also be categorized as pure Java or
thin drivers to indicate if they are used for client applications (pure Java drivers) or applets
(thin drivers). Newer drivers are usually Type 3 or 4. The four types are as follows:
Type 1 Drivers
Type 1 JDBC drivers are the bridge drivers such as the jdbc-odbc bridge. These drivers rely
on an intermediary such as ODBC to transfer the SQL calls to the database. Bridge drivers
often rely on native code, although the jdbc-odbc library native code is part of the Java 2 vir-
tual machine.
Type 2 Drivers
Type 2 Drivers use the existing database API to communicate with the database on the client.
Although Type 2 drivers are faster than Type 1 drivers, Type 2 drivers use native code and
require additional permissions to work in an applet. A Type 2 driver might need client-side
database code to connect over the network.
Type 3 Drivers
Type 3 Drivers call the database API on the server. JDBC requests from the client are first
proxied to the JDBC Driver on the server to run. Type 3 and 4 drivers can be used by thin cli-
ents as they need no native code.
Type 4 Drivers
The highest level of driver reimplements the database network API in the Java programming
language. Type 4 drivers can also be used on thin clients as they also have no native code.
Database Connections
A database connection can be established with a call to the DriverManager.getConnection
method. The call takes a URL that identifies the database, and optionally, the database login
user name and password.
//API Ref :static Connection getConnection(String url)
4: DISTRIBUTED COMPUTING 131
After a connection is established, a statement can be run against the database. The results of
the statement can be retrieved and the connection closed.
One useful feature of the DriverManager class is the setLogStream method. You can use this
method to generate tracing information to help you diagnose connection problems that
would normally not be visible. To generate tracing information, just call the method like this:
//API Ref :static void setLogStream(PrintStream out)
DriverManager.setLogStream(System.out);
Connection Pooling (page 344) shows you how to improve the throughput of JDBC connec-
tions by not closing the connection once the statement completes. Each JDBC connection to
a database incurs overhead in opening a new socket and using the username and password to
log into the database. Reusing the connections reduces the overhead. The Connection Pool
keeps a list of open connections and clears any connections that cannot be reused.
Statements
There are three basic types of SQL statements used in the JDBC API: CallableStatement,
Statement, and PreparedStatement. When a Statement or PreparedStatement is sent to the
database, the database driver translates it into a format the underlying database can recog-
nize.
Callable Statements
Once you have established a connection to a database, you can use the Connection.prepare-
Call method to create a callable statement. A callable statement lets you execute SQL stored
procedures. This next example creates a CallableStatement object with three parameters for
storing account login information.
//API Ref :CallableStatement prepareCall(String sql)
CallableStatement cs = con.prepareCall("{call accountlogin(?,?,?)}");
//API Ref :void setString(int index, String s)
cs.setString(1,theuser);
cs.setString(2,password);
//API Ref :void registerOutParameter(int index, int sqltype)
cs.registerOutParameter(3,Types.DATE);
cs.executeQuery();
//API Ref :Date getDate(int index)
Date lastLogin = cs.getDate(3);
132 4: DISTRIBUTED COMPUTING
Statements
The Statement interface lets you execute a simple SQL statement with no parameters. The
SQL instructions are inserted into the Statement object when the Statement.execute<type>
method is called.
Query Statement. This code segment creates a Statement object and calls the State-
ment.executeQuery method to select text from the dba database table. The results of the
query are returned in a ResultSet object. How to retrieve results from a ResultSet object is
explained in Result Sets (page 133) below.
//API Ref :Statement createStatement()
Statement stmt = con.createStatement();
//API Ref :int executeQuery(String sql)
ResultSet results = stmt.executeQuery("SELECT TEXT FROM dba ");
Update Statement. This next code segment creates a Statement object and calls the
Statement.executeUpdate method to add an email address to a table in the dba database
table.
String updateString = "INSERT INTO dba VALUES (‘some text’)";
//API Ref :int executeUpdate(String sql)
int count = stmt.executeUpdate(updateString);
Prepared Statements
The PreparedStatement interface descends from the Statement interface and uses a template
to create a SQL request. Use a PreparedStatement to make multiple database operations
where only the values change. The advantage to using a PreparedStatement is that the state-
ment is compiled the first time and subsequent calls are optimized by inserting only the
changed data.
Once the PreparedStatement template is initialized, only the changed values are inserted for
each call.
pstmt.setString(1, anotherEmailAddress);
Result Sets
The ResultSet interface manages access to data returned from a query. The data returned
equals one row in a database table. Some queries return one row of data while many queries
return multiple rows of data.
134 4: DISTRIBUTED COMPUTING
You use getType methods to retrieve data from specific columns for each row returned by the
query. The SELECT TEXT FROM dba query selects the TEXT column from the daba table.
Statement stmt = con.createStatement();
ResultSet results = stmt.executeQuery("SELECT TEXT FROM dba ");
//API Ref :boolean next()
while(results.next()){
//API Ref :String getString(String columnName)
String s = results.getString("TEXT");
displayText.append(s + "\n");
}
stmt.close();
Inserting a new row uses the same update<type> methods. The only difference being that the
method rs.moveToInsertRow is called before, and rs.insertRow is called after the fields have
been initialized. You can delete the current row with a call to rs.deleteRow.
Batch Jobs
By default, every JDBC statement is sent to the database individually. Apart from the addi-
tional network requests, this process incurs additional delays if a transaction spans several
statements. JDBC 2.0 lets you submit multiple statements at one time with the addBatch
method.
This next code segment shows how to use the addBatch statement. The calls to
stmt.addBatch append statements to the original Statement, and the call to executeBatch
submits the entire statement with all the appends to the database.
Statement stmt = con.createStatement();
stmt.addBatch("update registration set balance=balance-5.00
where theuser="+theuser);
stmt.addBatch("insert into auctionitems(description, startprice)
values("+description+","+startprice+")");
//API Ref :int executeBatch()
int[] results = stmt.executeBatch();
The addBatch method return result is an array of row counts affected for each statement exe-
cuted in the batch job. If a problem occurs, a java.sql.BatchUpdateException is thrown. An
incomplete array of row counts can be obtained from BatchUpdateException by calling its
getUpdateCounts method.
Storing and retrieving an image. It is very easy to store an object that can be serialized
or converted to a byte array. Unfortunately, java.awt.Image is not Serializable. However, as
shown in this next code example, you can store the image data to a file and store the informa-
tion in the file as bytes in a database binary field.
4: DISTRIBUTED COMPUTING 137
int itemnumber=400456;
// Each image is assumed to be in the format <auctionitem>.jpg
// 400456.jpg
File file = new File(itemnumber+".jpg");
FileInputStream fis = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("update auctionitems
set theimage=? where id= ?");
// The FileInputStream fis and the length of that stream are used
// as parameters to the setBinaryStream method
//API Ref :void setBinaryStream(int index, InputStream stream, int length)
pstmt.setBinaryStream(1, fis, (int)file.length()):
pstmt.setInt(2, itemnumber);
//API Ref :int executeUpdate()
pstmt.executeUpdate();
//API Ref :void close()
pstmt.close();
fis.close();
To retrieve this image and create a byte array that can be passed to createImage, do the fol-
lowing:
int itemnumber=400456;
byte[] imageBytes;
PreparedStatement pstmt = con.prepareStatement(
"select theimage from auctionitems where id= ?");
Storing and retrieving an object. A class can be serialized to a binary database field in
much the same way as the image was in the previous example. In this example, the Registra-
tionImpl class is changed to support default serialization by adding implements Serializable
to the Class declaration.
Next, a ByteArrayInputStream is created to be passed as the JDBC Binary Stream. To create
the ByteArrayInputStream, RegistrationImpl is first piped through an ObjectOutputStream
to an underlying ByteArrayInputStream with a call to RegistrationImpl.writeObject The
ByteArrayInputStream is then converted to a byte array, which can then be used to create the
ByteArrayInputStream. The create method in RegistrationServer.java is changed as follows:
138 4: DISTRIBUTED COMPUTING
// Finally, create the byte array input stream from the array of bytes
ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes);
ps=con.prepareStatement("insert into registration (theuser, theclass)
values (?, ?)");
ps.setString(1, theuser);
ps.setBinaryStream(2, regArrayStream, regBytes.length);
if(ps.executeUpdate() != 1) {
throw new CreateException ();
}
RegistrationPK primaryKey = new RegistrationPKImpl();
primaryKey.theuser(theuser);
return primaryKey;
} catch (IOException ioe) {
throw new CreateException ();
} catch (CreateException ce) {
throw ce;
} catch (SQLException sqe) {
System.out.println("sqe="+sqe);
throw new CreateException ();
} finally {
try {
ps.close();
con.close();
4: DISTRIBUTED COMPUTING 139
BLOBs and CLOBs . Storing large fields in a table with the other data is not necessarily
optimum especially if the data has a variable size. One way to handle large, variable sized
140 4: DISTRIBUTED COMPUTING
objects is with the Large Objects (LOBs) type. LOBs use a locator, essentially a pointer, in
the database record that points to the real database field.
There are two types of LOBs: Binary Large Objects (BLOBs) and Character Large Objects
(CLOBs). When you access a BLOB or CLOB, the data is not copied to the client. To
retrieve the actual data from a result set, you have to retrieve the pointer with a call to BLOB
blob = getBlob(1) or CLOB clob = getClob(1), and then retrieve the data with a call to
blob.getBinaryStream() or clob.getBinaryStream(). Both getBlob and getClob are in the
java.sql package.
Controlling Transactions
By default, JDBC statements are processed in full auto-commit mode. This mode works well
for a single database query, but if an operation depends on several database statements that
all have to complete successfully or the entire operation is cancelled, a finer transaction is
needed.
A description of transaction isolation levels is covered in more detail in 3: Data and Transac-
tion Management (page 55). To use transaction management in the JDBC platform, you first
need to disable the full auto-commit mode by calling:
Connection con= getConnection();
con.setAutoCommit(false);
At this point, you can either commit any following JDBC statements or undo any updates by
calling the Connection.rollback method. The rollback call is commonly placed in the Excep-
tion handler, although it can be placed anywhere in the transaction flow.
This next example inserts an auction item and decrements the user's balance. If the balance is
less than zero, the entire transaction is rolled back and the auction item is removed.
// New insertItem code to add to file SellerBean.java
static {
try{
new pool.JDCConnectionDriver("COM.cloudscape.core.JDBCDriver", "jdbc:clo
udscape:ejbdemo","none", "none");
} catch(Exception e) {
System.out.println("new pool error"+e);
}
}
try {
con = getConnection();
// Disable auto commit of jdbc transactions for this connection
//API Ref :void setAutoCommit(boolean autoCommit)
con.setAutoCommit(false);
//API Ref :Statement createStatement()
stmt = con.createStatement();
stmt.executeQuery("select counter from auctionitems");
//API Ref :ResultSet getResultSet()
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
count=rs.getInt(1);
}
// Calculate the end date of the auction
//API Ref :static Calendar getInstance()
Calendar currenttime = Calendar.getInstance();
//API Ref :long getTime()
java.util.Date currentdate = currenttime.getTime();
startdate=new java.sql.Date(currentdate.getTime());
//API Ref :void add(int partofdate, int dateamount)
currenttime.add(Calendar.DATE, auctiondays);
enddate = new java.sql.Date((currenttime.getTime()).getTime());
ps.close();
stmt = con.createStatement();
stmt.executeQuery("select balance from registration
where theuser='"+seller+"'");
//API Ref :ResultSet getResultSet()
rs = stmt.getResultSet();
if(rs.next()) {
balance=rs.getDouble(1);
}
stmt.close();
// Finally, check the users balance, its is less than 0 rollback
// the whole transaction else update the auction id number and
// commit everything to the database
if(balance <0) {
//API Ref :void rollback()
con.rollback();
con.close();
return (-1);
}
stmt= con.createStatement();
// Counter is the next auction item id number that can be
// used for a auction listing
//API Ref :int executeUpdate(String sql)
stmt.executeUpdate("update auctionitems set counter=counter+1");
stmt.close();
con.commit();
con.close();
return(0);
} catch(SQLException e) {
try {
// Always roll the transaction back if something unexpected happens
con.rollback();
con.close();
stmt.close();
ps.close();
} catch (Exception ignore){}
}
return (0);
}
Escaping Characters
The JDBC API provides the escape keyword so you can specify the character you want to
use to escape characters. For example, if you want to use the percent sign (%) as the percent
sign and not have it interpreted as the SQL wildcard used in SQL LIKE queries, you have to
escape it with the escape character you specify with the escape keyword. This next statement
shows how you would use the escape keyword to look for the value 10%.
stmt.executeQuery("select tax from sales where tax like ‘10\%' {escape '\'}");
4: DISTRIBUTED COMPUTING 143
If your program stores names and addresses entered from the command line or by way of a
user interface to the database, the single quotes (') symbol might appear in the data. Passing
single quotes directly into a SQL string causes problems when the SQL statement is parsed
because SQL gives this symbol another meaning unless it is escaped.
To solve this problem, the following method escapes any ' symbol found in the input line.
This method can be extended to escape any other characters such as commas that the data-
base or database driver might interpret another way.
static public String escapeLine(String s) {
String retvalue = s;
if(s.indexOf ("'") != -1 ) {
StringBuffer hold = new StringBuffer();
char c;
for(int i=0; i < s.length(); i++ ) {
if((c=s.charAt(i)) == '\'' ) {
hold.append ("''");
} else {
hold.append(c);
}
}
retvalue = hold.toString();
}
return retvalue;
}
int count=0;
Connection con=getConnection();
Statement stmt= con.createStatement();
stmt.executeQuery("select counter from auctionitems");
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
if(rs.getMetaData().getColumnType(1) == Types.INTEGER) {
Integer i=(Integer)rs.getObject(1);
count=i.intValue();
}
}
rs.close();
Note: The Timestamp class loses precision when it is converted to a java.util.Date because
java.util.Date does not contain a nanosecond field. It is better to not convert a Timestamp
instance if the value will be written back to the database.
This example uses the java.sql.Date class to convert the java.util.Date value returned by the
call to Calendar.getTime to a java.sql.Date.
Calendar currenttime = Calendar.getInstance();
java.sql.Date startdate = new java.sql.Date((currenttime.getTime()).getTime());
You can also use the java.text.SimpleDateFormat class to do the conversion. This example
uses the java.text.SimpleDateFormat class to convert a java.util.Date object to a
java.sql.Date object:
SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date enddate = new java.util.Date("10/31/99");
java.sql.Date sqlDate = java.sql.Date.valueOf(template.format(enddate));
4: DISTRIBUTED COMPUTING 145
If you find a database date representation cannot be mapped to a Java type with a call to
getObject or getDate, retrieve the value with a call to getString and format the string as a
Date value using the SimpleDateFormat class shown above.
Servlets
A servlet is a server-side program written in the Java programming language that interacts
with clients and is usually tied to a HyperText Transfer Protocol (HTTP) server. One com-
mon use for a servlet is to extend a web server by providing dynamic web content.
Servlets have an advantage over other technologies such as Perl scripts in that they are com-
piled, have threading capability built in, and provide a secure programming environment.
Even web sites that previously did not provide servlet support can do so now by using pro-
grams such as JRun or the Java module for the Apache web server.
The web-based auction application described in Duke’s Auction Demonstration (page 7)
uses a servlet to accept and process buyer and seller input through the browser and dynami-
cally return auction item information to the browser. The AuctionServlet program is created
by extending the HttpServlet class. The HttpServlet class provides a framework for handling
HTTP requests and responses.
This section examines the AuctionServlet and includes information on how to use Cookie
and Session objects in a servlet.
HttpServlet
The AuctionServlet (page 44) class extends HttpServlet, which is an abstract class.
A servlet can be either loaded when the web server starts up or when requested by way of an
HTTP URL that specifies the servlet. The servlet is usually loaded by a separate classloader
in the web server because this allows the servlet to be reloaded by unloading the class loader
that loaded the servlet class. However, if the servlet depends on other classes and one of
those classes changes, you will need to update the date stamp on the servlet for it to reload.
After a servlet loads, the first stage in its lifecycle is the web server calls the servlet's init
method. Once loaded and initialized, the next stage in the servlet's lifecycle is to serve
requests. The servlet serves requests through its service, doGet, or doPost method imple-
mentations.
The servlet can optionally implement a destroy method to perform clean-up operations
before the web server unloads the servlet.
146 4: DISTRIBUTED COMPUTING
try {
ctx = getInitialContext();
} catch (Exception e){
System.err.println("failed to contact EJB server"+e);
}
}
HTTP Requests
A request is a message sent from a client program such as a browser to a server program.
The first line of the request message contains a method that indicates the action to perform
on the incoming Uniform Resource Locator (URL). The two commonly used mechanisms
for sending information to the server are GET and POST.
• GET requests might pass parameters to a URL by appending them to the URL. GET
requests can be bookmarked and emailed and add the information to the URL of the
response.
• POST requests might pass additional data to a URL by directly sending it to the server
separately from the URL. POST requests cannot be bookmarked or emailed and do not
change the URL of the response.
4: DISTRIBUTED COMPUTING 149
• PUT requests are the reverse of GET requests. Instead of reading the page, PUT
requests write (or store) the page.
• DELETE requests are for removing web pages.
• OPTIONS requests are for getting information about the communication options avail-
able on the request/response chain.
• TRACE requests are for testing or diagnostic purposes because they let the client see
what is being received at the other end of the request chain.
Setting a Cookie
The Java Servlet API includes a Cookie class that you can use to set or retrieve the cookie
from the HTTP header. HTTP cookies include a name and value pair. The startSession
method shown here is in the Login Servlet (page 200) program. In this method, the name in
the name and value pair used to create the Cookie is JDCAUCTION, and a unique identifier
generated by the server is the value.
protected Session startSession(String theuser, String password,
HttpServletResponse response) {
Session session = null;
if( verifyPassword(theuser, password) ) {
// The user was validated in the user database,
// create a session
session = new Session (theuser);
// Set a timeout for this session that we control
session.setExpires (sessionTimeout + System.currentTimeMillis());
sessionCache.put (session);
// Create a client cookie
//API Ref :Cookie(String name, String value)
Cookie c = new Cookie("JDCAUCTION", String.valueOf(session.getId()));
//API Ref :void setPath(String path)
c.setPath ("/");
//API Ref :void setMaxAge(int expire)
c.setMaxAge (-1);
//API Ref :void setDomain(String domainstring)
150 4: DISTRIBUTED COMPUTING
c.setDomain (domain);
//API Ref :void addCookie(Cookie cookie)
response.addCookie (c);
}
return session;
}
Later versions of the Servlet API include a Session API, to create a session using the Servlet
API in the previous example you can use the getSession method.
The startSession method is called by requesting the login action from a POST to the Login-
Servlet as follows:
<FORM ACTION="/LoginServlet" METHOD="POST">
<TABLE>
<INPUT TYPE="HIDDEN" NAME="action" VALUE="login">
<TR><TD>Enter your user id:</TD>
<TD><INPUT TYPE="TEXT" SIZE=20 NAME="theuser"></TD>
</TR>
<TR><TD>Enter your password:<TD>
<TD><INPUT TYPE="PASSWORD" SIZE=20 NAME="password"></TD>
</TR>
</TABLE>
<INPUT TYPE="SUBMIT" VALUE="Login" NAME="Enter">
</FORM>
The cookie is created with an maximum age of -1, which means the cookie is not stored but
remains alive while the browser runs. The value is set in seconds, although when using val-
ues smaller than a few minutes you need to be careful of machine times being slightly out of
sync.
The path value can be used to specify that the cookie only applies to files and directories
under the path set on that machine. In this example the root path / means the cookie is appli-
cable to all directories.
The domain value in the example is read from the initialization parameters for the servlet. If
the domain is null, the cookie is applied to that machines domain only.
Retrieving a Cookie
The cookie is retrieved from the HTTP headers with a call to the getCookies method on the
request:
//API Ref :Cookie[] getCookies()
Cookie c[] = request.getCookies();
You can later retrieve the name and value pair settings by calling the Cookie.getName
method to retrieve the name, and the Cookie.getValue method to retrieve the value. Login-
4: DISTRIBUTED COMPUTING 151
Servlet has a validateSession method that checks the user's cookies to find a JDCAUCTION
cookie that was set in this domain:
private Session validateSession(HttpServletRequest request,
HttpServletResponse response) {
// Request the users cookies for this domain
Cookie c[] = request.getCookies();
Session session = null;
if( c != null ) {
for(int i=0; i < c.length && session == null; i++ ) {
// Look for a cookie whose name is JDCAUCTION in this
// domain. This cookie was previously set by us.
// The cookie value is the session id number stored in the
// session cache.
if(c[i].getName().equals("JDCAUCTION")) {
String key = String.valueOf (c[i].getValue());
session=sessionCache.get(key);
}
}
}
return session;
}
If you use the Servlet session API, you can use the following method. Note that the parame-
ter is false to specify that the session value is returned and a new session not created.
Generating Sessions
The LoginServlet.validateSession method returns a Session object represented by the Ses-
sion (Servlets) (page 204) class. The Session class uses an identifier generated from a
numeric sequence. This numbered session identifier is the value part of the name and value
pair stored in the cookie.
The only way to reference the user name on the server is with this session identifier, which is
stored in a simple memory cache with the other session IDs. When a user terminates a ses-
sion, the LoginServlet logout action is called like this:
http://phoenix.sun.com:7001/LoginServlet?action=logout
The session cache implemented in the SessionCache (Servlets) (page 205) program includes
a reaper thread to remove sessions older than a preset time. The preset timeout could be mea-
sured in hours or days depending on how many visitors visit the site.
The Expires expiration header is also set to 0. Alternately, you can set the time to be the cur-
rent system time. Even if the client does not cache the page, there are often proxy servers in
a corporate network that would. Only pages using Secure Socket Layer (SSL) are not cached
by default.
private void setNoCache (HttpServletRequest request,
HttpServletResponse response) {
//API Ref :String getProtocol()
if(request.getProtocol().compareTo ("HTTP/1.0") == 0) {
//API Ref :void setHeader(String name, String value)
response.setHeader ("Pragma", "no-cache");
} else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
response.setHeader ("Cache-Control", "no-cache");
}
//API Ref :void setDateHeader(String name, long datevalue)
response.setDateHeader ("Expires", 0);
}
The init method also retrieves the servlet context for the FileServlet servlet so methods can
be called on the FileServlet in the validateSession method. The advantage to calling methods
on FileServlet to serve the files rather than serving the files from within the LoginServlet, is
you get the full advantage of all the functionality added into FileServlet such as memory
mapping or file caching. The downside is that the code may not be portable to other servers
that do not have FileServlet. This code retrieves the FileServlet context.
FileServlet fileServlet = (FileServlet)
//API Ref :ServletContext getServletContext()
config.getServletContext().getServlet("file");
The validateSession method prevents users without a logon session from accessing the
restricted directory.
order of elements stored in it. The example keeps a reference to each name and value pair in
a vector that can be traversed to return the values in the order they were received by the
server.
// File auction.PostServlet.java
package auction;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
try {
offset = 0;
while(dataRemaining) {
inputLen = instream.read (postedBytes, offset, length - offset);
if(inputLen <= 0) {
throw new IOException ("read error");
}
offset += inputLen;
if((length-offset) ==0) {
dataRemaining=false;
}
}
} catch (IOException e) {
System.out.println("Exception ="+e);
return null;
}
// Create a string from the byte array and parse the name/value
// pairs.
postedBody = new String (postedBytes);
StringTokenizer st = new StringTokenizer(postedBody, "&");
String key=null;
String val=null;
while (st.hasMoreTokens()) {
String pair = (String)st.nextToken();
int pos = pair.indexOf('=');
if(pos == -1) {
throw new IllegalArgumentException();
}
try {
// Spaces and other http sensitive characters are url encoded
// before posting so convert the posted string into its original
// form
key = java.net.URLDecoder.decode(pair.substring(0, pos));
val = java.net.URLDecoder.decode(pair.substring(pos+1, pair.length()));
} catch (Exception e) {
throw new IllegalArgumentException();
}
if(ht.containsKey(key)) {
String oldVals[] = (String []) ht.get(key);
valArray = new String[oldVals.length + 1];
for(int i = 0; i < oldVals.length; i++) {
156 4: DISTRIBUTED COMPUTING
valArray[i] = oldVals[i];
}
valArray[oldVals.length] = val;
} else {
valArray = new String[1];
valArray[0] = val;
}
ht.put(key, valArray);
paramOrder.addElement(key);
}
return ht;
}
To find out whether the request is POST or GET, call the getMethod in the HttpServletRe-
quest class. To determine the format of the data being posted, call the getContentType
method in the HttpServletRequest class. For simple HTML web pages, the type returned by
this call will be application/x-www-form-urlencoded.
If you need to create a post with more than one part such as the one created by the following
HTML form, the servlet will need to read the input stream from the post to reach individual
sections. Each section is distinguished by a boundary defined in the post header.
<FORM ACTION="/PostMultiServlet" METHOD="POST" ENCTYPE="multipart/form-data">
<INPUT TYPE="TEXT" NAME="desc" value="">
<INPUT TYPE="FILE" NAME="filecontents" value="">
<INPUT TYPE="SUBMIT" VALUE="Submit" NAME="Submit">
</FORM>
The next example extracts a description and a file from the client browsers. It reads the input
stream looking for a line matching the boundary string, reads the content line, skips a line
and then reads the data associated with that part. The uploaded file is simply displayed, but
could also be written to disk.
// File auction.PostMultiServlet.java
package auction;
import java.io.*;
import java.util.*;
4: DISTRIBUTED COMPUTING 157
import javax.servlet.*;
import javax.servlet.http.*;
if(moreData) {
length = instream.readLine(tmpbuffer, 0, tmpbuffer.length);
inputLine = new String (tmpbuffer, 0, 0, length);
if(inputLine.indexOf("filename") >=0) {
// We know what the file name is now
int startindex=inputLine.indexOf("filename");
System.out.println("file name="+ inputLine.substring(startindex+10,
inputLine.indexOf("\"", startindex+10)));
length = instream.readLine(tmpbuffer, 0, tmpbuffer.length);
Threading
A servlet must be able to handle multiple concurrent requests. Any number of end users at
any given time could invoke the servlet, and while the init method is always run single-
threaded, the service method is multi-threaded to handle multiple requests.
This means any fields accessed by the service method should be restricted to simple thread
access. The example below uses the synchronized keyword to restrict access to a counter so
it can only be updated by one thread at a time:
4: DISTRIBUTED COMPUTING 159
HTTPS
Many servers, browsers, and the Java Plug-In can support the secure HTTP protocol called
HTTPS. HTTPS is similar to HTTP except the data is transmitted over a secure socket layer
(SSL) instead of a normal socket connection. Web servers often listen for HTTP requests on
one port while listening for HTTPS requests on another.
SSL has checks to find out if encrypted data sent over the network has been tampered with in
transit. SSL also authenticates the web server to its clients by providing a public key certifi-
cate. In SSL 3.0 the client can also authenticate itself with the server using a public key cer-
tificate.
Public key cryptography (also called asymmetric key encryption) uses a public and private
key pair. Any message encrypted with the private key in the pair can only be decrypted with
the corresponding public key. Certificates are digitally signed statements generated from a
trusted third party Certificate Authority. The Certificate Authority needs proof that you are
who you say you are because clients will be trusting the certificate they receive.
It is this certificate that contains the public key in the public and private key pair. The certifi-
cate is signed by the private key of the Certificate Authority, and most browsers know the
public key for the main Certificate Authorities.
While public key encryption is good for authentication purposes, it is not as fast as symmet-
ric key encryption and so the SSL protocol uses both types of keys in the lifecycle of an SSL
connection. The client and server begin an HTTPS transaction with a connection initializa-
tion or handshaking phase.
It is in the handshaking stage that the server is authenticated using the certificate that the cli-
ent has received. The client uses the server's public key to encrypt messages sent to the
server. After the client has been authenticated and the encryption algorithm or cipher has
been agreed between the two parties, new symmetric session keys are used to encrypt and
decrypt any further communication.
The encryption algorithm or cipher can be one of many popular algorithms like Rivest
Shamir and Adleman (RSA) or Data Encryption Standard (DES). The greater the number of
bits used to make the key, the more difficult it is to break into using brute force search tech-
niques.
160 4: DISTRIBUTED COMPUTING
HTTPS using public key cryptography and certificates lets you provide the amount of pri-
vacy your application needs for safe and secure transactions. Servers, browsers, and Java
Plug-In have their own setup for enabling HTTPS using SSL communications. In general,
the steps involve the following:
• Get a private key and a digitally-signed certificate with the matching public key.
• Install the certificate in a location specified by the software you are using (server,
browser, or Java Plug-In).
• Enable SSL features and specify your certificate and private key files as instructed in
your documentation.
You should enable SSL features according to your specific application requirements depend-
ing on the level of security you need. For example, you do not need to verify the identity of
customers browsing auction items, but you will want to encrypt credit card and other per-
sonal information supplied when buyers and sellers register to participate.
HTTPS can be used for any data not just HTTP web pages. Programs written in the Java pro-
gramming language can be downloaded over an HTTPS connection, and you can open a
connection to a HTTPS server in the Java Plug-in. To write a program in the Java program-
ming language that uses SSL, you need an SSL library and a detailed knowledge of the
HTTPS handshaking process. Your SSL library should provide all the functionality you need
because this information is restricted by export security control.
RegistrationServer (lookup)
package registration;
import java.sql.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;
}
public registration.Registration findByPrimaryKey(
registration.RegistrationPK pk)
throws registration.FinderException {
//Primary key cannot be nul
if((pk == null) || (pk.getUser() == null)) {l
throw new FinderException ();
}
return(refresh(pk));
}
private Registration refresh(RegistrationPK pk) throws FinderException {
if(pk == null) {//Primary key cannot be null
throw new FinderException ();
}
Connection con = null;
PreparedStatement ps = null;
try {
con=getConnection();
ps=con.prepareStatement(“select password, emailaddress, creditcard,
balance from registration where theuser = ?”);
ps.setString(1, pk.getUser());
ps.executeQuery();
ResultSet rs = ps.getResultSet();
if (rs.next()) {
RegistrationImpl reg= new RegistrationImpl();
reg.theuser = pk.getUser();
reg.password = rs.getString(1);
reg.emailaddress = rs.getString(2);
reg.creditcard = rs.getString(3);
reg.balance = rs.getDouble(4);
return reg;
} else {
throw new FinderException ();
}
} catch (SQLException sqe) {
throw new FinderException();
} finally {
try {
ps.close();
con.close();
} catch (Exception ignore) {}
}
return null;
}
public static void main(String args[]) {
String[] orbargs = { “-ORBInitialPort 1050”};
ORB orb = ORB.init(orbargs, null) ;
RegistrationServer rs= new RegistrationServer();
try {
org.omg.CORBA.Object nameServiceObj =
orb.resolve_initial_references(“NameService”) ;
NamingContext nctx= NamingContextHelper.narrow(nameServiceObj);
NameComponent[] fullname = new NameComponent[2];
4: DISTRIBUTED COMPUTING 163
SellerBean (lookup)
package seller;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
164 4: DISTRIBUTED COMPUTING
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;
RegistrationServer (RMI)
package registration;
import java.sql.*;
import java.rmi.*;
import java.rmi.server.*;
import java.util.Properties;
import java.util.*;
System.out.println("findLowCreditAccounts: "+e);
return;
}
finally {
try {
if(rs != null) {
rs.close();
}
if(ps != null) {
ps.close();
}
if(con != null) {
con.close();
}
}catch (Exception ignore) {}
}
} //run
};
Thread t = new Thread(bgthread);
t.start();
}
Registration (RMI)
package registration;
import java.rmi.*;
import java.util.*;
RegistrationHome (RMI)
package registration;
import java.rmi.*;
import java.util.*;
170 4: DISTRIBUTED COMPUTING
RegistrationPK (RMI)
package registration;
SellerBean (RMI)
package seller;
import java.rmi.RemoteException;
import java.rmi.*;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
ReturnResults (RMI)
package registration;
import java.rmi.*;
import java.util.*;
AuctionServlet (RMI)
package auction;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.NumberFormat;
import bidder.*;
import registration.*;
import seller.*;
import pool.*;
import search.*;
} else if(cmd.equals(“insert”)) {
insertItem(out, request);
} else if (cmd.equals(“details”)) {
itemDetails(out, request );
} else if (cmd.equals(“bid”)) {
itemBid(out, request) ;
} else if (cmd.equals(“auditAccounts”)) {
auditAccounts(out, request);
} else if (cmd.equals(“register”)) {
registerUser(out, request);
}
} else {// no command set
setTitle(out, “error”);
}
setFooter(out);
out.flush();
}
static private void addLine(String message, ServletOutputStream out)
throws IOException {
if(message !=null) {
out.println(“<BR>”+message);
}
}
static public javax.naming.Context getInitialContext() throws Exception {
Properties p = new Properties();
p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
“weblogic.jndi.TengahInitialContextFactory”);
return new InitialContext(p);
}
private void listAllItems(ServletOutputStream out) throws IOException{
String text = “Click Item number for description and to place bid.”;
setTitle(out, “Auction results”);
try {
addLine(“<BR>”+text, out);
BidderHome bhome=(BidderHome) ctx.lookup(“bidder”);
Bidder bid=bhome.create();
Enumeration enum=(Enumeration)bid.getItemList();
if(enum != null) {
displayitems(enum, out);
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet List All Items error”,out);
System.out.println(“AuctionServlet <list>:”+e);
}
out.flush();
}
private void listAllNewItems(ServletOutputStream out) throws IOException {
setTitle(out, “New Auction Items”);
try {
addLine(““, out);
String text = “Click Item number for description and to place bid.”;
addLine(text, out);
4: DISTRIBUTED COMPUTING 175
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet List Closed Items error”, out);
System.out.println(“AuctionServlet <close>:”+e);
}
out.flush();
}
private void insertItem(ServletOutputStream out, HttpServletRequest request)
throws IOException{
setTitle(out, “Insert Auction Item”);
String seller=request.getParameter(“seller”);
String description=request.getParameter(“description”);
String summary=request.getParameter(“summary”);
String password=request.getParameter(“password”);
String price=request.getParameter(“startprice”);
double startprice=0.00;
try {
startprice=((Number)NumberFormat.getCurrencyInstance(
Locale.US).parse(“$”+price)).doubleValue();
} catch(java.text.ParseException e) {
System.out.println(“money problem”+e);
return;
} catch (NumberFormatException e) {
System.out.println(“money problem”+e);
return;
}
int auctiondays=7;
try {
auctiondays=Integer.parseInt(request.getParameter(“auctiondays”));
} catch(NumberFormatException e){
System.out.println(“problem parsing auction days”+e);
return;
}
if(auctiondays<=0 || auctiondays>7) {
auctiondays=7;
}
try {
SellerHome home = (SellerHome) ctx.lookup(“seller”);
Seller si= home.create();
if(si != null) {
int result= si.insertItem(seller, password, description,
auctiondays, startprice, summary);
if(result >0) {
addLine(“Inserted item “+summary, out);
addLine(“Details available <A HREF=/AuctionServlet?action=details&item
= ” + resul + ”>here</A>”, out);
} else {
addLine(“Error inserting item”, out);
return;
}
addLine(““, out);
}
4: DISTRIBUTED COMPUTING 177
} catch (Exception e) {
addLine(“AuctionServlet Insert Item error”, out);
System.out.println(“AuctionServlet <insert>:”+e);
}
out.flush();
}
private void itemDetails(ServletOutputStream out, HttpServletRequest request)
throws IOException{
setTitle(out, “Item Details”);
String item=request.getParameter(“item”);
int itemid=0;
try {
itemid=Integer.parseInt(item);
} catch (NumberFormatException e) {
System.out.println(“problem with item id “+itemid);
return;
}
try {
AuctionItemHome home = (AuctionItemHome) ctx.lookup(“auctionitems”);
AuctionItemPK pk=new AuctionItemPK();
pk.id=itemid;
AuctionItem ai=home.findByPrimaryKey(pk);
displayPageItem(ai, out);
addLine(“<BR><HR><P>Do you want to bid on this item?”, out);
addLine(“<FORM ACTION=\”/AuctionServlet\” METHOD=\”POST\”>”, out);
addLine(“<TR>Enter your user id:<INPUT TYPE=\”TEXT\”
SIZE=20 NAME=\”buyer\”> “, out);
addLine(“and password:<INPUT TYPE=\”PASSWORD\”
SIZE=20 NAME=\”password\”></TR>”, out);
addLine(“<TR>Your bid amount:<INPUT TYPE=\”TEXT\”
SIZE=20 NAME=\”amount\”></TR>”, out);
addLine(“<INPUT TYPE=\”HIDDEN\” NAME=\”action\” VALUE=\”bid\”>”, out);
addLine(“<INPUT TYPE=\”HIDDEN\” NAME=\”item\” VALUE=\””+itemid+”\”>”, out);
addLine(“<INPUT TYPE=\”SUBMIT\” VALUE=\”Place Bid\” NAME=\”Bid\”>
</FORM>”, out);
} catch (Exception e) {
addLine(“AuctionServlet List Item error”, out);
System.out.println(“AuctionServlet <details>:”+e);
}
out.flush();
}
private void itemBid(ServletOutputStream out, HttpServletRequest request)
throws IOException{
setTitle(out, “Item Bid”);
String item=request.getParameter(“item”);
String buyer=request.getParameter(“buyer”);
String password=request.getParameter(“password”);
String bid=request.getParameter(“amount”);
int itemid=0;
double bidamount=0;
try {
itemid=Integer.parseInt(item);
} catch (NumberFormatException e) {
178 4: DISTRIBUTED COMPUTING
line.append(“<TR><TD><A HREF=/AuctionServlet?action=details&item=”+
key+”>”+key+”</A></TD>”);
line.append(“<TD>”+auctionItem.getSummary() +”</TD>”);
if(bidcount >0) {
line.append(“<TD>”+
NumberFormat.getCurrencyInstance().format(auctionItem.getHighBid())
+”</TD>”);
} else {
line.append(“<TD>-</TD>”);
}
line.append(“<TD>”+bidcount+”</TD>”);
line.append(“<TD>”+auctionItem.getEndDate() +”</TD></TR>”);
addLine(line.toString(), out);
}
static private void displayPageItem(AuctionItem auctionItem,
ServletOutputStream out)
throws RemoteException, IOException {
int bidcount=auctionItem.getBidCount();
addLine(auctionItem.getSummary(), out);
addLine(“Auction Item Number: “+auctionItem.getPrimaryKey(), out);
if(bidcount >0) {
addLine(“<P>Current price: “ +
NumberFormat.getCurrencyInstance().format(auctionItem.getHighBid()),
out);
addLine(“Minimum increment: “+
NumberFormat.getCurrencyInstance().format(
auctionItem.getIncrement()), out);
} else {
addLine(“<P>Current price: “+ NumberFormat.getCurrencyInstance().format(
auctionItem.getStartPrice()), out);
}
addLine(“# of bids: “+bidcount, out);
addLine(“<P>Auction Started: “+auctionItem.getStartDate(), out);
addLine(“Auction Ends: “+auctionItem.getEndDate(), out);
addLine(“<P>Seller: “+auctionItem.getSeller(), out);
if(bidcount >0) {
addLine(“High Bidder: “+auctionItem.getHighBidder(), out);
} else {
addLine(“High Bidder: “+”-”, out);
}
addLine(“<HR><P>”, out);
addLine(“Description: “+auctionItem.getDescription(), out);
}
private String readFile (String file) throws IOException {
if(file != null) {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader (new FileReader (file));
String line;
while( (line=reader.readLine()) != null ) {
buffer.append (line+’\n’);
}
reader.close();
return buffer.toString();
4: DISTRIBUTED COMPUTING 181
} else {
return null;
}
}
private void setTitle(ServletOutputStream out, String title) {
try {
out.println(“<HTML><HEAD><TITLE>”+title+”</TITLE></HEAD>”);
out.println(“<BODY BGCOLOR=\”WHITE\”>”);
} catch(IOException e) {
System.out.println(“Unable to set title”+e);
}
}
private void setFooter(ServletOutputStream out) {
try {
out.println(“<HR><CENTER> <A HREF=\”registration.html\”>Register</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”/AuctionServlet?action=newlist\”>New Items</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”/AuctionServlet?action=close\”>Closing Items</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”/AuctionServlet?action=list\”>All Items</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”sell.html\”>Sell Items</A>”);
out.println(“</CENTER>”);
} catch (IOException e) {
System.out.println(“Unable to set footer”+e);
}
}
}
RegistrationServer (CORBA)
//This file contains the RegistrationServer
//and RegistrationImpl implementations
package registration;
import java.sql.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;
import java.util.ArrayList;
}
public RegistrationServer(ORB orb) {
super();
this.orb=orb;
}
public registration.RegistrationPK create(String theuser, String password,
String emailaddress, String creditcard)
throws registration.CreateException{
double balance=0;
Connection con = null;
PreparedStatement ps = null;;
try {
con=getConnection();
ps=con.prepareStatement(“insert into registration(theuser, password,
emailaddress, creditcard, balance) values (?, ?, ?, ?, ?)”);
ps.setString(1, theuser);
ps.setString(2, password);
ps.setString(3, emailaddress);
ps.setString(4, creditcard);
ps.setDouble(5, balance);
if(ps.executeUpdate() != 1) {
throw new CreateException ();
}
RegistrationPK primaryKey = new RegistrationPKImpl();
primaryKey.theuser(theuser);
return primaryKey;
} catch (CreateException ce) {
throw ce;
} catch (SQLException sqe) {
System.out.println(“sqe=”+sqe);
throw new CreateException ();
} finally {
try {
ps.close();
con.close();
} catch (Exception ignore) {
}
}
public registration.Registration findByPrimaryKey(
registration.RegistrationPK pk)
if((pk == null) || (pk.theuser() == null)) {
throw new FinderException ();
}
return(refresh(pk));
}
private Registration refresh(RegistrationPK pk) throws FinderException {
if(pk == null) {
throw new FinderException ();
}
Connection con = null;
PreparedStatement ps = null;
try {
4: DISTRIBUTED COMPUTING 183
con=getConnection();
ps=con.prepareStatement(“select password, emailaddress, creditcard,
balance from registration where theuser = ?”);
ps.setString(1, pk.theuser());
ps.executeQuery();
ResultSet rs = ps.getResultSet();
if(rs.next()) {
RegistrationImpl reg= new RegistrationImpl();
reg.theuser = pk.theuser();
reg.password = rs.getString(1);
reg.emailaddress = rs.getString(2);
reg.creditcard = rs.getString(3);
reg.balance = rs.getDouble(4);
return reg;
} else {
throw new FinderException ();
}
} catch (SQLException sqe) {
throw new FinderException ();
} finally {
try {
ps.close();
con.close();
} catch (Exception ignore) {}
}
}
public void findLowCreditAccounts(final ReturnResults client)
throws FinderException {
Runnable bgthread = new Runnable() {
public void run() {
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
ArrayList ar = new ArrayList();
try {
con=getConnection();
ps=con.prepareStatement(“select theuser,
balance from registration where balance < ?”);
ps.setDouble(1, 3.00);
ps.executeQuery();
rs = ps.getResultSet();
RegistrationImpl reg=null;
while (rs.next()) {
try {
reg= new RegistrationImpl();
} catch (Exception e) {
System.out.println(“creating reg”+e);
}
reg.theuser = rs.getString(1);
reg.balance = rs.getDouble(2);
ar.add(reg);
}
rs.close();
184 4: DISTRIBUTED COMPUTING
}
if(ps != null) {
ps.close();
}
if(con != null) {
con.close();
}
} catch (Exception ignore) {}
}
returnResults.insert_long(tmpcount);
return(returnResults);
} else if(searchField.type().kind().value() ==
TCKind._tk_string) {
// return email addresses that match supplied address
String findEmail=searchField.extract_string();
Connection con = null;
ResultSet rs = null;
PreparedStatement ps = null;
ArrayList ar = new ArrayList();
RegistrationImpl reg=null;
try {
con = getConnection();
ps = con.prepareStatement(“select theuser,
emailaddress from registration where emailaddress like ?”);
ps.setString(1, findEmail);
ps.executeQuery();
rs = ps.getResultSet();
while(rs.next()) {
reg= new RegistrationImpl();
reg.theuser = rs.getString(1);
reg.emailaddress = rs.getString(2);
ar.add(reg);
}
rs.close();
RegistrationImpl[] regarray = (RegistrationImpl
[])ar.toArray( new RegistrationImpl[0]);
RegistrationHelper.insert(returnResults, regarray[0]);
return(returnResults);
} catch (Exception e) {
System.out.println(“custom search: “+e);
return(returnResults);
} finally {
try {
if(rs != null) {
rs.close();
}
if(ps != null) {
ps.close();
}
if(con != null) {
con.close();
}
} catch (Exception ignore) {}
186 4: DISTRIBUTED COMPUTING
}
}
return(returnResults);
}
public static void main(String args[]) {
java.util.Properties props=System.getProperties();
props.put(“org.omg.CORBA.ORBInitialPort”, “1050”);
System.setProperties(props);
ORB orb = ORB.init(args, props);
RegistrationServer rs= new RegistrationServer(orb);
try {
orb.connect(rs);
org.omg.CORBA.Object nameServiceObj =
orb.resolve_initial_references(“NameService”) ;
NamingContext nctx= NamingContextHelper.narrow(nameServiceObj);
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent(“auction”, ““);
fullname[1] = new NameComponent(“RegistrationBean”, ““);
NameComponent[] tempComponent = new NameComponent[1];
for(int i=0; i < fullname.length-1; i++ ) {
tempComponent[0]= fullname[i];
try {
nctx=nctx.bind_new_context(tempComponent);
} catch (Exception e){ System.out.println(“bind new”+e);}
}
tempComponent[0]=fullname[fullname.length-1];
try {
nctx.rebind(tempComponent, rs);
} catch (Exception e){
nctx.unbind(tempComponent);
nctx.rebind(tempComponent, rs);
System.out.println(“rebind”+e);
}
java.lang.Object sync= new java.lang.Object();
synchronized(sync) {
sync.wait();
}
} catch (Exception e) {
System.out.println(“e=”+e);
}
}
}
class RegistrationImpl extends _RegistrationImplBase {
public String theuser, password, creditcard, emailaddress;
public double balance;
Registration.idl (CORBA)
module registration {
interface Registration {
boolean verifyPassword(in string password);
string getEmailAddress();
string getUser();
long adjustAccount(in double amount);
double getBalance();
};
interface RegistrationPK {
attribute string theuser;
};
enum LoginError {INVALIDUSER, WRONGPASSWORD, TIMEOUT};
exception CreateException {};
exception FinderException {};
typedef sequence<Registration> IDLArrayList;
interface ReturnResults {
void updateResults(in IDLArrayList results) raises (FinderException);
};
interface RegistrationHome {
RegistrationPK create(in string theuser, in string password,
in string emailaddress, in string creditcard)
raises (CreateException);
Registration findByPrimaryKey(in RegistrationPK theuser)
raises (FinderException);
void findLowCreditAccounts(in ReturnResults rr) raises (FinderException);
any customSearch(in any searchfield, out long count);
};
};
SellerBean (CORBA)
package seller;
188 4: DISTRIBUTED COMPUTING
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;
}
try {
for(int i=0; i< ar.length; i++) {
returned.add(ar[i]);
}
} catch (Exception e) {
System.out.println(“updateResults=”+e);
throw new registration.FinderException();
}
synchronized(ready) {
ready.notifyAll();
}
}
public ArrayList auditAccounts() {
try {
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent(“auction”, ““);
fullname[1] = new NameComponent(“RegistrationBean”, ““);
RegistrationHome regRef = RegistrationHomeHelper.narrow(
nctx.resolve(fullname));
regRef.findLowCreditAccounts(this);
synchronized(ready) {
try {
ready.wait();
} catch (InterruptedException e){
}
return (returned);
} catch (Exception e) {
System.out.println(“error in auditAccounts “+e);
}
return null;
}
public String customFind(String searchField)
throws javax.ejb.FinderException, RemoteException{
int total=-1;
IntHolder count= new IntHolder();
try {
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent(“auction”, ““);
fullname[1] = new NameComponent(“RegistrationBean”, ““);
RegistrationHome regRef = RegistrationHomeHelper.narrow(
nctx.resolve(fullname));
if(regRef == null ) {
System.out.println(“cannot contact RegistrationHome”);
throw new javax.ejb.FinderException();
}
Any sfield=orb.create_any();
Double balance;
try {
balance=Double.valueOf(searchField);
try {
sfield.insert_double(balance.doubleValue());
} catch (Exception e) {
190 4: DISTRIBUTED COMPUTING
Seller (CORBA)
package seller;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
AuctionServlet (CORBA)
package auction;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.NumberFormat;
import bidder.*;
import registration.*;
import seller.*;
import pool.*;
import search.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;
try {
ctx = getInitialContext();
} catch (Exception e) {
System.err.println(“failed to contact EJB server”+e);
}
try {
String[] args = {};
Properties props= System.getProperties();
props.put(“org.omg.CORBA.ORBInitialPort”, “1050”);
System.setProperties(props);
orb = ORB.init(args, props) ;
org.omg.CORBA.Object nameServiceObj =
orb.resolve_initial_references(“NameService”) ;
nctx= NamingContextHelper.narrow(nameServiceObj);
} catch(org.omg.CORBA.SystemException e) {
System.err.println(“CORBA Error in AuctionServlet <init>”+e);
} catch(Exception e) {
System.err.println(“Error in AuctionServlet <init>”+e);
}
}
public void service(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String cmd;
response.setContentType(“text/html”);
ServletOutputStream out = response.getOutputStream();
if(ctx == null ) {
try {
ctx = getInitialContext();
} catch (Exception e){
System.err.println(“failed to contact EJB server”+e);
}
}
cmd=request.getParameter(“action”);
if(cmd !=null) {
if(cmd.equals(“list”)) {
listAllItems(out);
} else if(cmd.equals(“newlist”)) {
listAllNewItems(out);
} else if(cmd.equals(“search”)) {
searchItems(out, request);
} else if(cmd.equals(“close”)) {
listClosingItems(out);
} else if(cmd.equals(“insert”)) {
insertItem(out, request);
} else if (cmd.equals(“details”)) {
itemDetails(out, request );
} else if (cmd.equals(“bid”)) {
itemBid(out, request) ;
} else if (cmd.equals(“auditAccounts”)) {
auditAccounts(out, request);
} else if (cmd.equals(“register”)) {
registerUser(out, request);
} else if (cmd.equals(“customSearch”)) {
4: DISTRIBUTED COMPUTING 193
customSearch(out, request);
} else {
addLine(“unknown command “+cmd, out);
}
} else {
// no command set
setTitle(out, “error”);
}
setFooter(out);
out.flush();
}
static private void addLine(String message, ServletOutputStream out)
throws IOException {
if(message !=null) {
out.println(“<BR>”+message);
}
}
static public javax.naming.Context getInitialContext() throws Exception {
Properties p = new Properties();
p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
“weblogic.jndi.TengahInitialContextFactory”);
return new InitialContext(p);
}
private void listAllItems(ServletOutputStream out) throws IOException{
String text = “Click Item number for description and to place bid.”;
setTitle(out, “Auction results”);
try {
addLine(“<BR>”+text, out);
BidderHome bhome=(BidderHome) ctx.lookup(“bidder”);
Bidder bid=bhome.create();
Enumeration enum=(Enumeration)bid.getItemList();
if(enum != null) {
displayitems(enum, out);
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet List All Items error”,out);
System.out.println(“AuctionServlet <list>:”+e);
}
out.flush();
}
private void listAllNewItems(ServletOutputStream out) throws IOException {
setTitle(out, “New Auction Items”);
try {
addLine(““, out);
String text = “Click Item number for description and to place bid.”;
addLine(text, out);
BidderHome bhome = (BidderHome) ctx.lookup(“bidder”);
Bidder bid = bhome.create();
Enumeration enum = (Enumeration)bid.getNewItemList();
if(enum != null) {
displayitems(enum, out);
addLine(““, out);
194 4: DISTRIBUTED COMPUTING
}
} catch (Exception e) {
addLine(“AuctionServlet List New Items error”, out);
System.out.println(“AuctionServlet <newlist>:”+e);
}
out.flush();
}
private void searchItems(ServletOutputStream out,
HttpServletRequest request) throws IOException {
String searchString = request.getParameter(“searchString”);
String text = “Click Item number for description and to place bid.”;
setTitle(out, “Search Results”);
try {
addLine(“<BR>”+text, out);
AuctionItemHome ahome = (AuctionItemHome) ctx.lookup(“auctionitems”);
SearchHome shome = (SearchHome) ctx.lookup(“search”);
Search search = shome.create();
Enumeration enum = (Enumeration)
search.getMatchingItemsList(searchString);
addLine(“<TABLE BORDER=1 CELLPADDING=1 CELLSPACING=0>
<TR><TH>Item</TH><TH>Summary</TH>
<TH>Current High bid</TH><TH>Number of bids</TH>
<TH>Closing Date</TH></TR>”, out);
while ((enum != null) && (enum.hasMoreElements())) {
while(enum.hasMoreElements()) {
AuctionItem ai = ahome.findByPrimaryKey((
AuctionItemPK)enum.nextElement());
displayLineItem(ai, out);
}
}
addLine(“</TABLE>”, out);
} catch (Exception e) {
addLine(“AuctionServlet Search Items error”, out);
System.out.println(“AuctionServlet <searchItems>:”+e);
}
out.flush();
}
private void listClosingItems(ServletOutputStream out) throws IOException{
setTitle(out, “Items Due to Close Today”);
String text = “Click Item number for description and to place bid.”;
setTitle(out, “Items Due to Close Today”);
try {
addLine(“<BR>”+text, out);
BidderHome bhome=(BidderHome) ctx.lookup(“bidder”);
Bidder bid=bhome.create();
Enumeration enum=(Enumeration)bid.getClosedItemList();
if(enum != null) {
displayitems(enum, out);
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet List Closed Items error”, out);
System.out.println(“AuctionServlet <close>:”+e);
4: DISTRIBUTED COMPUTING 195
}
out.flush();
}
private void insertItem(ServletOutputStream out, HttpServletRequest request)
throws IOException{
setTitle(out, “Insert Auction Item”);
String seller=request.getParameter(“seller”);
String description=request.getParameter(“description”);
String summary=request.getParameter(“summary”);
String password=request.getParameter(“password”);
String price=request.getParameter(“startprice”);
double startprice=0.00;
try {
startprice=((Number)NumberFormat.
getCurrencyInstance(Locale.US).parse(“$”+price)).
doubleValue();
} catch(java.text.ParseException e){
System.out.println(“money problem”+e);
return;
} catch (NumberFormatException e) {
System.out.println(“money problem”+e);
return;
}
int auctiondays=7;
try {
auctiondays=Integer.parseInt(request.getParameter(“auctiondays”));
} catch(NumberFormatException e){
System.out.println(“problem parsing auction days”+e);
return;
}
if(auctiondays<=0 || auctiondays>7) {
auctiondays=7;
}
try {
SellerHome home = (SellerHome) ctx.lookup(“seller”);
Seller si= home.create();
if(si != null) {
int result= si.insertItem(seller, password, description,
auctiondays, startprice, summary);
if(result >0) {
addLine(“Inserted item “+summary, out);
addLine(“Details available
<A HREF=/AuctionServlet?action=details&item=”
+ result + ”>here</A>”, out);
} else {
addLine(“Error inserting item”, out);
return;
}
addLine(““, out);
}
} catch (Exception e) {
addLine(“AuctionServlet Insert Item error”, out);
System.out.println(“AuctionServlet <insert>:”+e);
196 4: DISTRIBUTED COMPUTING
}
out.flush();
}
private void itemDetails(ServletOutputStream out, HttpServletRequest request)
throws IOException{
setTitle(out, “Item Details”);
String item=request.getParameter(“item”);
int itemid=0;
try {
itemid=Integer.parseInt(item);
} catch (NumberFormatException e) {
System.out.println(“problem with item id “+itemid);
return;
}
try {
AuctionItemHome home = (AuctionItemHome) ctx.lookup(“auctionitems”);
AuctionItemPK pk=new AuctionItemPK();
pk.id=itemid;
AuctionItem ai=home.findByPrimaryKey(pk);
displayPageItem(ai, out);
addLine(“<BR><HR><P>Do you want to bid on this item?”, out);
addLine(“<FORM ACTION=\”/AuctionServlet\” METHOD=\”POST\”>”, out);
addLine(“<TR>Enter your user id:<INPUT TYPE=\”TEXT\”
SIZE=20 NAME=\”buyer\”> “, out);
addLine(“and password:<INPUT TYPE=\”PASSWORD\”
SIZE=20 NAME=\”password\”></TR>”, out);
addLine(“<TR>Your bid amount:<INPUT TYPE=\”TEXT\”
SIZE=20 NAME=\”amount\”></TR>”, out);
addLine(“<INPUT TYPE=\”HIDDEN\” NAME=\”action\” VALUE=\”bid\”>”, out);
addLine(“<INPUT TYPE=\”HIDDEN\” NAME=\”item\” VALUE=\””+itemid+”\”>”, out);
addLine(“<INPUT TYPE=\”SUBMIT\” VALUE=\”Place Bid\” NAME=\”Bid\”>
</FORM>”, out);
} catch (Exception e) {
addLine(“AuctionServlet List Item error”, out);
System.out.println(“AuctionServlet <details>:”+e);
}
out.flush();
}
private void itemBid(ServletOutputStream out, HttpServletRequest request)
throws IOException{
setTitle(out, “Item Bid”);
String item=request.getParameter(“item”);
String buyer=request.getParameter(“buyer”);
String password=request.getParameter(“password”);
String bid=request.getParameter(“amount”);
int itemid=0;
double bidamount=0;
try {
itemid=Integer.parseInt(item);
} catch (NumberFormatException e) {
System.out.println(“problem with item id “ +itemid);
return;
}
4: DISTRIBUTED COMPUTING 197
try {
bidamount=Double.valueOf(bid).doubleValue();
} catch (NumberFormatException e) {
return;
}
try {
BidderHome bhome = (BidderHome) ctx.lookup(“bidder”);
Bidder bidbean=bhome.create();
int result=bidbean.placeBid(itemid, buyer, password, bidamount);
switch(result) {
case Auction.OUT_BID:
addLine(“Your bid was not high enough”, out);
break;
case Auction.HIGH_BID:
addLine(“You are the high bidder”, out);
break;
case Auction.AUCTION_OVER:
addLine(“This auction has finished”, out);
break;
case Auction.INVALID_USER:
addLine(“Invalid user or password”, out);
break;
default:
addLine(“Problem submitting bid”, out);
}
} catch (Exception e) {
addLine(“AuctionServlet Bid error”, out);
System.out.println(“AuctionServlet <bid>:”+e);
}
out.flush();
}
private void registerUser(ServletOutputStream out,
HttpServletRequest request) throws IOException{
String user=request.getParameter(“user”);
String password=request.getParameter(“password”);
String creditcard=request.getParameter(“creditcard”);
String emailaddress=request.getParameter(“emailaddress”);
try {
NameComponent[] fullname = new NameComponent[2];
fullname[0] = new NameComponent(“auction”, ““);
fullname[1] = new NameComponent(“RegistrationBean”, ““);
RegistrationHome regRef = RegistrationHomeHelper.narrow(
nctx.resolve(fullname));
RegistrationPK reguser = RegistrationPKHelper.narrow(regRef.create(
user, password, emailaddress, creditcard));
if(reguser != null) {
addLine(“Created user: “+reguser.theuser(),out);
} else {
addLine(“Error creating user id, possibly already exists “, out);
}
} catch(org.omg.CORBA.SystemException e) {
addLine(“AuctionServlet registration error”, out);
System.out.println(“AuctionServlet CORBA <register>:”+e.toString());
198 4: DISTRIBUTED COMPUTING
} catch (Exception e) {
System.out.println(“AuctionServlet <register>:”+e.toString());
}
out.flush();
}
private void auditAccounts(ServletOutputStream out,
HttpServletRequest request) throws IOException {
String text = “Audit of users with low credit.”;
setTitle(out, “Audit Accounts”);
try {
addLine(“<BR>”+text, out);
addLine(“<TABLE BORDER=1 CELLPADDING=1 CELLSPACING=0><TR>
<TH>User</TH><TH>Accounts Balance</TH></TR>”, out);
SellerHome home = (SellerHome) ctx.lookup(“seller”);
Seller si= home.create();
if(si != null) {
ArrayList ar=si.auditAccounts();
for(Iterator i=ar.iterator(); i.hasNext();) {
Registration user=(Registration)(i.next());
addLine(“<TD>”+user.getUser()+”</TD>
<TD>”+user.getBalance()+”</TD></TR>”, out);
}
addLine(“</TABLE>”, out);
}
} catch (Exception e) {
addLine(“AuctionServlet auditAccounts error”,out);
System.out.println(“AuctionServlet <auditAccounts>:”+e);
}
out.flush();
}
private void customSearch(ServletOutputStream out,
HttpServletRequest request) throws IOException{
String text = “Custom Search”;
String searchField=request.getParameter(“searchfield”);
setTitle(out, “Custom Search”);
if(searchField == null ) {
addLine(“Error: SearchField was empty”, out);
out.flush();
return;
}
try {
addLine(“<BR>”+text, out);
SellerHome home = (SellerHome) ctx.lookup(“seller”);
Seller si= home.create();
if(si != null) {
String displayMessage=si.customFind(searchField);
if(displayMessage != null ) {
addLine(displayMessage+”<BR>”, out);
}
}
} catch (Exception e) {
addLine(“AuctionServlet customFind error”,out);
System.out.println(“AuctionServlet <customFind>:”+e);
4: DISTRIBUTED COMPUTING 199
}
out.flush();
}
static private void displayitems(Enumeration e,
ServletOutputStream out) throws Exception{
addLine(“<TABLE BORDER=1 CELLPADDING=1 CELLSPACING=0><TR>
<TH>Item</TH><TH>Summary</TH><TH>Current High bid</TH>
<TH>Number of bids</TH><TH>Closing Date</TH></TR>”, out);
while((e !=null) && (e.hasMoreElements())) {
while(e.hasMoreElements()) {
displayLineItem((AuctionItem) e.nextElement(), out);
}
}
addLine(“</TABLE>”, out);
}
static private void displayLineItem(AuctionItem auctionItem,
ServletOutputStream out)
throws RemoteException, IOException {
StringBuffer line= new StringBuffer();
int bidcount=auctionItem.getBidCount();
int key=(int)auctionItem.getId();
line.append(“<TR><TD><A HREF=/AuctionServlet?action=details&item=”
+ key + ”>” + key + ”</A></TD>”);
line.append(“<TD>”+auctionItem.getSummary() +”</TD>”);
if(bidcount >0) {
line.append(“<TD>“ + NumberFormat.getCurrencyInstance().format(
auctionItem.getHighBid()) +“</TD>”);
} else {
line.append(“<TD>-</TD>”);
}
line.append(“<TD>”+bidcount+”</TD>”);
line.append(“<TD>”+auctionItem.getEndDate() +”</TD></TR>”);
addLine(line.toString(), out);
}
static private void displayPageItem(AuctionItem auctionItem,
ServletOutputStream out)
throws RemoteException, IOException {
int bidcount=auctionItem.getBidCount();
addLine(auctionItem.getSummary(), out);
addLine(“Auction Item Number: “+auctionItem.getPrimaryKey(), out);
if(bidcount >0) {
addLine(“<P>Current price: “+ NumberFormat.getCurrencyInstance().format(
auctionItem.getHighBid()), out);
addLine(“Minimum increment: “+ NumberFormat.getCurrencyInstance().format(
auctionItem.getIncrement()), out);
} else {
addLine(“<P>Current price: “+ NumberFormat.getCurrencyInstance().format(
auctionItem.getStartPrice()), out);
}
addLine(“# of bids: “+bidcount, out);
addLine(“<P>Auction Started: “+auctionItem.getStartDate(), out);
addLine(“Auction Ends: “+auctionItem.getEndDate(), out);
addLine(“<P>Seller: “+auctionItem.getSeller(), out);
200 4: DISTRIBUTED COMPUTING
if(bidcount >0) {
addLine(“High Bidder: “+auctionItem.getHighBidder(), out);
} else {
addLine(“High Bidder: “+”-”, out);
}
addLine(“<HR><P>”, out);
addLine(“Description: “+auctionItem.getDescription(), out);
}
private String readFile (String file) throws IOException {
if(file != null) {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader (new FileReader (file));
String line;
while( (line=reader.readLine()) != null ) {
buffer.append (line+’\n’);
}
reader.close();
return buffer.toString();
} else {
return null;
}
}
private void setTitle(ServletOutputStream out, String title) {
try {
out.println(“<HTML><HEAD><TITLE>”+title+”</TITLE></HEAD>”);
out.println(“<BODY BGCOLOR=\”WHITE\”>”);
} catch(IOException e) {
System.out.println(“Unable to set title”+e);
}
}
private void setFooter(ServletOutputStream out) {
try {
out.println(“<HR><CENTER> <A HREF=\”registration.html\”>Register</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”/AuctionServlet?action=newlist\”>New Items</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”/AuctionServlet?action=close\”>Closing Items</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”/AuctionServlet?action=list\”>All Items</A>”);
out.println(“<STRONG>|</STRONG>”);
out.println(“<A HREF=\”sell.html\”>Sell Items</A>”);
out.println(“</CENTER>”);
} catch (IOException e) {
System.out.println(“Unable to set footer”+e);
}
}
}
Login Servlet
package login;
4: DISTRIBUTED COMPUTING 201
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
} else {
response.sendRedirect (defaultPage);
}
} else if (cmd.equals (“displayDetails”)) {
if(session != null) {
response.setContentType(“text/html”);
ServletOutputStream out = response.getOutputStream();
out.println(“User id is “+session.getUser());
out.flush();
} else {
response.sendRedirect (“/login.html”);
}
} else if (cmd.equals (“logout”)) {
if(session != null ) {
endSession (session);
}
response.sendRedirect (defaultPage);
} else {
response.sendRedirect (defaultPage);
}
} else {
if (session != null) {
// already logged in
if( response.containsHeader (“Expires”) == false ) {
response.setDateHeader (“Expires”, session.getExpires());
}
try {
fileServlet.doGet (request, response);
} catch (Exception e) {
response.sendRedirect (“/login.html”);
}
} else {
// no existing session
if(protectedDir &&
request.getRequestURI().indexOf(restricted)>=0) {
// restricted directory. Dont go in there!
response.sendRedirect (“/login.html”);
} else {
// this file looks ok to serve dispense
try {
fileServlet.doGet (request, response);
} catch (Exception e) {
response.sendRedirect (“/login.html”);
System.out.println(“error”+e);
}
}
}
}
}
protected boolean verifyPassword(String theuser, String password) {
String originalPassword=null;
try {
Connection con=getConnection();
4: DISTRIBUTED COMPUTING 203
}
private void setNoCache (HttpServletRequest request,
HttpServletResponse response) {
if(request.getProtocol().compareTo (“HTTP/1.0”) == 0) {
response.setHeader (“Pragma”, “no-cache”);
} else if (request.getProtocol().compareTo (“HTTP/1.1”) == 0) {
response.setHeader (“Cache-Control”, “no-cache”);
}
response.setDateHeader (“Expires”, 0);
}
}
Session (Servlets)
package login;
import java.util.Random;
import java.net.*;
SessionCache (Servlets)
package login;
import java.util.Hashtable;
import java.util.Enumeration;
}
void remove (Session s) {
sessionCache.remove (s.key());
}
}
5: JNI TECHNOLOGY 207
5: JNI Technology
The Java™ platform is relatively new, which means there could be times when you will need
to integrate programs written in the Java programming language with existing non-Java lan-
guage services, API toolkits, and programs. The Java platform provides the Java Native
Interface (JNI) to help ease this type of integration.
The JNI defines a standard naming and calling convention so the Java virtual machine can
locate and invoke native methods. In fact, JNI is built into the Java virtual machine so the
Java virtual machine can invoke local system calls to perform input and output, graphics,
networking, and threading operations on the host operating system.
This chapter explains how to use JNI in programs written in the Java programming language
to call any libraries on the local machine, call Java methods from inside native code, and
explains how to create and run a Java virtual machine instance. To show how you can put
JNI to use, the examples in this chapter include integrating JNI with the Xbase C++ database
API, and how you can call a mathematical function. Xbase (http://www.start-
ech.keller.tx.us/xbase/xbase.html) has sources you can download.
JNI Example
The ReadFile example program shows how you can use the Java Native Interface (JNI) to
invoke a native method that makes C function calls to map a file into memory.
the native code, and calling the native method. The ReadFile source code below does exactly
that.
However, successfully running the program requires a few additional steps beyond compil-
ing the Java programming language source file. After you compile, but before you run the
example, you have to generate a header file. The native code implements the function defini-
tions contained in the generated header file and implements the business logic as well. The
following sections walk through all the steps.
import java.util.*;
class ReadFile {
//Native method declaration
native byte[] loadFile(String name);
//Load the library
static {
System.loadLibrary("nativelib");
}
Note: You might need to configure your environment so the loadLibrary method can find your
native code library. See Compile the Dynamic or Shared Object Library (page 211) for this
information.
javac ReadFile.java
Next, you need to generate a header file with the native method declaration and implement
the native method to call the C functions for loading and reading a file.
Method Signature
The ReadFile.h header file defines the interface to map the Java method to the native C func-
tion. It uses a method signature to map the arguments and return value of the Java mapped-
file.loadFile method to the loadFile native method in the nativelib library. Here is the
loadFile native method mapping (method signature):
/*
* Class: ReadFile
* Method: loadFile
* Signature: (Ljava/lang/String;)[B
*/
JNIEXPORT jbyteArray JNICALL Java_ReadFile_loadFile
(JNIEnv *, jobject, jstring);
• JNIEnv *: A pointer to the JNI environment. This pointer is a handle to the current
thread in the Java virtual machine, and contains mapping and other housekeeping
information.
• jobject: A reference to the object that called this native code. If the calling method is
static, this parameter would be type jclass instead of jobject.
• jstring: The parameter supplied to the native method. In this example, it is the name of
the file to be read.
GNU C/Linux
gcc -o libnativelib.so -shared -Wl,-soname,libnative.so -I/export/home/jdk1.2/
include -I/export/home/jdk1.2/include/linux nativelib.c -static -lc
SunPro C/Solaris
cc -G -so libnativelib.so -I/export/home/jdk1.2/include -I/export/home/jdk1.2/
include/solaris nativelib.c
Win32/WinNT/Win2000
cl -Ic:/jdk1.2/include -Ic:/jdk1.2/include/win32 -LD nativelib.c -
Felibnative.dll
Unix or Linux:
LD_LIBRARY_PATH=.
export LD_LIBRARY_PATH
Windows NT/2000/95:
set PATH=%path%;.
With the library path properly specified for your platform, invoke the program as you nor-
mally would with the interpreter command:
java ReadFile
Passing Strings
The String object in the Java programming language, which is represented as jstring in Java
Native Interface (JNI), is a 16 bit unicode string. In C a string is by default constructed from
8 bit characters. So, to access a Java String object passed to a C or C++ function or return a
C or C++ string to a Java method, you need to use JNI conversion functions in your native
method implementation.
The GetStringUTFChar function retrieves 8-bit characters from a 16-bit jstring using the
Unicode Transformation Format (UTF). UTF represents Unicode as a string of 8 or 16 bit
characters without losing any information. The third parameter GetStringUTFChar returns
the result JNI_TRUE if it made a local copy of the jstring or JNI_FALSE otherwise.
C Version:
C++ Version:
env->GetStringUTFChars(name, iscopy)
(*env)->NewStringUTF(env, lastfile)
The example below converts the lastfile[80] C character array to a jstring, which is returned
to the calling Java method:
static char lastfile[80];
To let the Java virtual machine know you are finished with the UTF representation, call the
ReleaseStringUTFChars conversion function as shown below. The second argument is the
original jstring value used to construct the UTF representation, and the third argument is the
reference to the local representation of that String.
If your native code can work with Unicode, without needing the intermediate UTF represen-
tation, call the GetStringChars function to retrieve the unicode string, and release the refer-
ence with a call to ReleaseStringChars:
JNIEXPORT jbyteArray JNICALL Java_ReadFile_loadFile
(JNIEnv * env, jobject jobj, jstring name) {
caddr_t m;
jbyteArray jb;
struct stat finfo;
jboolean iscopy;
//API Ref :const jchar *GetStringChars(JNIEnv *env, jstring string, jboolean
*iscopy)
const jchar *mfile = (*env)->GetStringChars(env, name, &iscopy);
//...
//API Ref :void ReleaseStringChars(JNIEnv *env, jstring string, const jchar *chars)
(*env)->ReleaseStringChars(env, name, mfile);
Passing Arrays
In the example presented in the last section, the loadFile native method returns the contents
of a file in a byte array, which is a primitive type in the Java programming language. You can
retrieve and create primitive types in the Java programming language by calling the appro-
priate TypeArray function.
For example, to create a new array of floats, call NewFloatArray, or to create a new array of
bytes, call NewByteArray. This naming scheme extends to retrieving elements from, adding
elements to, and changing elements in the array. To get elements from an array of bytes, call
214 5: JNI TECHNOLOGY
Native Code
Type Functions Used
jboolean NewBooleanArray
GetBooleanArrayElements
GetBooleanArrayRegion/SetBooleanArrayRegion
ReleaseBooleanArrayRegion
jbyte NewByteArray
GetByteArrayElements
GetByteArrayRegion/SetByteArrayRegion
ReleaseByteArrayRegion
jchar NewCharArray
GetCharArrayElements
GetCharArrayRegion/SetCharArrayRegion
ReleaseCharArrayRegion
jdouble NewDoubleArray
GetDoubleArrayElements
GetDoubleArrayRegion/SetDoubleArrayRegion
ReleaseDoubleArrayRegion
jfloat NewFloatArray
GetFloatArrayElements
GetFloatArrayRegion/SetFloatArrayRegion
ReleaseFloatArrayRegion
jint NewIntArray
GetIntArrayElements
GetIntArrayRegion/SetIntArrayRegion
ReleaseIntArrayRegion
jlong NewLongArray
GetLongArrayElements
GetLongArrayRegion/SetLongArrayRegion
ReleaseLongArrayRegion
jobject NewObjectArray
GetObjectArrayElement/SetObjectArrayElement
5: JNI TECHNOLOGY 215
Native Code
Type Functions Used
jshort NewShortArray
GetShortArrayElements
GetShortArrayRegion/SetShortArrayRegion
ReleaseShortArrayRegion
In the loadFile native method from the example in the previous section, the entire array is
updated by specifying a region that is the size of the file being read in:
jbyteArray jb;
//API Ref :jbyteArray NewByteArray(JNIEnv *env, jsize length)
jb=(*env)->NewByteArray(env, finfo.st_size);
//API Ref :SetByteArrayRegion(JNIEnv *env, jbyteArray array, jsize startelement,
jsize length, jbyte *buffer)
(*env)->SetByteArrayRegion(env, jb, 0, finfo.st_size, (jbyte *)m);
close(fd);
The array is returned to the calling Java programming language method, which in turn, gar-
bage collects the reference to the array when it is no longer used. The array can be explicitly
freed with the following call.
//API Ref :void ReleaseByteArrayElements(JNIEnv *env, jbyteArray array, jbyte
*elems, jint mode)
(*env)-> ReleaseByteArrayElements(env, jb, (jbyte *)m, 0);
The last argument to the ReleaseByteArrayElements function above can have the following
values:
• 0: Updates to the array from within the C code are reflected in the Java programming
language copy.
• JNI_COMMIT: The Java programming language copy is updated, but the local jbyte-
Array is not freed.
• JNI_ABORT: Changes are not copied back, but the jbyteArray is freed. The value is
used only if the array is obtained with a get mode of JNI_TRUE meaning the array is
a copy.
See Memory Issues (page 227) for more information on memory management.
Pinning Array
When retrieving an array, you can specify if this is a copy (JNI_TRUE) or a reference to the
array residing in your Java program (JNI_FALSE). If you use a reference to the array, you
will want the array to stay where it is in the Java heap and not get moved by the garbage col-
216 5: JNI TECHNOLOGY
lector when it compacts heap memory. To prevent the array references from being moved,
the Java virtual machine pins the array into memory. Pinning the array ensures that when the
array is released, the correct elements are updated in the Java virtual machine.
In the loadfile native method example from the previous section, the array is not explicitly
released. One way to ensure the array is garbage collected when it is no longer needed is to
call a Java method, pass the byte array instead, and free the local array copy. This technique
is shown in the section on MultiDimensional Arrays (page 217).
Object Arrays
You can store any Java object in an array with the NewObjectArray and SetObjectArrayEle-
ment function calls. The main difference between an object array and an array of primitive
types is that when constructing a jobjectArray, the Java class is used as a parameter.
This next C++ example shows how to call NewObjectArray to create an array of String
objects. The size of the array is set to five, the class definition is returned from a call to Find-
Class, and the elements of the array are initialized with an empty string. The elements of the
array are updated by calling SetObjectArrayElement with the position and value to put in the
array.
/* ReturnArray.C */
#include <jni.h>
#include "ArrayHandler.h"
System.loadLibrary("nativelib");
}
public static void main(String args[]) {
String ar[];
ArrayHandler ah= new ArrayHandler();
ar = ah.returnArray();
for(int i=0; i<5; i++) {
System.out.println("array element"+i+ "=" + ar[i]);
}
}
}
MultiDimensional Arrays
You might need to call existing numerical and mathematical libraries such as the linear alge-
bra library CLAPACK/LAPACK or other matrix crunching programs from your Java pro-
gram using native methods. Many of these libraries and programs use two-dimensional and
higher order arrays.
In the Java programming language, any array that has more than one dimension is treated as
an array of arrays. For example, a two-dimensional integer array is handled as an array of
integer arrays. The array is read horizontally, or in what is also termed as row order.
Other languages such as FORTRAN use column ordering so extra care is needed if your pro-
gram hands a Java array to a FORTRAN function. Also, the array elements in an application
written in the Java programming language are not guaranteed to be contiguous in memory.
Some numerical libraries use the knowledge that the array elements are stored next to each
other in memory to perform speed optimizations, so you might need to make an additional
local copy of the array to pass to those functions.
The next example passes a two-dimensional array to a native method which then extracts the
elements, performs a calculation, and calls a Java method to return the results. The array is
passed as an object array that contains an array of jints. The individual elements are
extracted by first retrieving a jintArray instance from the object array by calling GetObjec-
tArrayElement, and then extracting the elements from the jintArray row.
The example uses a fixed-size matrix. If you do not know the size of the array being used,
the GetArrayLength(array) function returns the size of the outermost array. You will need to
call the GetArrayLength(array) function on each dimension of the array to discover the total
size of the array. The new array sent back to the program written in the Java language is built
in reverse. First, a jintArray instance is created and that instance is set in the object array by
calling SetObjectArrayElement.
218 5: JNI TECHNOLOGY
#include <jni.h>
#include <iostream.h>
#include "ArrayManipulation.h"
JNIEXPORT void
JNICALL Java_ArrayManipulation_manipulateArray
(JNIEnv *env, jobject jobj, jobjectArray elements, jobject lock){
jobjectArray ret;
int i,j;
jint arraysize;
int asize;
jclass cls;
jmethodID mid;
jfieldID fid;
5: JNI TECHNOLOGY 219
long localArrayCopy[3][3];
long localMatrix[3]={4,4,4};
for (i=0;i<3;i++) {
for (j=0; j<3 ; j++) {
localArrayCopy[i][j]=
localArrayCopy[i][j]*localMatrix[i];
}
}
// Create array to send back
//API Ref :jintArray NewIntArray(JNIEnv *env, jsize length)
jintArray row= (jintArray)env->NewIntArray(3);
//API Ref :jclass GetObjectClass(JNIEnv *env, jobject obj)
ret=(jobjectArray)env->NewObjectArray(3, env->GetObjectClass(row), 0);
for(i=0;i<3;i++) {
row= (jintArray)env->NewIntArray(3);
//API Ref :SetIntArrayRegion(JNIEnv *env, jintArray array, jsize startelement, jsize
length, jint *buffer)
env->SetIntArrayRegion((jintArray)row,(jsize)0,3,(jint *)localArrayCopy[i]);
env->SetObjectArrayElement(ret,i,row);
}
cls=env->GetObjectClass(jobj);
//API Ref :jmethodID GetMethodId(JNIEnv *env, jclass class, const char *methodname,
const char *methodsig)
mid=env->GetMethodID(cls, "sendArrayResults",
"([[I)V");
if (mid == 0) {
cout <<"Can't find method sendArrayResults";
return;
}
//API Ref :void ExceptionClear(JNIEnv *env)
env->ExceptionClear();
//API Ref :jint MonitorEnter(JNIEnv *env, jobject object)
env->MonitorEnter(lock);
//API Ref :CallVoidMethod(JNIEnv *env, jobject object, jmethodId methodid, object
arg1)
env->CallVoidMethod(jobj, mid, ret);
//API Ref :jint MonitorExit(JNIEnv *env, jobject object)
env->MonitorExit(lock);
220 5: JNI TECHNOLOGY
Language issues
So far, the native method examples have covered calling standalone C and C++ functions
that either return a result or modify parameters passed into the function. However, C++ like
the Java programming language, uses instances of classes. If you create a class in one native
method, the reference to this class does not have an equivalent class in the Java programming
language. This makes it difficult to call functions on the C++ class that was first created.
One way to handle this situation is to keep a record of the C++ class reference and pass that
back to a proxy or to the calling program. To ensure the C++ class persists across native
method calls, use the C++ new operator to create a reference to the C++ object on the heap.
The following code provides a mapping between the Xbase database and Java code. The
Xbase database has a C++ API and uses an initialization class to perform subsequent data-
base operations. When the class object is created, a pointer to this object is returned as a Java
int value. You can use a long or larger value for machines with greater than 32 bits.
5: JNI TECHNOLOGY 221
static {
//API Ref :static void loadLibrary(String libraryname)
System.loadLibrary("dbmaplib");
}
public static void main(String args[]) {
String prefix=null;
CallDB db=new CallDB();
int res=db.initdb();
if(args.length>=1) {
prefix=args[0];
}
System.out.println(db.opendb("MYFILE.DBF", res));
System.out.println(db.GetFieldNo("LASTNAME", res));
System.out.println(db.GetFieldNo("FIRSTNAME", res));
}
}
The return result from the call to the initdb native method, the int value, is passed to subse-
quent native method calls. The native code included in the dbmaplib.cc library dereferences
the Java object passed in as a parameter and retrieves the object pointer. The line xbDbf*
Myfile=(xbDbf*)ptr; casts the int pointer value to be a pointer of Xbase type xbDbf.
#include <jni.h>
#include <xbase/xbase.h>
#include "CallDB.h"
Calling Methods
The section on arrays highlighted some reasons for calling Java programming language
methods from within native code; for example, when you need to free the result you intend
to return. Other uses for calling Java native methods from within your native code are if you
need to return more than one result or you just simply want to modify Java programming
language values from within native code. Calling a Java programming language method
from within native code involves the following three steps:
1. Retrieve a class reference
2. Retrieve a method identifier
3. Call the Methods
or
Use the jclass argument:
JNIEXPORT void JNICALL Java_ArrayHandler_returnArray(JNIEnv *env, jclass jcls){
jclass cls=jcls;
}
javap -s Class
The method signature used is displayed as a comment after each method declaration as
shown here:
bash# javap -s ArrayHandler
Compiled from ArrayHandler.java
public class ArrayHandler extends java.lang.Object {
java.lang.String arrayResults[];
/* [Ljava/lang/String; */
static {};
/* ()V */
public ArrayHandler();
/* ()V */
public void displayArray();
/* ()V */
public static void main(java.lang.String[]);
/* ([Ljava/lang/String;)V */
public native void returnArray();
/* ()V */
public void sendArrayResults(java.lang.String[]);
/* ([Ljava/lang/String;)V */
}
Use the GetMethodID function to call instance methods in an object instance, or use the Get-
StaticMethodID function to call static method. Their argument lists are the same.
System.loadLibrary("nativelib");
}
public void sendArrayResults(String results[]) {
arraySize=results.length;
arrayResults=new String[arraySize];
System.arraycopy(results,0,arrayResults,0,arraySize);
}
public void displayArray() {
for (int i=0; i<arraySize; i++) {
System.out.println("array element "+i+ "= " + arrayResults[i]);
}
}
public static void main(String args[]) {
String ar[];
ArrayHandler ah= new ArrayHandler();
ah.returnArray();
ah.displayArray();
}
}
env->ExceptionDescribe();
env->ExceptionClear();
}
return;
}
If you want to specify a super class method to, for example, call the parent constructor, you
can do so by calling the CallNonvirtual<type>Method functions. One important point when
calling Java methods or fields from within native code is you need to catch any raised excep-
tions. The ExceptionClear function clears any pending exceptions while the ExceptionOc-
cured function checks to see if an exception has been raised in the current JNI session.
Accessing Fields
Accessing Java fields from within native code is similar to calling Java methods. However,
the set or field is retrieved with a field ID, instead of a method ID.
The first thing you need to do is retrieve a field ID. You can use the GetFieldID function, but
specify the field name and signature in place of the method name and signature. Once you
have the field ID, call a Get<type>Field function to set the field value. The <type> is the
same as the native type being returned except the j is dropped and the first letter is capital-
ized. For example, the <type> value is Int for native type jint, and Byte for native type jbyte.
The Get<type>Field function result is returned as the native type. For example, to retrieve
the arraySize field in the ArrayHandler class, call GetIntField as shown in the following
example.
The field can be set by calling the env->SetIntField(jobj, fid, arraysize) functions. Static
fields can be set by calling SetStaticIntField(jclass, fid, arraysize) and retrieved by calling
GetStaticIntField(jclass, fid).
#include <jni.h>
#include <iostream.h>
#include "ArrayHandler.h"
jmethodID mid;
jfieldID fid;
char *message[5]= {"first", "second", "third", "fourth", "fifth"};
ret=(jobjectArray)env->NewObjectArray(5,
env->FindClass("java/lang/String"),
env->NewStringUTF(""));
for(i=0;i<5;i++) {
env->SetObjectArrayElement(ret,i,env->NewStringUTF(message[i]));
}
cls=env->GetObjectClass(jobj);
mid=env->GetMethodID(cls, "sendArrayResults", "([Ljava/lang/String;)V");
if (mid == 0) {
cout <<“Can't find method sendArrayResults";
return;
}
env->ExceptionClear();
env->CallVoidMethod(jobj, mid, ret);
if(env->ExceptionOccurred()) {
cout << "error occured copying array back" << endl;
env->ExceptionDescribe();
env->ExceptionClear();
}
fid=env->GetFieldID(cls, "arraySize", "I");
if (fid == 0) {
cout <<“Can't find field arraySize";
return;
}
arraysize=env->GetIntField(jobj, fid);
if(!env->ExceptionOccurred()) {
cout<< "size=" << arraysize << endl;
} else {
env->ExceptionClear();
}
return;
}
The following example uses a Boolean object to restrict access to the CallVoidMethod func-
tion.
env->ExceptionClear();
env->MonitorEnter(lock);
env->CallVoidMethod(jobj, mid, ret);
env->MonitorExit(lock);
if(env->ExceptionOccurred()) {
cout << "error occured copying array back" << endl;
env->ExceptionDescribe();
env->ExceptionClear();
}
You may find that in cases where you want access to a local system resource like an MFC
window handle or message queue, it is better to use one Java.lang.Thread and access the
local threaded native event queue or messaging system from within the native code.
Memory Issues
By default, JNI uses local references when creating objects inside a native method. This
means when the method returns, the references are eligible to be garbage collected. If you
want an object to persist across native method calls, use a global reference instead. A global
reference is created from a local reference by calling NewGlobalReference on the local ref-
erence.
You can explicitly mark a reference for garbage collection by calling DeleteGlobalRef on
the reference. You can also create a weak style Global reference that is accessible outside the
method, but can be garbage collected. To create one of these references, call NewWeakGlo-
balRef and DeleteWeakGlobalRef to mark the reference for garbage collection.
You can even explicitly mark a local reference for garbage collection by calling the
env->DeleteLocalRef(localobject) method. This is useful if you are using a large amount of
temporary data.
static jobject stringarray=0;
ret=(jobjectArray)env->NewObjectArray(5,
env->FindClass("java/lang/String"),
env->NewStringUTF(""));
//Make the array available globally
//API Ref :jobject NewGlobalRef(JNIEnv *env, jobject object)
stringarray=env->NewGlobalRef(ret);
//Process array
// ...
//clear local reference when finished..
//API Ref :void DeleteLocalRef(JNIEnv *env, jobject localref)
env->DeleteLocalRef(ret);
}
Invocation
The section on calling methods showed you how to call a method or field in a Java program
using the JNI interface and a class loaded using the FindClass function. With a little more
code, you can create a standalone program that invokes a Java virtual machine and includes
its own JNI interface pointer that can be used to create instances of Java classes. In the Java
2 release, the runtime program named java is a small JNI application that does exactly that.
You can create a Java virtual machine with a call to JNI_CreateJavaVM, and shut the created
Java virtual machine down with a call to JNI_DestroyJavaVM. A Java virtual machine might
also need some additional environment properties. These properties can be passed to the
JNI_CreateJavaVM function in a JavaVMInitArgs structure.
The JavaVMInitArgs structure contains a pointer to a JavaVMOption value used to store
environment information such as the classpath and Java virtual machine version, or system
properties that would normally be passed on the command line to the program.
When the JNI_CreateJavaVM function returns, you can call methods and create instances of
classes using the FindClass and NewObject functions the same way you would for embed-
ded native code.
Note: The Java virtual machine invocation was only used for native thread Java virtual
machines. Some older Java virtual machines have a green threads option that is stable for invo-
cation use. On a Unix platform, you may also need to explicitly link with -lthread or -lpthread.
This next program invokes a Java virtual machine, loads the ArrayHandler class, and
retrieves the arraySize field which should contain the value minus one. The Java virtual
machine options include the current path in the classpath and turning the Just-In-Time (JIT)
compiler off with the option -Djava.compiler=NONE.
5: JNI TECHNOLOGY 229
#include <jni.h>
options[0].optionString = ".";
options[1].optionString = "-Djava.compiler=NONE";
vm_args.version = JNI_VERSION_1_2;
vm_args.options = options;
vm_args.nOptions = 2;
vm_args.ignoreUnrecognized = JNI_FALSE;
//API Ref :jint JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args)
result = JNI_CreateJavaVM(&jvm,(void **)&env, &vm_args);
if(result == JNI_ERR ) {
printf("Error invoking the JVM");
exit (-1);
}
cls = (*env)->FindClass(env,"ArrayHandler");
if( cls == NULL ) {
printf("can't find class ArrayHandler\n");
exit (-1);
}
(*env)->ExceptionClear(env);
mid=(*env)->GetMethodID(env, cls, "<init>", "()V");
jobj=(*env)->NewObject(env, cls, mid);
fid=(*env)->GetFieldID(env, cls, "arraySize", "I");
asize=(*env)->GetIntField(env, jobj, fid);
printf("size of array is %d",asize);
(*jvm)->DestroyJavaVM(jvm);
}
Attaching Threads
After the Java virtual machine is invoked, there is one local thread running the Java virtual
machine. You can create more threads in the local operating system and attach the Java vir-
tual machine to those new threads. You might want to do this if your native application is
multithreaded.
Attach the local thread to the Java virtual machine with a call to AttachCurrentThread. You
need to supply pointers to the Java virtual machine instance and JNI environment. In the Java
2 platform, you can also specify in the third parameter the thread name and/or group you
230 5: JNI TECHNOLOGY
want this new thread to live under. It is important to detach any thread that has been previ-
ously attached; otherwise, the program will not exit when you call DestroyJavaVM.
#include <jni.h>
#include <pthread.h>
JavaVM *jvm;
args.version= JNI_VERSION_1_2;
args.name="user";
args.group=NULL;
result=(*jvm)->AttachCurrentThread(jvm, (void **)&env, &args);
cls = (*env)->FindClass(env,"ArrayHandler");
if( cls == NULL ) {
printf("can't find class ArrayHandler\n");
exit (-1);
}
(*env)->ExceptionClear(env);
mid=(*env)->GetMethodID(env, cls, "<init>", "()V");
jobj=(*env)->NewObject(env, cls, mid);
fid=(*env)->GetFieldID(env, cls, "arraySize", "I");
asize=(*env)->GetIntField(env, jobj, fid);
printf("size of array is %d\n",asize);
(*jvm)->DetachCurrentThread(jvm);
}
void main(int argc, char *argv[], char **envp) {
JavaVMOption *options;
JavaVMInitArgs vm_args;
JNIEnv *env;
jint result;
pthread_t tid;
int thr_id;
int i;
options = (void *)malloc(3 * sizeof(JavaVMOption));
options[0].optionString = "-Djava.class.path=.";
options[1].optionString = "-Djava.compiler=NONE";
vm_args.version = JNI_VERSION_1_2;
vm_args.options = options;
vm_args.nOptions = 2;
vm_args.ignoreUnrecognized = JNI_FALSE;
result = JNI_CreateJavaVM(&jvm,(void **)&env, &vm_args);
if(result == JNI_ERR ) {
printf("Error invoking the JVM");
5: JNI TECHNOLOGY 231
exit (-1);
}
thr_id=pthread_create(&tid, NULL, native_thread, NULL);
// If you don't have join, sleep instead
// sleep(1000);
pthread_join(tid, NULL);
(*jvm)->DestroyJavaVM(jvm);
exit(0);
}
232 5: JNI TECHNOLOGY
6: PROJECT SWING: BUILDING A USER INTERFACE 233
6: Project Swing:
Building a User Interface
The Java™ Foundation Classes (JFC) Project Swing and Enterprise JavaBeans™ architec-
tures share one key design element: the separation of data from the display or manipulation
of that data. In Enterprise JavaBeans applications, the entity bean provides a view of the
data. The underlying data storage mechanism can be swapped out and replaced without
changing the entity bean view or recompiling any code that uses the view.
Project Swing separates the view and control of a visual component from its contents, or
data model. However, although Project Swing does have the components that make up a
Model-View-Controller (MVC) architecture, it is more accurately described as a model-del-
egate architecture. This is because the controller part of the Project Swing interface, often
the mouse and keyboard events the component responds to, is combined with the physical
view in one User Interface delegate (UI delegate) object.
Each component, for example a JButton or a JScrollBar, has a separate UI delegate class that
inherits from the ComponentUI class and is under the control of a separate UI manager.
While each component has a basic UI delegate, it is no longer tied to the underlying data so
a new set of delegates -- a set of metal-styled components, for example -- can be swapped in
while the application is still running. The ability to change the look and behavior reflects the
pluggable look and feel (PLAF) feature available in Project Swing.
This chapter describes Project Swing user interface components in terms of the AuctionCli-
ent example application.
Lightweight Components
All components in Project Swing, except JApplet, JDialog, JFrame and JWindow are light-
weight components. Lightweight components, unlike their Abstract Window Toolkit (AWT)
counterparts, do not depend on the local windowing toolkit.
For example, a heavyweight java.awt.Button running on the Java platform for the Unix plat-
form maps to a real Motif button. In this relationship, the Motif button is called the peer to
the java.awt.Button. If you create two java.awt.Buttons in an application, two peers and
hence two Motif Buttons are also created. The Java platform communicates with the Motif
Buttons using the Java Native Interface (JNI). For each and every component added to the
application, there is additional overhead tied to the local windowing system, which is why
these components are called heavyweight.
Lightweight components are termed peerless components and emulate the local window sys-
tem components. A lightweight button is represented as a rectangle with a label inside that
accepts mouse events. Adding more lightweight buttons means drawing more rectangles.
A lightweight component needs to be drawn on something, and an application written in the
Java programming language needs to interact with the local window manager so the main
application window can be closed or minimized. This is why the top-level parent compo-
6: PROJECT SWING: BUILDING A USER INTERFACE 235
nents mentioned above (JFrame, JApplet, and others) are implemented as heavyweight com-
ponents -- they need to be mapped to a component in the local window toolkit.
A JButton is a very simple shape to draw. For more complex components like JList or
JTable, the elements or cells of the list or table are drawn by a CellRenderer object. A Cell-
Renderer object provides flexibility because it makes it possible for any type of object to be
displayed in any row or column.
For example, a JTable can use a different CellRenderer for each column. This code segment
sets the second column, which is referenced as index 1, to use a CustomRenderer object to
create the cells for that column.
JTable scrollTable=new JTable(rm);
TableColumnModel scrollColumnModel = scrollTable.getColumnModel();
CustomRenderer custom = new CustomRenderer();
//API Ref :TableColumn getColumn(int index)
scrollColumnModel.getColumn(1).setCellRenderer(custom);
Ordering Components
Each Project Swing applet or application needs at least one heavyweight container compo-
nent (a JFrame, JWindow, JApplet, or JDialog). Each of these containers with JFrame's light-
weight multiple document interface (MDI) counterpart, JInternalFrame, contains a
component called a root pane. The JRootPane manages the additional layers used in the con-
tainer such as the JLayeredPane, JContentPane, GlassPane and the optional JMenuBar. It
also lets all emulated (lightweight) components interact with the AWT event queue to send
and receive events. Interacting with the event queue gives emulated components indirect
interaction with the local window manager.
JLayeredPane
The JLayeredPane sits on top of the JRootPane, and as its name implies, controls the layers
of the components contained within the boundary of the heavyweight container. The compo-
nents are not added to the JLayeredPane, but to the JContentPane instead. The JLayeredPane
determines the Z-ordering of the components in the JRootPane. The Z-order can be thought
of as the order of overlay among the various components. If you drag-and-drop a component
or request a dialog to pop up, you want that component to appear in front of the others in the
application window. The JLayeredPane lets you layer components.
The JLayeredPane divides the depth of the container into different bands that can be used to
assign a component to a type-appropriate level. The DRAG_LAYER band, value 400,
appears above all other defined component layers. The lowermost level of JLayeredpane, the
236 6: PROJECT SWING: BUILDING A USER INTERFACE
DEFAULT_FRAME_LAYER band, has value -3000 and is the level of the heavyweight con-
tainers, including the MenuBar. The bands are as follows:
Within these general depth bands, components can be further arranged with another number-
ing system to order the components in a particular band, but this system reverses the num-
bering priority.
For example, in a specific band such as DEFAULT_LAYER, components with a value of 0
appear in front of others in that band; whereas, components with a higher number or -1
appear behind them. The highest number in this scheme is the number of components minus
1, so one way to visualize it is shown in Figure 20, which shows a vector of components that
steps through painting the components with a higher number first finishing with the one at
position 0.
6: PROJECT SWING: BUILDING A USER INTERFACE 237
-3000
0
-1
2 0
3 0
etc. -1
2 400
3 0
etc. -1
2
3
etc.
For example, the following code adds a JButton to the default layer and specifies that it
appear in front of the other components in that same layer:
JButton enterButton = new JButton("Enter");
layeredPane.add(enterButton, LayeredPane.Default_Layer, 0);
You can achieve the same effect by calling the LayeredPane.moveToFront method within a
layer or using the LayeredPane.setLayer method to move to a different layer.
JContentPane
The JContentPane manages adding components to heavyweight containers. So, you have to
call the getContentPane method to add a component to the ContentPane of the RootPane. By
default, a ContentPane is initialized with a BorderLayout layout manager. There are two
ways to change the layout manager. You can call the setLayout method like this:
getContentPane()).setLayout(new BoxLayout())
Or you can replace the default ContentPane with your own ContentPane, such as a JPanel,
like this:
JPanel pane= new JPanel();
pane.setLayout(new BoxLayout());
setContentPane(pane);
238 6: PROJECT SWING: BUILDING A USER INTERFACE
GlassPane
The GlassPane is usually completely transparent and just acts as a sheet of glass in front of
the components. You can implement your own GlassPane by using a component like JPanel
and installing it as the GlassPane by calling the setGlassPane method. The RootPane is con-
figured with a GlassPane that can be retrieved by calling getGlassPane.
One way to use a GlassPane is to implement a component that invisibly handles all mouse
and keyboard events, effectively blocking user input until an event completes. The Glass-
Pane can block the events, but currently the cursor will not return to its default state if you
have set the cursor to be a busy cursor in the GlassPane. An additional mouse event is
required for the refresh.
MyGlassPane glassPane = new MyGlassPane();
setGlassPane(glassPane);
glassPane.setVisible(true); //before worker thread
..
glassPane.setVisible(false); //after worker thread
public MyGlassPane() {
addKeyListener(new KeyAdapter() { });
addMouseListener(new MouseAdapter() { });
super.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}
Data Models
Numerous model layers are combined to form the tables of the AuctionClient GUI. At a
foundational level, the TableModel interface and its two implementations AbstractTableM-
odel and DefaultTableModel provide the most basic means for storage, retrieval and modifi-
cation of the underlying data.
The TableModel defines and categorizes the data by its class. It also determines if the data
can be edited and how the data is grouped into columns and rows. It is important to note,
however, that while the TableModel interface is used most often in the construction of a
JTable, it is not fundamentally tied to their display. Implementations could just as easily
form the basis of a spreadsheet component, or even a non-GUI class that calls for the organi-
zation of data in tabular format.
The ResultsModel class is at the heart of the AuctionClient tables. It defines a dynamic data
set, dictates whether class users can edit the data through its ResultsModel.isCellEditable
method, and provides the update method to keep the data current. The model underlies the
scrolling and fixed tables, and lets modifications be reflected in each view.
6: PROJECT SWING: BUILDING A USER INTERFACE 239
At a higher level and representing an intermediate layer between data and its graphical repre-
sentation, is the TableColumnModel. At this level the data is grouped by column in anticipa-
tion of its ultimate display in the table. The visibility and size of these columns, their
headers, and the component types of their cell renderers and editors are all managed by the
TableColumnModel class.
For example, freezing the left-most columns in the AuctionClient GUI is possible because
column data is easily exchanged among multiple TableColumnModel and JTable objects.
This translates to the fixedTable and scrollTable objects of the AuctionClient program.
Higher still lie the various renderers, editors, and header components whose combination
define the look and organization of the JTable component. This level is where the fundamen-
tal layout and display decisions of the JTable are made.
The creation of the inner classes CustomRenderer and CustomButtonRenderer within the
AuctionClient application allows users of those classes to redefine the components upon
which the appearance of table cells are based. Likewise, the CustomButtonEditor class takes
the place of the table's default editor. In true object-oriented style, the default editors and
renderers are easily replaced, affecting neither the data they represent nor the function of the
component in which they reside.
Finally, the various component user interfaces are responsible for the ultimate appearance of
the JTable. It is here the look-and-feel-specific representation of the AuctionClient tables
and their data are rendered in final form to the user. The end result is that adding a Project
Swing front-end to existing services requires little additional code. In fact, coding the model
is one of the easier tasks in building a Project Swing application.
Table Model
The JTable class has an associated DefaultTableModel class that internally uses a Vector of
vectors to store data. The data for each row is stored in a single Vector object while another
Vector object stores each of those rows as its constituent elements. The DefaultTableModel
object can be initialized with data in several different ways. This code shows the DefaultTa-
bleModel created with a two-dimensional array and a second array representing column
headings. The DefaultTableModel in turn converts the Object arrays into the appropriate
Vector objects:
Object[][] data = new Object[][]{{"row 1 col1", "row 1 col2" },
{"row 2 col 1", "row 2 col 2"}};
Object[] headers = new Object[] {"first header","second header"};
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
//API Ref :void setAutoResizeMode(int mode)
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
240 6: PROJECT SWING: BUILDING A USER INTERFACE
Creating a custom table model is nearly as easy as using DefaultTableModel, and requires
little additional coding. You can implement a table model by implementing a method to
return the number of entries in the model, and a method to retrieve an element at a specific
position in that model. For example, the JTable model can be implemented from
javax.swing.table.AbstractTableModel by implementing the methods getColumnCount,
getRowCount and getValueAt as shown here:
final Object[][] data = new Object[][]{ {"row 1 col1","row 1 col2" },
{"row 2 col 1","row 2 col 2"} };
final Object[] headers = new Object[] {"first header","second header"};
TableModel model = new AbstractTableModel(){
public int getColumnCount() {
return data[0].length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return (String)headers[col];
}
public Object getValueAt(int row,int col) {
return data[row][col];
}
};
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
This table is read-only and its data values are already known. In fact, the data is even
declared final so it can be retrieved by the inner TableModel class. This is not normally the
situation when working with live data.
You can create an editable table by adding the isCellEditable verification method, which is
used by the default cell editor and the AbstractTableModel class for setting a value at a posi-
tion. Up until this change, the AbstractTableModel has been handling the repainting and
resizing of the table by firing different table changed events. Because the AbtractTableModel
does not know that something has occurred to the table data, you need to inform it by calling
the fireTableCellUpdated method. The following lines are added to the AbstractTableModel
inner class to allow editing of the data:
public void setValueAt (Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated (row, col);
}
//API Ref :boolean isCellEditable(int row, int column)
public boolean isCellEditable(int row, int col) {
return true;
}
6: PROJECT SWING: BUILDING A USER INTERFACE 241
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;
import java.text.NumberFormat;
import java.util.*;
import java.awt.*;
The table is created from the ResultsModel model. Then, the first table column is removed
from that table and added to a new table. Because there are now two tables, the only way the
selections can be kept in sync is to use a ListSelectionModel object to set the selection on the
table row in the other tables that were not selected by calling the setRowSelectionInterval
method. The full example can be found in the AuctionClient (page 270) source file:
private void listAllItems() throws IOException{
ResultsModel rm=new ResultsModel();
try {
BidderHome bhome=(BidderHome)ctx.lookup("bidder");
Bidder bid=bhome.create();
Enumeration enum=(Enumeration)bid.getItemList();
if (enum != null) {
rm.update(enum);
}
} catch (Exception e) {
System.out.println("AuctionServlet <list>:"+e);
}
// Create a new table using the ResultsModel object as the table model
scrollTable=new JTable(rm);
// Force the End Date and Description columns to have
// a set width
6: PROJECT SWING: BUILDING A USER INTERFACE 243
// Get the first column, remove it from the scroll column, and
// add it to the fixed table
TableColumn col = scrollColumnModel.getColumn(0);
scrollColumnModel.removeColumn(col);
fixedColumnModel.addColumn(col);
// Keep the heights of the fixed and scroll tables the same
fixedTable.setRowHeight(scrollTable.getRowHeight());
scrollColumnModel.getColumn(3).setCellEditor(customEdit);
// Create a panel for the top left of the display that contains
// the headers for the column that does not move
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
adjustColumnWidth(fixedColumnModel.getColumn(0), 100);
JTableHeader fixedHeader=fixedTable.getTableHeader();
fixedHeader.setAlignmentY(Component.TOP_ALIGNMENT);
topPanel.add(fixedHeader);
//API Ref :Component createRigidArea(Dimension d)
topPanel.add(Box.createRigidArea(new Dimension(2, 0)));
topPanel.setPreferredSize(new Dimension(400, 40));
headers.setViewPosition(p);
headers.repaint(headers.getViewRect());
innerPort.setViewPosition(p);
innerPort.repaint(innerPort.getViewRect());
}
});
c.setPreferredWidth(size);
c.setMaxWidth(size);
c.setMinWidth(size);
}
JList Model
The JList component displays a vertical list of data elements and uses a ListModel to hold
and manipulate the data. It also uses a ListSelectionModel object to enable selection and
subsequent retrieval of elements in the list.
Default implementations of the AbstractListModel and AbstractListSelectionModel classes
are provided in the Project Swing API in the form of the DefaultListModel and DefaultList-
SelectionModel classes. If you use these two default models and the default cell renderer,
you get a list that displays model elements by calling the toString method on each object.
The list uses the MULTIPLE_INTERVAL_SELECTION list selection model to select each
element from the list.
Three selection modes are available to DefaultListSelectionModel: SINGLE_SELECTION,
where only one item is selected at a time; SINGLE_INTERVAL_SELECTION in which a
range of sequential items can be selected; and MULTIPLE_INTERVAL_SELECTION,
which allows any or all elements to be selected. The selection mode can be changed by call-
ing the setSelectionMode method in the JList class.
public SimpleList() {
JList list;
DefaultListModel deflist;
JTree Model
The JTree class models and displays a vertical list of elements or nodes arranged in a tree-
based hierarchy as shown in Figure 21.
A JTree object has one root node and one or more child nodes, which can contain further
child nodes. Each parent node can be expanded to show all its children similar to directory
trees familiar to Windows users.
Like the JList and JTable components, the JTree consists of more than one model. The selec-
tion model is similar to the one detailed for the JList model. The selection modes have the
following slightly different names: SINGLE_TREE_SELECTION,
DISCONTIGUOUS_TREE_SELECTION, and CONTIGUOUS_TREE_SELECTION.
While DefaultTreeModel maintains the data in the tree and is responsible for adding and
removing nodes, it is the DefaultTreeMutableTreeNode class that defines the methods used
for node traversal. The DefaultTreeModel is often used to implement custom models
248 6: PROJECT SWING: BUILDING A USER INTERFACE
because there is no AbstractTreeModel in the JTree package. However, if you use custom
objects, you must implement TreeModel. This code example creates a JTree using the
DefaultTreeModel so the adminstrator can search and browse the auction numbers and
details for reporting.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
// Arrange the tree so that from the top level All Auctions
// closed and open auctions are children from that top level
nodes[0].add(nodes[1]);
nodes[0].add(nodes[2]);
The toString method is used to retrieve the value for the Integer objects in the tree. And
although the DefaultTreeModel is used to maintain the data in the tree and to add or remove
nodes, the DefaultMutableTreeNode class defines the methods used to traverse through the
nodes in the tree.
A primitive search of the nodes in a JTree is accomplished with the depthFirstEnumeration
method, which is the same as the postorderEnumeration method and works its way from the
end points of the tree first. You can also call the preorderEnumeration method, the reverse of
the postorderEnumeration method, which starts from the root and descends each tree in turn.
Or you can call the breadthFirstEnumeration method, which starts from the root and visits
all the child nodes in one level before visiting the child nodes at a lower depth.
The following code expands the parent node if it contains a child node that matches the
search field entered. It uses a call to Enumeration e = nodes[0].depthFirstEnumeration(); to
return a list of all the nodes in the tree. Once it has found a match, it builds the TreePath from
the root node to the node that matched the search to pass to the makeVisible method in the
JTree class that ensures the node is expanded in the tree.
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public SimpleSearchTree() {
String[] treelabels = { "All Auctions", "Closed Auction", "Open Auctions"};
Integer[] closedItems = { new Integer(500144), new Integer(500146),
new Integer(500147) };
Integer[] openItems ={ new Integer(500148), new Integer(500149)};
// Create an array of nodes based on the size of the labels and
// open and closed items
JTree, JTable and JList are probably the most common components you will want to custom-
ize. But you can use models such as SingleSelectionModel for general data manipulation.
The SingleSelectionModel class lets you specify how data is selected in a component.
If the component being displayed inside the JTable column requires more functionality than
is available using a JLabel, you can create your own TableCellRenderer. This next code
example uses a JButton as the renderer cell.
6: PROJECT SWING: BUILDING A USER INTERFACE 253
Like the default JLabel cell renderer, this class relies on an underlying component (in this
case, JButton) to do the painting. Selection of the cell toggles the button colors. As before,
the cell renderer is secured to the appropriate column of the auction table with the setCell-
Renderer method:
//API Ref :void setCellRenderer(TableCellRenderer renderer)
scrollColumnModel.getColumn(3).setCellRenderer(new CustomButtonRenderer());
An exact copy of the getTableCellEditorComponent method paints the button in edit mode.
A JDialog component that displays the number of days left appears when the getCellEditor-
Value method is called. The value for the number of days left is calculated by moving the
current calendar date towards the end date. The Calendar class does not have a method that
expresses a difference in two dates in anything other than the milliseconds between those
two dates.
// From AuctionClient.java
class CustomButtonEditor extends DefaultCellEditor {
final JButton mybutton;
JFrame frame;
CustomButtonEditor(JFrame frame) {
super(new JCheckBox());
mybutton = new JButton();
this.editorComponent = mybutton;
// To activate this button requires to mouse clicks (double click)
this.clickCountToStart = 2;
this.frame=frame;
mybutton.setOpaque(true);
mybutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//API Ref :void fireEditingStopped()
fireEditingStopped();
}
});
}
while(today.before(end)) {
//API Ref :void roll(int datefield, boolean up)
today.roll(Calendar.DATE, true);
days++;
}
jd.setSize(200,100);
// If the end date was originally after today, mark the auction as
// completed. Otherwise, display the number of days remaining.
if (today.after(end)) {
jd.getContentPane().add(new JLabel("Auction completed"));
} else {
jd.getContentPane().add(new JLabel("Days left="+days));
}
jd.setVisible(true);
return new String(mybutton.getText());
}
//API Ref :Component getTableCellEditorComponent(JTable table, Object value, boolean
isSelected, int row, int column)
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
((JButton) editorComponent).setText(((JButton)value).getText());
if (isSelected) {
((JButton) editorComponent).setForeground(table.getSelectionForeground());
((JButton) editorComponent).setBackground(table.getSelectionBackground());
} else {
((JButton) editorComponent).setForeground(table.getForeground());
((JButton) editorComponent).setBackground(table.getBackground());
}
return editorComponent;
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
button.requestFocus();
}
});
Printing API
The Java 2 platform java.awt.print package lets you print anything that can be rendered to a
Graphics or Graphics2D context--including AWT components, Project Swing components,
and 2D graphics.
The Printing API is easy to use. Your application tells the printing system what to print, and
the printing system determines when each page is rendered. This callback printing model
enables printing support on a wide range of printers and systems. The callback model also
lets users print to a bitmap printer from a computer that does not have enough memory or
disk space to hold the bitmap for an entire page.
A graphics context lets a program paint to a rendering device such as a screen, printer, or off
screen image. Because Project Swing components are rendered through a Graphics object
using AWT graphics support, it is easy to print Project Swing components with the new
printing API. However, AWT components are not rendered to a graphics device, so you must
extend the AWT component class and implement the AWT component paint method.
•PrinterGraphics
• Classes
•Book
•PageFormat
•Paper
•PrinterJob
• Exceptions
•PrinterAbortException
•PrinterException
•PrinterIOException
In the code, the Button class is extended to implement Printable and includes the paint and
print method implementations. The print method is required because the class implements
Printable, and the paint method is needed to describe how the button shape and label text
looks when printed.
To see the button, the printer graphics context is translated into the imageable area of the
printer, and to see the label text, a font is set on the printer graphics context.
In this example, the button is printed at a 164/72 inches inset from the left imageable margin
(there are 72 pixels per inch) and 5/72 inches from the top imageable margin. This is where
the button is positioned in the frame by the layout manager and those same numbers are
returned by the following calls:
int X = (int)this.getLocation().getX();
int Y = (int)this.getLocation().getY();
Note: The printing Graphics2D is based on the BufferedImage class and on some platforms
does not default to a foreground color of black. If this is the case on your platform, you have to
add g2.setColor(Color.black) to the print method before the paint invocation.
The PrintButton (Project Swing) (page 281) application for Project Swing displays a panel
with a MyButton on it.
class MyButton extends JButton implements Printable {
public MyButton() {
super("MyButton");
}
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi >= 1) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
g2.translate(pf.getImageableX(), pf.getImageableY());
Font f = new Font("Monospaced", Font.PLAIN,12);
g2.setFont (f);
paint(g2);
return Printable.PAGE_EXISTS;
}
//.. }
If you extend a JPanel and implement Printable, you can print a panel component and all of
its contents.
public class printpanel extends JPanel implements ActionListener, Printable {
The PrintPanel (page 282) code prints a JPanel object and the JButton it contains, and the
ComponentPrinterFrame (page 283) code prints a JFrame object and the JButton, JList,
JCheckBox, and JComboBox components it contains.
(page 284) Project Swing application borrowed from The Java Tutorial (http://
java.sun.com/docs/books/tutorial) shows how this is done. It is modified for this article to
include a TextLayout object.
The paintComponent method calls the drawShapes method to render the 2D graphics to the
screen when the application starts. When you click the Print button, a printer graphics con-
text is created and passed to the drawShapes method for the printing shown in Figure 24.
Print Dialog
It is easy to display a Print dialog (Figure 25) so the end user can interactively change the
print job properties. The actionPerformed method of the previous Project Swing example is
modified here to do just that.
Note: Some platforms do not support a page dialog. On those platforms, the pageDialog call
simply returns the passed-in PageFormat object and no dialog appears.
copies of the Print 2 button in portrait more, as specified in the actionPerformed method
implementation shown below.
Note: Currently a bug restricts the Solaris platform to only print in portrait mode.
Advanced Printing
The previous section explained how to print simple components and covered techniques that
can be used to print screen captures. However, if you want to print more than one component
per page, or if your component is larger than one page size, you need to do some additional
work inside your print method. This section explains what you need to do and concludes
with an example of how to print the contents of a JTable component.
264 6: PROJECT SWING: BUILDING A USER INTERFACE
Example
You can replace the print method in the PrintButton (AWT) (page 280) and PrintButton
(Project Swing) (page 281) examples with the following code to add the footer message
Company Confidential to the page.
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if (pi >= 1) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
Font f= Font.getFont("Courier");
//API Ref :double getImageableWidth()
//API Ref :double getImageableHeight()
double height=pf.getImageableHeight();
double width=pf.getImageableWidth();
g2.translate(pf.getImageableX(), pf.getImageableY());
g2.setColor(Color.black);
g2.drawString("Company Confidential", (int)width/2,
(int)height-g2.getFontMetrics().getHeight());
g2.translate(0f,0f);
//API Ref :void setClip(int x, int y, int width, int height)
g2.setClip(0,0,(int)width,(int)(height-g2.getFontMetrics().getHeight()*2));
paint (g2);
return Printable.PAGE_EXISTS;
}
6: PROJECT SWING: BUILDING A USER INTERFACE 265
In the new print method, the Graphics2D context is clipped before calling the parent JButton
paint method. This prevents the JButton paint method from overwriting the bottom of the
page. The translate method is used to point the JButton paint method to start the paint at off-
set 0,0 from the visible part of the page. The visible area was already calculated by the previ-
ous translate call:
//API Ref :void translate(double x, double y)
g2.translate(pf.getImageableX(), pf.getImageableY());
For some components, you might need to set the foreground color to see your results. In this
example the text color is printed in black.
getImageableHeight()
Returns the page height you can use for printing your output.
getImageableWidth()
Returns the page width you can use for printing your output.
Graphics2D methods:
//API Ref :void scale(double sx, double sy)
scale(xratio, yratio)
Scales the 2D graphics context by this size. A ratio of one maintains the size, less than one
shrinks the graphics context.
by the component from the value returned by getImageableHeight. Once the total number of
pages is calculated, you can run the following check inside the print method:
if(pageIndex >=TotalPages) {
return NO_SUCH_PAGE;
}
The Printing framework calls the print method multiple times until pageIndex is less than or
equal to TotalPages. All you need to do is create a new page from the same component on
each print loop. This is done by treating the printed page like a sliding window over the com-
ponent.
The part of the component that is to be printed is selected by a translate call to mark the top
of the page and a setClip call to mark the bottom of the page. Figure 27 illustrates this pro-
cess. The left side of the diagram represents the page sent to the printer. The right side con-
tains the long component being printed in the print method. The first page can be represented
as follows:
0,0 translate
0 row1 yes 2 (0,600)
row2 yes 1
print
row3 no
direction setClip
row4 yes 4 (0,0,600,400)
600
600,0 600,400
Page Index 0
Figure 28 shows how the printed page window slides along the component to print the sec-
ond page, page index one. This process continues until the last page is reached.
Printed Page Component
0,0 600
row11 yes 2
row12 yes 2
print setClip
direction (0, 600,600, 400)
1200
600,0 600,400
Page Index 1
Page 1
grant {
permission java.lang.RuntimePermission "queuePrintJob";
};
To launch the applet assuming a policy file named printpol and an HTML file named Sales-
Report.html, you would type:
AuctionClient
package auction;
import java.io.*;
import javax.naming.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.NumberFormat;
import bidder.*;
import registration.*;
import seller.*;
import search.*;
6: PROJECT SWING: BUILDING A USER INTERFACE 271
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
import java.text.*;
import javax.swing.table.*;
import javax.swing.tree.*;
public AuctionClient() {
try {
ctx = getInitialContext();
} catch (Exception e) {
System.out.println(“error contacting EJB server”+e);
}
filePrint.addActionListener(this);
fileQuit.addActionListener(this);
itemList.addActionListener(this);
browseItems.addActionListener(this);
272 6: PROJECT SWING: BUILDING A USER INTERFACE
} catch (Exception e) {
System.out.println("AuctionServlet <list>:"+e);
}
// Create a new table using the ResultsModel object as the table model
scrollTable=new JTable(rm);
// Force the End Date columns and Description columns to have
// a set width
adjustColumnWidth(scrollTable.getColumn("End Date"), 150);
adjustColumnWidth(scrollTable.getColumn("Description"), 120);
// The scroll column model is initially mapped to
// display all the table data. The fixed column model
// is initially empty
scrollColumnModel = scrollTable.getColumnModel();
fixedColumnModel = new DefaultTableColumnModel();
// Get the first column, remove it from the scroll column and
// add it to the fixed table
TableColumn col = scrollColumnModel.getColumn(0);
scrollColumnModel.removeColumn(col);
fixedColumnModel.addColumn(col);
// Keep the heights of the fixed and scroll tables the same
fixedTable.setRowHeight(scrollTable.getRowHeight());
});
// Create a custom renderer and use it on column 2
CustomRenderer custom = new CustomRenderer();
custom.setHorizontalAlignment(JLabel.CENTER);
//API Ref :void setCellRenderer(TableCellRenderer renderer)
scrollColumnModel.getColumn(2).setCellRenderer(custom);
// Use the custom button renderer on column 3
scrollColumnModel.getColumn(3).setCellRenderer(new CustomButtonRenderer());
// Add the custom button editor to column 3
CustomButtonEditor customEdit=new CustomButtonEditor(frame);
scrollColumnModel.getColumn(3).setCellEditor(customEdit);
// Create a panel for the top left of the display that contains
// the headers for the column that does not move
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
adjustColumnWidth(fixedColumnModel.getColumn(0), 100);
JTableHeader fixedHeader=fixedTable.getTableHeader();
//API Ref :void setAlignmentY()
fixedHeader.setAlignmentY(Component.TOP_ALIGNMENT);
topPanel.add(fixedHeader);
//API Ref :Component createRigidArea(Dimension d)
topPanel.add(Box.createRigidArea(new Dimension(2, 0)));
topPanel.setPreferredSize(new Dimension(400, 40));
innerPort.setView(scrollTable);
scrollpane.setViewport(innerPort);
scrollBar.getModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
//API Ref :Point getViewPosition()
Point q = headers.getViewPosition();
Point p = innerPort.getViewPosition();
int val = scrollBar.getModel().getValue();
p.x = val;
q.x = val;
fixedTable.setRowSelectionInterval(index, index);
}
void setScrollableRow() {
// Highlight the row by calling setRowSelectionInterval with a
// range of 1
int index=fixedTable.getSelectedRow();
scrollTable.setRowSelectionInterval(index, index);
}
void adjustColumnWidth(TableColumn c, int size) {
c.setPreferredWidth(size);
c.setMaxWidth(size);
c.setMinWidth(size);
}
Enumeration e = nodes[0].depthFirstEnumeration();
Object currNode;
while(e.hasMoreElements()) {
currNode = e.nextElement();
if(currNode.toString().equals(field)) {
TreePath path = new TreePath(((
DefaultMutableTreeNode)currNode).getPath());
tree.makeVisible(path);
tree.setSelectionRow(tree.getRowForPath(path));
return;
}
}
}
278 6: PROJECT SWING: BUILDING A USER INTERFACE
}
int days = 0;
// To work out if the date in the button is later or earlier than
// today, roll the date forward a day at a time until it is later
// than today
while(today.before(end)) {
today.roll(Calendar.DATE,true);
days++;
}
jd.setSize(200,100);
// If the end date was originally after today, mark the auction as
// completed. Otherwise, display the number of days remaining.
if(today.after(end)) {
jd.getContentPane().add(new JLabel(“Auction completed”));
} else {
jd.getContentPane().add(new JLabel(“Days left=”+days));
}
jd.setVisible(true);
return new String(mybutton.getText());
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
((JButton) editorComponent).setText(((JButton)value).getText());
if(isSelected) {
((JButton) editorComponent).setForeground(table.getSelectionForeground());
((JButton) editorComponent).setBackground(table.getSelectionBackground());
} else {
((JButton) editorComponent).setForeground(table.getForeground());
((JButton) editorComponent).setBackground(table.getBackground());
}
return editorComponent;
}
}
class CustomButtonRenderer extends JButton implements TableCellRenderer {
public CustomButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if(isSelected) {
((JButton)value).setForeground(table.getSelectionForeground());
((JButton)value).setBackground(table.getSelectionBackground());
} else {
((JButton)value).setForeground(table.getForeground());
((JButton)value).setBackground(table.getBackground());
}
return (JButton)value;
}
}
280 6: PROJECT SWING: BUILDING A USER INTERFACE
PrintButton (AWT)
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
f.pack();
f.setSize(new Dimension(400,300));
f.show();
}
}
};
Frame f = new Frame(“printbutton”);
f.addWindowListener(l);
f.add(“Center”, new printbutton());
f.pack();
f.setSize(new Dimension(400,300));
f.show();
}
}
PrintPanel
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
ComponentPrinterFrame
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
printButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(ComponentPrinterFrame.this);
if(pj.printDialog()) {
try { pj.print(); }
catch (PrinterException pe) {
System.out.println(pe);
}
}
}
});
setContentPane(panel);
setSize(400, 400);
// Center.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = getSize();
int x = (screenSize.width - frameSize.width) / 2;
int y = (screenSize.height - frameSize.height) / 2;
setLocation(x, y);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
284 6: PROJECT SWING: BUILDING A USER INTERFACE
}
public int print(Graphics g, PageFormat pf, int pageIndex) {
if (pageIndex != 0) return NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D)g;
g2.translate(pf.getImageableX(), pf.getImageableY());
getContentPane().paint(g2);
return PAGE_EXISTS;
}
}
ShapesPrint
import java.awt.geom.*;
import java.awt.font.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.print.PrinterJob;
import java.awt.event.*;
import java.awt.*;
import java.awt.print.*;
drawShapes(g2);
}
public void drawShapes(Graphics2D g2){
Dimension d = getSize();
int gridWidth = 400 / 6;
int gridHeight = 300 / 2;
int rowspacing = 5;
int columnspacing = 7;
int rectWidth = gridWidth - columnspacing;
int rectHeight = gridHeight - rowspacing;
Color fg3D = Color.lightGray;
g2.setPaint(fg3D);
g2.drawRect(80, 80, 400 - 1, 310);
g2.setPaint(fg);
int x = 85;
int y = 87;
//draw Text Layout
FontRenderContext frc = g2.getFontRenderContext();
Font f = new Font(“Times”,Font.BOLD, 24);
String s = new String(“24 Point Times Bold”);
TextLayout tl = new TextLayout(s, f, frc);
g2.setColor(Color.green);
tl.draw(g2, x, y-10);
// draw Line2D.Double
g2.draw(new Line2D.Double(x, y+rectHeight-1, x + rectWidth, y));
x += gridWidth;
// draw Rectangle2D.Double
g2.setStroke(stroke);
g2.draw(new Rectangle2D.Double(x, y, rectWidth, rectHeight));
x += gridWidth;
// draw RoundRectangle2D.Double
g2.setStroke(dashed);
g2.draw(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10));
x += gridWidth;
// draw Arc2D.Double
g2.setStroke(wideStroke);
g2.draw(new Arc2D.Double(x, y, rectWidth, rectHeight, 90, 135, Arc2D.OPEN));
x += gridWidth;
// draw Ellipse2D.Double
g2.setStroke(stroke);
g2.draw(new Ellipse2D.Double(x, y, rectWidth, rectHeight));
x += gridWidth;
// draw GeneralPath (polygon)
int x1Points[] = {x, x+rectWidth, x, x+rectWidth};
int y1Points[] = {y, y+rectHeight, y+rectHeight, y};
GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x1Points.length);
polygon.moveTo(x1Points[0], y1Points[0]);
for(int index = 1; index < x1Points.length; index++ ) {
polygon.lineTo(x1Points[index], y1Points[index]);
};
polygon.closePath();
g2.draw(polygon);
286 6: PROJECT SWING: BUILDING A USER INTERFACE
// NEW ROW
x = 85;
y += gridHeight;
// draw GeneralPath (polyline)
int x2Points[] = {x, x+rectWidth, x, x+rectWidth};
int y2Points[] = {y, y+rectHeight, y+rectHeight, y};
GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x2Points.length);
polyline.moveTo (x2Points[0], y2Points[0]);
for(int index = 1; index < x2Points.length; index++ ) {
polyline.lineTo(x2Points[index], y2Points[index]);
};
g2.draw(polyline);
x += gridWidth;
// fill Rectangle2D.Double (red)
g2.setPaint(red);
g2.fill(new Rectangle2D.Double(x, y, rectWidth, rectHeight));
g2.setPaint(fg);
x += gridWidth;
// fill RoundRectangle2D.Double
GradientPaint redtowhite = new GradientPaint(x,y,red,x+rectWidth, y,white);
g2.setPaint(redtowhite);
g2.fill(new RoundRectangle2D.Double(x, y, rectWidth, rectHeight, 10, 10));
g2.setPaint(fg);
x += gridWidth;
// fill Arc2D
g2.setPaint(red);
g2.fill(new Arc2D.Double(x, y, rectWidth, rectHeight, 90,135, Arc2D.OPEN));
g2.setPaint(fg);
x += gridWidth;
// fill Ellipse2D.Double
redtowhite = new GradientPaint(x,y,red,x+rectWidth, y,white);
g2.setPaint(redtowhite);
g2.fill (new Ellipse2D.Double(x, y, rectWidth, rectHeight));
g2.setPaint(fg);
x += gridWidth;
// fill and stroke GeneralPath
int x3Points[] = {x, x+rectWidth, x, x+rectWidth};
int y3Points[] = {y, y+rectHeight, y+rectHeight, y};
GeneralPath filledPolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
x3Points.length);
filledPolygon.moveTo(x3Points[0], y3Points[0]);
for (int index = 1; index < x3Points.length; index++ ) {
filledPolygon.lineTo(x3Points[index], y3Points[index]);
}
filledPolygon.closePath();
g2.setPaint(red);
g2.fill(filledPolygon);
g2.setPaint(fg);
g2.draw(filledPolygon);
}
public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
if(pi >= 1) {
6: PROJECT SWING: BUILDING A USER INTERFACE 287
return Printable.NO_SUCH_PAGE;
}
Graphics g2 = button.getGraphics();
button.printAll(g2);
drawShapes((Graphics2D) g);
return Printable.PAGE_EXISTS;
}
public static void main(String s[]){
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
public void windowClosed(WindowEvent e) {System.exit(0);}
};
Frame f = new Frame();
f.addWindowListener(l);
Panel panel = new Panel();
f.add(BorderLayout.SOUTH, panel);
f.add(BorderLayout.CENTER, new ShapesPrint());
panel.add(button);
f.add(BorderLayout.SOUTH, panel);
f.setSize(580, 500);
f.show();
}
}
Print2Button
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
b2.addActionListener(this);
add(b);
add(b2);
}
public void actionPerformed(ActionEvent e) {
PrinterJob printJob = PrinterJob.getPrinterJob();
/* Set up Book */
PageFormat landscape = printJob.defaultPage();
PageFormat portrait = printJob.defaultPage();
landscape.setOrientation(PageFormat.LANDSCAPE);
landscape.setOrientation(PageFormat.PORTRAIT);
Book bk = new Book();
bk.append((Printable)b, landscape);
bk.append((Printable)b2, portrait, 2);
printJob.setPageable(bk);
//Page dialog
PageFormat pf = printJob.pageDialog(printJob.defaultPage());
//Print dialog
if(printJob.printDialog()){
try { printJob.print(); } catch (Exception PrintException) { }
}
/*
try { printJob.print(); } catch (Exception PrintException) { }
*/
}
public static void main(String s[]) {
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
};
Frame f = new Frame(“print2button”);
f.addWindowListener(l);
f.add(“Center”, new print2button());
f.pack();
f.setSize(new Dimension(400,300));
f.show();
}
}
Report
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.Dimension;
public Report() {
frame = new JFrame(“Sales Report”);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}});
final String[] headers = {“Description”, “open price”,
“latest price”, “End Date”, “Quantity”};
final Object[][] data = {
{“Box of Biros”, “1.00”, “4.99”, new Date(), new Integer(2)},
{“Blue Biro”, “0.10”, “0.14”, new Date(), new Integer(1)},
{“legal pad”, “1.00”, “2.49”, new Date(), new Integer(1)},
{“tape”, “1.00”, “1.49”, new Date(), new Integer(1)},
{“stapler”, “4.00”, “4.49”, new Date(), new Integer(1)},
{“legal pad”, “1.00”, “2.29”, new Date(), new Integer(5)}};
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() {
return headers.length;
}
public int getRowCount() {
return data.length;
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public String getColumnName(int column) {
return headers[column];
}
public Class getColumnClass(int col) {
return getValueAt(0,col).getClass();
}
public boolean isCellEditable(int row, int col) {
return (col==1);
}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}};
tableView = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setPreferredSize(new Dimension(500, 80));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
frame.pack();
JButton printButton= new JButton();
printButton.setText(“print me!”);
frame.getContentPane().add(BorderLayout.SOUTH,printButton);
// for faster printing turn double buffering off
RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
printButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
PrinterJob pj=PrinterJob.getPrinterJob();
pj.setPrintable(Report.this);
pj.printDialog();
try {
pj.print();
290 6: PROJECT SWING: BUILDING A USER INTERFACE
g2.translate(0f, -headerHeightOnPage);
g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage),
(int)Math.ceil(headerHeightOnPage));
g2.scale(scale,scale);
tableView.getTableHeader().paint(g2);//paint header at top
return Printable.PAGE_EXISTS;
}
public static void main(String[] args) {
new Report();
}
}
SalesReport
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.Dimension;
int columnIndex = 0;
temp[0] = 0;
int columnWidth;
int length = 0;
subTableSplitSize = 0;
while( columnIndex < columns ) {
columnWidth = tableColumnModel.getColumn(columnIndex).getWidth();
if(length + columnWidth + columnMargin > pageWidth ) {
temp[subTableSplitSize+1] = temp[subTableSplitSize] + length;
length = columnWidth;
subTableSplitSize++;
} else {
length += columnWidth + columnMargin;
}
columnIndex++;
} //while
if(length > 0 ) { // if are more columns left, part page
temp[subTableSplitSize+1] = temp[subTableSplitSize] + length;
subTableSplitSize++;
}
subTableSplitSize++;
subTableSplit = new int[subTableSplitSize];
for(int i=0; i < subTableSplitSize; i++ ) {
subTableSplit[i]= temp[i];
}
totalNumPages = (int)(tableHeight/tableHeightOnFullPage);
// at least 1 more row left
if(tableHeight%tableHeightOnFullPage >= rowHeight ) {
totalNumPages++;
}
totalNumPages *= (subTableSplitSize-1);
pageinfoCalculated = true;
}
public void printTablePart(Graphics2D g2, PageFormat pageFormat,
int rowIndex,int columnIndex) {
String pageNumber = “Page: “+(rowIndex+1);
if(subTableSplitSize > 1 ) {
pageNumber += “-” + (columnIndex+1);
}
int pageLeft = subTableSplit[columnIndex];
int pageRight = subTableSplit[columnIndex + 1];
int pageWidth = pageRight-pageLeft;
// page number message
g2.drawString(pageNumber, pageWidth/2-35, (int)(pageHeight - fontHeight));
double clipHeight = Math.min(tableHeightOnFullPage,
tableHeight - rowIndex*tableHeightOnFullPage);
g2.translate(-subTableSplit[columnIndex], 0);
g2.setClip(pageLeft ,0, pageWidth, (int)headerHeight);
tableHeader.paint(g2); // draw the header on every page
g2.translate(0, headerHeight);
g2.translate(0, -tableHeightOnFullPage*rowIndex);
// cut table image and draw on the page
6: PROJECT SWING: BUILDING A USER INTERFACE 295
7: Debugging Applets,
Applications, and Servlets
An unwritten law of programming states you will spend 10 percent of your time on the first
90 percent of a project, and the other 90 percent of your time on the remaining 10 percent. If
this sounds like any of your projects, you are probably spending 90 percent of your time on
debugging and integration. While there are plenty of books and people to help you start a
project, there are far fewer resources available to help you finish it.
The good news is this chapter focuses completely on debugging and fixing to get your
project out on time. This chapter and 8: Performance Techniques (page 339) depart from the
auction application and use simple examples to walk you through the steps to debugging,
fixing, and tuning your programs.
By the time you finish this chapter, you should be an expert at troubleshooting programs
written in the Java™ programming language--applets, applications, and servlets--of all
shapes and sizes.
In a Rush?
If you have a pressing problem you need an answer to right now, this table might help. It tells
you where to find answers for common problems so you can go directly to the information.
Problem Section
Problem in a running program Getting Behind the Seat with jdb (page 304)
Collecting Evidence
The first step in trying to solve any problem is to gather as much evidence and information as
possible. If you can picture a crime scene, you know that everything is checked, cataloged
and analyzed before any conclusions are reached. When debugging a program, you do not
have weapons, hair samples, or fingerprints, but there is plenty of evidence you can gather
that might contain or ultimately lead to the solution. This section explains how to gather that
evidence.
Class Path
In the Java 2 platform, the CLASSPATH environment variable is needed to specify the appli-
cation's own classes only, and not the Java platform classes as was required in earlier
releases. So it is possible your CLASSPATH environment variable is pointing at Java plat-
form classes from earlier releases and causing problems. To examine the CLASSPATH, type
the following at the command line for your operating system.
Windows 95/98/NT
echo %CLASSPATH%
Unix Systems
echo $CLASSPATH
Java classes are loaded on a first come, first served basis from the CLASSPATH list. If the
CLASSPATH variable contains a reference to a lib/classes.zip file, which in turn points to a
different Java platform installation, this can cause incompatible classes to be loaded.
Note: In the Java 2 platform, the system classes are chosen before any class on the CLASS-
PATH list to minimize the possibility of any old broken Java classes being loaded instead of a
Java 2 class of the same name.
The CLASSPATH variable can get its settings from the command line or from configuration
settings such as those specified in the User Environment on Windows NT, an autoexec.bat
file, or a shell startup file like .cshrc on Unix.
You can control the classes the Java virtual machine uses by compiling your program with a
special command-line option that lets you supply the CLASSPATH you want. The Java 2
platform option and parameter is -Xbootclasspath classpath, and earlier releases use -class-
path classpath and -sysclasspath classpath. Regardless of which release you are running, the
classpath parameter specifies the system and user classpath, and zip or Java Archive (JAR)
files to be used in the compilation.
As an example, to compile and run the Myapp.java program with a system CLASSPATH
supplied on the command line, use the following instructions for your operating system.
Windows 95/98/NT
In this example, the Java platform is installed in the C:\java directory. Type everything on
one line. The -J option lets you pass extra conditions to the compiler.
300 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
javac -J -Xbootclasspath:c\javaıib\tools.jar;c:\java\jreıibt.jar;
c:\java\jreıib\i18n.jar;.Myapp.java
You do not need the -J runtime flag to run the compiled Myapp program, just type the fol-
lowing on one line:
java -Xbootclasspath:c:\java\jreıibt.jar;c:\java\jreıib\i18n.jar;.
Myapp
Unix Systems:
In this example, the Java platform is installed in the /usr/local/java directory. Type every-
thing on one line:
javac -J-Xbootclasspath:/usr/local/java/lib/tools.jar:/usr/local/java/
jre/lib/rt.jar:/usr/local/java/jre/lib/i18n.jar:. Myapp.java
You do not need the -J runtime flag to run the compiled Myapp program, just type the fol-
lowing on one line:
java -Xbootclasspath:/usr/local/java/jre/lib/rt.jar:/usr/local/java/
jre/lib/i18n.jar:. Myapp
Class Loading
Another way to analyze CLASSPATH problem is to locate where your application is loading its
classes. The verbose option to the java interpreter command shows which .zip or .jar file
a class comes from when it is loaded. This way, you will be able to tell if it came from the
Java platform zip file or from some other application’s JAR file.
For example, an application might be using the Password class you wrote for it or it might
be loading a Password class from an installed integrated development environment (IDE)
tool. You should see each jar and zip file named as in the example below:
$ java -verbose SalesReport
[Opened /usr/local/java/jdk1.2/solaris/jre/lib/rt.jar in 498 ms]
[Opened /usr/local/java/jdk1.2/solaris/jre/lib/i18n.jar in 60 ms]
[Loaded java.lang.NoClassDefFoundError from /usr/local/java/jdk1.2/solaris/jre/
lib/rt.jar]
[Loaded java.lang.Class from /usr/local/java/jdk1.2/solaris/jre/lib/rt.jar]
[Loaded java.lang.Object from /usr/local/java/jdk1.2/solaris/jre/lib/rt.jar]
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 301
The source code for theTestRuntime class needs to examine this property and set the debug
boolean flag as follows:
public class TestRuntime {
boolean debugmode; //global flag that we test
public TestRuntime () {
String dprop=System.getProperty("debug");
if((dprop !=null) && (dprop.equals("yes"))){
debugmode=true;
}
if(debugmode) {
System.err.println("debug mode!");
}
}
}
302 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
You can also add the following line to your application to dump your own stack trace. You
can find out how to read a stack trace in Analyzing Stack Traces (page 320), but for now you
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 303
can think of a stack trace as a snapshot of the current thread running in the Java virtual
machine.
Thread.currentThread().dumpStack();
To get access to the local variable information, you have to obtain the source (src.zip or
src.jar) and recompile it with a debug flag. You can get the source for most java.* classes
with the binary downloads from java.sun.com(http://java.sun.com).
Once you download the src.zip or src.jar file, extract only the files you need. For exam-
ple, to extract the String class, type the following at the command line:
or
Recompile the extracted class or classes with the -g option. You could also add your own
additional diagnostics to the source file at this point.
javac -g src/java/lang/String.java
Note: The Java 2 javac compiler gives you more options than just the original -g option for
debug code, and you can reduce the size of your classes by using -g:none, which gives you
on average about a 10 percent reduction in size.
To run the application with the newly compiled debug class or classes, you need to use the
boot classpath option so these new classes are picked up first. Type the following on one line
with a space before myapp.
304 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
jdb -Xbootclasspath:c:\java\src;c:\java\jreıibt.jar;c:
\java\jre\i18n.jar;. myapp
Unix Systems:
This example assumes the Java platform is installed in c:\java, and the source files are in
c:\java\src.
jdb -Xbootclasspath:/usr/java/src;/usr/java/jre/lib/rt.jar;/usr/java/
jre/i18n.jar;. myapp
SimpleJdbTest() {
setSize(100,200);
setup();
}
void setup (){
p=new Panel();
b[0]= new Button("press");
p.add(b[0]);
add(p);
b[0].addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
counter++;
}
});}
public static void main(String args[]) {
SimpleJdbTest sjb=new SimpleJdbTest();
sjb.setVisible(true);
}
}
Compile SimpleJdbTest:
javac -g SimpleJdbTest.java
jdb SimpleJdbTest
Initializing jdb...
0xad:class(SimpleJdbTest)
The jdb tool stops at the first line in the constructor. To list the methods that were called to
get to this breakpoint, enter the where command:
main[1] where
[1] SimpleJdbTest.<init> (SimpleJdbTest:10)
[2] SimpleJdbTest.main (SimpleJdbTest:29)
The numbered method in the list is the last stack frame that the Java virtual machine has
reached. In this case the last stack frame is the SimpleJdbTest constructor that was called
from SimpleJdbTest main.
Whenever a new method is called, it is placed on this stack list. Java Hotspot Performance
Engine achieves some of its speed gains by eliminating a new stack frame when a new
method is called.
To get a general appreciation of where the code has stopped, enter the list command.
main[1] list
6 Panel p;
7 Button b;
8 int counter=0;
9
10 SimpleJdbTest() {
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 307
11 setSize(100,200);
12 setup();
13 }
14 void setup (){
Looking at a Method
To see what happens in the setup method for SimpleJdbText, use the step command to step
through the 4 lines to get to it.
main[1] step
main[1]
Breakpoint hit: java.awt.Frame.<init> (Frame:222)
This is now the Frame class constructor! If you keep stepping you follow the Frame Con-
structor and not the SimpleJdbText class. Because SimpleJdbTest extends the Frame class,
the parent constructor, which in this case is Frame, is called on your behalf.
the setup method, use a next command. To debug the setup method, you can step through the
setup method.
main[1] step
Breakpoint hit: SimpleJdbTest.<init>
(SimpleJdbTest:11)
main[1] list
7 Button b[]=new Button[2];
8 int counter=0;
9
10 SimpleJdbTest() {
11 setSize(100,200);<
12 setup();
13 }
14 void setup (){
15 p=new Panel();
16 }
main[1] next
Breakpoint hit: SimpleJdbTest.<init>
(SimpleJdbTest:12)
main[1] step
Breakpoint hit: SimpleJdbTest.setup (SimpleJdbTest:15)
The first thing the setup method does is create a Panel p. If you try to display the value of p
with the print p command, you will find that the value is null.
main[1] print p
p = null
This occurred because the line has not been executed and so field p has not been assigned a
value. You need to step over that assignment operation with the next command and then use
the print p command again.
main[1] next
main[1] print p
p = java.awt.Panel[panel0,0,0,0x0,invalid, layout=java.awt.FlowLayout]
The message explains why jdb cannot stop in this method without more information, but the
message is slightly misleading as you do not need to specify the return type for overloaded
methods, you just need to be explicit about exactly which one of the overloaded methods
you want to stop in. To stop in the Button constructor that creates this Button, use stop in
java.awt.Button.<init>(java.lang.String).
Later releases of jdb let you choose the desired method as a numbered option.
If the Button class had not been recompiled with debug information as described earlier, you
would not see the internal fields from the print command.
Clearing Breakpoints
To clear this breakpoint and not stop every time a Button is created use the clear command.
This example uses the clear command with no arguments to display the list of current break-
points, and the clear command with the java.awt.Button:130 argument to clear the
java.awt.Button:130 breakpoint.
main[1] clear
Current breakpoints set:
SimpleJdbTest:10
java.awt.Button:130
main[1] clear java.awt.Button:130
Breakpoint cleared at java.awt.Button: 130
310 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
0xee2f9820:class(SimpleJdbTest)
> quit
Remote Debugging
The jdb tool is an external process debugger, which means it debugs the program by sending
messages to and from a helper inside the Java virtual machine. This makes it is easy to debug
a running program, and helps you debug a program that interacts with the end user. A remote
debug session from the command-line does not interfere with the normal operation of the
application.
ies, make the library name end in _g. For example, you would need to copy nativelib.dll to
nativelib_g.dll to debug with that library.
In Java 2, things are a little more complicated. You need to tell the Java virtual machine
where the tools.jar file is with the CLASSPATH variable. The tools.jar file contains non-core
class files to support tools and utilities in the SDK. It is normally found in the lib directory of
the Java platform installation.
You also need to disable the Just In Time (JIT) compiler if one exists. The JIT compiler is
disabled by setting the java.compiler property to NONE or to an empty string. Finally, as the
-classpath option overrides any previously set user classpath, you also need to add the
CLASSPATH needed by your application.
Putting all of this together, here is the command line needed to start a program in remote
debug mode. Put this all on one line and include all the classes you need on the command
line.
Windows
Unix:
The output is the agent password (in this case, 4gk5hm) if the program was successfully
started. The agent password is supplied when starting jdb so jdb can find the corresponding
application started in debug mode on that machine.
To start jdb in remote debug mode, supply a host name, which can be either the machine
where the remote program was started or localhost if you are debugging on the same
machine as the remote program, and the agent password.
Listing Threads
Once inside the jdb session, you can list the currently active threads with the threads com-
mand, and use the thread <threadnumber> command, for example, thread 7 to select the
thread to analyze. Once the thread is selected, use the where command to see which methods
have been called for this thread.
312 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
Listing Source
To list the source, the thread needs to be suspended using the suspend command. To let this
thread continue use the resume command. The example uses resume 7.
AWT-EventQueue-0[1] suspend 7
AWT-EventQueue-0[1] list
Current method is native
AWT-EventQueue-0[1] where
[1] java.lang.Object.wait (native method)
[2] java.lang.Object.wait (Object:424)
[3] java.awt.EventQueue.getNextEvent (EventQueue:179)
[4] java.awt.EventDispatchThread.run (EventDispatchThread:67)
AWT-EventQueue-0[1] resume 7
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 313
Using Auto-Pilot
One little known trick with jdb is the jdb startup file. jdb automatically looks for a file called
jdb.ini in the user.home directory. If you have multiple projects, it is a good idea to set a dif-
ferent user.home property for each project when you start jdb. To start jdb with a jdb.ini file
in the current directory, type the following:
jdb -J-Duser.home=.
The jdb.ini file lets you set up jdb configuration commands, such as use, without having to
enter the details each time a jdb runs. The following example jdb.ini file starts a jdb session
for the FacTest class. It includes the Java platform sources on the source path list and passes
the parameter 6 to the program. It then runs and stops at line 13, displays the free memory,
and waits for further input.
load FacTest
stop at FacTest:13
use /home/calvin/java:/home/calvin/jdk/src/
run FacTest 6
memory
$ jdb -J-Duser.home=/home/calvin/java
Initializing jdb...
0xad:class(FacTest)
Breakpoint set at FacTest:13
running ...
Free: 662384, total: 1048568
main[1]
Breakpoint hit: FacTest.compute (FacTest:13)
main[1]
314 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
You might wonder if jdb.ini files can be used to control an entire jdb session. Unfortunately,
commands in a jdb.ini startup file are executed synchronously, and jdb does not wait until a
breakpoint is reached before executing the next command. This makes printing variables
awkward. You can add artificial delays with repeated help commands, but there is still no
guarantee the thread will be suspended when you need it to be.
jdblog
When you next run jdb or java -debug, you will see jdb session information as shown below.
You can use this information to retrieve the breakpoint hits and the commands entered if you
need to reproduce this debug session.
---- debug agent message log ----
[debug agent: adding Debugger agent to system thread list]
[debug agent: adding Breakpoint handler to system thread list]
[debug agent: adding Step handler to system thread list]
[debug agent: adding Finalizer to system thread list]
[debug agent: adding Reference Handler to system thread list]
[debug agent: adding Signal dispatcher to system thread list]
[debug agent: Awaiting new step request]
[debug agent: cmd socket: Socket[addr=localhost/127.0.0.1, port=38986,localport=3
8985]]
[debug agent: connection accepted]
[debug agent: dumpClasses()]
[debug agent: no such class: HelloWorldApp.main]
[debug agent: Adding breakpoint bkpt:main(0)]
[debug agent: no last suspended to resume]
[debug agent: Getting threads for HelloWorldApp.main]
Servlet Debugging
You can debug servlets with the same jdb commands you use to debug an applet or an appli-
cation. The JavaServer™ Web Development Kit (JSWDK) provides a standalone program
called servletrunner that lets you run a servlet without a web browser. On most systems, this
program simply runs the java sun.servlet.http.HttpServer command. You can, therefore, start
a jdb session with the HttpServer class.
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 315
A key point to remember when debugging servlets is that Java WebServer™ and servletrun-
ner achieve servlet loading and unloading by not including the servlets directory on the
CLASSPATH. This means the servlets are loaded using a custom classloader and not the
default system classloader.
Unix
Windows
$ set CLASSPATH=lib\jsdk.jar;examples;%classpath%
To start the servletrunner program to debug SnoopServlet, either run the supplied startup
script called servletrunner or just supply the servletrunner classes as a parameter to jdb. This
example uses the parameter to servletrunner.
$ jdb sun.servlet.http.HttpServer
Initializing jdb...
0xee2fa2f8:class(sun.servlet.http.HttpServer)
> stop in SnoopServlet.doGet
Breakpoint set in SnoopServlet.doGet
> run
run sun.servlet.http.HttpServer
running ...
main[1] servletrunner starting with settings:
port = 8080
backlog = 50
max handlers = 100
timeout = 5000
servlet dir = ./examples
document dir = ./examples
servlet propfile = ./examples/servlet.properties
To run SnoopServlet in debug mode, enter the following URL in a browser where your
machine is the machine where you started servlet runner and 8080 is the port number dis-
played in the settings output.
http://yourmachine:8080/servlet/SnoopServlet
316 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
In this example jdb stops at the first line of the servlet's doGet method. The browser will wait
for a response from your servlet until a timeout is reached.
main[1] SnoopServlet: init
We can use the list command to work out where jdb has stopped in the source.
Thread-105[1] list
41 throws ServletException, IOException
42 {
43 PrintWriter out;
44
45 => res.setContentType("text/html");
46 out = res.getWriter ();
47
48 out.println("<html>");
49 out.println("<head>
<title>Snoop Servlet
</title></head>");
Thread-105[1]
The servlet can continue using the cont command.
Thread-105[1] cont
Before:
After:
Here is how to remotely connect to Java WebServer. The agent password is generated on the
standard output from the Java WebServer so it can be redirected into a file somewhere. You
can find out where by checking the Java WebServer startup scripts.
The servlets are loaded by a separate classloader if they are contained in the servlets direc-
tory, which is not on the CLASSPATH used when starting Java WebServer. Unfortunately,
when debugging remotely with jdb, you cannot control the custom classloader and request it
to load the servlet, so you have to either include the servlets directory on the CLASSPATH
for debugging or load the servlet by requesting it through a web browser and placing a
breakpoint once the servlet has run.
In this next example, the jdc.WebServer.PasswordServlet is included on the CLASSPATH
when Java WebServer starts. The example sets a breakpoint to stop in the service method of
this servlet, which is the main processing method of this servlet. The Java WebServer stan-
dard output produces this message, which lets you proceed with the remote jdb session:
Agent password=3yg23k
The second stop lists the current breakpoints in this session and shows the line number
where the breakpoint is set. You can now call the servlet through your HTML page. In this
example, the servlet is run as a POST operation
You get control of the Java Web Server thread when the breakpoint is reached, and you can
continue debugging using the same techniques as used in Remote Debugging (page 310).
Breakpoint hit: jdc.WebServer.PasswordServlet.service
(PasswordServlet:111) webpageservice Handler[1] where
[1] jdc.WebServer.PasswordServlet.service
(PasswordServlet:111)
318 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
[2] javax.servlet.http.HttpServlet.service
(HttpServlet:588)
[3] com.sun.server.ServletState.callService
(ServletState:204)
[4] com.sun.server.ServletManager.callServletService
(ServletManager:940)
[5] com.sun.server.http.InvokerServlet.service
(InvokerServlet:101)
A common problem when using the Java WebServer and other servlet environments is that
Exceptions are thrown but are caught and handled outside the scope of your servlet. The
catch command allows you to trap all these exceptions.
webpageservice Handler[1] catch java.io.IOException
webpageservice Handler[1]
Exception: java.io.FileNotFoundException
at com.sun.server.http.FileServlet.sendResponse(FileServlet.java:153)
at com.sun.server.http.FileServlet.service(FileServlet.java:114)
at com.sun.server.webserver.FileServlet.service(FileServlet.java:202)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
at com.sun.server.ServletManager.callServletService(ServletManager.java:936)
at com.sun.server.webserver.HttpServiceHandler.handleRequest(
HttpServiceHandler.java:416)
at com.sun.server.webserver.HttpServiceHandler.handleRequest(
HttpServiceHandler.java:246)
at com.sun.server.HandlerThread.run(HandlerThread.java:154)
This simple example was generated when the file was not found, but this technique can be
used for problems with posted data. Remember to use cont to allow the web server to pro-
ceed. To clear this trap use the ignore command.
webpageservice Handler[1] ignore java.io.IOException
webpageservice Handler[1] cont
webpageservice Handler[1]
Using AWTEventListener
You can use an AWTEventListener to monitor the AWT events from a system event queue.
This listener takes an event mask built from an OR operation of the AWTEvents you want to
monitor.
Note: Do not use AWTEventListener in a shipping product because it will degrade system per-
formance
//EventTest.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
At runtime, the EventTest program tracks and outputs mouse and focus events. For exam-
ple, when you click the button, you get this output:
java.awt.event.MouseEvent[MOUSE_CLICKED,(58,14),mods=16,clickCount=1] on
javax.swing.JButton[,0,0,96x27,layout=javax.swing.OverlayLayout,alignmentX=0.0,a
lignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@
e466ea9c,flags=48,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabled
Icon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=
14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnab
led=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=hello,defaultCa
pable=true]
To obtain a simple list of the AWTEvent events, use the javap -public java.awt.AWTEvent
command.
320 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
Unix Systems
For example, on the Solaris™ and other Unix platforms, you can use the kill -QUIT
process_id command, where process_id is the process number of your program. Alternately,
you can enter the key sequence <ctrl>\ in the window where the program started. Sending
this signal instructs a signal handler in the Java virtual machine to recursively print out all
the information on the threads and monitor inside the Java virtual machine.
Windows 95/NT
To generate a stack trace on the Windows 95 or Windows NT platforms, enter the key
sequence <ctrl><break> in the window where the program is running.
Core Files
If the JVM generated the stack trace because of an internal error then some native code in
your own application or the JVM is probably to blame. If you are using UNIX, and you find
a core file, run the following command to find out which JDK™ software it came from:
However, if there is no version string, you can still take a pretty good guess at which release
this stack trace came from. Obviously, if you generated the stack trace yourself this should
not be much of an issue, but you may see a stack trace posted on a news group or in an email.
First identify where the Registered Monitor Dump section is in the stack trace:
• If you see a utf8 hash table lock in the Registered Monitor Dump, this is a Java 2 plat-
form stack trace. The final release of the Java 2 platform also contains a version string
so if a version string is missing this stack trace may be from a Java 2 beta release.
• If you see a JNI pinning lock and no utf8 hash lock, this is a JDK 1.1+ release.
If neither of these appears in the Registered Monitor Dump, it is probably a JDK 1.0.2
release.
By verifying the existence of an Alarm monitor in the stack trace output you can identify
that this stack trace came from a green threads Java virtual machine.
Key Meaning
Key Meaning
S Suspended thread
CW Thread waiting on a condition variable
MW Thread waiting on a monitor lock.
Could indicate a deadlock.
MS Thread suspended waiting on a moni-
tor lock
Normally, only threads in R, S, CW or MW should appear in the stack trace. If you see a
thread in state MS, report it to Sun Microsystems, through the Java Developer Connection
(JDC) Bug Parade feature, because there is a good chance it is a bug. The reason being that
most of the time a thread in Monitor Wait (MW) state will appear in the S state when it is
suspended.
Monitors let you manage access to code that should only be run by one thread at a time. See
Examining Monitors (page 324) for more information on monitors.
The other two common thread states you may see are R, runnable threads and CW, threads in
a condition wait state. Runnable threads by definition are threads that could be running or
are running at that instance of time. On a multi-processor machine running a true multi-pro-
cessing Operating System, it is possible for all the runnable threads to be running at one
time. However, it is more likely for the other runnable threads to be waiting on the thread
scheduler to have their turn to run.
Threads in a condition wait state can be thought of as waiting for an event to occur. Often a
thread will appear in state CW if it is in a Thread.sleep or in a synchronized wait. In our ear-
lier stack trace our main method was waiting for a thread to complete and to be notified of its
completion. In the stack trace this appears as
synchronized(t1) {
try {
t1.wait(); //line 33
}catch (InterruptedException e){}
}
In the Java 2 release, monitor operations, including our wait here, are handled by the Java
virtual machine through a JNI call to sysMonitor. The condition wait thread is kept on a spe-
cial monitor wait queue on the object it is waiting on. This explains why even though you are
only waiting on an object that the code still needs to be synchronized on that object as it is in
fact using the monitor for that object.
Examining Monitors
This brings us to the other part of the stack trace: the monitor dump. If you consider that the
threads section of a stack trace identifies the multithreaded part of your application, then the
monitors section represents the parts of your application that are single threaded.
It may be easier to imagine a monitor as a car wash. In most car washes, only one car can be
in the wash at a time. In your Java code only one thread at a time can have the lock to a syn-
chronized piece of code. All the other threads queue up to enter the synchronized code just
as cars queue up to enter the car wash.
A monitor can be thought of as a lock on an object, and every object has a monitor. When
you generate a stack trace, monitors are either listed as being registered or not. In the major-
ity of cases these registered monitors, or system monitors, should not be the cause of your
software problems, but it helps to be able to understand and recognize them. The following
table describes the common registered monitors:
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 325
Monitor Description
Monitor Description
The monitor registry itself is protected by a monitor. This means the thread that owns the
lock is the last thread to use a monitor. It is very likely this thread is also the current thread.
Because only one thread can enter a synchronized block at a time, other threads queue up at
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 327
the start of the synchronized code and appear as thread state MW. In the monitor cache
dump, they are denoted as "waiting to enter" threads. In user code a monitor is called into
action wherever a synchronized block or method is used.
Any code waiting on an object or event (a wait method) also has to be inside a synchronized
block. However, once the wait method is called, the lock on the synchronized object is given
up.
When the thread in the wait state is notified of an event to the object, it has to compete for
exclusive access to that object, and it has to obtain the monitor. Even when a thread has sent
a "notify event" to the waiting threads, none of the waiting threads can actually gain control
of the monitor lock until the notifying thread has left its synchronized code block. You will
see "Waiting to be notified" for threads at the wait method
The AWT-EventQueue-0 thread is in a runnable state inside the remove method. Remove is
synchronized, which explains why the AWT-Windows thread cannot enter the select method.
The AWT-Windows thread is in MW state (monitor wait); however, if you keep taking stack
traces, this situation does not change and the graphical user interface (GUI) appears to have
frozen.
328 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
This indicates that the remove call never returned. By following the code path to the Choice-
Peer class, you can see this is making a native MFC call that does not return. That is where
the real problem lies and is a bug in the Java core classes. The user's code was okay.
Example 2
In this second example you will investigate a bug that on initial outset appears to be a fault in
Project Swing, but as you will discover is due to the fact that Project Swing is not thread
safe. Again the bug report is available to view on the JDC site, the bug number this time is
4098525.
Here is a cut down sample of the code used to reproduce this problem. The modal dialog is
being created from within the JPanel paint method.
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
frame.getContentPane().add(gui);
frame.setSize(800, 600);
frame.pack();
frame.setVisible(true);
}
}
When you run this program, you find it deadlocks straight away. By taking a stack trace you
see the key threads shown in Stack Trace 2 (page 332). This stack trace is slightly different
from the stack trace that appears in the bug report, but is caused by the same problem.
Stack Trace 2 is produced by the Java 2 platform release using the -Djava.compiler=NONE
option to the java interpreter command so you can see the source line numbers. The thread
to look for is the thread in monitor wait, which in this case is thread AWT-EventQueue-1.
"AWT-EventQueue-1" (TID:0xebca8c20, sys_thread_t:0x376660, state:MW) prio=6
at java.awt.Component.invalidate(Component.java:1664)
at java.awt.Container.invalidate(Container.java:507)
at java.awt.Window.dispatchEventImpl(Window.java:696)
at java.awt.Component.dispatchEvent(Component.java:2289)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:258)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:68)
If you look for that line in file java/awt/Component.java which is contained in the src.jar
archive, you see the following:
public void invalidate() {
synchronized (getTreeLock()) { //line 1664
This is where the application is stuck. It is waiting for the getTreeLock monitor lock to
become free. The next task is to find out which thread has this getTreeLock monitor lock
held. To see who is holding this monitor lock you look at the Monitor cache dump and in this
example you can see the following:
Monitor Cache Dump:
java.awt.Component$AWTTreeLock@EBC9C228/EBCF2408:
owner "AWT-EventQueue-0" (0x263850) 3 entries
Waiting to enter: "AWT-EventQueue-1" (0x376660)
The method getTreeLock monitor is actually a lock on a specially created inner class object
of AWTTreeLock. This is the code used to create that lock in file Component.java.
The current owner is AWT-EventQueue-0. This thread called the paint method to create the
modal Dialog with a call to the paintComponent method. The paintComponent method was
called from an update call of JFrame.
330 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
So where was the lock set? Well there is no simple way to find out which stack frame actu-
ally held the lock, but on a simple search of javax.swing.JComponent, you see that getTree-
Lock is called inside the method paintChildren which you left at line 388.
at Tester.paint(Tester.java:39)
at javax.swing.JComponent.paintChildren(JComponent.java:388)
The rest of the puzzle is pieced together by analyzing the MDialogPeer show method. The
Dialog code creates a new ModalThread which is why you see an AWT-Modal thread in the
stack trace output, this thread is used to post the Dialog. It is when this event is dispatched
using AWT-EventQueue-1, which used to be the AWT Dispatch proxy, that getTreeLock
monitor access is required and so you have a deadlock.
Unfortunately, Project Swing code is not designed to be thread safe, and so the workaround
in this example is to not create modal dialogs inside Project Swing paint methods. Since
Swing has to do a lot of locking and calculations as to which parts of a lightweight compo-
nent needs to be painted, it is strongly recommended to not include synchronized code or
code that will result in a synchronized call such as in a modal dialog, inside paint method.
You should now know what to look for the next time you see a stack trace. To save time, you
should make full use of the JDC bug search to see if the problem you are having has already
been reported by someone else.
Expert's Checklist
To summarize, these are the steps to take the next time you come across a problem in a Java
program:
• Hanging, deadlocked or frozen programs: If you think your program is hanging,
generate a stack trace. Examine the threads in states MW or CW. If the program is dead-
locked, some of the system threads will probably show up as the current thread because
there is nothing else for the Java virtual machine to do.
• Crashed or aborted programs: On UNIX look for a core file. You can analyze this
file in a native debugging tool such as gdb or dbx. Look for threads that have called
native methods. Because Java technology uses a safe memory model, any corruption
probably occurred in the native code. Remember that the Java virtual machine also
uses native code so it might not be a bug in your application.
• Busy programs: The best course of action you can take for busy programs is to gen-
erate frequent stack traces. This will narrow down the code path that is causing the
errors, and you can start your investigation from there.
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 331
Stack Trace 1
$ java -Djava.compiler=NONE HangingProgram
^\SIGQUIT
Stack Trace 2
Full thread dump Classic VM (JDK-1.2-V, green threads):
“AWT-Modal” (TID:0xebca8a40, sys_thread_t:0x376d50, state:CW) prio=6
at java.lang.Object.wait(Native Method)
at sun.awt.motif.MDialogPeer.pShow(Native Method)
at sun.awt.motif.ModalThread.run(MDialogPeer.java:247)
“AWT-EventQueue-1” (TID:0xebca8c20, sys_thread_t:0x376660, state:MW) prio=6
at java.awt.Component.invalidate(Component.java:1664)
at java.awt.Container.invalidate(Container.java:507)
at java.awt.Window.dispatchEventImpl(Window.java:696)
at java.awt.Component.dispatchEvent(Component.java:2289)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:258)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:68)
“Screen Updater” (TID:0xebca9a08, sys_thread_t:0x3707c8, state:CW) prio=4
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:424)
at sun.awt.ScreenUpdater.nextEntry(ScreenUpdater.java:79)
at sun.awt.ScreenUpdater.run(ScreenUpdater.java:99)
“AWT-Motif” (TID:0xebcafa30, sys_thread_t:0x285370, state:CW) prio=5
at sun.awt.motif.MToolkit.run(Native Method)
at java.lang.Thread.run(Thread.java:479)
“SunToolkit.PostEventQueue-0” (TID:0xebcafc58, sys_thread_t:0x263988,
state:CW) prio=5
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:424)
at sun.awt.PostEventQueue.run(SunToolkit.java:363)
“AWT-EventQueue-0” (TID:0xebcafc28, sys_thread_t:0x263850, state:CW) prio=6
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:424)
at sun.awt.motif.MDialogPeer.show(MDialogPeer.java:181)
at java.awt.Dialog.show(Dialog.java:368)
at Tester.showDialogs(Tester.java:32)
at Tester.paint(Tester.java:39)
at javax.swing.JComponent.paintChildren(JComponent.java:388)
at javax.swing.JComponent.paint(JComponent.java:550)
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 333
at javax.swing.JComponent.paintChildren(JComponent.java:388)
at javax.swing.JComponent.paint(JComponent.java:550)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:547)
at javax.swing.JComponent.paintChildren(JComponent.java:388)
at javax.swing.JComponent.paint(JComponent.java:535)
at java.awt.Container.paint(Container.java:770)
at javax.swing.JFrame.update(JFrame.java:255)
at sun.awt.motif.MComponentPeer.handleEvent(MComponentPeer.java:248)
at java.awt.Component.dispatchEventImpl(Component.java:2429)
at java.awt.Container.dispatchEventImpl(Container.java:1032)
at java.awt.Window.dispatchEventImpl(Window.java:714)
at java.awt.Component.dispatchEvent(Component.java:2289)
... (more frames not shown)
“Finalizer” (TID:0xebc98320, sys_thread_t:0x69418, state:CW) prio=8
at java.lang.Object.wait(Native Method)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:112)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:174)
“Reference Handler” (TID:0xebc983b0, sys_thread_t:0x64f68, state:CW) prio=10
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:424)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:114)
“Signal dispatcher” (TID:0xebc983e0, sys_thread_t:0x5e1e8, state:R) prio=5
“Thread-0” (TID:0xebcaa000, sys_thread_t:0x26bb0, state:CW) prio=5
Monitor Cache Dump:
java.awt.Component$AWTTreeLock@EBC9C228/EBCF2408: owner “AWT-EventQueue-0”
(0x263850) 3 entries
Waiting to enter:
“AWT-EventQueue-1” (0x376660)
java.lang.Class@EBCA5148/EBD11A48: <unowned>
Waiting to be notified:
“AWT-Modal” (0x376d50)
sun.awt.motif.ModalThread@EBCA8A40/EBD67998: owner “AWT-Modal” (0x376d50) 1
entry
Waiting to be notified:
“AWT-EventQueue-0” (0x263850)
java.lang.ref.ReferenceQueue$Lock@EBC98338/EBCCDCD8: <unowned>
Waiting to be notified:
“Finalizer” (0x69418)
sun.awt.PostEventQueue@EBCAFC58/EBD405B0: <unowned>
Waiting to be notified:
“SunToolkit.PostEventQueue-0” (0x263988)
sun.awt.ScreenUpdater@EBCA9A08/EBD633F8: <unowned>
Waiting to be notified:
“Screen Updater” (0x3707c8)
java.lang.ref.Reference$Lock@EBC983C0/EBCCD8A8: <unowned>
Waiting to be notified:
“Reference Handler” (0x64f68)
Registered Monitor Dump:
utf8 hash table: <unowned>
JNI pinning lock: <unowned>
JNI global reference lock: <unowned>
BinClass lock: <unowned>
334 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
Version Issues
This section summarizes problems and solutions related to having different versions of the
Java platform installed on your system.
JDK 1.0.2
Deployment
Uses CLASSPATH to find and load the core system classes.
On Windows 95:
CLASSPATH=c:\java\lib\classes.zip:.
On Unix:
CLASSPATH=/usr/java/lib/classes.zip:.
Unix dynamic libraries, .dll files, shared objects, and .so files are located by the PATH vari-
able.
Side Effects
The Win95 Autoexec.bat file contains an outdated CLASSPATH variable set by a user or the
installation of other applications.
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 335
Diagnostics
Use the -classpath option to force the Java VM to use the command-line CLASSPATH only:
java -classpath c:\java\lib\classes.zip;. myapp
JDK 1.1
Deployment
Uses relative paths to find the classes.zip file from the Java platform installation. The
CLASSPATH environment variable is used to load application classes.
Side Effects
Other Java releases found on the application path might be picked up if the new JDK bin
directory is not explicitly set at the front of the PATH environment variable.
Diagnostics
Use the -sysclasspath option to force the Java VM to use the CLASSPATH supplied on the
command line only: java -sysclasspath c:\java\lib\classes.zip;. myapp
Java 2 Platform
Deployment
The platform is split into a Java Runtime Environment (JRE) and Java compiler. The JRE is
included as a subdirectory in the release, and the traditional java and javac programs in the
bin directory invoke the real program in the jre/bin directory. The separate jre launcher is no
longer provided, and the java program is solely used instead.
The Java Archive (JAR) files containing the core Java platform system classes, rt.jar and
i18.jar, are located in the jre/lib directory with a relative search path.
Side Effects
If applications previously used the classes.zip file to load the core Java platform systems,
they might still try to load an additional set of classes in error.
336 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
Diagnostics
Use the -Xbootclasspath option to force the Java VM to use the CLASSPATH supplied on
the command line only: java -Xbootclasspath:c:\java\jre\lib\rt.jar;c:\java\jre\lib\i18n.jar;.
myapp
You might need to supply this as a runtime option as follows: javac -J-Xbootclass-
path:c\java\lib\tools.jar;c: \java\jre\lib\rt.jar;c:\java\jre\lib\i18n.jar;. myapp.java
Java Plug-In
Deployment
On Windows 95 and Windows NT uses the registry to find installed plug-in Java platform
releases.
Side Effects
Registry can become corrupted, or plug-in removed physically but not from the registry.
Diagnostics
Display the java.version and java.class.path property in your code and display it on the Java
Plug-in Console
System.out.println("version="+System.getProperty("java.version"));
System.out.println("class path="+System.getProperty("java.class.path");
If there is a conflict, check the registry with the regedit command, search for the word VM
and if it exists, delete it and reinstall the plug-in
Netscape
Deployment
Uses .jar files such as java40.jar in the netscape directory.
Side Effects
Not all Netscape releases are fully JDK 1.1 compliant. You can get upgrade patches at
http://www.netscape.com.
Diagnostics
Start the browser on the command line with the -classes option.
7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS 337
Internet Explorer
Deployment
Uses .cab files to contain system classes. Also uses system registry on Windows 95/NT.
Side Effects
Use the regedit command to search for the word VM. There is a CLASSPATH entry to
which you can add your own classes.
Diagnostics
The registry can become corrupted. Search for CLASSPATH using the regedit program and
edit the value that CLASSPATH points to.
338 7: DEBUGGING APPLETS, APPLICATIONS, AND SERVLETS
8: PERFORMANCE TECHNIQUES 339
8: Performance Techniques
One of the biggest challenges in developing large applications for the Java platform is to
make the application meet its performance criteria. This chapter departs from the auction
application and uses simple and targeted examples to show you how to track down perfor-
mance bottlenecks to improve application performance.
ing the images as GIF files on the server, the files are encoded as Strings and stored in a
single class file.
This code sample uses packages from the JavaCup winner at JavaOne 1996, which contains
the XImageSource and XpmParser classes. These classes provide all you need to read a stan-
dard XPM file. You can see these files at SunSite (http://sunsite.utk.edu/winners_circle/
developer_tools/DESVS7NU/applet.html).
For the initial encoding process, there are a number of graphics tools you can use to create
XPM files. On Solaris you can use ImageTool or a variety of other GNU image packages
(http://www.gnu.ai.mit.edu/software/software.html). Go to the Download.com web site
(http://download.cnet.com) to get the encoding software for Windows platforms.
The following code excerpted from the MyApplet (page 369) sample class loads the images
shown in Figure 33. You can see the coded String form for the images in the XPM Definition
(page 375) of the images.
Figure 33 Images
The Toolkit class creates an Image object for each image from the XPM Image Source
object. The parameters to XImageSource represent a coded String form from the XPM Def-
inition (page 375).
Toolkit kit = Toolkit.getDefaultToolkit();
Image image;
mage = kit.createImage (new XImageSource (_reply));
image = kit.createImage (new XImageSource (_post));
image = kit.createImage (new XImageSource (_reload));
image = kit.createImage (new XImageSource (_catchup));
image = kit.createImage (new XImageSource (_back10));
image = kit.createImage (new XImageSource (_reset));
image = kit.createImage (new XImageSource (_faq));
The alternative technique below uses GIF files. It requires a request back to the web server
for each image loaded.
Image image;
image = getImage (reply.gif);
image = getImage (post.gif);
image = getImage (reload.gif);
image = getImage (catchup.gif);
8: PERFORMANCE TECHNIQUES 341
This technique reduces network traffic because all images are available in a single class file.
• Using XPM encoded images makes the class size larger, but the number of network
requests fewer.
• Making the XPM image definitions part of your applet class file makes the image load-
ing process part of the regular loading of the applet class file with no extra classes.
Once loaded, you can use the images to create buttons or other user interface components.
This next code segment shows how to use the images with the javax.swing.JButton class.
ImageIcon icon = new ImageIcon(kit.createImage(new XImageSource(_reply)));
JButton button = new JButton (icon, Reply);
The applet downloads the entire JAR file, regardless of whether or not the JAR file includes
infrequently used files.
<APPLET CODE=MyApplet.class ARCHIVE=jarfile1, jarfile2 WIDTH=100 HEIGHT=200>
</APPLET>
342 8: PERFORMANCE TECHNIQUES
To improve performance when an applet has infrequently used files, put the frequently used
files into the JAR file and the infrequently used files into the applet class directory. Infre-
quently used files are then located and downloaded by the browser only when needed.
Thread Pooling
Bandwidth restrictions imposed on networks around the world make network-based opera-
tions potential bottlenecks that can have a significant impact on an application's perfor-
mance. Many network-based applications are designed to use connection pools so they can
reuse existing network connections and save on the time and overhead invested in opening
and closing network connections.
The Java Developer Connection (JDC) applet servers and the Java WebServer™ make exten-
sive use of thread pooling to improve performance. Thread pooling is creating a ready sup-
ply of sleeping threads at the beginning of execution. Thread creation and their statup
process is expensive, so rutime performance is improved with thread pooling because
threads are not created during runtime; they are simply reused.
This code sample taken from the Pool (page 380) class shows one way to implement thread
pooling. In the pool's constructor (shown below), the WorkerThreads are initialized and
started. The call to the start method executes the run method of the WorkerThread, and the
call to wait in the run method suspends the Thread while the Thread waits for work to arrive.
The last line of the constructor pushes the sleeping Thread onto the stack.
public Pool (int max, Class workerClass) throws Exception {
_max = max;
_waiting = new Stack();
_workerClass = workerClass;
Worker worker;
WorkerThread w;
for ( int i = 0; i < _max; i++ ) {
worker = (Worker)_workerClass.newInstance();
w = new WorkerThread (Worker#+i, worker);
w.start();
_waiting.push(w);
}
}
Besides the run method, the WorkerThread class has a wake method. When work comes in,
the wake method is called, which assigns the data and notifies the sleeping WorkerThread
(the one initialized by the Pool) to resume running. The wake method's call to notify causes
the blocked WorkerThread to fall out of its wait state, and the run method of the HttpServer-
Worker (page 383) class is executed. Once the work is done, the WorkerThread is either put
back onto the Stack (assuming the thread pool is not full) or terminates.
8: PERFORMANCE TECHNIQUES 343
At its highest level, incoming work is handled by the performWork method in the Pool class
(shown below). As work comes in, an existing WorkerThread is popped off of the Stack (or a
new one is created if the Pool is empty). The sleeping WorkerThread is then activated by a
call to its wake method.
public void performWork (Object data) throws InstantiationException{
WorkerThread w = null;
synchronized (_waiting){
if( _waiting.empty() ){
try {
w = new WorkerThread (additional worker,
(Worker)_workerClass.newInstance());
w.start();
} catch (Exception e){
throw new InstantiationException(
Problem creating instance of Worker.class: + e.getMessage());
} else{
w = (WorkerThread)_waiting.pop();
}
}
w.wake (data);
}
The HttpServer (page 384) class constructor creates a new Pool instance to service HttpServ-
erWorker (page 383) instances. HttpServerWorker instances are created and stored as part of
the WorkerThread data. When a WorkerThread is activated by a call to its wake method, the
HttpServerWorker instance is invoked by way of its run method.
try{
_pool = new Pool (poolSize, HttpServerWorker.class);
344 8: PERFORMANCE TECHNIQUES
This next code is in the run method of the HttpServer (page 384) class. Every time a request
comes in, the data is initialized and the Thread starts work.
Note: If creating a new Hashtable for each WorkerThread presents too much overhead, just
modify the code so it does not use the Worker abstraction.
try {
Socket s = _serverSocket.accept();
Hashtable data = new Hashtable();
data.put (Socket, s);
data.put (HttpServer, this);
_pool.performWork (data);
} catch (Exception e){
e.printStackTrace();
}
Thread pooling is an effective performance-tuning technique that puts the expensive thread
startup process at the startup of an application. This way, the negative impact on perfor-
mance occurs once at program startup where it is least likely to be noticed.
Connection Pooling
If you have used an SQL or other similar tool to connect to a database and act on the data,
you probably know that getting the connection and logging in is the part that takes the most
time. An application can easily spend several seconds every time it needs to establish a con-
nection.
In releases prior to JDBC™ 2.0 every database session requires a new connection and login
even if the previous connection and login used the same table and user account. If you are
using a JDBC release prior to 2.0 and want to improve performance, you can cache JDBC
connections instead of creating a new connection and login.
Cached connections are kept in a runtime object pool and can be used and reused as needed
by the application. One way to implement the object pool is to make a simple hashtable of
connection objects. However, a more flexible way to do it is to write a wrapper JDBC Driver
that is an intermediary between the client application and database.
The wrapper approach works particularly well in an Enterprise Bean that uses Bean-man-
aged persistence for two reasons: 1) Only one Driver class is loaded per Bean, and 2) spe-
8: PERFORMANCE TECHNIQUES 345
cific connection details are handled outside the Bean. This section explains how to write a
wrapper JDBC Driver class.
Wrapper Classes
The wrapper JDBC Driver created for this example consists of the following three classes:
• JDCConnectionDriver
• JDCConnectionPool
• JDCConnectio
Connection Driver
The JDCConnectionDriver (page 391) class implements the java.sql.Driver interface, which
provides methods to load drivers and create new database connections. A JDCConnection-
Manager object is created by the application seeking a database connection. The application
provides the database Uniform Resource Locator (URL) for the database, login user ID, and
login password.
The JDCConnectionManager constructor does the following:
• Registers the JDCConnectionManager object with the DriverManager.
• Loads the Driver class passed to the constructor by the calling program.
• Initializes a JDCConnectionPool object for the connections with the database URL,
login user ID, and login password passed to the constructor by the calling program.
public JDCConnectionDriver(String driver, string url, String user,
String password)
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException, SQLException {
DriverManager.registerDriver(this);
Class.forName(driver).newInstance();
pool = new JDCConnectionPool(url, user, password);
}
When the calling program needs a database connection, it calls the JDCConnection-
Driver.connect method, which in turn, calls the JDCConnectionPool.getConnection method.
Connection Pool
The JDCConnectionPool (page 391) class makes connections available to a calling program
in its getConnection method. This method searches for an available connection in the con-
nection pool. If no connection is available from the pool, a new connection is created. If a
346 8: PERFORMANCE TECHNIQUES
connection is available from the pool, the getConnection method leases the connection and
returns it to the calling program.
public synchronized Connection getConnection() throws SQLException {
JDCConnection c;
for(int i = 0; i < connections.size(); i++) {
c = (JDCConnection)connections.elementAt(i);
if (c.lease()) {
return c;
}
}
The JDCConnection (page 393) class represents a JDBC connection in the connection pool,
and is essentially a wrapper around a real JDBC connection. The JDCConnection object
maintains a state flag to indicate if the connection is in use and the time the connection was
taken from the pool. This time is used by the ConnectionReaper class to identify hanging
connections.
Closing Connections
The connection is returned to the connection pool when the calling program calls the JDC-
Connection.close method in its finally clause.
public void close() throws SQLException {
pool.returnConnection(this);
}
Example Application
You use a connection pool in an application in a similar way to how you would use any other
JDBC driver. Here is the code for a Bean-managed RegistrationBean (page 395). This Regis-
trationBean is adapted from the auction house Enterprise JavaBeans™ example described in
Chapters 1 - 3.
When the first RegistrationBean object is created, it creates one static instance of the JDC-
ConnectionDriver class. This static driver object registers itself with the DriverManager in
the JDCConnectionDriver constructor making it available for connection requests to all Reg-
istrationBean objects created by the client application.
Passing the URL as jdbc:jdc:jdcpool in the getConnection method, lets the DriverManager
match the getConnection request to the registered driver. The DriverManager uses simple
String matching to find an available driver that can handle URLs in that format.
public class RegistrationBean implements EntityBean{
Method Inlining
The Java 2 release of the Java virtual machine automatically inlines simple methods at runt-
ime. In an un-optimized Java virtual machine, every time a new method is called, a new
stack frame is created. The creation of a new stack frame requires additional resources as
well as some remapping of the stack. The end result is that creating new stack frames incurs
a small overhead.
Method inlining increases performance by reducing the number of method calls your pro-
gram makes. The Java virtual machine inlining code inlines methods that return constants or
only access internal fields. To take advantage of method inlining you can do one of two
things: You can either make a method look attractive to the virtual machine to inline, or man-
ually inline a method if it does not break your object model. Manual inlining in this context
means moving the code from a method into the method that is calling it. Automatic virtual
machine inlining is illustrated in this next example:
public class InlineMe {
int counter=0;
In its current state the addCount method does not look very attractive to the inline detector in
the virtual machine because the addCount method returns a value. To find out if this method
is inlined, run the compiled example with profiling enabled:
This generates a java.hprof.txt output file. The top ten methods will look similar to this:
CPU TIME (ms) BEGIN (total = 510) Thu Jan 28 16:56:15 1999
rank self accum count trace method
1 5.88% 5.88% 1 25 java/lang/Character. <clinit>
2 3.92% 9.80% 5808 13 java/lang/String.charAt
3 3.92% 13.73% 1 33 sun/misc/Launcher$AppClassLoader.getPermissions
4 3.92% 17.65% 3 31 sun/misc/URLClassPath.getLoader
5 1.96% 19.61% 1 39 java/net/URLClassLoader.access$1
6 1.96% 21.57% 1000 46 InlineMe.addCount
7 1.96% 23.53% 1 21 sun/io/Converters.newConverter
8 1.96% 25.49% 1 17 sun/misc/Launcher$ExtClassLoader.getExtDirs
9 1.96% 27.45% 1 49 java/util/Stack.peek
10 1.96% 29.41% 1 24 sun/misc/Launcher.<init>
If you change the addCount method to no longer return a value, the virtual machine will
inline it for you at runtime. To make the code friendly to inlining, replace the addCount
method with the following code:
This time the java.hprof.txt output should look different. The addCount method is gone
because it has been inlined!
350 8: PERFORMANCE TECHNIQUES
CPU TIME (ms) BEGIN (total = 560) Thu Jan 28 16:57:02 1999
rank self accum count trace method
1 5.36% 5.36% 1 27 java/lang/Character.<clinit>
2 3.57% 8.93% 1 23 java/lang/System.initializeSystemClass
3 3.57% 12.50% 2 47 java/io/PrintStream.<init>
4 3.57% 16.07% 5808 15 java/lang/String.charAt
5 3.57% 19.64% 1 42 sun/net/www/protocol/file/Handler.openConnection
6 1.79% 21.43% 2 21 java/io/InputStreamReader.fill
7 1.79% 23.21% 1 54 java/lang/Thread.<init>
8 1.79% 25.00% 1 39 java/io/PrintStream.write
9 1.79% 26.79% 1 40 java/util/jar/JarFile.getJarEntry
10 1.79% 28.57% 1 38 java/lang/Class.forName0
Streamlined synchronization
Up until Java 2 synchronized methods and objects have always incurred an additional perfor-
mance hit. This is because the mechanism used to implement the locking used a global mon-
itor registry, which was only single-threaded in some areas such as when searching for
existing monitors.
In the Java 2 release, each thread has a monitor registry and so many of the existing bottle-
necks have been removed. If you have previously used other locking mechanisms because of
the performance hit with synchronized methods, it is now worthwhile to revisit this code and
incorporate the new Java 2 streamlined locks.
This next example creates monitors for the synchronized block and achieves a 40 percent
increase in speed. Time was 14ms using JDK 1.1.7 and only 10ms with Java 2 on a Sun Ultra
1.
class MyLock {
static Integer count=new Integer(5);
int test=0;
Adaptive optimization
Hotspot does not include a plug-in JIT compiler, but instead compiles and inlines methods it
determines as being the most used in the application. This means that on the first pass
through, Java bytecodes are interpreted as if you did not have a JIT compiler present. If the
code then appears to be a hot spot in your application, the Hotspot compiler compiles the
bytecodes into native code that is stored in a cache and inlines methods at the same time. See
Method Inlining (page 348) for details on the advantages to inlining code.
One advantage to selective compilation over a JIT compiler is the byte compiler can spend
more time generating highly optimized code for the areas that would benefit from the opti-
mization most. The compiler can also avoid compiling code that may best run in interpreted
mode.
Earlier versions of HotSpot did not optimize code not currently in use. The downside to this
is if the application is in a big busy loop, the optimizer is unable to compile the code for that
area until the loop finishes. Later Hotspot releases use on-stack replacement, meaning that
code can be compiled into native code even if it is in use by the interpreter.
For older objects the garbage collector sweeps through the heap and compacts holes from
dead objects directly, which removes the need for a free list used in earlier garbage collec-
tion algorithms.
The third area of improvement is to remove the perception of garbage collection pauses by
staggering the compaction of large free object spaces into smaller groups and compacting
them incrementally.
Just-In-Time Compilers
The simplest tool used to increase the performance of your application is the Just-In-Time
(JIT) compiler. A JIT is a code generator that converts Java bytecodes into native machine
code. Java programs invoked with a JIT generally run much faster than when the bytecode is
executed by the interpreter. Hotspot removes the need for a JIT compiler in most cases; how-
ever, you might still find the JIT compiler being used in earlier releases.
The JIT compiler was first made available as a performance update in the Java Development
Kit (JDK™) 1.1.6 software release and is now a standard tool invoked whenever you use the
java interpreter command in the Java 2 platform release. You can disable the JIT compiler
with the -Djava.compiler=NONE option to the Java virtual machine. This is covered in more
detail at the end of the JIT section.
The JIT compiler uses its own invoker. Sun production releases check the method access bit
for value ACC_MACHINE_COMPILED to notify the interpreter that the code for this
method has already been compiled and stored in the loaded class.
Notice that inlined methods such as String.length are exempt. The String.length is also a spe-
cial method because it is normally compiled into an internal shortcut bytecode by the Java
Interpreter. When using the JIT compiler these optimizations provided by the Java Inter-
preter are disabled to enable the JIT compiler to understand which method is being called.
The JIT compiler also achieves a minor performance gain by not prechecking certain bound-
ary conditions in the Java programming language such as null pointer or array out of bounds
exceptions. The only way the JIT compiler knows it has a null pointer exception is by a sig-
nal raised by the operating system. Because the signal comes from the operating system and
not the Java virtual machine, your program takes a performance hit. To ensure the best per-
formance when running an application with the JIT, make sure your code is very clean with
no errors like null pointer or array out of bounds exceptions.
You might want to disable the JIT compiler if you are running the Java virtual machine in
remote debug mode, or if you want to see source line numbers instead of the label (Compiled
Code) in your Java stack traces. To disable the JIT compiler, supply a blank or invalid name
for the name of the JIT compiler when you invoke the interpreter command. The following
examples show the javac command to compile the source code into bytecodes, and two
forms of the java interpreter command to invoke the interpreter without the JIT compiler.
javac MyClass.java
java -Djava.compiler=NONE MyClass
or
javac MyClass.java
java -Djava.compiler="" MyClass
Third-Party Tools
Some of the other tools available include those that reduce the size of the generated Java
class files. A Java class file contains an area called a constant pool. The constant pool keeps
a list of strings and other information for the class file in one place for reference. One of the
pieces of information available in the constant pool are the method and field name.
The class file refers to a field in the class as a reference to an entry in the constant pool. This
means as long as the references stay the same, it does not matter what the values stored in the
constant pool are. This knowledge is exploited by several tools that rewrite the names of the
field and methods in the constant pool into shortened names. This technique can reduce the
class file by a significant percentage with the benefit that a smaller class file means a shorter
network download.
Performance Analysis
Another way to improve performance is with performance analysis. Performance analysis is
looking at program execution to pinpoint where bottlenecks or other performance problems
8: PERFORMANCE TECHNIQUES 355
such as memory leaks might occur. Once you know where potential trouble spots are, you
can change your code to remove or reduce their impact.
Profiling
Java virtual machines have been able to provide simple profile reports since the introduction
of Java Developer Kit (JDK) 1.0.2. However, the information provided is limited to a sorted
list of methods called by a program.
The Java® 2 platform software provides much better profiling capabilities than previously
available, and analysis of this generated data is made easier by the Heap Analysis Tool
(HAT). The heap analysis tool, as its name implies, lets you analyze heap profile reports. The
heap is a block of memory the Java virtual machine uses at run time. You can locate the
Heap Analysis Tool using the search engine on the http://java.sun.com web site.
The heap analysis tool lets you generate reports on objects that were used to run your appli-
cation. Not only can you get a listing of the most frequently called methods and the memory
used in calling those methods, but you can also track down memory leaks. Memory leaks
can have a significant impact on performance.
Analyze a Program
This section shows you how to analyze the TableExample3 program included in the demo/
jfc/Table directory in the Java 2 platform download. To do this, you need to generate a pro-
file report. The simplest report to generate is a text profile.
To generate a text profile, run the application with the -Xhprof parameter. In the final release
of the Java 2 platform software, this option was renamed -Xrunhprof. To see a list of the cur-
rently available options run the java interpreter command as follows:
java -Xrunhprof:help
Hprof usage: -Xrunhprof[:help]|[<option>=<value>, ...]
Option Name and Value Description Default
--------------------- ----------- --------
heap=dump|sites|all heap profiling all
cpu=samples|times|old CPU usage off
monitor=y|n monitor contention n
format=a|b ascii or binary output a
file=<file> write data to file java.hprof(.txt for ascii)
net=<host>:<port> send data over a socket write to file
depth=<size> stack trace depth 4
cutoff=<value> output cutoff poin 0.0001
lineno=y|n line number in traces y
thread=y|n thread in traces? n
doe=y|n dump on exit? y
Example: java -Xrunhprof:cpu=samples,file=log.txt, depth=3 FooClass
356 8: PERFORMANCE TECHNIQUES
The following invocation creates a text output file that you can view without the
java.hprof.txt heap analysis tool, which is called when the program generates a stack trace or
exits. A different invocation is used to create a binary file to use with the heap analysis tool.
java -Xrunhprof TableExample3
The profile option literally logs every object created on the heap, so even just starting and
stopping the small TableExample3 program results in a four megabyte report file. Although
the heap analysis tool uses a binary version of this file and provides a summary, there are
some quick and easy things you can learn from the text file without using the heap analysis
tool.
The [S notation at the end of the last line above indicates the first entry is an array of short,
which is a primitive type. This notation is expected with Project Swing or Abstract Window
Toolkit (AWT) applications.
The five count under the objs header means there are currently five of these arrays, there
have only been five in the lifetime of this application, and they take up 826516 bytes.
The reference key to this object is the value listed under stack trace. To find where this object
was created in this example, search for TRACE 3981. You will see the following:
TRACE 3981:
java/awt/image/DataBufferUShort.<init>(DataBufferUShort.java:50)
java/awt/image/Raster.createPackedRaster(Raster.java:400)
java/awt/image/DirectColorModel.createCompatibleWritableRaster(
DirectColorModel.java:641)
sun/awt/windows/WComponentPeer.createImage(WComponentPeer.java:186)
The TableExample3 code sets a scrollpane that is 700 by 300. When you look at the source
of Raster.java, which is in the src.jar file, you find these statements at line 400:
8: PERFORMANCE TECHNIQUES 357
The values w and h above are the width and height from the createImage call at the start of
TRACE 3981. The DataBufferUShort constructor creates and array of shorts as follows:
data = new short[size];
where size is w*h. So, in theory there should be an entry for an array of 210000 elements.
You look for each instantiation of this class by searching for trace=3981. One of the five
entries will look like this:
OBJ 5ca1fc0 (sz=28, trace=3979,class=java/awt/image/DataBufferUShort@9a2570)
data 5ca1670
bankdata 5ca1f90
offsets 5ca1340
ARR 5ca1340 (sz=4, trace=3980, nelems=1, elem type=int)
ARR 5ca1670 (sz=420004, trace=3981, nelems=210000,elem type=short)
ARR 5ca1f90 (sz=12, trace=3982, nelems=1, elem type=[S@9a2d90)
[0] 5ca1670
You can see that the data value of this raster image references an array 5ca1670 which in
turns lists 210000 elements of a short of size 2. This means 420004 bytes of memory are
used in this array.
From this data you can conclude that the TableExample3 program uses nearly 0.5Mb to map
each table. If the example application is running on a small memory machine, you should
make sure you do not keep unnecessary references to large tables or images that are built by
the createImage method.
To generate the binary report, close the TableExample3 window. The binary report file
TableExample3.hprof is created when the program exits. The Heap Analysis tool starts an
HTTP Server that analyzes the binary profile file and displays the results in HTML that you
can view with a browser.
You can get a copy of the Heap Analysis Tool from the java.sun.com web site. Once you
install it, you can run shell and batch scripts in the installed bin directory to start the Heap
Analysis Tool server as follows:
>hat TableExample3.hprof
358 8: PERFORMANCE TECHNIQUES
The above output tells you an HTTP server is started on port 7000 by default. To view this
report enter the url http://localhost:7000 or http://your_machine_name:7000 in your web
browser. If you have problems starting the server using the scripts, you can alternately run
the application by including the hat.zip classes file on your CLASSPATH and use the follow-
ing command:
java hat.Main TableExample3.hprof
The default report view contains a list of all the classes. At the bottom of this initial page are
the following two key report options:
Show all members of the rootset
Show instance counts for all classes
If you select the Show all members of the rootset link, you see a list of the following refer-
ences because these reference are likely targets for potential memory leaks.
Java Static References
Busy Monitor References
JNI Global References
JNI Local References
System Class References
What you look for here are instances in the application that have references to objects that
have a risk of not being garbage collected. This can sometimes occur in the case of JNI if
memory is allocated for an object, the memory is left to the garbage collector to free up, and
the garbage collector does not have the information it needs to do it. In this list of references,
you are mainly interested in a large number of references to objects or objects of a large size.
The other key report is the Show instance counts for all classes. This lists the number of calls
to a particular method. The String and Character array objects, [S and [C, are always going
to be high on this list, but some objects are a bit more intriguing. Why are there 323
instances of java.util.SimpleTimeZone for example?
5109 instances of class java.lang.String
5095 instances of class [C
2210 instances of class java.util.Hashtable$Entry
968 instances of class java.lang.Class
407 instances of class [Ljava.lang.String;
8: PERFORMANCE TECHNIQUES 359
To get more information on the SimpleTimeZone instances, click on the link (the line begin-
ning with 323). This will list all 323 references and calculate how much memory has been
used. In this example, 21964 bytes have been used.
Instances of java.util.SimpleTimeZone
class java.util.SimpleTimeZone
If you click on one of these SimpleTimeZone instances, you see where this object was allo-
cated.
Object allocated from:
In this example the object was allocated from TimeZone.java. The source to this file is in the
standard src.jar file, and on examining this file, you can see that indeed there are nearly 300
of these objects in memory.
static SimpleTimeZone zones[] = {
// Total Unix zones: 343
// Total Java zones: 289
// Not all Unix zones become Java zones due to
// duplication and overlap.
//-------------------------------------------
new SimpleTimeZone(-11*ONE_HOUR, "Pacific/Niue" /*NUT*/),
360 8: PERFORMANCE TECHNIQUES
Unfortunately, you have no control over the memory used in this example because it is allo-
cated when the program first requests a default time zone. However, this same technique can
be applied to analyzing your own application where you may be able to make some improve-
ments
CPU TIME (ms) BEGIN (total = 11080) Fri Jan 8 16:40:59 1999
rank self accum count trace method
1 13.81% 13.81% 1 437 sun/awt/X11GraphicsEnvironment.initDisplay
2 2.35% 16.16% 4 456 java/lang/ClassLoader$NativeLibrary.load
3 0.99% 17.15% 46 401 java/lang/ClassLoader.findBootstrapClass
If you contrast this with the cpu=samples output, you see the difference between how often a
method appears during the runtime of the application in the samples output compared to how
long that method took in the times output.
The W32LockView method, which calls a native windows lock routine, is called 425 times.
So when it is sampled, it appears in the active runnings threads because 425 calls take time
to complete. However although the initDisplay method is called only once, it takes the long-
est time to complete in real time.
such as disk access or networking. However, what occurs in these libraries after the Java vir-
tual machine calls them is beyond the reach of most profiling tools for the Java platform.
The next sections describe tools you can use to analyze performance problems on some
common operating systems.
The truss command traces and records the details of every system call called by the Java vir-
tual machine to the Solaris kernel. A common way to run truss is:
truss -f -o /tmp/output -p <process id>
The -f parameter follows any child processes that are created, the -o parameter writes the
output to the named file, and the -p parameter traces an already running program from its
process ID. Alternately, you can replace -p <process id> with the Java virtual machine, for
example:
truss -f -o /tmp/output java MyDaemon
The /tmp/output is used to store the truss output, which should look similar to the following:
15573: execve("/usr/local/java/jdk1.2/solaris/bin/java", 0xEFFFF2DC,
0xEFFFF2E8) argc = 4
15573: open("/dev/zero", O_RDONLY) = 3
15573: mmap(0x00000000, 8192, PROT_READ|PROT_WRITE|PROT_EXEC,
MAP_PRIVATE, 3, 0) = 0xEF7C0000
15573: open("/home/calvin/java/native4/libsocket.so.1", O_RDONLY)
Err#2 ENOENT
362 8: PERFORMANCE TECHNIQUES
In the truss output, look for files that fail when opened due to access problems, such as error
ENOPERM, or a missing file error ENOENT. You can also track data read or written with
the truss parameters -rall to log all data read, or -wall to log all data written by the program.
With these parameters, it is possible to analyze data sent over a network or to a local disk.
Linux Platform
Linux has a trace command called strace. It traces system calls to the underlying Linux ker-
nel. This example traces the SpreadSheet example in the JDK demo directory.
$ strace -f -o /tmp/output java sun.applet.AppletViewer example1.html
$ cat /tmp/output
639 execve("/root/java/jdk117_v1at/java/jdk117_v1a/bin/java"
, ["java","sun.applet.AppletViewer ", "example1.html"], [/* 21 vars */]) = 0
639 brk(0) = 0x809355c
639 open("/etc/ld.so.preload", O_RDONLY) = -1 ENOENT
(No such file or directory)
639 open("/etc/ld.so.cache", O_RDONLY) = 4
639 fstat(4, {st_mode=0, st_size=0, ...}) = 0
639 mmap(0, 14773, PROT_READ, MAP_PRIVATE, 4, 0) = 0x4000b000
639 close(4) = 0
639 open("/lib/libtermcap.so.2", O_RDONLY) = 4
639 mmap(0, 4096, PROT_READ, MAP_PRIVATE, 4, 0) = 0x4000f000
To obtain system information similar to the Solaris sar command, read the contents of the
file /proc/stat. The format of this file is described in the proc man page. Look at the cpu line
to get the user and system time.
In the above example, the cpu line indicates 48.27 seconds in user space, 0.04 at nice prior-
ity, 16.36 seconds processing system calls, and 168 seconds idle. This is a running total;
individual entries for each process are available in /proc/<process_id>/stat.
8: PERFORMANCE TECHNIQUES 363
Windows95/98/NT Platforms
There are no standard performance analysis tools included on this platform, but the follow-
ing tools are available by way of freeware or shareware resources such as http://www.down-
load.com.
import java.io.*;
class DBCacheRecord {
Object data;
long time;
public DBCache() {
cache = new HashMap();
}
results.completed) <=SYSDATE");
}
}
}
Note: There are other techniques to constrain cache size besides MRU. MRU is one of the sim-
pler algorithms.
With an MRU cache, you can place a constraint on which objects remain in cache, and
thereby, control the size of the cache. There are three main operations that the MRU cache
has to perform:
• If the cache is not full, new objects not already in the cache are inserted at the head of
the list.
• If the cache is not full and the object to be inserted already exists in the cache, it is
moved to the head of the list.
• If the cache is full and a new object is to be inserted, the last object in the cache is
removed and the new object is inserted at the head of the list.
366 8: PERFORMANCE TECHNIQUES
This diagram shows how the LinkedList and HashMap work together to implement the oper-
ations described above. A discussion of the diagram follows.
LinkedList HashMap
Add recently
accessed
objects to the Key hashkey File
front of the list Contents
hashkey
If the recently
accessed Key
object already
exists, move it
to the front of
the list hashkey
Key
hashkey
Remove entries Key
from the end of
the list if the list
is full
The LinkedList provides the queue mechanism, and the entries in the LinkedList contain the
key to the data in the HashMap. To add a new entry to the front of the list, the addFirst
method is called.
• If the list is already full, the removeLast method is called and the data entry is also
removed from the HashMap.
• If an entry is already in the list, it is removed with a call to the remove method and
inserted at the front of the list with a call to the addFirst method.
The Collections API does not implement locking, so if you remove entries from or add
entries to LinkedList or HashMap objects, you need to lock access to these objects. You can
also use a Vector or ArrayList to get the same results as shown in the code below with the
LinkedList.
This code example uses an MRU cache to keep a cache of files loaded from disk. When a file
is requested, the program checks to see if the file is in the cache. If the file is not in the cache,
the program reads the file from disk and places the cache copy at the beginning of the list.
8: PERFORMANCE TECHNIQUES 367
• If the file is in cache, the program compares the modification times of the file and cache
entry.
• If the cache entry time is older, the program reads the file from disk, removes the cache
copy, and places a new copy in the cache at the front of the LinkedList.
• If the file time is older, the program gets the file from the cache and moves the cache
copy to the front of the list.
// File MRUCache.java
import java.util.*;
import java.io.*;
class myFile {
long lastmodified;
String contents;
Map cache;
LinkedList mrulist;
int cachesize;
try {
BufferedReader br=new BufferedReader(new FileReader(f));
String line;
while((line =br.readLine()) != null) {
filecontents.append(line);
}
} catch (FileNotFoundException fnfe){
return (null);
} catch ( IOException ioe) {
return (null);
}
return (new myFile(f.lastModified(),
filecontents.toString()));
}
MyApplet
import java.applet.*;
// import XPM Parser classes
import java.awt.*;
import javax.swing.*;
}
static final public String post[] = {"32 32 6 1",
" c #C0C0C0C0C0C0",
". c #FFFFFFFFFFFF",
"X c #000000000000",
"o c #FFFF99990000",
"O c #333333333333",
"+ c #00009999FFFF",
" ",
" ",
" ",
" ",
" ",
" ",
" ............................. ",
" .XXXXXX................oooo..O ",
" .......................++++..O ",
" .XXXXXX................++++..O ",
" .......................++++..O ",
" .............................O ",
" .............................O ",
" .............................O ",
" .............................O ",
" .............................O ",
" ...............XXXXXXXXXXXX..O ",
" .............................O ",
" .............................O ",
" ...............XXXXXXXXXXXX..O ",
" .............................O ",
" .............................O ",
" ...............XXXXXXXXXXXX..O ",
" .............................O ",
" OOOOOOOOOOOOOOOOOOOOOOOOOOOOO ",
" ",
" ",
" ",
" ",
" ",
" ",
" "};
static final public String reply[] = {"32 32 7 1",
" c #C0C0C0C0C0C0",
". c #FFFFFFFFFFFF",
"X c #000000000000",
"o c #FFFF99990000",
"O c #333333333333",
"+ c #00009999FFFF",
"@ c #FFFF00000000",
" ",
" ",
" ",
" ............................. ",
" .XXXXXX................oooo..O ",
8: PERFORMANCE TECHNIQUES 371
".O@@@@XX%%@%%%@@%%%%@%%X@@@Xoo ",
" .+@@@@@@@@@@@@@@@@@@@@@@@@O#o ",
" .#@@@@XX&@&%%@%&&@@&&XX@@@#Xo ",
" .O@@@@@@@@@@@@@@@@@@@@@@@@+Xoo ",
" .+@@@@XX%%&%@&%%%%&&%%X@@@OOo ",
" .#@@@@@@@@@@@@@@@@@@@@@@@@#Xo ",
" .O@@@@XX%&@&&%%@&&&@%%X@@@+Xoo",
" .@@@@@@@@@@@@@@@@@@@@@@@@@OXo",
" .O@@@@@@@@@@@@@@@@@@@@@@@@@X+o",
" .@@@@XX%&&@%%%@@@&@&%XX@@@OXo",
" .O@@@@@@@@@@@@@@@@@@@@@@@@@X+o",
" .#@@@@XX&@&&&@%%@@&&&%XX@@+X+o",
" .+@@@@@@@@@@@@@@@@@@@@@@@@#$oo",
" .@@@@@XX&%&&@&&@&&%@%@X@@@O$o ",
" .O@@@@@@@@@@@@@@@@@@@@@@@@+$oo ",
" .#@@@@XXX&%@%%@@@@@@@@@@@@#Xoo ",
" .+@@@@@@@@@@@@@@@@@@@@@@@@O$o ",
".O@@@@@@@@@@@@@@@@@@@@@@@@#X+o ",
"%%%%%%%%%%%%%%%%%%%%%%%%%%%%o "};
}
XPM Definition
static final public String _post[] = {"32 32 6 1",
" c #C0C0C0C0C0C0",
". c #FFFFFFFFFFFF",
"X c #000000000000",
"o c #FFFF99990000",
"O c #333333333333",
"+ c #00009999FFFF",
" ",
" ",
" ",
" ",
" ",
" ",
" ............................. ",
" .XXXXXX................oooo..O ",
" .......................++++..O ",
" .XXXXXX................++++..O ",
" .......................++++..O ",
" .............................O ",
" .............................O ",
" .............................O ",
" .............................O ",
" .............................O ",
" ...............XXXXXXXXXXXX..O ",
" .............................O ",
" .............................O ",
" ...............XXXXXXXXXXXX..O ",
" .............................O ",
" .............................O ",
376 8: PERFORMANCE TECHNIQUES
"X c #000099999999",
"o c #00009999FFFF",
" ",
" .. ",
" ..X ",
" .......X ooooooo ",
" .........X oooooooX ",
" ...........X oooooooX ",
" .....XXXXX..X oooooooX ",
" ....XXX ..X oooooooX ",
" ....XX ..X oooooooX ",
" ...XX XX oooooooX ",
" ...XX XXXXXXX ",
" ..XX ",
" ...X ",
" ..XX ",
" ..X ",
" ..X .X ",
" ..X ...X ",
" ..X .....X ",
" ..X .......X ",
" ... .........X ",
" ..X ...XXXXX ",
" ... ...X ",
" ... ...XX ",
" .... ....X ",
" .... ....XX ",
" ..... .....XX ",
" ...............XX ",
" X...........XXX ",
" X.......XXX ",
" XXXXXXX ",
" ",
" "};
static final public String _catchup[] = {"32 32 9 1",
" c #C0C0C0C0C0C0",
". c #000000000000",
"X c #FFFFCCCC0000",
"o c #00009999FFFF",
"O c #333333333333",
"+ c #000099999999",
"@ c #999999999999",
"# c #9999CCCCFFFF",
"$ c #00009999FFFF",
" ",
" ",
" . ",
" ... ",
" XX.XX ",
" XXXXXXX ",
" oXXXXXoO ",
" o+XXX+oO ",
" o+o+o+oO ",
378 8: PERFORMANCE TECHNIQUES
" ",
" ",
" ",
" ",
" ",
" "};
static final public String _reset[] = {"32 32 5 1",
" c #C0C0C0C0C0C0",
". c #99999999FFFF",
"X c #000099999999",
"o c #9999CCCCFFFF",
"O c #00009999FFFF",
" ",
" ",
" ",
" ....... ",
" ............. ",
" ............... ",
" ......XXXXXXX...... ",
" .....XXoooooooXX..... ",
" ....XoooooooooooX.... ",
" ....XoooooooooooooX.... ",
" ....XoooooooooooooooX.... ",
" ...XoooooooooooooooooX... ",
" ...XoooooooooooooooooX... ",
" ...XooooooooXXXooooooooX... ",
" ...XoooooooXOOOXoooooooX... ",
" ...XooooooXOOOOOXooooooX... ",
" ...XooooooXOOOOOXooooooX... ",
" ...XooooooXOOOOOXooooooX... ",
" ...XoooooooXOOOXoooooooX... ",
" ...XooooooooXXXooooooooX... ",
" ...XoooooooooooooooooX... ",
" ...XoooooooooooooooooX... ",
" ....XoooooooooooooooX.... ",
" ....XoooooooooooooX.... ",
" ....XoooooooooooX.... ",
" .....XXoooooooXX..... ",
" ......XXXXXXX...... ",
" ............... ",
" ............. ",
" ....... ",
" ",
" "};
Pool
import java.util.*;
Worker
public interface Worker {
//Method invoked to request worker to perform task
public void run(Object data);
}
8: PERFORMANCE TECHNIQUES 383
HttpServerWorker
import java.io.*;
import java.net.*;
import java.util.*;
} catch (IOException e) {
e.printStackTrace();
}
}
}
HttpServer
import java.io.*;
import java.net.*;
import java.util.*;
try {
Socket s = _serverSocket.accept();
Hashtable data = new Hashtable();
data.put (“Socket”, s);
data.put (“HttpServer”, this);
_pool.performWork (data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//Convience method to write the HTTP Response header
* @param out Stream to write the response too
* @throws IOException Thrown if response can’t be written
void writeResponse (DataOutputStream out) throws IOException {
out.writeBytes (_httpResponse);
}
}
HttpServerListener
/**
* Used by the server to listen for messages from the HttpClient
*/
public interface HttpServerListener extends java.util.EventListener
{
/*
* Method invoked when a message is received by the HttpServer
* @param data Message data
* @param results Stream to write response too
* @return void
*/
public void service (java.io.InputStream data,
java.io.OutputStream results);
}
HttpListener
/**
* Used by the client’s to listen for messages from the HttpServer
*/
public interface HttpListener extends java.util.EventListener
{
/**
* Method invoked when a message is sent from the HttpServer
* @param data Message data
* @return void
*/
public void service (java.io.InputStream data);
8: PERFORMANCE TECHNIQUES 387
HttpClient
import java.net.*;
import java.io.*;
import java.util.*;
/**
* Implementation of a basic HTTP client for Firewall
* tunneling. The client supports both Client->Server and
* Server->Client communication.
*/
public class HttpClient implements Runnable {
// Type of message: also used in HttpServerWorker
final static public int PENDING = 1;
final static public int DATA = 2;
/**
* Creates a new HttpClient instance configured
* to connect to the server specified in the url
* parameter.
* @param url URL of the server, example http://bogus:9000
*/
public HttpClient (String url) {
_url = url;
_pendingTID = new Thread(this);
_pendingTID.setPriority (Thread.MAX_PRIORITY);
_listener = null;
}
/**
* Removes the HttpListener. The pending connection
* is stopped, so the client won’t receive any more
* messages from the server
* @param l HttpListener to remove
* @return void
*/
public void removeHttpListener (HttpListener l) {
if ( _listener != null ) {
synchronized (this) {
388 8: PERFORMANCE TECHNIQUES
_stop = true;
}
_pendingTID.destroy();
_listener = null;
}
}
/**
* Adds the HttpListener. The pending connection
* is started, so the client will receive
* messages from the server.
* @param l HttpListener to remove
* @return void
* @throws TooManyListenersException Thrown if more then one
* HttpListener is added.
*/
public void addHttpListener (HttpListener l)
throws TooManyListenersException {
if ( _listener == null ) {
_listener = l;
synchronized (this) {
_stop = false;
}
_pendingTID.start();
} else {
throw new TooManyListenersException();
}
}
/**
* Convience method to send the PENDING connection to
* the server
* @return void
* @throws IOException Thrown if a problem occurs while setting
* up the pending message.
*/
private URLConnection _sendPending () throws IOException {
URL url = new URL (_url);
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput (true);
return connection;
}
/**
* Thread used to maintain the pending connection
* @return void
*/
public void run() {
boolean s;
do {
URLConnection connection;
int length;
8: PERFORMANCE TECHNIQUES 389
try {
connection = _sendPending();
DataOutputStream output = new DataOutputStream
(connection.getOutputStream());
output.writeInt (PENDING);
output.flush();
output.close();
output = null;
}
synchronized (this) {
s = _stop;
}
}while ( s == false );
/**
* Sends a message to the server
* @param data Array of bytes to send
* @return void
* @throws IOException Thrown if a problem occurs while sending
* the message
*/
synchronized public byte[] send (byte data[])
throws IOException {
byte buffer[];
// Establish a connection
URL url = new URL (_url);
URLConnection connection = url.openConnection();
connection.setUseCaches (false);
connection.setDoOutput(true);
int length;
DataInputStream input =
new DataInputStream (
new BufferedInputStream (connection.getInputStream()));
int type = input.readInt();
if ( type == HttpClient.DATA ) {
length = input.readInt();
buffer = new byte[length];
input.readFully (buffer);
} else {
buffer = null;
throw new IOException ("Unknown Response Type");
}
input.close();
return buffer;
}
}
8: PERFORMANCE TECHNIQUES 391
JDCConnectionDriver
package pool;
import java.sql.*;
import java.util.*;
JDCConnectionPool
package pool;
import java.sql.*;
import java.util.*;
import java.io.*;
392 8: PERFORMANCE TECHNIQUES
JDCConnection
package pool;
import java.sql.*;
import java.util.*;
import java.io.*;
} catch (Exception e) {
return false;
}
return true;
}
public boolean inUse() {
return inuse;
}
public long getLastUse() {
return timestamp;
}
public void close() throws SQLException {
pool.returnConnection(this);
}
protected void expireLease() {
inuse=false;
}
protected Connection getConnection() {
return conn;
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
}
public CallableStatement prepareCall(String sql) throws SQLException {
return conn.prepareCall(sql);
}
public Statement createStatement() throws SQLException {
return conn.createStatement();
}
public String nativeSQL(String sql) throws SQLException {
return conn.nativeSQL(sql);
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
conn.setAutoCommit(autoCommit);
}
public boolean getAutoCommit() throws SQLException {
return conn.getAutoCommit();
}
public void commit() throws SQLException {
conn.commit();
}
public void rollback() throws SQLException {
conn.rollback();
}
public boolean isClosed() throws SQLException {
return conn.isClosed();
}
public DatabaseMetaData getMetaData() throws SQLException {
return conn.getMetaData();
}
public void setReadOnly(boolean readOnly) throws SQLException {
conn.setReadOnly(readOnly);
}
8: PERFORMANCE TECHNIQUES 395
RegistrationBean
package registration;
import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.sql.*;
}
}
public String getEmailAddress() throws RemoteException {
return emailaddress;
}
public String getUser() throws RemoteException {
return theuser;
}
public int adjustAccount(double amount) throws RemoteException {
balance=balance+amount;
return(0);
}
public double getBalance() throws RemoteException {
return balance;
}
public RegistrationPK ejbCreate(String theuser, String password,
String emailaddress, String creditcard)
throws CreateException, RemoteException {
System.out.println(“registration create”);
this.theuser=theuser;
this.password=password;
this.emailaddress=emailaddress;
this.creditcard=creditcard;
this.balance=0;
Connection con = null;
PreparedStatement ps = null;;
try {
con=getConnection();
ps=con.prepareStatement(“insert into registration (theuser,
password, emailaddress, creditcard, balance) values (?, ?, ?, ?, ?)”);
ps.setString(1, theuser);
ps.setString(2, password);
ps.setString(3, emailaddress);
ps.setString(4, creditcard);
ps.setDouble(5, balance);
if(ps.executeUpdate() != 1) {
System.out.println(“registration create failed”);
throw new CreateException (“JDBC did not create any row”);
}
RegistrationPK primaryKey = new RegistrationPK();
primaryKey.theuser = theuser;
return primaryKey;
} catch (CreateException ce) {
throw ce;
} catch (SQLException sqe) {
throw new CreateException (sqe.getMessage());
} finally {
try {
ps.close();
con.close();
} catch (Exception ignore) {}
}
}
8: PERFORMANCE TECHNIQUES 397
With the auction application tested, debugged, and tuned, you are ready to deploy it. In this
chapter, Administration applet replaces the AuctionClient (page 270) application so you can
see how to deploy an applet, which is a little more involved than deploying an application.
To deploy the complete application, you bundle the application files, move the application
files to their production locations, install Java™ Plug-In so auction administrators can run the
Administration applet from their browsers, and install the Administration applet policy file.
Java Plug-In is needed because the Administration applet is written with JDK 1.2 APIs, but
the administrators' browsers will likely run an earlier version of the Java Runtime Environ-
ment™ (JRE) software.
This chapter explains how to use the Java Archive (JAR) file format to bundle and deploy the
application files, and how to install Java Plug-In and a security policy file for the Solaris™
and Win32 platforms to run the Administration applet.
jar is the Java Archive command. If you type jar with no options, you get the following help
screen. You can see from the help screen that the cf options to the jar command mean create
a new JAR file named HTML.jar and put the list of files that follows into it. The new JAR file
is placed in the current directory.
kq6py% jar
Usage: jar {ctxu}[vfm0M][jar-file][manifest-file][-C dir] files ...
Options:
-c create new archive
-t list table of contents for archive
-x extract named (or all) files from archive
-u update existing archive
-v generate verbose output on standard output
-f specify archive file name
-m include manifest information from specified manifest file
-0 store only; use no ZIP compression
-M Do not create a manifest file for the entries
-C change to the specified directory and include the following file
9: DEPLOYING THE AUCTION APPLICATION 401
If any file is a directory then it is processed recursively. The manifest file name
and the archive file name needs to be specified in the same order the 'm' and 'f'
flags are specified.
Example 1: to archive two class files into an archive called classes.jar: jar cvf
classes.jar Foo.class Bar.class
Example 2: use an existing manifest file 'mymanifest' and archive all the files in
the foo/ director into 'classes.jar': jar cvfm classes.jar mymanifest -C foo/ .
To deploy the HTML files, all you have to do is move the HTML.jar file to a publicly acces-
sible directory under the web server and decompress the JAR file:
Note: If you included a full or relative pathname when you added the files to the JAR file, the
files are placed in the same directory structure when they are unpacked.
The JAR file contains a manifest file, META-INF/MANIFEST.MF that the jar tool automatically
placed there. A manifest file contains information about the files packaged in the JAR file.
You can tailor this information to enable JAR file functionality such as electronic signing,
version control, package sealing, and more. You can find more information on manifest files
on the web at http://java.sun.com/docs/books/tutorial/jar/basics/manifest.html.
Note: Because there are so many files, these steps bundle the example code into four JAR files,
one each for the auction, registration, bidder, and seller packages. You could also
bundle all the packages into one JAR file and deploy that instead.
auction Package
These are the application files in the auction package that make up the AuctionServlet serv-
let and AuctionItemBean Enterprise Bean. Because they are all to be installed in an auction
directory accessible to the production Enterprise JavaBeans server, bundle them together so
402 9: DEPLOYING THE AUCTION APPLICATION
they can be unpacked in one step in the destination directory and placed in the auction subdi-
rectory.
• auction.AuctionServlet.class
• auction.AuctionItem.class
• auction.AuctionItemBean.class
• auction.AuctionItemHome.class
• auction.AuctionItemPK.class
• auction.DeploymentDescriptor.txt
• AuctionItemBeanHomeImpl_ServiceStub.class
• WLStub1h1153e3h2r4x3t5w6e82e6jd412c.class
• WLStub364c363d622h2j1j422a4oo2gm5o.class
• WLSkel1h1153e3h2r4x3t5w6e82e6jd412c.class
• WLSkel364c363d622h2j1j422a4oo2gm5o.class
Here is how to bundle them. Everything goes on one line, and the command is executed one
directory above where the class files are located.
Unix:
Win32:
Once the JAR file is copied to the destination directory for the Enterprise beans, unpack it as
follows. The extraction creates an auction directory with the class files in it.
registration Package
Here are the application files in the registration package that make up the Registration Enter-
prise Bean.
• registration.Registration.class
• registration.RegistrationBean.class
• registration.RegistrationHome.class
• registration.RegistrationPK.class
• registration.DeploymentDescriptor.txt
9: DEPLOYING THE AUCTION APPLICATION 403
• RegistrationBeanHomeImpl_ServiceStub.class
• WLStub183w4u1f4e70p6j1r4k6z1x3f6yc21.class
• WLStub4z67s6n4k3sx131y4fi6w4x616p28.class
• WLSkel183w4u1f4e70p6j1r4k6z1x3f6yc21.class
• WLSkel4z67s6n4k3sx131y4fi6w4x616p28.class
Here is how to bundle them. Everything goes on one line, and the command is executed one
directory above where the class files are located.
Unix:
Win32:
Once the JAR file is copied to the destination directory for the Enterprise beans, unpack it as
follows. The extraction creates a registration directory with the class files in it.
bidder Package
Here are the application files in the bidder package that make up the Bidder Enterprise Bean.
• bidder.Bidder.class
• bidder.BidderHome.class
• bidder.BidderBean.class
• bidder.DeploymentDescriptor.txt
• BidderBeanEOImpl_ServiceStub.class
• BidderBeanHomeImpl_ServiceStub.class
• WLStub1z35502726376oa1m4m395m4w5j1j5t.class
• WLStub5g4v1dm3m271tr4i5s4b4k6p376d5x.class
• WLSkel1z35502726376oa1m4m395m4w5j1j5t.class
• WLSkel5g4v1dm3m271tr4i5s4b4k6p376d5x.class
Here is how to bundle them. Everything goes on one line, and the command is executed one
directory above where the class files are located.
Unix:
404 9: DEPLOYING THE AUCTION APPLICATION
Win32:
Once the JAR file is copied to the destination directory for the Enterprise beans, unpack it as
follows. The extraction creates a bidder directory with the class files in it.
seller Package
Here are the application files in the seller package that make up the Seller Enterprise Bean.
• seller.Seller.class
• seller.SellerHome.class
• seller.SellerBean.class
• seller.DeploymentDescriptor.txt
• SellerBeanEOImpl_ServiceStub.class
• SellerBeanHomeImpl_ServiceStub.class
• WLStub3xr4e731e6d2x3b3w5b693833v304q.class
• WLStub86w3x4p2x6m4b696q4kjp4p4p3b33.class
• WLSkel3xr4e731e6d2x3b3w5b693833v304q.class
• WLSkel86w3x4p2x6m4b696q4kjp4p4p3b33.class
Here is how to bundle them. Everything goes on one line, and the command is executed one
directory above where the class files are located.
Unix:
Win32:
Once the JAR file is copied to the destination directory for the Enterprise beans, unpack it as
follows. The extraction creates a seller directory with the class files in it.
grant {
permission java.lang.RuntimePermission "queuePrintJob";
};
Here is the jar command to bundle them. Everything goes on one line, and the command is
executed where the policy file is located which is one directory above where the class files
are located.
Unix:
Win32:
To deploy the applet, copy the applet.jar file to the destination applet directory and extract it
as follows. The extraction creates an admin directory with the Administration applet class
files in it.
This section explains how to install Java Plug-In with Netscape Communicator on the
Solaris operating system.
Get Downloads
To install and use Java Plug-In on Solaris 2.6 or Solaris 7, you need the following down-
loads. Put the downloads in a directory anywhere you want.
• Java Plug-In for Solaris operating systems. It is available for either Intel or Sparc plat-
forms.
• Java Plug-In patches for either Solaris 2.6 or Solaris 7, depending on which one you
have.
• Netscape Communicator 4.5.1 or newer (webstart version).
• Java Plug-In HTML Converter
These instructions were tested on a Sun Microsystems Ultra 2 running Solaris 2.6 with
Netscape Communicator 4.5.1.
plugin-12-webstart-sparc/Java_Plug-in_1.2.2/common/Docs/en/
Users_Guide_Java_Plug-in.html
The user guide explains how to install Java Plug-In. There are several easy ways to do it, and
the command sequence below is one quick way that installs Java Plug-In in the default /opt/
NSCPcom directory using the pkgadd command:
su
<root password>
cd ~/plugin-12-webstart-sparc
pkgadd -d ./Java_Plug-in_1.2.2/sparc/Product
cd ~/JPI1.2-Patches-Solaris2.6-sparC
su
<password>
kq6py#ls
105210-19 105490-07 105568-13
kq6py#./105210-19/installpatch 105210-19
You will see this output when the patch is successfully installed:
Continue installing the patches one-by-one until all patches have successfully installed. The
user's guide provides a list of required and suggested patches and links to where you can
download additional suggested patches if you want to install them.
408 9: DEPLOYING THE AUCTION APPLICATION
cd ~/NETSCAPE/Netscape_Communicator_4.51/sparc/Product
su
<password>
pkgadd -d .
cd /opt/NSCPcom/j2pi
ControlPanel &
unzip htmlconv12.zip
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy
policy.url.3=file:/<mypolicyfile path and name>
cp admin.jar /home/zelda/public_html/
jar xvf applet.jar
The extraction places the policy file under the public_html directory and creates an admin
directory under the public_html directory with the applet class file in it. Make sure the policy
file in the public_html directory is named .java.policy and copy it to your home directory.
In the public_html directory, create an HTML file that invokes the Administration applet
class. Be sure to include the admin directory when you specify the applet class to the CODE
option. Note that when using Java Plug-In, you cannot have the browser load the class file
from the Java Archive (JAR) file.
<HTML>
<BODY>
<APPLET CODE=admin/AdminApplet.class
WIDTH=550
HEIGHT=150>
</APPLET>
</BODY>
</HTML>
java HTMLConverter
9: DEPLOYING THE AUCTION APPLICATION 411
In the HTML Converter graphical user interface shown in Figure 36, select One File, specify
the path to the admin.html file, and click the Convert button. After the conversion completes,
load the admin.html file in your browser.
Get Downloads
To install and use the Java Runtime Environment with Java Plug-In, you need the following
downloads. Put the downloads in a temporary directory.
• Java Runtime Environment with Java Plug-In for Win32 Platforms.
412 9: DEPLOYING THE AUCTION APPLICATION
Either way, install the Java 2 Runtime Environment with Java Plug-In by double-clicking its
icon and following the installation instructions. When the installation completes, you will
see the Java Plug-In control panel on your Windows Start menu under Programs.
unzip htmlconv12.zip
The user policy file is located in the user's home directory. The user policy file provides a
way to give certain users additional permissions over those granted to everyone on the sys-
tem. The permissions in the system file are combined with the permissions in the user file.
A program policy file can be located anywhere. It is specifically named when an application
is invoked with the java command or when an applet is invoked with applet viewer.
When an application or applet is invoked with a specific policy file, the permissions in that
policy file take the place of (are not combined with) permissions specified in the system or
user policy file. Program policy files are used for program testing or intranet deployment of
applets and applications.
policy.url.1=file:${java.home}\lib\security\java.policy
policy.url.2=file:${user.home}\java.policy
policy.url.3=file:\<mypolicyfile path and name>
Note: On Windows/NT machines, you might place the policy file in the C:\Winnt\Pro-
files\<userid>\java.policy directory.
The extraction places the policy file under public_html and creates an admin directory under
the public_html directory with the applet class file in it. Rename the policy file in the
public_html directory to java.policy and copy it to your home directory.
In the public_html directory, create an HTML file that invokes the Administration applet
class. Be sure to include the admin directory when you specify the applet class to the CODE
option. Note that when using Java Plug-In, you cannot have the browser load the class file
from the Java Archive (JAR) file.
<HTML>
<BODY>
<APPLET CODE=admin/AdminApplet.class
WIDTH=550
HEIGHT=150>
</APPLET>
</BODY>
</HTML>
java HTMLConverter
9: DEPLOYING THE AUCTION APPLICATION 415
In the HTML Converter graphical user interface shown in Figure 37, select One File, specify
the path to the admin.html file, and click the Convert button. After the conversion completes,
load the admin.html file in your browser.
This chapter concludes the book with security topics you should find useful--signing applets
and writing a security manager. The examples do not relate directly to the auction house, but
are simple and targeted to illustrate these concepts.
Signed Applets
A policy file can be defined to require a signature on all applets or applications that attempt
to run with the policy file. The signature is a way to verify that the applet or application is
from a reliable source and can be trusted to run with the permissions granted in the policy
file.
If a policy file requires a signature, an applet or application can get the access granted by the
policy file only if it has the correct signature. If the applet or application has the wrong sig-
nature or no signature, it will not get access to the file.
This section walks through an example of signing an applet, verifying the signature, and run-
ning the applet with a policy file.
signed. This example shows you how to sign and grant permission to an applet so it can cre-
ate demo.ini in the user's home directory when it executes in Applet Viewer.
These files are used for the example. You can copy them to or create them in your working
directory.
• SignedAppletDemo (page 426) source file containing the applet code
• Write.jp policy file granting access to the user's home directory
/* AUTOMATICALLY GENERATED ON Mon Sep 14 09:55:03 PDT 1998*/
/* DO NOT EDIT */
keystore "raystore";
<applet code=”SignedAppletDemo.class”
archive=”SSignedApplet.jar”
width=400 height=400>
<param name=file value=”/etc/inet/hosts”>
</applet>
10: SIGNED APPLETS & SECURITY MANAGERS 419
Usually an applet is bundled and signed by an intranet developer and handed off to the end
user who verifies the signature and runs the applet. In this example, the intranet developer
performs Steps 1 through 5 and Ray, the end user, performs Steps 6 through 8. But, to keep
things simple for this example, all steps occur in the same working directory.
1. Compile the applet
2. Create a JAR file
3. Generate Keys
4. Sign the JAR file
5. Export the Public Key Certificate
6. Import the Certificate as a Trusted Certificate
7. Create the policy file
8. Run the applet
Intranet Developer
Susan, the intranet developer, bundles the applet executable in a JAR file, signs the JAR file,
and exports the public key certificate.
1: Compile the Applet
In her working directory, Susan uses the javac command to compile the SignedApplet-
Demo.java class. The output from the javac command is the SignedAppletDemo.class.
javac SignedAppletDemo.java
3: Generate Keys
A JAR file is signed with the private key of the creator of the JAR file and the signature is
verified by the recipient of the JAR file with the public key in the pair. The certificate is a
statement from the owner of the private key that the public key in the pair has a particular
value so the person using the public key can be assured the public key is authentic. Public
and private keys must already exist in the keystore database before jarsigner can be used to
sign or verify the signature on a JAR file.
420 10: SIGNED APPLETS & SECURITY MANAGERS
Susan creates a keystore database named compstore that has an entry for a newly generated
public and private key pair with the public key in a certificate using the keytool command. In
her working directory, Susan creates a keystore database and generates the keys:
The above keytool -genkey command invocation generates a key pair that is identified by the
alias signFiles. Subsequent keytool command invocations use this alias and the key pass-
word (-keypass kpi135) to access the private key in the generated pair.
The generated key pair is stored in a keystore database called compstore (-keystore comp-
store) in the current directory, and accessed with the compstore password (-storepass
ab987c).
The -dname “cn=jones” option specifies an X.500 Distinguished Name with a common-
Name (cn) value. X.500 Distinguished Names identify entities for X.509 certificates. In this
example, Susan uses her last name, Jones, for the common name. She could use any com-
mon name that suits her purposes. You can view all keytool options and parameters by typ-
ing:
keytool -help
The -storepass ab987c and -keystore compstore options specify the keystore database and
password where the private key for signing the JAR file is stored. The -keypass kpi135
option is the password to the private key, SSignedApplet.jar is the name of the signed JAR
file, and signFiles is the alias to the private key. jarsigner extracts the certificate from the
keystore whose entry is signFiles and attaches it to the generated signature of the signed JAR
file.
5: Export the Public Key Certificate
The public key certificate is sent with the JAR file to the end user who will be using the
applet. That person uses the certificate to authenticate the signature on the JAR file. A certif-
icate is sent by exporting it from the compstore database.
10: SIGNED APPLETS & SECURITY MANAGERS 421
In her working directory, Susan uses keytool to copy the certificate from compstore to a file
named CompanyCer.cer as follows:
As the last step, Susan posts the JAR and certificate files to a distribution directory on a web
page.
End User
Ray, the end user, downloads the JAR file from the distribution directory, imports the certifi-
cate, creates a policy file granting the applet access, and runs the applet.
6: Import Certificate as a Trusted Certificate
Ray downloads SSignedApplet.jar and CompanyCer.cer to his home directory. Ray must
now create a keystore database (raystore) and import the certificate into it using the alias
company. Ray uses keytool in his home directory to do this:
Note: Type everything on one line and put a space after Write.jp
The -J-Djava.security.policy=Write.jp option tells Applet Viewer to run the applet refer-
enced in the SignedApplet.html file with the Write.jp policy file.
Note: The Policy file can be stored on a server and specified in the appletviewer invocation as
a URL.
cific files. The implementation includes access verification code so once the end user makes
it through the password check, he or she still needs the file read and write permissions in his
or her policy file.
The example consists of the FileIO application, and the PasswordSecurityManager program
that provides the custom security manager implementation.
The custom security manager for this program prompts the end user to enter a password
before it allows FileIO to write text to or read text from a file. The main method of FileIO
creates a custom security manager called PasswordSecurityManager.
public static void main(String[] args){
BufferedReader buffy = new BufferedReader(
new InputStreamReader(System.in));
try {
System.setSecurityManager(
new PasswordSecurityManager(“pwd”, buffy));
} catch (SecurityException se) {
System.err.println(“SecurityManager already set!”);
}
password instance variable contains the actual password, and the buffy instance variable is
an input buffer that stores the end user’s password input.
public class PasswordSecurityManager extends SecurityManager{
private String password;
private BufferedReader buffy;
The accessOK method prompts the end user for a password, verifies the password, and
returns true if the password is correct and false if it is not.
private boolean accessOK() {
int c;
String response;
System.out.println(“Password, please:”);
try {
response = buffy.readLine();
if (response.equals(password))
return true;
else
return false;
} catch (IOException e) {
return false;
}
}
Verify Access
The SecurityManager parent class provides methods to verify file system read and write
access. The checkRead and checkWrite methods each have a version that accepts a String
and another version that accepts a file descriptor. This example overrides only the String
versions to keep the example simple, and because the FileIO program accesses directories
and files as Strings.
//API Ref :void checkRead(String filename)
public void checkRead(String filename) {
if((filename.equals(File.separatorChar + “home” +
File.separatorChar + “monicap” +
File.separatorChar + “text2.txt”))){
if(!accessOK()){
super.checkRead(filename);
throw new SecurityException(“No Way!”);
} else {
FilePermission perm = new FilePermission(
File.separatorChar + “home” +
10: SIGNED APPLETS & SECURITY MANAGERS 425
File.separatorChar + “monicap” +
File.separatorChar + “text2.txt”, “read”);
checkPermission(perm);
}
}
}
//API Ref :void checkWrite(String filename)
public void checkWrite(String filename) {
if((filename.equals(File.separatorChar + “home” +
File.separatorChar + “monicap” +
File.separatorChar + “text.txt”))){
if(!accessOK()){
super.checkWrite(filename);
throw new SecurityException(“No Way!”);
} else {
FilePermission perm = new FilePermission(
File.separatorChar + “home” +
File.separatorChar + “monicap” +
File.separatorChar + “text.txt” , “write”);
//API Ref :void checkPermission(Permission perm)
checkPermission(perm);
}
}
}
}
The checkWrite method is called before the end user input is written to the output file. This
is because the FileOutputStream class calls SecurityManager.checkWrite first.
The custom implementation for SecurityManager.checkWrite tests for the pathname
/home/monicap/text.txt, and if true prompts the end user for the password. If the pass-
word is correct, the checkWrite method performs the access check by creating an instance
of the required permission and passing it to the SecurityManager.checkPermission
method. This check will succeed if the security manager finds a system, user, or program
policy file with the specified permission. Once the write operation completes, the end user is
prompted for the password two more times. The first time to read the /home/monicap direc-
tory, and the second time to read the text2.txt file. An access check is performed before
the read operation takes place.
Policy File
Here is the policy file the FileIO program needs for its read and write operations. It also
grants permission to the custom security manager to access the event queue on behalf of the
application and show the application window without the warning banner.
grant {
permission java.io.FilePermission “${user.home}/text.txt”, “write”;
permission java.util.PropertyPermission “user.home”, “read”;
permission java.io.FilePermission “${user.home}/text2.txt”, “read”;
426 10: SIGNED APPLETS & SECURITY MANAGERS
Reference Information
A: Security and Permissions (page 431) describes the available permissions and explains the
consequences of granting permissions. One way to use this information is to help you limit
what permissions a given applet or application might need to successfully execute. Another
way to use this information is to educate yourself on the ways in which a particular permis-
sion can be exploited by malicious code.
B: Classes, Methods, and Permissions (page 447) provides lists of Java 2 platform software
methods that are implemented to perform security access checks, the permission each
requires, and the java.security.SecurityManager method called to perform the access
check. You can use this reference to write your own security manager implementations or
when you implement abstract methods that perform security-related tasks.
C: Security Manager Methods (page 465) lists the permissions checked for by the Securi-
tyManager methods.
SignedAppletDemo
//File: @(#)SignedAppletDemo.java
//(#)author: Satya Dodda
import java.applet.Applet;
import java.awt.Graphics;
import java.io.*;
import java.awt.Color;
public class SignedAppletDemo extends Applet {
public String test() {
setBackground(Color.white);
10: SIGNED APPLETS & SECURITY MANAGERS 427
PasswordSecurityManager
import java.io.*;
import java.security.AccessController;
FileIO
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
} else {
//Save text to file
text.setText("Text to save to file:");
textField.setText("");
button.setText("Click Me");
_clickMeMode = true;
}
}
}
public static void main(String[] args){
FileIO frame = new FileIO();
frame.setTitle("Example");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
}
}
A: SECURITY AND PERMISSIONS 431
All applets and any applications invoked with a security manager must be granted explicit
permission to access local system resources apart from accessing the directory where the
program is invoked and its subdirectories. The Java™ platform provides permissions to allow
various levels of access to different types of local information. Because permissions let an
applet or application override the default security policy, you should be very careful when
you assign permissions to not create an opening for malicious code to attack your system.
This appendix describes the available permissions and explains how each permission can
create an opening for malicious attacks. One way to use this information is to help you limit
what permissions a given applet or application might need to successfully execute. Another
way to use this information is to educate yourself on the ways in which a particular permis-
sion can be exploited by malicious code so you can take steps against that.
As a safeguard, never trust an unknown applet or application. Always check the code care-
fully against the information in this appendix to be sure you are not giving malicious code
permission to cause serious problems on the local system.
Overview
Permissions are granted to a program with a policy file. A policy file contains permissions
for specific access. A permission consists of the permission name, a target, and in some
cases, a comma-separated list of actions.
For example, the following policy file entry specifies a java.io.FilePermission permission
that grants read access (the action) to the ${user.home}/text2.txt target.
grant {
permission java.io.FilePermission "${user.home}/text2.txt", "read";
};
There is one policy file for the Java platform installation (system) and an optional policy file
for each user. The system policy file is in {java.home}/lib/security/java.policy, and the user
policy file is in each user's home directory. The system and user policy files are combined.
So, for example, there could be a system policy file with very few permissions granted to all
users on the system, and individual policy files granting additional permissions to certain
users.
To run an application with the security manager and a policy file named polfile in the user's
home directory, type:
To run an applet in appletviewer with a policy file named polfile in the user's home directory,
type:
When running an applet in a browser, the browser looks for the user and system policy files
to find the permissions the applet needs to access local system resources on behalf of the
user who downloaded the applet.
Another way to determine which permission your program needs is to browse B: Classes,
Methods, and Permissions (page 447). This appendix tells you which Java 2 platform soft-
ware methods are prevented from executing without the listed permission. The information
is also useful for developers who want to write their own security manager to customize the
verifications and approvals needed in a program.
Here is a short example to show how to translate the first couple of lines in a stack trace to a
policy file entry. The first line tells you access is denied. This means this stack trace was gen-
erated because the program tried to access a system resource without the proper permission.
The second line means you need a java.net.SocketPermission that gives the program permis-
sion to connect to and resolve the host name for Internet Protocol (IP) address
129.144.176.176, port 1521.
To turn this into a policy file entry, list the permission name, a target, and an action list as
follows where java.net.SocketPermission is the permission name, 129.144.176.176:1521 is
the target, and connect,resolve is the action list.
grant {
permission java.net.SocketPermission "129.144.176.176:1521",
"connect,resolve";
};
AllPermission
java.security.AllPermission specifies all permissions in the system for all possible targets
and actions. This permission should be used only during testing because it grants permission
to run with all security restrictions disabled as if there were no security manager.
grant {
permission java.security.AllPermission;
};
AWTPermission
java.awt.AWTPermission grants access to the following Abstract Window Toolkit (AWT)
targets. The possible targets are listed by name with no action list.
434 A: SECURITY AND PERMISSIONS
grant {
permission java.awt.AWTPermission "accessClipboard";
permission java.awt.AWTPermission "accessEventQueue";
permission java.awt.AWTPermission "showWindowWithoutWarningBanner";
};
accessClipboard: This target grants permission to post information to and retrieve informa-
tion from the AWT clipboard. Granting this permission could allow malicious code to share
potentially sensitive or confidential information.
accessEventQueue: This target grants permission to access the AWT event queue. Granting
this permission could allow malicious code to peek at and remove existing events from the
system, or post bogus events that could cause the application or applet to perform malicious
actions.
listenToAllAWTEvents: This target grants permission to listen to all AWT events through-
out the system. Granting this permission could allow malicious code to read and exploit con-
fidential user input such as passwords.
Each AWT event listener is called from within the context of that event queue's EventDis-
patchThread, so if the accessEventQueue permission is also enabled, malicious code could
modify the contents of AWT event queues throughout the system, which can cause the appli-
cation or applet to perform unintended and malicious actions.
readDisplayPixels: This target grants permission to read pixels back from the display
screen. Granting this permission could allow interfaces such as java.awt.Composite that
allow arbitrary code to examine pixels on the display to include malicious code that snoops
on user activities.
showWindowWithoutWarningBanner: This target grants permission to display a window
without also displaying a banner warning that the window was created by an applet. Without
this warning, an applet might pop up windows without the user knowing they belong to an
applet. This could be a problem in environments where users make security-sensitive deci-
sions based on whether the window belongs to an applet or an application. For example, dis-
abling the banner warning might trick the end user into entering sensitive user name and
password information.
FilePermission
java.io.FilePermission grants access to a file or directory. The targets consist of the target
pathname and a comma-separated list of actions.
This policy file grants read, write, delete, and execute permission to all files.
A: SECURITY AND PERMISSIONS 435
grant {
permission java.io.FilePermission
"<<ALL FILES>>", "read, write, delete, execute";
};
This policy file grants read and write permission to text.txt in the user's home directory.
grant {
permission java.io.FilePermission
"${user.home}/text.txt", "read, write";
};
You can use the following wild cards to specify the target pathname.
• A pathname that ends in /* where /* is the file separator character, indicates a directory
and all the files contained in that directory.
• A pathname that ends with /- indicates a directory, and recursively, all files and subdi-
rectories contained in that directory.
• A pathname consisting of a single asterisk (*) indicates all files in the current directory.
• A pathname consisting of a single dash (-) indicates all files in the current directory,
and recursively, all files and subdirectories contained in the current directory.
The actions are specified in a list of comma-separated keywords and have the following
meanings:
• read: Permission to read a file or directory.
• write: Permission to write to and create a file or directory.
• execute: Permission to execute a file or search a directory.
• delete: Permission to delete a file or directory.
When granting file permissions, always think about the implications of granting read and
especially write access to various files and directories. The <<ALL FILES>> permission
with write action is especially dangerous because it grants permission to write to the entire
file system. This means the system binary can be replaced, which includes the Java1 Virtual
Machine (VM) runtime environment.
NetPermission
java.net.NetPermission grants access to various network targets. The possible targets are
listed by name with no action list.
436 A: SECURITY AND PERMISSIONS
grant {
permission java.net.NetPermission "setDefaultAuthenticator";
permission java.net.NetPermission "requestPasswordAuthentication";
};
setDefaultAuthenticator: This target grants permission to set the way authentication infor-
mation is retrieved when a proxy or HTTP server asks for authentication. Granting this per-
mission could mean malicious code can set an authenticator that monitors and steals user
authentication input as it retrieves the input from the user.
requestPasswordAuthentication: This target grants permission to ask the authenticator
registered with the system for a password. Granting this permission could mean malicious
code might steal the password.
specifyStreamHandler: This target grants permission to specify a stream handler when
constructing a Uniform Resource Locator (URL). Granting this permission could mean
malicious code might create a URL with resources to which it would not normally have
access, or specify a stream handler that gets the actual bytes from somewhere to which it
does have access. This means the malicious code could trick the system into creating a Pro-
tectionDomain/CodeSource for a class even though the class really did not come from that
location.
PropertyPermission
java.util.PropertyPermission grants access to system properties. The java.util.Properties
class represents persistent settings such as the location of the installation directory, the user
name, or the user's home directory.
grant {
permission java.util.PropertyPermission "java.home", "read";
permission java.util.PropertyPermission "os.name", "write";
permission java.util.PropertyPermission "user.name", "read, write";
};
The target list contains the name of the property; for example, java.home or os.name. The
naming convention for the properties follows the hierarchical property naming convention,
and includes wild cards. An asterisk at the end of the property name, after a dot (.), or alone
signifies a wild card match. For example, java.* or * are valid, but *java or a*b are invalid.
The actions are specified in a list of comma-separated keywords, and have the following
meanings:
• read: Permission to read (get) a property.
A: SECURITY AND PERMISSIONS 437
ReflectPermission
java.lang.reflect.ReflectPermission grants permission for various reflective operations. The
possible targets are listed by name with no action list.
grant {
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};
suppressAccessChecks: This target grants permission to access fields and invoke methods
in a class. This includes public, protected, and private fields and methods. Granting this per-
mission could reveal confidential information and make normally unavailable methods
accessible to malicious code.
RuntimePermission
java.lang.RuntimePermission grants access to various runtime targets such as the class
loader, Java VM, and thread. The possible targets are listed by name with no action list.
grant {
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.RuntimePermission "getClassLoader";
permission java.lang.RuntimePermission "exitVM";
permission java.lang.RuntimePermission "setFactory";
permission java.lang.RuntimePermission "setIO";
permission java.lang.RuntimePermission "modifyThread";
permission java.lang.RuntimePermission "modifyThreadGroup";
permission java.lang.RuntimePermission "getProtectionDomain";
permission java.lang.RuntimePermission "setProtectionDomain";
permission java.lang.RuntimePermission "readFileDescriptor";
permission java.lang.RuntimePermission "writeFileDescriptor";
permission java.lang.RuntimePermission "loadLibrary.<library name>";
permission java.lang.RuntimePermission
"accessClassInPackage.<package name>";
permission java.lang.RuntimePermission
438 A: SECURITY AND PERMISSIONS
"defineClassInPackage.<package name>";
permission java.lang.RuntimePermission
"accessDeclaredMembers.<class name>";
permission java.lang.RuntimePermission "queuePrintJob";
};
The naming convention for target information where a library, package, or class name is
added follows the hierarchical property naming convention, and includes wild cards. An
asterisk at the end of the target name, after a dot (.), or alone signifies a wild card match. For
example, loadLibrary.* or * are valid, but *loadLibrary or a*b are not.
createClassLoader: This target grants permission to create a class loader. Granting this per-
mission might allow a malicious application to instantiate its own class loader and load
harmful classes into the system. Once loaded, the class loader could place these classes into
any protection domain and give them full permissions for that domain.
getClassLoader: This target grants permission to retrieve the class loader for the calling
class. Granting this permission could enable malicious code to get the class loader for a par-
ticular class and load additional classes.
setContextClassLoader: This target grants permission to set the context class loader used
by a thread. System code and extensions use the context class loader to look up resources
that might not exist in the system class loader. Granting this permission allows code to
change which context class loader is used for a particular thread, including system threads.
This can cause problems if the context class loader has malicious code.
setSecurityManager: This target grants permission to set or replace the security manager.
The security manager is a class that allows applications to implement a security policy.
Granting this permission could enable malicious code to install a less restrictive manager,
and thereby, bypass checks that would have been enforced by the original security manager.
createSecurityManager: This target grants permission to create a new security manager.
Granting this permission could give malicious code access to protected and sensitive meth-
ods that might disclose information about other classes or the execution stack. It could also
allow the introduction of a weakened security manager.
exitVM: This target grants permission to halt the Java VM. Granting this permission could
allow malicious code to mount a denial-of-service attack by automatically forcing the VM to
stop.
setFactory: This target grants permission to set the socket factory used by the ServerSocket
or Socket class, or the stream handler factory used by the URL class. Granting this permis-
sion allows code to set the actual implementation for the socket, server socket, stream han-
dler, or Remote Method Invocation (RMI) socket factory. An attacker might set a faulty
implementation that mangles the data stream.
A: SECURITY AND PERMISSIONS 439
setIO: This target grants permission to change the value of the System.out, System.in, and
System.err standard system streams. Granting this permission could allow an attacker to
change System.in to steal user input, or set System.err to a null output stream, which would
hide any error messages sent to System.err.
modifyThread: This target grants permission to modify threads by calls to the stop, sus-
pend, resume, setPriority, and setName methods in the Thread class. Granting this permis-
sion could allow an attacker to start or suspend any thread in the system.
stopThread: This target grants permission to stop threads. Granting this permission allows
code to stop any thread in the system provided the code already has permission to access that
thread. Malicious code could corrupt the system by killing existing threads.
modifyThreadGroup: This target grants permission to modify threads by calls to the
destroy, resume, setDaemon, setmaxPriority, stop, and suspend methods of the ThreadGroup
class. Granting this permission could allow an attacker to create thread groups and set their
run priority.
getProtectionDomain: This target grants permission to retrieve the ProtectionDomain
instance for a class. Granting this permission allows code to obtain policy information for
that code source. While obtaining policy information does not compromise the security of
the system, it does give attackers additional information, such as local file names for exam-
ple, to better aim an attack.
readFileDescriptor: This target grants permission to read file descriptors. Granting this per-
mission allows code to read the particular file associated with the file descriptor, which is
dangerous if the file contains confidential data.
writeFileDescriptor: This target grants permission to write file descriptors. Granting this
permission allows code to write to the file associated with the descriptor, which is dangerous
if the file descriptor points to a local file.
loadLibrary.{library name}: This target grants permission to dynamically link the speci-
fied library. Granting this permission could be dangerous because the security architecture is
not designed to and does not extend to native code loaded by way of the java.lang.Sys-
tem.loadLibrary method.
accessClassInPackage.{package name}: This target grants permission to access the speci-
fied package by way of a class loader's loadClass method when that class loader calls the
SecurityManager.checkPackageAcesss method. Granting this permission gives code access
to classes in packages to which it normally does not have access. Malicious code may use
these classes to help in its attempt to compromise security in the system.
defineClassInPackage.{package name}: This target grants permission to define classes in
the specified package by way of a class loader's defineClass method when that class loader
440 A: SECURITY AND PERMISSIONS
SecurityPermission
java.security.SecurityPermission grants access to various security configuration parameters.
The possible targets are listed by name with no action list. Security permissions currently
apply to methods called on the following objects:
• java.security.Policy, which represents the system security policy for applications.
• java.security.Security, which centralizes all security properties and common security
methods. It manages providers.
• java.security.Provider, which represents an implementation of such things as security
algorithms (DSA, RSA, MD5, or SHA-1) and key generation.
• java.security.Signer, which manages private keys. Even though, Signer is deprecated,
the related permissions are available for backwards compatibility.
• java.security.Identity, which manages real-world objects such as people, companies, or
organizations whose identities can be authenticated using their public keys.
grant {
permission java.security.SecurityPermission "getPolicy";
permission java.security.SecurityPermission "setPolicy";
permission java.security.SecurityPermission "getProperty.os.name";
permission java.security.SecurityPermission "setProperty.os.name";
permission java.security.SecurityPermission “insertProvider.SUN";
permission java.security.SecurityPermission "removeProvider.SUN";
A: SECURITY AND PERMISSIONS 441
getPolicy: This target grants permission to retrieve the system-wide security policy. Grant-
ing this permission discloses which permissions would be granted to a given application or
applet. While revealing the policy does not compromise the security of the system, it does
provide malicious code with additional information it could use to better aim an attack.
setPolicy: This target grants permission to set the system-wide security policy. Granting this
permission could allow malicious code to grant itself all the necessary permissions to suc-
cessfully mount an attack an attack on the system.
getProperty.{key}: This target grants permission to retrieve the security property specified
by {key}. Depending on the particular key for which access has been granted, the code may
have access to the list of security providers and the location of the system-wide and user
security policies. While revealing this information does not compromise the security of the
system, it does provide malicious code with additional information which it may use to bet-
ter aim an attack.
setProperty.{key}: This target grants permission to set the security property specified by
{key}. This could include setting a security provider or defining the location of the system-
wide security policy. Malicious code that has permission to set a new security provider may
set a rogue provider that steals confidential information such as cryptographic private keys.
In addition, malicious code with permission to set the location of the system-wide security
policy may point it to a security policy that grants the attacker all the necessary permissions
it requires to successfully mount an attack on the system.
insertProvider.{provider name}: This target grants permission to add the new security pro-
vider specified by {provider name}. Granting this permission allows the introduction of a
possibly malicious provider that could do such things as disclose the private keys passed to
it. This is possible because the Security object, which manages the installed providers, does
not currently check the integrity or authenticity of a provider before attaching it.
442 A: SECURITY AND PERMISSIONS
carol[/home/luehe/identitydb.obj][not trusted].
SerializablePermission
java.io.SerializablePermission grants access to serialization operations. The possible targets
are listed by name with no action list.
grant {
permission java.io.SerializablePermission
"enableSubclassImplementation";
permission java.io.SerializablePermission
"enableSubstitution";
};
store confidential private field data in a way easily accessible to attackers; or, during deseri-
alization malicious code could deserialize a class with all its private fields zeroed out.
enableSubstitution: This target grants permission to substitute one object for another dur-
ing serialization or deserialization. Granting this permission could allow malicious code to
replace the actual object with one that has incorrect or malignant data.
SocketPermission
The java.net.SocketPermission permission grants access to a network by way of sockets. The
target is a host name and port address, and the action list specifies ways to connect to that
host. Possible connections are accept, connect, listen, and resolve.
This policy file entry allows a connection to and accepts connections on port 7777 on the
host puffin.eng.sun.com.
grant {
permission java.net.SocketPermission
"puffin.eng.sun.com:7777","connect, accept";
};
This policy file entry allows connections to, accepts connections on, and listens on any port
between 1024 and 65535 on the local host.
grant {
permission java.net.SocketPermission
"localhost:1024-","accept, connect, listen";
};
The host is expressed with the following syntax as a DNS name, as a numerical IP address,
or as localhost (for the local machine). The asterisk (*) wild card can be included once in a
DNS name host specification. If included, it must be in the left-most position, as in
*.sun.com.
The port or port range is optional. A port specification of the form N-, where N is a port
number, means all ports numbered N and above, while a specification of the form -N indi-
cates all ports numbered N and below.
The listen action is only meaningful when used with localhost, and the resolve (resolve host/
ip name service lookups) action is implied when any of the other actions are present.
A: SECURITY AND PERMISSIONS 445
Granting code permission to accept or make connections to remote hosts may be dangerous
because malevolent code can more easily transfer and share confidential data among parties
that might not otherwise have access to the data.
Note: On Unix platforms, only root is normally allowed access to ports lower than 1024.
446 A: SECURITY AND PERMISSIONS
B: CLASSES, METHODS, AND PERMISSIONS 447
A number of Java™ 2 platform methods are implemented to verify access permissions. This
means that before they execute, they verify that the system, user, or program has a policy file
with the required permissions for execution to continue. If no such permission is found, exe-
cution stops with an error condition.
The access verification code passes the required permissions to the security manager, and the
security manager checks that permission against the policy file permissions to determine
whether to allow access. This means that Java 2 platform API methods are associated with
specific permissions, and specific permissions are associated with specific java.secu-
rity.SecurityManager methods.
This appendix lists the Java 2 platform methods, the permission associated with each
method, and the java.security.SecurityManager method called to verify the existence of that
permission. You need this information when you implement certain abstract methods or cre-
ate your own security manager so you can include access verification code to keep your
implementations in line with Java 2 platform security policy. If you do not include access
verification code, your implementations will bypass the built-in Java 2 platform security
checks.
java.awt.Graphics2D
public abstract void setComposite(Composite comp)
java.Security.SecurityManager.checkPermission
java.awt.AWTPermission "readDisplayPixels"
Graphics2D context draws to a Component on the display screen and the Composite is a cus-
tom object rather than an AlphaComposite object.
java.awt.Toolkit
public void addAWTEventListener(AWTEventListener listener, long eventMask)
public void removeAWTEventListener(AWTEventListener listener)
checkPermission
java.awt.AWTPermission "listenToAllAWTEvents"
java.awt.Window
Window()
checkTopLevelWindow
java.awt.AWTPermission "showWindowWithoutWarningBanner"
java.beans.Beans
public static void setDesignTime(boolean isDesignTime)
public static void setGuiAvailable(boolean isGuiAvailable)
checkPropertiesAccess
java.util.PropertyPermissions "*", "read,write"
java.beans.Introspector
public static synchronized void setBeanInfoSearchPath(String path[])
checkPropertiesAccess
java.util.PropertyPermissions "*", "read,write"
450 B: CLASSES, METHODS, AND PERMISSIONS
java.beans.PropertyEditorManager
public static void registerEditor(Class targetType, Class editorClass)
public static synchronized void setEditorSearchPath(String path[])
checkPropertiesAccess
java.util.PropertyPermissions "*", "read,write"
java.io.File
public boolean delete()
public void deleteOnExit()
checkDelete(String)
java.io.FilePermission "{name}", "delete"
java.io.FileInputStream
FileInputStream(FileDescriptor fdObj)
checkRead(FileDescriptor)
java.lang.RuntimePermission "readFileDescriptor"
B: CLASSES, METHODS, AND PERMISSIONS 451
FileInputStream(String name)
FileInputStream(File file)
checkRead(String)
java.io.FilePermission "{name}", "read"
java.io.FileOutputStream
FileOutputStream(FileDescriptor fdObj)
checkWrite(FileDescriptor)
java.lang.RuntimePermission "writeFileDescriptor"
FileOutputStream(File file)
FileOutputStream(String name)
FileOutputStream(String name, boolean append)
checkWrite(String)
java.io.FilePermission "{name}", "write"
java.io.ObjectInputStream
protected final boolean enableResolveObject(boolean enable);
checkPermission
java.io.SerializablePermission "enableSubstitution"
protected ObjectInputStream()
protected ObjectOutputStream()
checkPermission
java.io.SerializablePermission "enableSubclassImplementation"
java.io.ObjectOutputStream
protected final boolean enableReplaceObject(boolean enable)
checkPermission
java.io.SerializablePermission "enableSubstitution"
java.io.RandomAccessFile
RandomAccessFile(String name, String mode)
RandomAccessFile(File file, String mode)
checkRead(String)
java.io.FilePermission "{name}", "read"
java.lang.Class
public static Class forName(String name, boolean initialize, ClassLoader loader)
checkPermission
java.lang.RuntimePermission("getClassLoader")
The access verification code for this method calls checkPermission and pass it
java.lang.RuntimePermission(“getClassLoader”) when loader is null and the caller's class
loader is not null.
public Class[] getClasses()
checkMemberAccess(this, Member.DECLARED)
java.lang.RuntimePermission "accessDeclaredMembers"
java.lang.RuntimePermission "accessClassInPackage.{pkgName}
The access verification code for this class and each of its superclasses calls checkMember-
Access(this, Member.DECLARED). If the class is in a package, checkPackageAccess({pkg-
Name}) is also called. By default, checkMemberAccess does not require permission if this
class's classloader is the same as that of the caller. Otherwise, it requires java.lang.Runtime-
Permission “accessDeclaredMembers”. If the class is in a package, java.lang.RuntimePer-
mission “accessClassInPackage.{pkgName}” is also required.
public ClassLoader getClassLoader()
checkPermission
java.lang.RuntimePermission "getClassLoader"
If the caller's class loader is null, or is the same as or an ancestor of the class loader for the
class whose class loader is being requested, no permission is needed. Otherwise,
java.lang.RuntimePermission “getClassLoader” is required.
public Class[] getDeclaredClasses()
public Field[] getDeclaredFields()
public Method[] getDeclaredMethods()
public Constructor[] getDeclaredConstructors()
public Field getDeclaredField(String name)
public Method getDeclaredMethod(...)
public Constructor getDeclaredConstructor(...)
checkMemberAccess(this, Member.DECLARED)
checkPackageAccess({pkgName})
java.lang.RuntimePermission "accessDeclaredMembers”
java.lang.RuntimePermission "accessClassInPackage.{pkgName}”
B: CLASSES, METHODS, AND PERMISSIONS 453
If Class is not in a package, the access verification code for these methods calls checkMem-
berAccess(this, Member.PUBLIC), but no permission is passed.
If Class is in a package, the access verification code for these methods should call check-
PackageAccess({pkgName}) and pass it checkPackageAccess({pkgName}).
public ProtectionDomain getProtectionDomain()
checkPermission
java.lang.RuntimePermission "getProtectionDomain"
java.lang.ClassLoader
ClassLoader()
ClassLoader(ClassLoader parent)
checkCreateClassLoader
java.lang.RuntimePermission "createClassLoader"
If the caller's class loader is null or is the same as or an ancestor of the class loader for the
class whose class loader is being requested, no permission is needed. Otherwise,
java.lang.RuntimePermission “getClassLoader” is required.
454 B: CLASSES, METHODS, AND PERMISSIONS
java.lang.Runtime
public Process exec(String command)
public Process exec(String command, String envp[])
public Process exec(String cmdarray[])
public Process exec(String cmdarray[], String envp[])
checkExec
java.io.FilePermission "{command}", "execute"
java.lang.SecurityManager
<all methods>
checkPermission
See C: Security Manager Methods (page 465).
java.lang.System
public static void exit(int status)
public static void runFinalizersOnExit(boolean value)
checkExit(status) where status is 0 for runFinalizersOnExit
java.lang.RuntimePermission "exitVM"
java.lang.Thread
public ClassLoader getContextClassLoader()
checkPermission
java.lang.RuntimePermission "getClassLoader"
If the caller's class loader is null or is the same as or an ancestor of the context class loader
for the thread whose context class loader is being requested, no permission is needed. Other-
wise, java.lang.RuntimePermission “getClassLoader” is required.
public void setContextClassLoader(ClassLoader cl)
checkPermission
java.lang.RuntimePermission "setContextClassLoader"
The access verification code should call checkAccess and pass it java.lang.RuntimePermis-
sion “modifyThread”, unless the current thread is trying to stop a thread other than itself. In
this case, the access verification code should call checkPermission and pass it
java.lang.RuntimePermission “stopThread”.
public final synchronized void stop(Throwable obj)
checkAccess(this).
checkPermission
java.lang.RuntimePermission "modifyThread"
java.lang.RuntimePermission "stopThread"
The access verification code should call checkAccess and pass it java.lang.RuntimePermis-
sion “modifyThread” unless the current thread is trying to stop a thread other than itself or
obj is not an instance of ThreadDeath. In this case, the access verification code should call
checkPermission and pass it java.lang.RuntimePermission “stopThread”.
Thread()
Thread(Runnable target)
Thread(String name)
Thread(Runnable target, String name)
checkAccess({parentThreadGroup})
java.lang.RuntimePermission "modifyThreadGroup"
java.lang.ThreadGroup
public final void checkAccess()
public int enumerate(Thread list[])
public int enumerate(Thread list[],boolean recurse)
public int enumerate(ThreadGroup list[])
public int enumerate(ThreadGroup list[],boolean recurse)
public final ThreadGroup getParent()
public final void setDaemon(boolean daemon)
public final void setMaxPriority(int pri)
public final void suspend()
public final void resume()
B: CLASSES, METHODS, AND PERMISSIONS 457
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent,
String name)
checkAccess({parentThreadGroup})
java.lang.RuntimePermission "modifyThreadGroup"
The access verification code for this method also requires java.lang.RuntimePermission
“modifyThread” because the java.lang.Thread interrupt() method is called for each thread in
the thread group and in all of its subgroups.
public final void stop()
checkAccess(this)
java.lang.RuntimePermission "modifyThreadGroup"
java.lang.RuntimePermission "modifyThread"
java.lang.RuntimePermission "stopThread"
The access verification code for this method also requires java.lang.RuntimePermission
“modifyThread” and possibly java.lang.RuntimePermission “stopThread” because the
java.lang.Thread stop() method is called for each thread in the thread group and in all of its
subgroups.
java.lang.reflect.AccessibleObject
public static void setAccessible(...)
public void setAccessible(...)
checkPermission
java.lang.reflect.ReflectPermission "suppressAccessChecks"
java.net.Authenticator
public static PasswordAuthentication
requestPasswordAuthentication(InetAddress addr,int port,
String protocol, String prompt, String scheme)
checkPermission
java.net.NetPermission "requestPasswordAuthentication"
458 B: CLASSES, METHODS, AND PERMISSIONS
java.net.DatagramSocket
public void send(DatagramPacket p)
checkMulticast(p.getAddress())
checkConnect(p.getAddress().getHostAddress(), p.getPort())
java.net.SocketPermission((p.getAddress()).getHostAddress(), "accept,connect")
java.net.SocketPermission "{host}","resolve"
The access verification code for send calls checkMulticast in the following case:
if(p.getAddress().isMulticastAddress()) {
java.net.SocketPermission((p.getAddress()).getHostAddress(),"accept,connect")
}
The access verification code for send calls checkConnect in the following case:
else {
port = p.getPort();
host = p.getAddress().getHostAddress();
if (port == -1) {
java.net.SocketPermission
"{host}","resolve";
} else {
java.net.SocketPermission
"{host}:{port}","connect"
}
DatagramSocket(...)
checkListen({port})
The access verification code for this method calls checkListen and passes in socket permis-
sions as follows:
if (port == 0){
java.net.SocketPermission "localhost:1024-", "listen";
} else {
java.net.SocketPermission "localhost:{port}", "listen";
}
java.net.HttpURLConnection
public static void setFollowRedirects(boolean set)
checkSetFactory
java.lang.RuntimePermission "setFactory"
java.net.InetAddress
public String getHostName()
public static InetAddress[] getAllByName(String host)
public static InetAddress getLocalHost()
checkConnect({host}, -1)
java.net.SocketPermission "{host}", "resolve"
java.net.MulticastSocket
public void joinGroup(InetAddress mcastaddr)
public void leaveGroup(InetAddress mcastaddr)
checkMulticast(InetAddress)
java.net.SocketPermission(mcastaddr.getHostAddress(),"accept,connect")
The access verification code for send calls checkMulticast in the following case:
if(p.getAddress().isMulticastAddress()) {
java.net.SocketPermission((p.getAddress()).getHostAddress(), "accept,connect")
}
The access verification code for this method calls checkConnect in the following case:
} else {
port = p.getPort();
host = p.getAddress().getHostAddress();
if (port == -1) {
java.net.SocketPermission "{host}","resolve"
} else {
java.net.SocketPermission "{host}:{port}","connect"
}
MulticastSocket(...)
checkListen({port})
The access verification code for this method calls checkListen in the following case:
460 B: CLASSES, METHODS, AND PERMISSIONS
if (port == 0) {
java.net.SocketPermission "localhost:1024-", "listen";
} else {
java.net.SocketPermission "localhost:{port}","listen";
}
java.net.ServerSocket
ServerSocket(...)
checkListen({port})
The access verification code for this method calls checkListen in the following case:
if (port == 0) {
java.net.SocketPermission "localhost:1024-","listen";
} else {
java.net.SocketPermission "localhost:{port}","listen";
}
java.net.Socket
public static synchronized void setSocketImplFactory(...)
checkSetFactory
java.lang.RuntimePermission "setFactory"
Socket(...)
checkConnect({host}, {port})
java.net.SocketPermission "{host}:{port}", "connect"
java.net.URL
public static synchronized void setURLStreamHandlerFactory(...)
checkSetFactory
java.lang.RuntimePermission "setFactory"
URL(...)
checkPermission
java.net.NetPermission "specifyStreamHandler"
B: CLASSES, METHODS, AND PERMISSIONS 461
java.net.URLConnection
public static synchronized void setContentHandlerFactory(...)
public static void setFileNameMap(FileNameMap map)
checkSetFactory
java.lang.RuntimePermission "setFactory"
java.net.URLClassLoader
URLClassLoader(...)
checkCreateClassLoader
java.lang.RuntimePermission "createClassLoader"
java.rmi.activation.ActivationGroup
public static synchronized ActivationGroup createGroup(...)
public static synchronized void setSystem(ActivationSystem system)
checkSetFactory
java.lang.RuntimePermission "setFactory"
java.rmi.server.RMISocketFactory
public synchronized static void setSocketFactory(...)
checkSetFactory
java.lang.RuntimePermission "setFactory"
java.security.Identity
public void addCertificate(...)
checkSecurityAccess("addIdentityCertificate")
java.security.SecurityPermission "addIdentityCertificate"
java.security.IdentityScope
protected static void setSystemScope()
checkSecurityAccess("setSystemScope")
java.security.SecurityPermission "setSystemScope"
java.security.Permission
public void checkGuard(Object object)
checkPermission(this)
java.security.Policy
public static Policy getPolicy()
checkPermission
java.security.SecurityPermission "getPolicy"
java.security.Provider
In the following methods, the parameter name represents the provider name.
public synchronized void clear()
checkSecurityAccess("clearProviderProperties."+{name})
java.security.SecurityPermission "clearProviderProperties.{name}"
java.security.SecureClassLoader
SecureClassLoader(...)
checkCreateClassLoader
java.lang.RuntimePermission "createClassLoader"
java.security.Security
public static void getProperty(String key)
checkPermission
java.security.SecurityPermission "getProperty.{key}"
java.security.Signer
public PrivateKey getPrivateKey()
checkSecurityAccess("getSignerPrivateKey")
java.security.SecurityPermission "getSignerPrivateKey"
java.util.Locale
public static synchronized void setDefault(Locale newLocale)
checkPermission
java.util.PropertyPermission "user.language","write"
464 B: CLASSES, METHODS, AND PERMISSIONS
java.util.zip.ZipFile
ZipFile(String name)
checkRead
java.io.FilePermission "{name}","read"
C: SECURITY MANAGER METHODS 465
This appendix lists the java.lang.SecurityManager methods and the permissions their default
implementations check for. Each check method calls the SecurityManager.checkPermission
method with the indicated permission, except the checkConnect and checkRead methods,
which take a context argument instead. The checkConnect and checkRead methods expect
the context to be an AccessControlContext and call the context's checkPermission method
with the specified permission.
public void checkAccept(String host, int port);
java.net.SocketPermission "{host}:{port}", "accept";
public SecurityManager();
java.lang.RuntimePermission "createSecurityManager";
468 C: SECURITY MANAGER METHODS
D: API REFERENCE 469
D: API Reference
This appendix lists Java™ class and interface methods used in the examples for this book.
The methods are grouped by the class or interface to which they belong. Each method listing
provides a page number where the method is used. You can find information on the method
in the surrounding text or earlier in the chapter. You can also use the Index to locate these
same methods using the method names or the fully qualified class or interface names to
which the methods belong.
ActionListener Interface
Interface java.awt.event.ActionListener
void actionPerformed(ActionEvent e) (page 250)
WindowListener Interface
Interface java.awt.event.WindowListener
void windowClosing(WindowEvent e) (page 251)
Graphics Class
Class java.awt.Graphics
void drawRect(int x, int y, int width, int height) (page 258) page 261
FontMetrics getFontMetrics() (page 293)
void setClip(int x, int y, int width, int height) (page 264)
Graphics2D class
Class java.awt.Graphics2D
470 D: API REFERENCE
Book Class
Class java.awt.print.Book
void append(Printable painter, PageFormat page) (page 263)
void append(Printable painter, PageFormat page, int numPages) (page 263)
PageFormat Class
Class java.awt.print.PageFormat
double getImageableX() (page 258)
double getImageableY() (page 258)
double getImageableWidth() (page 264)
double getImageableHeight() (page 264)
void setOrientation(int orientation) (page 263)
Printable Interface
Interface java.awt.print.Printable
int print(Graphics graphics, PageFormat pageFormat, int pageIndex) (page 258)
PrinterJob Class
Class java.awt.print.PrinterJob
PageFormat defaultPage() (page 262)
static PrinterJob getPrinterJob() (page 262)
PageFormat pageDialog(PageFormat page) (page 262)
void print() (page 262)
D: API REFERENCE 471
Toolkit Class
Class java.awt.Toolkit
void addAWTEventListener(AWTEventListener l, long eventmask) (page 319)
ByteArrayOutputStream Class
Class java.io.ByteArrayOutputStream
byte[] toByteArray() (page 383)
DataOutputStream Class
Class java.io.DataOutputStream
byte[] toByteArray() (page 383)
Double Class
Class java.lang.Double
static Double valueOf(double doublevalue) (page 126)
SecurityManager Class
Class java.lang.SecurityManager
void checkRead(String filename) (page 424)
void checkWrite(String filename) (page 425)
void checkPermission(Permission perm) (page 425)
472 D: API REFERENCE
System Class
Class java.lang.System
static SecurityManager getSecurityManager() (page 103)
static SecurityManager setSecurityManager(SecurityManager s) (page 103)
static void loadLibrary(String libraryname) (page 209), (page 216), (page 218), (page 221)
static void loadLibrary(String libraryname) (page 223)
Naming Class
Class java.rmi.Naming
static void rebind(String rminame, Remote obj) (page 85)
static Remote lookup(String rminame) (page 88), (page 90)
static void rebind(String rminame, Remote obj) (page 103)
RMISocketFactory Class
Class java.rmi.server.RMISocketFactory
static void setFailureHandler(RMIFailureHandler fh) (page 103)
CallableStatement Interface
Class java.sql.CallableStatement
void setString(int index, String s) (page 131)
void registerOutParameter(int index, int sqltype) (page 131)
Date getDate(int index) (page 131)
Connection Interface
Class java.sql.Connection
CallableStatement prepareCall(String sql) (page 131)
D: API REFERENCE 473
DatabaseMetaData Interface
Class java.sql.DatabaseMetaData
boolean supportsResultSetConcurrency(int type, int concurrency) (page 135)
DriverManager Class
Class java.sql.DriverManager
static Connection getConnection(String url) (page 130)
static Connection getConnection(String url, String user, String password) (page 131)
static void setLogStream(PrintStream out) (page 131)
PreparedStatement Interface
Class java.sql.PreparedStatement
ResultSet executeQuery() (page 123), (page 127), (page 133)
int executeUpdate() (page 59), (page 137)
void setDate(int index, Date datavalue) (page 141)
void setDouble(int index, double doublevalue) (page 59), (page 123), (page 127), (page 141)
void setInt(int index, int intvalue) (page 137)
void setString(int index, String s) (page 58), (page 131)
void setBinaryStream(int index, InputStream stream, int length) (page 137)
474 D: API REFERENCE
ResultSet Interface
Interface java.sql.ResultSet
void close() (page 137)
boolean first() (page 135)
byte[] getBytes(String ColumnName) (page 137)
double getDouble(String columnName) (page 123), (page 135)
int getInt(String ColumnName) (page 127)
boolean next() (page 127), (page 134)
String getString(String columnName) (page 58), (page 123), (page 134)
double updateDouble(String columnName) (page 135)
Statement Interface
Class java.sql.Statement
void close() (page 137)
int executeQuery(String sql) (page 132)
int executeBatch() (page 136)
int executeUpdate(String sql) (page 132), (page 142)
ResultSet getResultSet() (page 58), (page 141), (page 142)
ArrayList Class
Class java.util.ArrayList
boolean add(Object object) (page 123)
Object[] toArray(Object[] objarray) (page 123)
Calendar Class
Class java.util.Calendar
D: API REFERENCE 475
Date Class
Class java.util.Date
long getTime() (page 141)
Enumeration Interface
Interface java.util.Enumeration
boolean hasMoreElements() (page 392)
Object nextElement() (page 392)
HashMap Class
Class java.util.HashMap
boolean containsKey(Object key (page 367)
Object get(Object key) (page 368)
Object put(Object key, Object value) (page 367)
Object remove(Object key) (page 367)
Iterator Interface
Class java.util.Iterator
boolean hasNext() (page 121)
476 D: API REFERENCE
LinkedList Class
Class java.util.LinkedList
void addFirst(Object value) (page 368)
((myFile)cache.get(fname)).getLastModified()) { cache.put(fname, readFile(fname));
} boolean remove(Object value) (page 368)
Object removeLast() (page 367)
List Class
Class java.util.List
Interator iterator() (page 121)
EntityBean Interface
Interface javax.ejb.EntityBean
void ejbRemove() (page 39)
void ejbActivate() (page 39)
void ejbPassivate() (page 39)
void ejbLoad() (page 27)
void ejbStore() (page 27)
void setEntityContext(EntityContext ectx) (page 27)
void unsetEntityContext(EntityContext ectx) (page 27)
SessionBean Interface
Interface javax.ejb.SessionBean
void ejbRemove() (page 79)
void ejbActivate() (page 79)
void ejbPassivate() (page 79)
D: API REFERENCE 477
UserTransaction Interface
Interface javax.jts.UserTransaction
void begin() (page 67)
void commit() (page 67)
void rollback() (page 67)
RemoteObject Class
Class javax.rmi.PortableRemoteObject
static object narrow(Object narrowFrom, Class narrowTo (page 90)
Cookie Class
Class javax.servlet.http.Cookie
void setPath(String path) (page 149)
void setMaxAge(int expire) (page 149)
void setDomain(String domainstring) (page 149)
Cookie(String name, String value) (page 149)
HttpServlet Class
Class javax.servlet.http.HttpServlet
void service(HttpServletRequest request, HttpServletResponse response) page 145
HttpServletRequest Interface
Class javax.servlet.http.HttpServletRequest
Cookie[] getCookies() (page 150)
478 D: API REFERENCE
HttpServletResponse Interface
Class javax.servlet.http.HttpServletResponse
void addCookie(Cookie cookie) (page 150)
void sendRedirect(String urlstring) (page 152)
void setDateHeader(String name, long datevalue) (page 152)
void setHeader(String name, String value) (page 152)
ServletConfig Interface
Interface javax.servlet.ServletConfig
String getInitParameter(String parametername) (page 152)
ServletContext getServletContext() (page 153)
ServletRequest Interface
Interface javax.servlet.ServletRequest
String getProtocol() (page 152)
ServletResponse Interface
Interface javax.servlet.ServletResponse
PrintWriter getWriter() (page 154)
void setContentType(String type) (page 154)
Box Class
Class javax.swing.Box
Component createRigidArea(Dimension d) (page 244)
D: API REFERENCE 479
DefaultCellEditor Class
Class javax.swing.DefaultCellEditor
void fireEditingStopped() (page 254)
Object getCellEditorValue() (page 254)
Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column) (page 255)
JButton Class
Class javax.swing.JButton
void addActionListener(ActionListener l) (page 250)
JComponent Class
Class javax.swing.JComponent
void setAlignmentY() (page 274)
JFrame Class
Class javax.swing.JFrame
void addWindowListener(WindowListener l) (page 251)
JLabel Class
Class javax.swing.JLabel
void setIcon(Icon icon) (page 252)
JScrollPane Class
Class javax.swing.JScrollPane
JScrollBar getHorizontalScrollBar() (page 244)
480 D: API REFERENCE
JTable Class
Class javax.swing.JTable
int getRowHeight() (page 293)
int getRowMargin() (page 293)
ListSelectionMode getSelectionModel() (page 243)
JTableHeader getTableHeader() (page 244)
boolean isCellEditable(int row, int column) (page 240)
void setAutoResizeMode(int mode) (page 239)
void setDefaultRenderer(Class columnClass, TableCellRenderer renderer) (page 253)
JTree Class
Class javax.swing.JTree
void makeVisible(TreePath path) (page 251)
void setSelectionRow(int row) (page 251)
JViewPort Class
Class javax.swing.JViewport
Point getViewPosition() (page 244)
void setView(Component view) (page 244)
Point getViewPosition() (page 244)
ListSelectionModel Interface
Interface javax.swing.ListSelectionModel
D: API REFERENCE 481
SwingUtilities Class
Class javax.swing.SwingUtilities
static void invokeLater(Runnable run) (page 255)
DefaultTableCellRenderer Class
Class javax.swing.table.DefaultTableCellRenderer
Component getTableCellRendererComponent(JTable table, Object value, boolean isSe-
lected, boolean hasFocus, int row, int column) (page 252), (page 253)
DefaultTableModel Class
Class javax.swing.table.DefaultTableModel
void fireTableStructureChanged() (page 242)
TableColumn Class
Class javax.swing.table.TableColumn
void setCellRenderer(TableCellRenderer renderer) (page 243), (page 253)
TableColumnModel Interface
Interface javax.swing.table.TableColumnModel
TableColumn getColumn(int index) (page 235)
int getColumnCount() (page 293)
int getColumnMargin() (page 293)
482 D: API REFERENCE
DefaultMutableTreeNode Class
Class javax.swing.tree.DefaultMutableTreeNode
DefaultMutableTreeNode(Object node) (page 250)
Enumeration depthFirstEnumeration() (page 251)
TreePath Class
Class javax.swing.tree.TreePath
TreePath(Object singlePath) (page 251)
Any Class
Class org.omg.CORBA.Any
void insert_double(double doublevalue) (page 126)
void insert_string(String stringvalue) (page 126)
IntHolder Class
Class org.omg.CORBA.IntHolder
IntHolder() (page 121)
ORB Class
Class org.omg.CORBA.ORB
status ORB init(String[] args, Properties props) (page 85), (page 117)
Any create_any() (page 125)
void connect(Object object) (page 85), (page 118)
void disconnect(Object object) (page 118)
String object_to_String(Object object) (page 87)
Object resolve_initial_references(String servicename) (page 86)
D: API REFERENCE 483
NameComponent Class
Class org.omg.CosNaming.NameComponent
NameComponent(String nameid, String kind) (page 85), (page 119), (page 120), (page 122),
(page 125)
NamingContext Interface
Interface org.omg.CosNaming.NamingContext
NamingContext bind_new_context(NameComponent[] nc) (page 85)
Object resolve_initial_references(String servicename) (page 86)
JNI C methods
CallVoidMethod(JNIEnv *env, jobject object, jmethodId methodid, object arg1) (page 219)
void DeleteLocalRef(JNIEnv *env, jobject localref) (page 228)
void ExceptionClear(JNIEnv *env) (page 219)
void ExceptionDescribe(JNIEnv *env) (page 220)
jthrowable ExceptionOccurred(JNIEnv *env) (page 220)
jclass FindClass(JNIenv *env, const char *name) (page 216)
jfieldID GetFieldID(JNIEnv *env, jclass class, const char *fieldname, const char *fieldsig)
(page 220)
jint* GetIntArrayElements(JNIEnv *env, jintArray array, jboolean *iscopy) (page 219)
jobject GetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index) (page 219)
jclass GetObjectClass(JNIEnv *env, jobject obj) (page 219)
jmethodID GetMethodId(JNIEnv *env, jclass class, const char *methodname, const char
*methodsig) (page 219)
const char* GetStringUTFChars(JNIEnv *env, jstring string, jboolean *iscopy) (page 210)
const jchar *GetStringChars(JNIEnv *env, jstring string, jboolean *iscopy) (page 213)
484 D: API REFERENCE