Distributed Programming With Java
Distributed Programming With Java
Technology
SL-301
Please
Recycle
Contents
About This Course.................................................................................... xiii
Course Goal ....................................................................................... xiii
Course Overview .............................................................................. xiv
Course Map......................................................................................... xv
Module-by-Module Overview ........................................................ xvi
Course Objectives........................................................................... xviii
Skills Gained by Module.................................................................. xix
Guidelines for Module Pacing ......................................................... xx
Topics Not Covered.......................................................................... xxi
How Prepared Are You?................................................................. xxii
Introductions .................................................................................. xxiii
How to Use Course Materials ...................................................... xxiv
Course Icons and Typographical Conventions ......................... xxvi
Icons ......................................................................................... xxvi
Typographical Conventions ................................................ xxvii
Notes to the Instructor.................................................................... xxix
Philosophy ...............................................................................xxix
Course Tools ............................................................................xxix
Instructor Setup Notes .................................................................. xxxii
Overview of Distributed Computing.....................................................1-1
Objectives ............................................................................................1-1
Relevance............................................................................................ 1-2
Additional Resources ....................................................................... 1-3
History of Computing ...................................................................... 1-4
Distributed Computing.................................................................... 1-6
Importance of Distributed Computing ..................................1-7
Characteristics of Distributed Computing ............................1-8
Design Considerations ..................................................................... 1-9
Latency........................................................................................1-9
Partial Failure ............................................................................1-9
Distributed Programming Architectures..................................... 1-11
Overview of Daemon Processes ...........................................1-12
Using Java Technologies to Implement Daemons .............1-13
iii
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Third-Party Java Technologies Using Daemons ................1-15
Understanding Daemons.......................................................1-15
Overview of Remote Procedure Call ...................................1-16
Third-Party Java Technologies Using RPC .........................1-17
Understanding Remote Procedure Call (RPC) ...................1-17
Overview of Remote Objects.................................................1-18
Implementing Remote Objects With Java Technologies ...1-19
Understanding Remote Objects ............................................1-20
Overview of Object Bus Systems ..........................................1-21
JavaBeans InfoBus...................................................................1-22
Understanding Object Bus Systems .....................................1-23
Overview of Mobile Agents ..................................................1-24
Understanding Mobile Agents..............................................1-26
Supporting Technologies for Distributed Computing .............. 1-27
Naming Service .......................................................................1-28
Security Service .......................................................................1-28
Transaction Service .................................................................1-28
Event Service............................................................................1-29
Message Queueing..................................................................1-29
Supporting Technologies .......................................................1-30
Check Your Progress ...................................................................... 1-31
Think Beyond .................................................................................. 1-32
Java Database Connectivity (JDBC) .......................................................2-1
Objectives ............................................................................................2-1
Relevance............................................................................................ 2-2
Additional Resources ....................................................................... 2-2
Introduction ....................................................................................... 2-3
JDBC Drivers and Driver Managers............................................... 2-4
java.sql Package ............................................................................ 2-7
JDBC Flow........................................................................................ 2-10
JDBC Programmer’s Interface ....................................................... 2-11
JDBC Example .........................................................................2-12
Exercise: Compiling a JDBC Application .................................... 2-14
Preparation...............................................................................2-14
Tasks .........................................................................................2-14
Exercise Summary...................................................................2-15
Using JDBC Drivers ................................................................2-16
Exercise: Loading a Driver............................................................. 2-18
Tasks .........................................................................................2-18
Exercise Summary...................................................................2-19
Exercise: Loading Driver 2 (Optional) ......................................... 2-22
Tasks .........................................................................................2-22
Specifying a Database.............................................................2-24
NIS Name Resolution Example ............................................2-26
Opening a Database Connection ..........................................2-27
v
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Exercise: Compiling a Basic RMI Application ............................ 3-31
Tasks .........................................................................................3-31
Exercise Summary...................................................................3-33
RMI Architecture............................................................................. 3-34
RMI Architecture Overview ..................................................3-34
Invocation Overview ..............................................................3-36
Interface Descriptions.............................................................3-38
The Application Layer............................................................3-39
The Stub and Skeleton Layer.................................................3-40
Stub Communication..............................................................3-41
Skeleton Communication.......................................................3-42
The Remote Reference Layer.................................................3-43
The Transport Layer ...............................................................3-44
Garbage Collection .................................................................3-46
RMI Object Hierarchy.............................................................3-49
The rmiregistry Application..............................................3-53
Remotely Loaded Code.................................................................. 3-56
The java.rmi.server.codebase Property ......................3-57
Security Aspects ......................................................................3-58
Exercise: Remotely Loaded Code ................................................. 3-59
Preparation...............................................................................3-59
Tasks .........................................................................................3-59
Exercise Summary...................................................................3-61
Object Factories .......................................................................3-62
Exercise: Object Factory ................................................................. 3-66
Tasks .........................................................................................3-66
Exercise Summary...................................................................3-68
Object Activation.....................................................................3-69
Exercise: Object Activation ............................................................ 3-74
Tasks .........................................................................................3-74
Exercise Summary...................................................................3-75
Objects as Parameters in Remote Calls ................................3-76
RMI “Agents” ..........................................................................3-76
Exercise: Objects as Parameters in Remote Calls ....................... 3-80
Preparation...............................................................................3-80
Tasks .........................................................................................3-80
Exercise Summary...................................................................3-82
HTTP Tunneling......................................................................3-83
Exercise: Developing an RMI Application From
Scratch (Optional) ........................................................................ 3-85
Tasks .........................................................................................3-85
Exercise Summary...................................................................3-87
Check Your Progress ...................................................................... 3-88
Think Beyond .................................................................................. 3-89
vii
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Array .........................................................................................4-58
The enum Construct ...............................................................4-59
Exercise: IDL-to-Java Programming Language Mapping
Details ............................................................................................ 4-61
Tasks .........................................................................................4-61
Exercise Summary...................................................................4-64
Objects as Parameters in Remote Calls ........................................ 4-65
Exercise: Objects as Parameters in Remote Calls ....................... 4-67
Tasks .........................................................................................4-67
Exercise Summary...................................................................4-69
Futures ......................................................................................4-71
Check Your Progress ...................................................................... 4-73
Think Beyond .................................................................................. 4-74
Servlets.........................................................................................................5-1
Objectives ............................................................................................5-1
Relevance............................................................................................ 5-2
Additional Resources ....................................................................... 5-3
Servlets Overview ............................................................................. 5-4
Servlets API........................................................................................ 5-5
The javax.servlet Package..................................................5-6
Simple Servlet ............................................................................5-7
Servlet Interaction .....................................................................5-8
HTTP Servlets .................................................................................... 5-9
The javax.servlet.http Package.....................................5-10
HTTP Servlet Example ...........................................................5-12
Exercise: Creating Simple HTTP Servlets.................................... 5-14
Preparation...............................................................................5-14
Tasks .........................................................................................5-14
Using an HTTP Servlet...........................................................5-17
Example Usage ........................................................................5-18
Servlet Life Cycle ............................................................................ 5-19
HTTP Servlet Request .................................................................... 5-20
Exercise: Snoop Servlet................................................................... 5-22
Tasks .........................................................................................5-22
Exercise Summary...................................................................5-23
HTTP Servlet Response..........................................................5-24
HTTP Session Management ..................................................5-25
Exercise: Session Servlet................................................................. 5-26
Preparation...............................................................................5-26
Tasks .........................................................................................5-26
Exercise Summary...................................................................5-27
Application Designs ....................................................................... 5-28
Two-Tier Design......................................................................5-29
Three-Tier Design ...................................................................5-30
ix
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Module Exercise Overview ........................................................... 7-11
Using JNDI to Access COS Naming.....................................7-12
Exercise: Java Naming and Directory Interface.......................... 7-13
Preparation...............................................................................7-13
Tasks .........................................................................................7-13
Java Transaction Service ................................................................ 7-16
Java Message Service ...................................................................... 7-17
JMS Service Provider ..............................................................7-18
JMS Domains ...........................................................................7-18
JMS Domains – Point-to-Point ...................................................... 7-19
JMS Domains – Publish and Subscribe ........................................ 7-20
Check Your Progress ...................................................................... 7-21
Think Beyond .................................................................................. 7-22
Technology Summary and Comparison................................................8-1
Objectives ............................................................................................8-1
Relevance............................................................................................ 8-2
Complementary or Overlapping Technology?............................. 8-3
JDBC Usage........................................................................................ 8-5
Using Servlets .................................................................................... 8-6
Example of an n-Tier Architecture ................................................. 8-7
RMI Compared to JavaIDL.............................................................. 8-8
JavaIDL Advantages......................................................................... 8-9
JavaIDL Disadvantages.................................................................. 8-11
Java RMI Advantages..................................................................... 8-13
Java RMI Disadvantages ................................................................ 8-14
RMI Over IIOP................................................................................. 8-15
RMI and JavaIDL ............................................................................ 8-16
Request-Reply Compared to Publish-Subscribe ........................ 8-17
Bus Example 1 – Real-Time Enterprise ........................................ 8-19
Bus Example 2 – Flat Architecture................................................ 8-20
Check Your Progress ...................................................................... 8-21
Think Beyond .................................................................................. 8-22
Flags for the idltojava Utility ..............................................................A-1
The IDL-to-Java Compiler: idltojava......................................... A-2
Syntax ........................................................................................A-2
Description................................................................................A-2
Options ......................................................................................A-2
Flags ...........................................................................................A-3
Using the #pragma compiler directive..................................A-5
xi
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
About This Course
Course Goal
Distributed Programming With Java Technology provides you with the
knowledge and skills necessary to program distributed computing
applications using the distributed technologies from JavaSoft™:
You will also learn about the supporting technologies, such as Java
Transaction Services (JTS), Java Naming and Directory Interface
(JNDI), and Java Message Service (JMS). At the end of the course, the
knowledge gained should enable you to make informed decisions
about which technology is best used under which circumstances.
✓ Use this module to get the students excited about this course.
✓ With regard to the overheads: To avoid confusion among the students, it is very important
to tell them that the page numbers on the overheads have no relation to the page numbers
in their course materials. They should use the title of each overhead as a reference.
✓ The strategy provided by the “About This Course” is to introduce students to the course
before they introduce themselves to you and one another. By familiarizing them with the
content of the course first, their introductions will have more meaning in relation to the
course prerequisites and objectives.
✓ Use this introduction to the course to determine how well students are equipped with the
prerequisite knowledge and skills. The pacing chart on xx enables you to determine what
adjustments you need to make in order to accommodate the learning needs of students.
xiii
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Course Overview
This course is concerned with providing you with the skills and
concepts necessary to solve distributed computing problems using the
four distributed computing technologies from JavaSoft:
● JDBC
● RMI
● JavaIDL
● Java servlets
The following course map enables you to see what you have
accomplished and where you are going in reference to the course goal.
Overview
Overview of
Distributed Computing
Java Technology
Java Database Remote Method
Connectivity (JDBC) Invocation (RMI)
Push Technology
Object Bus
Systems
Supporting Technology
Supporting
Technologies
Summary
Technology Summary
and Comparison
● Module 5 – “Servlets”
The skills for Distributed Programming With Java Technology are shown
in the first column of the matrix below. The black boxes indicate the
main coverage for a topic; the gray boxes indicate that the topic is
briefly discussed.
Module
Skills Learned 1 2 3 4 5 6 7 8
✓ Refer students back to this matrix as you progress through the course to show them the
progress they are making in learning the skills advertised for this course.
✓ This table should only be used as a guideline for timing throughout the week. The time
you spend on each module and lab may differ from class to class, as knowledge and Java
programming language experience of the students varies.
This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services. Refer to the Sun Educational
Services catalog for specific information and registration.
To be sure you are prepared to take this course, you should be able to
do the following:
Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.
Icons
Exercise objective – Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.
!
Warning – Anything that poses personal danger or irreversible
damage to data or the operating system.
Courier bold is used for characters and numbers that you type. For
example:
system% su
Password:
It is also used for each code line that will be referenced in text.
For example:
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
Palatino italics is used for book titles, new words or terms, or words
that are emphasized. For example:
cd server_root/bin
On Microsoft Windows
cd server_root\bin
Philosophy
The Distributed Programming With Java Technology course has been
created to allow for interactions between the instructor and the
student as well as between the students themselves. In an effort to
enable you to accomplish the course objectives easily, and in the time
frame given, a series of tools have been developed and support
materials created for your discretionary use.
Course Tools
To enable you to follow this structure, the following supplementary
materials are provided with this course:
● Relevance
The course map allows the students to get a visual picture of the
course. It also helps students know where they have been, where
they are, and where they are going. The course map is presented
in the “About This Course” section in the student guide.
● Lecture overheads
● Small-group discussion
● Module self-check
If you have a projection system for projecting HTML slides and are
planning to use the HTML slides, you need to do the following:
/SL301_OH/HTML/OH.Title.doc.html
Note – This document does not describe the steps necessary to set up
an overhead projection system because it is unknown what will be
available in each training center. This setup is the responsibility of
each training center.
All of the course files for this course are available from the
education.central server. You can use ftp or the
education.central Web site,
http://education.central/courses/ to download the files from
education.central. Either of these methods requires you to know
the user ID and password for FTP access. See your manager for these
if you have not done this before.
Course Components
This course consists of the following components:
● Instructor guide
● Student guide
● Art
● Instructor notes
● Lab Files
Objectives
Upon completion of this module, you should be able to:
1-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
1
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
● Orfali, Robert, Bruce Harkey, and Bob Edwards. 1996. The Essential
Distributed Objects Survival Guide. Wiley Press.
History of Computing
Distributed Computing
To solve the problem of program size, you need a way of moving the
major processing pieces to another address space. This would allow
the client to concentrate on the specific pieces required for the end-
user of the application.
Design Considerations
Latency
Proper analysis of what should reside locally and what can be
accessed remotely is crucial to the performance of the distributed
application. Obviously, a service that can be accessed over a local bus
will be faster than one that must use the network. As the number and
speed of processors that can be put in a system increases, the speed
gap between local and remote access increases.
✓ “Note on Distributed Computing” states that latency can be as high as four to five orders
of magnitude between local and remote access.
Partial Failure
In a local application, if a single component fails (a disk crashes, a
CPU panics, or memory fills up), the application will fail to run. When
writing a local application you do not have to take catastrophic failure
into consideration, because there is little if anything that you can do to
recover.
● Daemons
● Remote objects
● Mobile agents
● ftpd
● telnetd
● httpd
● sendmail
Do not be confused by the fact that these two daemons are not on the
same side of a client-server relationship. JDBC allows you to build
systems of Java technology clients (Java clients) that connect to
potentially non-Java programming language servers. Servlets allow
you to build Java technology elements to run on a Web server,
interfacing with potentially non-Java programming language web
clients.
This means that the Java 2 SDK alone usually is not sufficient to test a
JDBC application. To connect to a specific database, you need a JDBC
driver from a vendor. However, there is one driver included with the
Java 2 SDK: the JDBC-ODBC bridge driver. When you have a working
open database connectivity (ODBC) driver on a client, you can make a
JDBC connection to the database with only the Java 2 SDK.
Servlets
The most common servlets today are HTTP servlets, which are
modular extensions to a Web server. Common usages of HTTP servlets
are:
Understanding Daemons
Discussion – Take a couple of minutes to read through the following
questions, and prepare some answers on your own. Then discuss the
questions in the class.
RMI was introduced with the JDK™ software, Version 1.1. All you
need to implement and test an RMI application is part of the Java 2
SDK. However, before you put an RMI application into production,
consider carefully your requirements for fault tolerance and
performance. The Java 2 SDK “RMI Registry” (a simple naming
service, as well as a simple implementation repository) is usually too
weak in production environments. As one result of the Enterprise
JavaBeans initiative, robust RMI servers should be available soon.
JavaIDL is part of the Java 2 SDK. The JavaIDL technology allows you
to build and test client and server objects conforming to the CORBA
specification. The JavaIDL technology shares the limitations about
production environments with the RMI technology. To put a JavaIDL
application in production, you should consider using an extremely
robust object request broker (ORB) to host your server objects.
JavaBeans InfoBus
The JavaBeans Infobus is a type of object bus, but it has a different
focus than “pure” object buses. It facilitates the distribution of data
(rather than the flow of objects) between different JavaBeans objects.
However, because the data to be exchanged is encapsulated in objects,
the InfoBus is still considered to be an object bus. Because the InfoBus
specializes in exchanging data, it supports the following items that are
not supported by a “pure” object bus.
● Membership protocols
● Security protocols
So far, when objects are created they remain on one machine. They use
the network to communicate with each other, using remote method
invocation. While they can exchange other objects with each other
(remember, even a Java programming language String is an object), the
objects being exchanged tend to represent pure data, with accessor
methods to this data.
Mobile agents go one step further: The objects being exchanged carry
behavior as well as data. For example, an object representing a bid to
buy some stock. The “pure data” version contains a desired buying
price and a desired amount. If, at the other end, the price is at your
price or lower, you will make the deal with exactly your price, certainly
not cheaper. Your application creating the bid object is therefore
responsible for getting you a reasonable price.
Exactly how intelligent these objects are, whether they can travel by
themselves or have to be moved, and whether there is a strong
security focus or no security focus, differentiates the mobile agent
frameworks that are currently available or being researched.
✓ One popular project is the IBM Aglet Workbench. According to the Aglets home page:
“Aglets Workbench is a visual development environment for building aglets, a new breed
of intelligent agent that can travel over a network and execute tasks at the same time.
Aglets combine intelligent agent technology with network-savvy Java technology objects.
They can go from one computer, or Internet host, to another while running and carrying
data with them as they go.”
✓ In many ways, mobile agents are still “a solution seeking a problem to solve”. Systems in
development include network management agents, trading agents, or information-
gathering agents.
● Naming service
● Security service
● Transaction service
● Event service
● Message queueing
Security Service
Security in large distributed systems, potentially multi-enterprise, is a
difficult issue. For example, objects arriving on a system might claim
to work “on behalf” of some person (remember the “bid” object). How
do you guarantee that this claim is true? How do you prevent the
introduction of malicious code into your system? With the Java 2 SDK,
the Java programming language has most of the necessary basic
mechanisms built in to construct a secure system. However, you still
must construct the security system, which is error prone. A security
service does this for you, giving you a whole system to work with,
instead of several basic, less effective mechanisms.
Transaction Service
A transaction service helps you build transactions. A transaction is a
unit of work that has several characteristics. The most important
characteristic is that a transaction is atomic; this means if a transaction
is interrupted by failure, all effects are undone (rolled back). It also
means that you cannot see intermediate states, such as a temporarily
inconsistent database. Transactions can be local to an address space, on
a remote address space, or span multiple address spaces.
So far, not much is known about the Java Transaction Service. The
following paragraph is cited from the “Java for the Enterprise” home
page:
Event Service
An event service enables you to send and receive events in distributed
systems, in much the same way you do it locally with the regular Java
programming language event mechanism.
Using an event service frees you from thinking about how events are
optimally delivered in distributed systems; you just use the API.
However, when purchasing an event service, be sure to keep the
discussion in Module 6, ‘‘Object Bus Systems,” in mind. How the event
service is implemented has a huge impact on performance and
network traffic.
Message Queueing
A regular RMI call is synchronous. If object A calls object B remotely
using RMI, object A’s calling thread is blocked until the call returns.
This is exactly the same as in a local environment.
Supporting Technologies
Discussion – Take a couple of minutes to read through the following
question, and prepare some answers on your own. Then discuss the
question in the class.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this module, you should be able to:
● Explain JDBC
The JDBC API enables developers to write code for interfacing with a
database, without knowing the specifics of the database
implementation.
2-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
2
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
✓ You do not need to know very much about the database at all. By creating a generic set of
interfaces that can be used to connect to any database vendor’s product, the JDBC API
does not restrict you to a specific database. Moreover, the JDBC API does not restrict you
in the database design, because there are several design alternatives.
Additional Resources
Introduction
With the JDBC, the developer can write an application using the
interface names and methods described in the API, regardless of how
they were implemented in the driver. The developer writes an
application using the interfaces described in the API as though they
are actual class implementations. The driver vendor provides a class
implementation of every interface in the API so that when an interface
method is used, it is actually referring to an object instance of a class
that implemented the interface.
JDBC API also enables developers to pass any string directly to the
driver level. This makes it possible for developers to make use of
custom features of their database without requiring that the
application use only American National Standards Institute (ANSI)
Structured Query Language (SQL).
2. Mini SQL is provided with the courtesy of Hughes Technologies Pty Ltd, Australia
(see http://www.Hughes.com.au).
Java application
(JDBC API)
JDBC-ODBC
JDBC-NET
driver Driver A Driver B
Bridge driver
ODBC and
JDBC implementation
DB drivers alternatives
java.sql Package
There are 18 interfaces associated with the JDBC. They are included in
the following list and shown in Figure 2-2 on page 2-9:
● Driver
● Connection
● Statement
● PreparedStatement
● CallableStatement
● ResultSet
● ResultSetMetaData
● DatabaseMetaData
ArrayLocator
java.lang.Throwable
BlobLocator
java.lang.Exception
ClobLocator
SQLException
StructLocator
BatchUpdateException
SQLData
SQLWarning
Struct
DataTruncation
SQLInput
Connection
SQLOutput
DatabaseMetaData
SQLType
Driver
DriverManager java.util.Date
DriverPropertyInfo Date
Ref Time
ResultSet TimeStamp
ResultSetMetaData Legend
Statement Class
Abstract
PreparedStatement Class
Interface
CallableStatement
Extends
Types
Implements
JDBC Flow
This section covers some of the common tasks you perform using the
JDBC programmer’s interface. The following discussion assumes that
you communicate with an mSQL database driver through the JDBC
API. The information is divided into the following parts, which are
separated by lessons:
When the code is run, the contents of the Coffee table in the database
are printed.
java JDBCExample jdbc:msql://<host name>:4333/le-shop
Preparation
You need to know the following to complete this exercise:
● What JDBC driver you are using and how the URL is called
✓ Assign each student a different database to work with. The databases are named le-shop1
to le-shop9. The URL for the exercise is jdbc:msql://<host name>:4333/<database>,
where <host name> is the machine name designated as the database server and
<database> is replaced with le-shop1 to le-shop9.
Tasks
2. Compile JDBCExample.java.
1. Study the source code and get an idea of how JDBC works.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Tasks
3. Compile and run your application. Use the same JDBC URL as in
the previous exercise.
2. Find out why the mSQL driver is not JDBC compliant (optional).
✓ The mSQL database does not implement all features needed for JDBC compliance.
Therefore the driver is not compliant either.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
You can have more than one database driver loaded into memory. You
can also have more than one of the drivers loaded into memory, ODBC
or a JDBC generic network protocol is capable of connecting to the
same database. If this is the case, JDBC allows you to specify a list of
drivers in a specified order. The order of selection is specified by a Java
programming language properties tag, jdbc.drivers. The
jdbc.drivers property should be defined as a colon-separated list of
driver class names:
jdbc.drivers = com.imaginary.sql.msql.MsqlDriver:Acme.cool.driver
Properties are set through the -D option to the java interpreter (or the
-J option to the appletviewer application). For example:
java -Djdbc.drivers=com.imaginary.sql.msql.MsqlDriver:Acme.cool.driver
Tasks
3. Compile and run the program. Set the name of the drivers class
(com.imaginary.sql.msql.MsqlDriver) in the jdbc.drivers
property.
java -Djdbc.drivers=com.imaginary.sql.msql.MsqlDriver
LoadDriver2 jdbc:msql://<host name>:4333/le-shop
✓ Note – The property jdbc.drivers does not determine the sequence in which JDBC
drivers are checked. It eliminates the need for any class.forName(“...”) statement.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Specifying a Database
Now that you have created the instance of the JDBC driver, you need
to name the database to which you want to connect.
jdbc:subprotocol:parameters
This is the URL for the JDBC access to the mSQL Ticketing database
you will connect to in the lab. serverName is a variable set to the host
name of the database server.
URL string
Driver manager Program
getConnection(URL string);
Explanation Connection to
le-shop DB
Driver manager calls getConnection(URL),
which calls driver.connection(URL) for the
drivers in the vector until a match is found.
✓ Note that the driver does not have a “connection” with the database—this is the job of the
Connection interface implementation.
Tasks
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Submitting a Query
To submit a standard query, get a Statement object from the
Connection.createStatement method.
try {
stmt = con.createStatement();
} catch (SQLException e) {
System.out.println (e.getMessage());
}
✓ SQL exceptions occur when there is a database access error; that is, a connection is
broken or the database server went down. SQL exceptions provide information for
debugging, such as
• A string describing the error
• An SQL state string following XopenSQL state conventions
• A vendor-specific integer error code
The setXXX methods in Table 2-1 on page 2-34 for setting SQL IN
parameter values must specify types that are compatible with the
defined SQL type of the input parameter. For example, if the IN
parameter has SQL type Integer, then you should use setInt.
✓ IN parameters are passed by value into the operation; the value of the parameter is not
expected to be changed.
✓ OUT parameters are passed by reference from the operation; the operation is to set the
value of the reference.
✓ INOUT parameters are passed by reference into an operation; the value of the parameter
passed into the operation is expected to be changed by the operation.
✓ JDBC only supports IN and OUT, but JavaIDL (CORBA) supports all three.
setArrayLocator LOCATOR(<array>)
setASCIIStream Uses an American Standard Code for
Information Exchange (ASCII) stream to
produce a LONGVARCHAR
setBigDecimal NUMERIC
setBinaryStream Uses a binary stream to produce a
LONGVARBINARY
setBlobLocator LOCATOR(BLOB)
setBoolean BIT
Receiving Results
The result of executing a statement can be a table of data that is
accessible using a java.sql.ResultSet object. The table consists of a
series of rows and columns. The rows are received in order. A
ResultSet keeps a cursor pointing to the current row of data and is
initially positioned before its first row. The first call to next makes the
first row the current row, the second call makes the second row the
current row, and so forth.
The ResultSet object provides a set of get methods that enable access
to the various column values of the current row. These values can be
retrieved using either a column name or an index. You should use an
index when referencing a column. Column indexes start at 1. When
using a name to reference a column, it is possible that more than one
column will have the same name, thus causing a conflict.
1 while (rs.next()) {
2 System.out.println();
3 System.out.println("Coffee Name: " + rs.getString(1));
4 System.out.println("Supplier Id: " + rs.getInt(2));
5 System.out.println("Price : " + rs.getFloat(3));
6 System.out.println("Sales : " + rs.getInt(4));
7 }
The various getXXX methods access columns within the result sets
table. The columns can be accessed in a random order, within the
specified row.
To retrieve data from the ResultSet object, you must be familiar with
the columns returned and their data types. A table mapping Java
technology types (“Java types”) to SQL data types is provided in
Table 2-3 on page 2-43.
Note – Once you have read the ResultSet object, the results are
cleared; you can read the results only once.
Tasks
2. Use SQL queries that do not return ResultSet objects, such as:
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
getArrayLocator LOCATOR(<array>)
getASCIIStream java.io.InputStream
getBigDecimal java.math.BigDecimal
getBinaryStream java.io.InputStream
getBlobLocator LOCATOR(BLOB)
getBoolean boolean
getByte byte
getBytes byte[]
getCharacterStream java.io.Reader
getClobLocator LOCATOR(CLOB)
getDate java.sql.Date
getDouble double
getFloat float
getInt int
getLong long
getObject Object
getShort short
getString java.lang.String
getStructLocator LOCATOR(<structured-type>)
getTime java.sql.Time
getTimestamp java.sql.Timestamp
getUnicodeStream java.io.InputStream or Unicode characters
✓ Obviously, getNull makes no sense, but if the getXXX method encounters an SQL NULL
type, the result of the method is null.
Table 2-3 shows the standard Java types for mapping various common
SQL types.
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
By allowing you to create a generic set of interfaces that you can use to
connect to any database vendor’s product, the JDBC API does not
restrict you to a specific database. In addition, the JDBC API also does
not restrict you in the application design, because you use either a
two- or three-tier model to build your application.
Application Designs
Applets
The use of Java applets has been the most publicized use of the Java
platform. JDBC can be incorporated into applets to bring database
access to the World Wide Web (WWW). For example, you can
download a Java applet that can display the available flights for a
specified date to and from specified destinations. This applet could
access a relational database over the Internet, enabling a client to
inquire about seat availability, book a reservation, or update the
database.
Performance Considerations
Performance considerations for database connectivity implementations
differ when the database might be halfway around the world. The
response time for an Internet-based database applet will be
considerably slower than a database applet running on a local
network.
Security Limitations
You can avoid some of the security limitations encountered with
untrusted applets by using a digital signature or cryptographic key
scenario. In these circumstances, an applet is treated like an
application in the security sense, but there still would be problems
interacting with client-side databases because of the difficulty locating
the directory structure of the database or database driver.
Exercise objective – Combine all of the aspects shown earlier and use
JDBC to build a larger application.
Preparation
LeShop is a small coffee shop that uses a database (le-shop) for its
business. The example’s focus is on JDBC, so there is a minimum of
supporting functions, no GUI, and a simple two-tier design. It consists
of five classes: LeShop is the main application. It uses ConsoleMenu
and ConsoleDialog for user interaction on the console. The classes
Coffee and Supplier interact with the database using JDBC. They
both have a main method, so you can use them as standalone
programs to test the code. Use FirstConnection and Exec from the
previous exercises to verify that your code manipulates the database
correctly.
Tasks
Tasks
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
For more information on JDBC, refer to the latest revision of the JDBC
specification. This specification is available at the
http://java.sun.com/products/jdbc web site. It specifies the
interface both from the points of view of the application programmer
and the writer of the vendor driver.
Before continuing on to the next module, check that you were able to
accomplish the following in this module:
❑ Explain JDBC
Objectives
Upon completion of this module, you should be able to:
● Generate client stubs and skeletons for remote services using the
RMI stub compiler
3-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
3
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
● How many of the programs that you write could take advantage
of existing programs/classes that you have already written in the
Java programming language, but need to run on another machine
elsewhere on the network?
✓ The RMI API may be viewed as a communication mechanism that takes care of TCP socket
connectivity and putting objects “on the wire” (using the Java programming language’s
Object Serialization) between separate JVM invocations. The developer is removed one
level by not having to write that functionality into the program each time.
1. See “Command pattern,” pp. 233–242 of Design Patterns – Elements of Reusable Object-Oriented
Software by Gamma, Helm, Johnson, and Vlissedes (Addison-Wesley, 1995).
Until the release of the Java Remote Method Invocation API, sockets
were the only facility built into the Java programming language that
provided direct communication between machines. In a fashion
similar to Remote Procedure Calls (RPC), RMI abstracts the socket
connectivity and data streaming, enabling developers to write code
that accesses remote objects in the same fashion as objects instantiated
from within the local runtime system.
RMI Characteristics
The characteristics of RMI include the following:
RMI allows you to move behavior from server to client and from client
to server. Imagine an application for an insurance company allowing
you to calculate some installments. The interface for this application
certainly includes some methods that check whether the entered
figures conform to values that are set by the company rules. To fill out
an insurance form, clients get an object from the server that
implements these rules. When these rules change, clients get the
updated implementation the next time they request the insurance form
object. The clients’ interface does not need to be touched at all. The
checking takes place at the client side with the advantage of
immediate feedback to the user and reduced load on the server. You
can move behavior in both directions: imagine, in the design in the
overhead, a server handling asynchronous computation-intensive
requests from some of the client applications.
What Is Serialization?
Serialization allows you to save and restore the state of an object.
Without serialization, parameters and return values would have to be
simple primitive data types. The RMI architecture would not work as
seamlessly as it does without mechanisms for sending objects over the
network. This would limit drastically the usefulness of a distributed
design, and make the power of remote objects applicable only to trivial
applications.
Classes that are made up of fields other than static or transient fields,
you can serialize, but the default mechanism does not make values of
the static or transient fields persistent. When you serialize the object,
the default values for the transient and static fields are set as if the
object would have been instantiated from scratch. For most RMI
applications, the default built-in serialization is all you need.
You must add some exception handling, and the upper code in a try-
catch clause must be included as usual when dealing with
input/output (I/O) methods. The constructor for
ObjectOutputStream expects an OutputStream object.
FileOutputStream is a valid subclass allowing you to write the object
into a file stream.
Time-Consuming Process
For special cases, the default serialization might not fulfill all needs.
Then you must customize the serialization according to your
requirements. You should be aware of the following rules:
You cannot serialize fields that are marked transient or static. This
offers an easy way to prevent fields from being serialized. Changing a
non-static field to static also changes the semantics of this class. The
preferred way to protect a field from serialization without affecting its
behavior is to mark it as transient. Providing the methods
writeObject or readObject offers a way to set non-default values for
transient fields after deserializing the respective object.
Object Streams
Java object serialization produces just one stream format for the
encoding and storing of objects. Each object acting as a container
implements one of two interfaces: ObjectOutput or ObjectInput.
They define some methods for the reading or writing of objects and
primitives and some basic stream operations, such as close or flush.
ObjectOutputStream Class
Serializable Interface
Tasks
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
4. Create the client, which uses the remote object (in the end, the
client uses the servant).
6. Run the RMI compiler (rmic) to create the helper classes (stubs
and skeletons).
The Java interface describes the server object. This interface has two
differences, as compared to a “regular” Java interface: the Echo
interface must extend java.rmi.Remote, and every method must
throw java.rmi.RemoteException.
For each interface, you must write a servant class. Instances of the
servant class implement remote objects. Each instance implements a
single remote object, and each remote object is implemented by a
single servant. The servant must extend the class
java.rmi.server.UnicastRemoteObject
The RMI runtime uses the server to instantiate and publish the
servant. In its simplest form, the server pre-instantiates all the required
servants and keeps them alive forever (or at least as long as the server
lives). In a production system this would usually not be good enough.
To keep thousands of servants alive, even when they are not actively
used by clients, is a waste of resources. In this case, more complex
servers must be developed and used. They must be able to instantiate
servants on demand, and maybe even persist and discard them after a
period of non-usage. The server, EchoServer.java, is a simple server:
1 package EchoApp;
2
3 import java.rmi.Naming;
4
5 public class EchoServer {
6 public static void main(String args[])
throws Exception{
You have to instantiate the servant and register it with the name server
(which is part of rmiregistry). After the servant is registered, its
object reference can be retrieved and used by the client application.
The following section describes how this works.
Echo was used as a name to bind the servant into the name server.
Now use the same name to look it up. The result is an object of type
java.lang.Object, which you have to cast to an Echo to be able to
use its methods.
To complete the setup, you need the stub and the skeleton class.
Provide a stub and a skeleton for every class that implements the
java.rmi.Remote interface. In this case, this is EchoImpl.java,
which implements Echo.java, which extends Remote. The stub
compiler runs against the previously compiled class file.
The utility to create the stub and skeleton is called the RMI compiler or
rmic. The syntax is similar to the javac compiler. The stub and
skeleton are compiled by typing the following:
rmic -d . EchoApp.EchoImpl
If this is not the case on your system, redo steps 1–6 or ask your
instructor what could have gone wrong.
The RMI registry does not produce any output, so you can safely start
it in the background.
The server, which creates the servant and registers it with the RMI
registry, is started next.
java EchoApp.EchoServer
This line connects you to host <host name>. Because a server can
bind servants only to an RMI registry running on the same host as the
server itself, <host name> also runs the servant.
Right now, all the files necessary to start up the server, servant, and
client are accessible in the current directory or through the class path.
You will see in a later section how to download the necessary code on
demand.
Tasks
Work through the six steps described in the handout to compile the
Echo application.
2. Team up with somebody, and distribute the client and the server
parts of Echo on two different machines.
After Echo runs successfully, try to break the code in several ways to
test the fault tolerance of RMI. Try out the following in the servant
code (EchoImpl.java):
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
RMI Architecture
● Application
● Stub/skeleton
● Remote reference
● Transport
The client code first talks to its stub, which then sends the message to
the remote reference layer (RRL). The RRL then passes it through the
transport layer to the server machine.
At the server, the message goes all the way up again. The transport
layer passes it to the RRL, which in turn retranslates it to the skeleton
where it finally appears at the server’s object implementation.
Invocation Overview
Local Java objects are invoked by reference; however, the RMI system
is passing objects in parameters or return values by copy and not by
reference, because a reference to a local object makes sense only within
one virtual machine. RMI uses the Java programming language
serialization mechanism to flatten a local object into a serial stream
and send it over the wire to the receiving instance.
The Java 2 SDK can get rid of the skeleton class. This does not imply
that a skeleton is no longer needed. The RMIRemoteObject class has
been modified and now has the additional job of being a universal
skeleton, in combination with the Java programming language
introspection mechanism.
Interface Descriptions
You can use RMI between virtual machines on a single system or over
a network between virtual machines (VMs) on multiple machines.
Using interfaces allow you to create a highly modular application
design.
In RMI, all interfaces are described in pure Java code. With the RMI
stub compiler (rmic) the stub and skeleton files are generated directly
from the compiled code that implements the interfaces.
The final part for an RMI application is to register the remote object
with a name server to be available for the first contact of a requesting
client.
The stub is responsible for the initiation of calls to the remote object it
represents. It is also the stub that marshals method arguments to a
stream object that contains parameters, errors, and exceptions, and
unmarshals (receives and interprets) streams returned by the remote
object.
All interfaces of a remote object are also implemented by the stub class
that represents this object at the client. A stub class is type equivalent
to any of the represented remote interfaces and can therefore be cast as
any of those. A test with the instanceof operator answers whether a
certain interface is implemented by a remote object.
Stub Communication
Stubs interact with the client-side RRL in the following ways:
● The stub receives the remote method invocation and initiates a call
to the remote object.
● The stub makes the remote method call, passing any arguments to
the stream.
Skeleton Communication
The skeleton class receives the method calls, marshals the parameters,
and dispatches the methods to be exported. Skeletons interact with the
server-side RRL in the following ways:
The RRL is responsible for carrying out the semantics of the method
invocation. It manages communication between the stubs/skeletons
and the lower-level transport interface using a specific remote
reference protocol, which is independent of the client stubs and server
skeletons. The RRL’s responsibilities include managing references to
remote objects and reconnection strategies if an object should become
unavailable.
The RRL has two cooperating components: the client side and the
server side. The client-side component contains information specific to
the remote server, and communicates using the transport layer to the
server-side component. The server-side component implements the
specific remote reference semantics prior to delivering a remote
method invocation to the skeleton.
You can adjust the transport layer to deal with special requirements,
such as encryption or data compression.
Garbage Collection
RMI uses a reference-counting garbage collection scheme that keeps
track of external live references to remote objects within a local virtual
machine. A live reference is, in this case, an active connection over a
TCP/IP session.
Garbage Collection
The steps involved in garbage collection are:
2. When the client requests the object, the client’s JVM creates a live
reference, and the first reference to the object sends a
“referenced” message to the server.
4. When the count on the object goes to 0, and there are no local
references to the object, the object reference can be passed to the
server’s local garbage collector for collection.
The RemoteObject class acts like a remote representative for the Java
root class Object and provides some overridden methods in their
distributed version, such as hashCode, equals, and toString. The
getClass method works for local as well as for remote objects. Used
with a remote object, it returns the stub’s type.
The RemoteServer class is used for the creation and export of server
objects and is therefore the superclass of all RMI servers. The
getClientHost method returns the IP address of the requesting client.
The getLog and setLog methods allow logging.
The RMI system currently does not support multicast remote objects
and replication.
and in the RMI server class with the binding to the Naming class.
// ;
// EchoServer.java:
...
// Create the servant instance for registration
EchoImpl echoRef = new EchoImpl();
The Naming class provides two static methods that enable the
developer to register an implementation, bind and rebind. The only
difference is that the bind method throws a
java.rmi.AlreadyBoundException if another object has already
been registered on this server, using the name passed as the first
argument to the method.
rmi://host:port/name
where rmi is the protocol, host is the name of the RMI server (which
might need to be fully DNS or NIS+ qualified), port is the port
number that the server should be listening to for requests, and name is
the exact name that clients should use in Naming.lookup requests for
this object. If not specified, the protocol defaults to rmi, host defaults
to the local host, and port defaults to 1099.
✓ For security reasons, an application can bind only to a registry running on the same host.
You can set properties for the RMI server JVM from the command line:
Catching Exceptions
There are many more ways for distributed applications to fail than
there are for their local counterparts. Consequently, the RMI systems
extend the Java exception classes to deal with the additional
complexity. The exception handling is therefore not bound to a local
virtual machine.
In the Echo application, there are try-catch clauses in the client class
embracing the lookup method, as well as in the server class around
the code that binds the object to the registry.
With RMI, you can download some of the required classes for an RMI
application from a Web server. There is a special class called
RMIClassLoader, which is part of the rmi.server package. This class
loader is used by the RMI runtime system transparently if it cannot
find a required class in the local class path. The most important class
that does not have to be on the client is the stub. Other new classes
could be acquired as a return value from a remote call. If all the client
“knows” about a return value is the interface, the actual class that
implements this interface is known only at runtime.
RMI offers a better approach. The URL is set on the server side, and
RMI clients learn about the URL automatically; it is embedded in the
RMI wire protocol. The URL is set as a system property when the
server is started. For example:
java -Djava.rmi.server.codebase=http://myhost:8080/
EchoApp.EchoServer
This line tells the clients to get their class files from the host galahad on
port 81. The trailing “/” is mandatory, because the URL always
denotes a directory, and never a single file.
Note – The rmiregistry application also gets the URL from the
server. At the moment the server binds the servant into the registry,
the rmiregistry needs the class file. If the rmiregistry is able, at
this moment, to locate the class using the class path, instead of using
the server supplied URL, the URL system ceases to work. A client
cannot get the class using the URL anymore. It is unclear why this is
the case, but this behavior causes a lot of confusion about the
java.rmi.server.codebase property. If you start the rmiregistry,
be sure to start it with an empty class path.
A client can supply a URL in the same way a server does, by setting
the java.rmi.server.codebase property on the client.
Exercise objective – So far, all the code needed to run the Echo client
and server was loaded from the current directory or from the class
path. Change this so that the client receives its stub automatically
using a Web server.
Preparation
With the lab setup comes a mini Web server that is precompiled. Start
the mini Web server, and pass the port number where it should serve
the files, and the path where the EchoApp package is found after you
complete it.
Tasks
Modify the Client so That it Can Receive Code From a Web Server
The Java programming language allows you to load code only from a
remote location if a security manager is in place. The first task is to
modify the client to instantiate and install a security manager.
The class path is always searched before any remote location is tried.
Therefore, you must move the client code so that the stub is no longer
in the class path.
3. Launch the server and pass the location of the Web server in the
java.rmi.server.codebase property.
java -Djava.rmi.server.codebase=http://yourhost:8080/
EchoApp.EchoServer
The client should still work, even if the stub is no longer available
from the class path.
Once you are convinced the download of code works, try to break it to
find out how robust the system is. Try the following:
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Advanced RMI
Object Factories
A servant must be running to be used by its clients, but a client cannot
start a servant directly (this is the job of the server). The technique that
defines this limitation is called object factory and allows the creation of
multiple instances of remote objects on the fly, controlled by the client
application.
The cast from EchoImp to Echo in line 3, which is needed to fulfill the
return value defined in the interface definition. With this factory
implementation, a client can create different remote Echos
dynamically.
The Echo server does the same task. It creates a servant that is up and
running and waiting to be called. However, the servant is the factory.
The factory then is in charge of instantiating instances of Echo.
EchoFactory factoryRef = new EchoFactoryImpl();
The client now has the additional job of requesting one or more Echo
instances. But first, it needs a reference to the remote factory object
from the registry:
EchoFactory remoteFactory =
(EchoFactory)Naming.lookup(url);
Tasks
4. Create the implementation for the new factory interface. Take the
EchoImpl.java as a model. Name the new file
EchoFactoryImpl.java. The goal of the getEcho method is
to create new instances of objects that implement the original
Echo interface and to return a handle to this new instance.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Object Activation
Before the release of the Java 2 SDK, a remote object had to be
instantiated and running on the server before it could be used. This
can be inefficient, because not all objects are used all the time. For
example, a remote object that is used only on Sundays should not be
required to be running seven days per week. The Java 2 SDK changes
this. There is a new remote object class, which complements
UnicastRemoteObject: java.rmi.activation.Activatable. An
object of this type can be activated (instantiated), deactivated
(potentially serialized), and reactivated (deserialized) on demand. All
this is completely transparent to the client: as far as the client is
concerned, all objects are constantly active, just like before.
Modifying EchoImpl
2. Modify the class declaration so that the class now extends from
java.rmi.activation.Activatable.
public class EchoImpl
extends Activatable implements Echo {
Unlike the RMI server class that must stay alive as long as the
implementation needs to be made available, the job of the “setup”
class is to create all the information necessary for the activatable class,
without creating an instance of the remote object.
The setup class passes information about the activatable class to rmid,
and registers a remote reference (an instance of the activatable class's
stub class) and an identifier with the rmiregistry. The setup class
then exits. There are six steps to creating a setup class:
2. Install a SecurityManager.
System.setSecurityManager(new RMISecurityManager());
ActivationGroupID agi =
ActivationGroup.getSystem().registerGroup(adg);
ActivationGroup.createGroup(agi,agd,0);
ActivationDesc desc =
new ActivationDesc("EchoApp.EchoImpl", location, data);
Tasks
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
RMI “Agents”
By exploiting this capability of leaving the actual implementation of an
object until runtime, you can design an RMI system in which the
server receives objects from clients and executes those objects on the
client’s behalf.
The servant calls the Agent’s run method and passes the modified
Agent back as the return argument.
2. The CalcFactorial class travels over the wire to the server (it is
serialized on the client, sent to the server, and deserialized on
arrival). The server is now in possession of an exact copy of the
CalcFactorial class the client created.
You might wonder if, instead, it would have been simpler to make the
Agent a remote interface, and create an AgentImpl class. But this
method’s setup is powerful enough to create additional classes that
implement the Agent interface. Because a client takes the name of the
Agent from the command line, you do not have to change anything to
support the new agents. You do not have to recompile any of the
Worker classes, stop and restart the RMI system, or install modified
code on the server. The name Worker is appropriate; it is a generic
service to “work” on compute-intensive tasks.
Exercise objective – Use the provided Agent code and test whether
anything can be gained by letting the Agent run on somebody else’s
machine.
Preparation
Team up with somebody else (preferably somebody with either a
slower or a faster machine than you have).
Tasks
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
HTTP Tunneling
RMI provides a means for clients behind firewalls to communicate
with remote servers. This allows you to use RMI to deploy clients on
the Internet, such as in applets available on the World Wide Web.
● If this also fails, build a URL to the server’s host using port 80 (the
standard HTTP port) using a CGI script that forwards the posted
RMI request to the server.
✓ The client application may disable the packaging of RMI calls as HTTP requests by setting
the java.rmi.server.disableHTTP property to be true.
✓ By default only port 80 is used.
Tasks
▼ sum returns an int value showing how many times the remote
method increment was invoked. It should be called after the
iterations have finished.
This calls the remote method 1000 times. The client console should
then look like the following:
sum = 0
Now calling the remote method
Average Time for a method call = 1.7 milliseconds
The client measures the time at the beginning of the loop and at
the end. Dividing the time measured by the number of loops
returns the average time a remote call takes. The method for
getting the current time is System.currentTimeMillis.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Before continuing on to the next module, check that you were able to
accomplish the following in this module:
❑ Generate client stubs and skeletons for remote services using the
RMI stub compiler
Objectives
Upon completion of this module, you should be able to:
● Explain why the RMI Agent example does not work with the
current CORBA
4-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
4
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
● How would you wrap existing legacy code (C, C++, COBOL)?
✓ This is the primary function of CORBA. This technology is exemplified by JavaIDL. CORBA
allows problems to be modeled in a single language (IDL) and then compiled to other
languages.
● How does a system publish its services in such a way that any
client can request any service?
✓ This is the job of the ORB—to provide a central naming service for all services.
✓ This module covers JavaIDL. All of the IDL mapping and features described are supported
by JavaIDL. There are other features that are supported by other implementations of
CORBA—this document is intended only to introduce students to JavaIDL.
✓ JavaIDL supports IIOP, a generic ORB core that communicates via IIOP; an idltojava
“compiler” that generates both stub and skeleton code; and an implementation of the
CORBA Object Service (COS) Naming service called tnameserv.
ORB Implementation
Object Adapter
In general, an adapter allows objects with incompatible interfaces to
communicate. CORBA defines the object adapter as an ORB
component that provides object reference, activation, and state-related
services to an object implementation. These include:
● Invoking methods
✓ Explain that the object adapter, represents a basic design pattern of OO software
engineering. Like an electrical adapter, it is used to connect interfaces which do not
communicate directly.
CORBAfacilities
This is a collection of shared services at a higher architectural level
than the CORBAservices.
In general:
● Accounting
● Application development
● Computer-integrated manufacturing
● Currency
● Distributed simulation
● Information superhighways
● Internationalization
● Mapping
● Security
● Telecommunications
● On the server side, the IDL is compiled and “linked” into the
legacy code. This can happen by calling legacy libraries, or, in
some cases, compiling the legacy code directly into the skeletons
created by the IDL compiler.
JavaIDL is a good choice on the client, as long as you do not need any
special features: tunnelling of IIOP through HTTP (to circumvent
firewalls), and using SSL to encrypt the IIOP datastream. If you need
these features, you must switch to another ORB on the client. RMI
supports both features (SSL since Java 2 SDK), so there is a chance that
JavaIDL will support tunnelling and SSL as well.
● An interface repository
After learning the basics, you can start with the first step of creating
your own CORBA application: declaring the interface of your server
object. With RMI, you used the Java programming language to do this;
you declared a Java interface that described the server object.
The IDL standard, like a Java interface, declares only the interface of
the server objects, abstracting all of the implementation details.
JavaSoft’s JavaIDL generates both stub and skeleton code from an IDL
file by compiling the IDL file with idltojava. The IDL compiler for
JavaIDL generates a set of stubs and skeletons that provide
functionality for static invocation on CORBA objects.
● The ORB uses the object reference to determine which remote ORB
should receive the request, passes the marshalled parameters over
the wire to the ORB, and waits for a result.
5. Create the client, which uses the remote object (in the end, the
client uses the servant).
6. Create the Java class files. Use the Java technology compiler (“Java
compiler”) javac to create the Java technology class (“Java class”)
files for all of the Java technology files (“Java files”).
The IDL file is the contract between the server object and the client
application. It is usually developed at the time a new server object is
developed. Therefore, in a productive CORBA environment, the IDL
for existing server objects can usually be acquired, if you have to
develop a matching Java client.
Assuming the JavaIDL directory is in your path, compile the IDL file
by specifying what you want idltojava to do with the file. For
example, the simplest use of the compiler is to generate both client
code (stubs) and server code (skeletons), and not to use a preprocessor
first (CPP).
idltojava -fno-cpp Echo.IDL
For each interface, you must write a servant class. Instances of the
servant class implement ORB objects. Each instance implements a
single ORB object, and each ORB object is implemented by a single
servant.
The server is what the ORB uses to instantiate and publish the servant.
In its simplest form, the server pre-instantiates all the needed servants
and keeps them alive forever (or at least as long as the server lives). In
a production system this is usually not good enough. To keep
thousands of servants alive, even when they are not actively used by
clients, is a waste of resources. In this case, more complex servers must
be developed and used. They must be able to instantiate servants on
demand, and maybe even persist and discard them after a period of
non-usage. The server, EchoServer.java, is a simple one:
1 package EchoApp;
2
3 import org.omg.CosNaming.*;
4 import org.omg.CORBA.*;
5
6
7 public class EchoServer {
8 public static void main(String args[]) {
9 try{
10 // create and initialize the ORB
11 // pass the command line arguments to it
12 ORB orb = ORB.init(args, null);
13
14 // create servant and register it with the ORB
15 // it is now a CORBA object,
16 // but not yet retrievable
17 // via the COS name server.
18 EchoImpl echoRef = new EchoImpl();
19 orb.connect(echoRef);
20
21 // get the remote reference to the
22 // COS name server
Echo was used as a name to bind the servant into the name server.
Now use the same name to look it up. The result is an object of type
org.omg.CORBA.Object, but you need an object of type Echo. A
simple cast, such as(Echo)ncRef.resolve(path) does not always
work; it depends on the ORB. The CORBA way to do casting is to use
the narrow-method of the generated helper class
EchoHelper.narrow.
You start the server next, which creates the servant and registers it
with the name server.
java EchoApp.EchoServer
This might be a good time to find out why passing arguments works:
nothing was done in the code to support this. You should be able to
find this out by yourself, by looking through your EchoClient source
code and the Java documentation.
✓ The line ORB orb = ORB.init(args, null); passes all the command line arguments
unchanged to the ORB. Unfortunately, the documentation of the valid parameters is a little
hard to find: The ORB.init method documentation reveals nothing. Currently, the
description of the valid parameters can be found in the Java 2 SDK documentation,
JavaIDL part, “Programming Guide”, section “initialization”. Part of this section is also a
description on how to set the parameters for an Applet.
Tasks
Work through the six steps described in this module to compile the
Echo application.
2. Team up with somebody and distribute the client and the server
part of Echo on two different machines.
After Echo runs successfully, try to break the code in several ways to
test the fault tolerance of the JavaIDL.
▼ Comment out the part at the end, where the server stops
“forever.”
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
What Is Bootstrapping?
Using remote objects in a client application is easy and transparent,
once you have the references. The bootstrapping protocol describes
how you can get at the initial remote object references in a
standardized way.
If this protocol were not standardized, then every ORB vendor would
do it differently. Consequently, an applet written for Visibroker would
not work if run on a client with only JavaIDL installed. You would
have to download not only the applet, but also the Visibroker ORB to
the client, which wastes bandwidth.
Alternatively, you can use the ORB to resolve a named object reference
to an actual reference. This might be necessary if no naming service is
available.
The following line retrieves the ORB, when called from a Java
application:
ORB orb = ORB.init(args, null);
● ORB.list_initial_services()
● ORB.resolve_initial_references()
NamingContext ncRef =
NamingContextHelper.narrow(objRef);
Preparation
Copy EchoApplet.java and EchoApplet.html to
ServicesApplet.java and ServicesApplet.html.
Tasks
1. See what happens if you use the second field in naming (kind)
▼ When looking up the object, but use a wildcard (“*”) as the kind
✓ Surprisingly, both the name and the kind have to match, and wildcards do not work. This
is surprising because the kind is only a further description of the object, and not really a
part of the name.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
With IDL, you can declare items that are unknown to the Java
programming language, such as constants, structs, or variable size
arrays. Because there are several ways to implement these declarations
using constructs known to the Java programming language, a standard
on exactly how the IDL-to-Java programming language mapping is
done is needed. This section covers the details of this standard,
including how each IDL keyword maps to the Java programming
language.
Module Construct
The module construct is used to scope IDL identifiers. Here EchoApp is
the enclosing scope:
1 // IDL
1 module EchoApp {
2 ...
3 };
Interface Construct
An interface defines the basic IDL service. Interfaces are a collection of
attributes, exceptions, and operations that can be requested of an object
by a client. JavaIDL maps IDL interfaces to a Java interface. The issue
is that IDL supports multiple inheritance of interfaces only (as IDL
defines interfaces only) while the Java programming language
supports multiple inheritance of interfaces, it does not support
multiple inheritance of classes.
Interface Example
Consider the following example of an IDL interface:
1 // IDL
2 module EchoApp {
3 interface Echo {
4 ...
5 };
6 };
Operations
Parameters
1. Technically, if you pass an object by value in the Java programming language, you
pass a copy of the reference variable. Therefore it is true that the Java programming
language does not support passing by value.
Attribute Declaration
An interface can have attributes as well as operations. IDL attributes
are similar to JavaBeans properties: an attribute definition is logically
equivalent to declaring an accessor and a mutator function. These,
respectively, retrieve and set the value of the attribute. The optional
readonly keyword indicates that there is only an accessor function.
Raises Expressions
Thetypedef Keyword
IDL provides constructs for naming data types. The typedef keyword
is used to associate a name with a data type.
typedef long IDNumber;
typedef string SSNumber;
float float
double double
long, unsigned longa int
long long, unsigned long long* long
short, unsigned short* short
unsigned long int
unsigned short int
char, wchar char
boolean boolean
octet byte
string, wstring java.lang.String
enum, struct, union class
a. It is up to the developer to maintain the accuracy of unsigned numbers
because Java technology does not support unsigned types.
// generated Java
package EchoApp;
public final class Address {
//instance variables
public String name;
public boolean grownUp;
● It is one-dimensional.
Array
IDL arrays are mapped in the Java programming language in the same
way as the bounded sequence. The difference is that while a bounded
sequence can accept arrays smaller than its bound, the array must be
exactly the same size. The size is checked when the array is marshalled
as an argument to an IDL operation.
Tasks
The IDL, the server, and the client are already written and do not
need to be changed.
3. Compile the servant and run it. It does a DB lookup, but does not
use the retrieved ResultSet to fill in the sequence. Compile and
run the provided application to confirm that it is working.
4. Replace the existing code with code that converts the ResultSet
into an array of Coffee! (Hint – Use a Java programming language
Vector temporarily.)
In this exercise, you use an IDL containing the most important IDL
keywords: MappingTest.IDL. This IDL can be used to test the whole
range of the IDL to Java programming language mapping
specification.
2. Compile the IDL file, and look at the various generated files,
especially MInterface.java. MStruct.java,
MSequenceHolder.java, MEnum.java and MEnumHolder.java,
because these are the classes that are used in the source code.
5. Change the client so that the custom exception gets fired (look at
the servant code to see how to trigger this). Even if you fill in the
arguments on the servant before throwing the exception, they are
not sent back to the client.
▼ Instead of using the Holder you get, create a new one (that is,
replace theMSequenceHolder.value = new ... with
theMSequenceHolder = new MSequenceHolder...). What
happens?
✓ A CORBA internal error is thrown. You are allowed to replace the value of a holder, but
never the holder itself.
▼ The sequence is bounded, as you can see in the IDL file. Try to
give back too many elements. What happens?
✓ A CORBA marshalling error, org.omg.CORBA.MARSHAL, is thrown.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
module WorkerApp {
interface Worker {
void accept (inout AgentApp::Agent agent);
};
};
The source code is derived from the RMI example, so it looks similar.
One difference is in the IDL. It contains an additional method, long
getResult. You will see later why you need this method. Another
difference is the requirement for a holder class: inout arguments get
mapped this way. The following is a section from
WorkerClient.java:
Agent agent = new CalcFactorial(10);
AgentHolder holder = new AgentHolder(agent);
workerRef.accept(holder);
System.out.println("Returned from remote call\n");
agent = holder.value;
System.out.println("Result: " + agent.getResult());
Tasks
Solve the Agent Example From RMI With JavaIDL and Find the
Differences From RMI
● On what class does the holder “hold” the client before returning:
CalcFactorial.class or _AgentStub.class?
✓ CalcFactorial.class. After all, you just created this object and assigned it to the holder’s
value.
● On what class does the holder “hold” the client after returning:
CalcFactorial.class or _AgentStub.class?
✓ _AgentStub.class. A remote reference to the newly created CalcFactorial on the server is
passed back.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
If you call run from the WorkerServant code, you will do a remote
call, this time back to the client. This is what is known as a callback. The
server calls back to the client, and the roles are reversed.
Now that you know this rule, what happens if you create a new
CalcFactorial on the server, and pass this object back inside of the
holder class? Again, the rule holds. You cannot send back a copy of the
object to the client; it has to be a remote reference. An unusual situation
now exists. You had a local object on the client before the accept call,
and a remote reference right after the call. This gets confusing, for both
you as the developer and for CORBA. The ORB on the server keeps a
reference to the newly created CalcFactorial, because CalcFactorial is a
CORBA object. Theoretically, it could be dropped once the server ORB
“knows” that no remote references to this object exist anymore (which
is the case as soon as the client exits). This behavior is known as remote
garbage collection. However, JavaIDL does not implement remote
garbage collection, and so the object stays on the server forever,
wasting resources.
This callback is also the reason why you needed the additional method
getResult. The server created a CalcFactorial, but the client does
not “know” this. As far as the client is concerned, it gets back a remote
reference to an Agent, not to a CalcFactorial. (You do not even
have an IDL for a CalcFactorial.) If the Agent does not have a
method getResult, the client cannot get at the result of the
calculation. Compare this to the RMI case. There, you got back a copy
of an Agent, which happened to be a CalcFactorial. Because you do
have the copy back on the client, you can cast it to any class this Agent
happens to be.
Futures
Objects by Value
You have seen several times that you cannot transmit CORBA objects
by value. This is going to change; the next version of CORBA, 3.0, is
supposed to contain this enhancement. A draft specification is already
under review. You can find the FTP address of the draft document in
the “Additional Resources” section of this module.
✓ At http://www.omg.org/news/pr98/compnent.html you can also find more current
information on the most current version of CORBA.
Another possibility for writing better servers is to use RMI. Once the
RMI over IIOP extension is available, you can write servers using RMI,
with little CORBA knowledge. Because RMI supports object activation
today, you would not have to wait for POA to arrive in JavaIDL.
❑ Explain why the RMI Agent example does not work with the
current CORBA
Objectives
Upon completion of this module, you should be able to:
5-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
Servlets 5-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Servlets Overview
Servlets were first developed for the Java Web Server™. The Servlet
API is generic enough to implement any request-response type of
server, although today’s main usage are Web-based services.
The server calls the servlet’s service method to handle a request from
a client. Servlets are running in a multithreaded environment and
many requests to a servlet’s service method can be made
simultaneously. Therefore, servlets must be implemented in a thread-
safe way. To simplify thread-safe servlets development, a servlet can
implement the SingleThreadModel interface. A single-threaded
servlet’s service method is never called more then once at a time. The
server ensures that the service is never called several times
simultaneously.
Figure 5-1 on page 5-6 shows the class hierarchy for the
javax.servlet package.
Servlets 5-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Servlets API
Servlet
GenericServlet
ServletConfig
ServletContext
ServletRequest
ServletResponse
SingleThreadModel
java.lang.Exception
java.lang.Throwable
ServletException
UnavailableException
Legend
java.io.InputStream Class
ServletInputStream Abstract
Class
java.io.OutputStream Interface
Extends
ServletOutputStream
Implements
Simple Servlet
The implementation of a simple servlet is outlined in the following
example. It extends the GenericServlet class included in the
Servlet package. The GenericServlet implements the Servlet
interface and eases development of servlets, because an
implementation of every method defined by the interface is provided.
1 import java.io.IOException;
2 import javax.servlet.*;
3
4 public class SimpleServlet extends GenericServlet {
5 public void service(
6 ServletRequest request,
7 ServletResponse response)
8 throws ServletException, IOException
9 {
10 // The Servlet's functionality is
11 // implemented here.
12 }
13 }
Servlets 5-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Servlet Interaction
The service method is provided with two parameters, Request and
Response, which encapsulate the interaction with clients or chained
servlets. The request parameter contains all data sent by the client,
including status and meta information. The response parameter is
used to send a result back to the client. Usually the data is read from
an InputStream, processed and written to an OutputStream. The
SimpleServlet’s service method retrieves the two streams as follows:
ServletInputStream in =request.getInputStream();
ServletOutputStream out =response.getOutputStream();
The data format used to communicate is not specified within the API.
It is up to the user to specify how requests and responses are encoded.
The javax.servlet.http package defines new Request and
Response interfaces, which are used to implement HTTP
communication channels.
HTTP Servlets
HTTP servlets are used by Web servers enabled for the Java
programming language to build interactive Web applications, generate
dynamic Web pages, or integrate databases or other systems into the
Web. The servlets are loaded upon request into the running Web
server in response to client requests.
The Java Web Server provided by Sun was the first Web server that
used servlets to build complex interactive Web applications. Today,
many other Web servers are enabled for the Java programming
language servlets.
Servlets 5-9
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Note – You can extend Netscape, Microsoft, and other web server
products with servlet support.
Cookie
Servlet
GenericServlet
HttpServlet
HttpSession
EventListener
HttpSessionBindingListener
HttpSessionContext
ServletRequest
HttpServletRequest
ServletResponse
Legend
HttpServletResponse Class
Abstract
java.util.EventObject Class
Interface
HttpSessionBindingEvent
Extends
HttpUtils Implements
Servlets 5-11
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
HTTP Servlet Example
The following example servlet prints the date and time formatted in
HTML to its response stream. The result displayed by a Web browser
looks similar to Figure 5-3.
1 import java.io.*;
2 import java.util.Date;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5
6 public class DateServlet extends HttpServlet
7 {
8 public void doGet(HttpServletRequest request,
9 HttpServletResponse response)
10 throws ServletException, IOException {
11
12 // set response header fields first
13 response.setContentType("text/html");
14
15 // then write the data of the response
16 PrintWriter out = response.getWriter();
17
18 out.println("<HTML><HEAD><TITLE>");
19 out.println(getServletInfo());
20 out.println("</TITLE></HEAD><BODY>");
21 out.println("<H1>"+getServletInfo()+"</H1>");
22 out.println("<P>This Page has last been " +
23 "accessed on "+new Date()+".");
24 out.println("</BODY></HTML>");
25 out.close();
26 }
27
28 public String getServletInfo() {
29 return "Date Servlet";
30 }
31 }
32
Servlets 5-13
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Exercise: Creating Simple HTTP Servlets
Preparation
1. Change the directory to labfiles/mod5-servlets/lab and
compile DateServlet.java.
Tasks
Run DateServlet and test its functionality.
2. Click on the Reload button several times and watch for the
different response times, from the first to subsequent requests.
Also check the date and time change for each request. Observe
the different response times by shutting the server down and
restarting it. Click on Reload in the browser again.
Run DateCounterServlet
Note – The servlet counts every request and not just requests from one
person or machine. The exercise in this module shows how accesses
from individual persons are counted.
Servlets 5-15
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Servlets 5-17
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Example Usage
When dynamic HTML pages must be created “on the fly” (while the
program is running) or HTML forms must be processed, you can use
HTTP servlets. For HTML page generation, two approaches are used:
● Some Web servers offer Server Side Includes (SSI), where the Web
server parses the requested HTML pages. Special HTML tags can
denote servlets, which are executed by the server. The HTML tag
is replaced by the output of the servlet.
Many Web applications use some sort of HTML form processing, such
as feedback or registration pages, online shopping, or access to other
systems.
Servlets have their own life cycle that is independent of the server’s
life cycle. You can load and unload servlets at runtime. On the first
request for a specific servlet, the server loads the appropriate class files
either from a local disk or through the network. Exactly one instance
of the servlet is created and the servlet’s init method is called. A
ServletConfig object is passed along to the servlet. If the servlet does
not throw an UnavailableException, it is ready to answer requests
through the service method. The server ensures that no service
method call is performed before init returns.
Servlets 5-19
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
● Obtain a stream or a reader object from which the data sent by the
Web browser can be read. The input gathered this way must be
parsed according to the HTML specification to get the data entered
into the form.
Servlets 5-21
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Exercise: Snoop Servlet
Tasks
Run DateLinkServlet
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Servlets 5-23
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Client Interaction
Sessions are either implemented using cookies or special URLs that are
generated on the fly. The session management facilities within the
HTTP servlets package do both in a transparent manner.
Implementations of the Session interface manage sessions. They
provide methods to identify sessions and store and retrieve data
associated with the session.
Servlets 5-25
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Exercise: Session Servlet
Preparation
This exercise requires a Web browser that supports cookies.
Tasks
4. Study the source code and find out how session management is
done using HttpServlets.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Servlets 5-27
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Application Designs
The servlets API is generic; therefore, you can build many different
applications with completely different designs. This section looks at
application designs using HTTP servlets.
Two-Tier Design
In a two-tier architecture, the servlet interacts with the users and gets
and sends data to another system: a database, for example. This design
is best suited for providing a Web front end to legacy systems, which
already contain all the business and application logic.
Of course, you can enhance servlets with business logic and directly
access databases using JDBC. For small applications, with the servlet
as the only client of the database, this design might be a viable
solution. For larger applications with many clients, it would be a bad
choice, because the business logic needs to be rebuilt in the other
clients as well.
Servlets 5-29
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Three-Tier Design
Within a three-tier design using HTTP servlets, the business or
application logic is isolated in a middle tier. The middle tier offers a
more abstract API to the top tier using RMI or CORBA, for example.
The top tier provides for user interaction and forwards the user’s
requests to the middle tier by API calls. The top tiers are small and
lightweight and can be implemented in many different ways, such as
full Java programs, applets, programs built using some other
language, and HTTP servlets. The bottom tier is used to store and
retrieve data. Instead of rebuilding legacy systems, a middle tier can
integrate several systems and databases and build new applications on
top of them. The new API is then used by the clients to interact with
the end users.
Preparation
Check that the path specified in the servlet.properties for the
LeShopServlet exists. Depending on the setup in your classroom,
your path might be different. Look in the properties file or ask your
instructor.
Tasks
Fill out the HTML form in LeShopServlet.html and let the servlet
process the data entered.
3. Fill out the form and send it to the servlet for further processing.
4. Watch the file where the data entered is stored. See how it grows
when more data is entered.
5. Study the source code and learn how data entered in a form is
extracted and processed.
Servlets 5-31
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Before continuing on to the next module, check that you were able to
accomplish the following in this module:
Servlets 5-33
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
5
Think Beyond
Objectives
Upon completion of this module, you should be able to:
6-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
6
Relevance
✓ You need to provide a network-centric broker daemon to which the listeners of the events
connect. A listener typically is a graphical user interface on the workstation of a stock
trader. When the talker application has a new stock quote to deliver, it requests that the
broker daemon distribute that event to any registered listener application. Another
solution consists of the receivers setting up an RMI connection to the talker application,
to periodically poll the talker for new quotes.
In this model, an event can cause any kind of (Java technology) object,
(such as a stock quote, an audio data packet, an alert indicating that an
aircraft engine is getting too hot, or even a user interface component)
to be displayed by the listeners.
Consider the stock quote example. With Object Bus middleware, you
can implement the application without providing a network-centric
broker daemon, and without polling the talker for new events. The
Object Bus provides ubiquitous communication channels to which
listeners of stock quotes (user interfaces on the traders’ desks)
subscribe and to which producers of stock quotes (so-called data
collectors) transmit.
Hub-and-Spoke Architecture
The straightforward approach provides a network-centric “hub”
daemon. Listener applications connect to the hub; talker applications
use the hub to deliver an event on their behalf. There might be a hub
per channel, or a hub serving multiple channels simultaneously.
✓ Hub-and-spoke corresponds to the RMI broker architecture outlined in the “Relevance”
section.
✓ A special range of IP addresses (the class D) has been reserved for IP multicast. The
difference from conventional IP addresses is that applications running in an Intranet can
all bind to the same class D address and receive IP packets sent to the address. IP
multicast addresses thus are location independent.
✓ IP multicast is an unreliable protocol. Messages can get lost or duplicated. It is up to the
Object Bus middleware to provide the necessary reliability protocols. There is no TCP
over IP multicast. One typically creates UDP sockets to communicate through IP multicast.
The Object Bus model is well suited for applications that require one-
to-many or many-to-many transmission of real-time events to a
dynamically changing set of receivers. Examples are systems that push
financial events from a data collection unit to many trader
workstations. Teleconferencing applications and distributed
multimedia are other examples.
✓ Hints on the architecture of the product appear in parentheses. OrbixTalk is a pure C++
product. VisiBroker Event Service is available both for C++ and Java programming
language. Castanet is a pure Java technology middleware. TIBCO ObjectBus is
implemented in C and C++. iBus is a lightweight “pure Java” Object Bus.
SoftWired iBus
You must declare a URL for the channel to which you want to
transmit. registerTalker informs iBus that transmission will take
place using the stack and to the given channel.
Now it is time to create a posting object to fill with a quote for Sun
Microsystems shares. Transmit the posting by invoking the push
operation on the stack object. push is an asynchronous operation
meaning that it returns immediately without waiting until the listeners
have received the posting.
✓ iBus also provides a synchronous (that is, blocking) push operation as well as a
request/reply style operation, called pull.
The iBus protocol stack takes care of fragmenting large postings into
chunks fitting an IP datagram size, recovering from packet loss,
bringing packets in a first-in-first-out order, and so on. More
sophisticated stacks might perform failure detection, posting
encryption, and so on.
Tasks
You can add more Listeners and Talkers now. You can shut a Talker
down, relocate it to another console window, for example, and restart
it without disturbing the Listeners.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
The Stack
iBus applications communicate through so-called communication
stacks. A stack defines a quality of service, such as reliable multicast,
real-time multicast, reliable point-to-point streaming, data encryption,
and so on. iBus is extensible in respect to incorporating yet
unsupported qualities of services.
Posting Objects
Any Java object that is serializable can be transmitted using iBus. This
includes user-defined objects, JFC components, JavaBeans, and so on.
iBus provides the class Posting to help in packing several Java
objects and transmitting them at once.
Exercise objective – Show how you can use objects more complex
than simple Strings in object bus applications.
Tasks
Use the Quote class to send and receive stock quotes in a extremely
simplified stock quote example. Complete the Talker and the Listener
and run the application.
2. Compile Quote.java.
5. Compile the Talker and the Listener and run the application.
6. As more and more people in your class complete the exercise and
run their Talkers, your Listener will automatically get all stock
quotes sent by all Talkers.
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
Before continuing on to the next module, check that you were able to
accomplish the following:
Objectives
Upon completion of this module, you should be able to:
● Write a simple JNDI client that binds a CORBA object into the
service and later looks it up
7-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
7
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
● If all you know about a remote object is its name, how do you get
its reference?
✓ So far, a technology-specific naming service, rmiregistry with RMI and COS naming with
JavaIDL, has been used.
● What do you think about when you hear the term messaging?
✓ Often, email comes to mind. However, messaging is not email. While messaging shares
some characteristics with email (especially the asynchronous nature of the service),
messaging is about asynchronous requests, reports, or events that are consumed by
enterprise applications, not humans.
Overview
A developer now faces this choice: use JNDI, or use the “older” API?
How you decide depends on whether you know the “older” API. If
you know how to reach COS naming, there is no advantage in using
JNDI. On the other hand, once you know JNDI, you can use this
knowledge to reach other naming and directory services easily.
Naming and directory services are often confused, but the following
sections describe the differences.
Naming Services
A naming service does only one task: it looks up an object, given the
object’s name. You have to know the name of the object you are
looking for, or you will not find anything. The types of objects that are
supported depends on the particular naming service. DNS, for
example, supports only IP addresses; COS naming service supports
CORBA objects.
For more information about the directory service part of JNDI, consult
the Java Naming and Directory Interface specification
(http://java.sun.com/products/jndi/ ).
Composite Names
Usually, you do not have one large dictionary that contains all the
names. Instead, the dictionary is distributed in a hierarchical manner.
The domain name system, for example, is highly distributed; each
company manages the machines in its own domain. The domains, in
turn, are managed differently for example, by a public organization
and grouped to a country-wide context. To reach a domain in another
country, still higher hierarchical levels are needed. A single dictionary
would be a namespace.
Architecture Overview
Service Providers
● COS naming
● LDAP
● NIS, NIS+
● Novell NDS
● File system
● rmiregistry
In Module 4, the client and the server both used COS naming directly
to bind and look up the Echo implementation. If you convert to use
JNDI, the picture looks different; the client uses JNDI to look up the
object reference. This is translated using the COS naming service
provider to COS naming. Because it is translated on the client, the
server can continue to use COS naming directly.
You use properties to configure the JNDI core and the individual
service providers. As usual, you can set a property in the form of a
system property (using the -D command-line option), or by passing a
Properties object on JNDI initialization. Because the class
java.util.Properties accepts only Strings, but some service
providers require arbitrary objects to configure themselves, you can
use a java.util.Hashtable instead of a Properties object. Setting
such a property with the -D command-line option does not work.
Exercise objective – Learn about JNDI and the COS naming service
provider by coding an example.
Preparation
Install the JNDI JAR file, and two of the service providers: COS
naming and local file system.
Tasks
So far, in all the JavaIDL examples, the CORBA native naming service,
COS naming, was used. Thanks to the COS naming service provider,
you can use the Java Naming and Directory Interface instead. A
modified client is already provided as part of this exercise. Your job is
to modify the server as well, and then to test whether “old” and “new”
clients and servers can interoperate.
2. Analyze the code of the modified client, which uses JNDI instead
of COS naming to get the remote Echo object reference.
Can You Use the File System Service Provider Instead of COS
Naming?
The Java Naming and Directory Interface unifies the API to different
products. Does it also mask the implementation differences? You can
find out by trying to use the file system service provider instead of the
COS naming service provider.
1. Start with the server code, and replace the COS naming service
provider with the file system service provider. The initial factory
is com.sun.jndi.fscontext.FSContextFactory. Instead of a
handle to the ORB, the file system service provider needs a URL-
like string that indicates the root of the file system. The property
called java.naming.provider.url can be set, for example, to
file:///tmp, or file:///D:/temp
✓ Manage the discussion here based on the time allowed for this module, which was given
in the “About This Course” module. If you find you do not have time to spend on
discussion, then just highlight the key concepts students should have learned from the
lab exercise.
● Experiences
✓ Ask students what their overall experiences with this exercise have been. You may want to
go over any trouble spots or especially confusing areas at this time.
● Interpretations
✓ Ask students to interpret what they observed during any aspects of this exercise.
● Conclusions
✓ Have students articulate any conclusions they reached as a result of this exercise
experience.
● Applications
✓ Explore with students how they might apply what they learned in this exercise to
situations at their workplace.
JMS Domains
There are two different types of messaging products on the market
today. One group of products uses point-to-point semantics; that is, a
message is sent from one sender to one receiver. The other group uses
publish and subscribe semantics, which is typically a many-to-many
approach. The JMS API provides support for both types of messaging
products.
Before continuing on to the next module, check that you were able to
accomplish the following:
❑ Write a simple JNDI client that binds a CORBA object into the
service and later looks it up
Objectives
Upon completion of this module, you should be able to:
8-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
8
Relevance
✓ Present the following questions to stimulate the students and get them thinking about the
issues and topics presented in this module. They are not expected to know the answers to
these questions. The answers to these questions should be of interest to the students,
and inspire them to learn the content presented in this module.
● Will you be using all the technologies you learned about in one
and the same application?
✓ Usually not. RMI and JavaIDL tend to exclude each other. This is not a technical issue, but
one of personal preference, company regulations, or existing legacy code.
From these five technologies, only two overlap to a large degree: RMI
and JavaIDL. Both technologies serve basically the same purpose: they
allow for the development of remote objects. To a lesser degree
RMI/JavaIDL and object buses overlap, because you can solve several
distributed computing problems using either technology.
JDBC Usage
JDBC is used for one simple purpose: to work with databases. In the
Java technology environment, there is no alternative to JDBC. There
are commercial tools to assist the developer, such as Java Blend™ from
Sun Microsystems. But even this tool produces JDBC code as a result.
You can use JDBC directly on a client system, although it is not the
preferred usage. Mostly JDBC is used on a business logic server, which
translates the raw JDBC calls into a higher-level business object. This
object is then called remotely, using RMI or JavaIDL.
Using Servlets
● The third group consists of all the developers that are new to
distributed objects in the Java technology environment, and are
not prejudiced towards a certain solution.
JavaIDL Advantages
● Technical advantages
● Market advantages
JavaIDL Disadvantages
With RMI, Java objects in different VMs can transparently invoke each
other’s methods. Since VMs can exist on different systems, RMI can
provide full polymorphism.
The RMI system enables the garbage collection of active objects. The
distributed garbage collection mechanism frees the developer of all the
tedious memory management.
The 100% Pure Java RMI solution has an obvious drawback: the
interaction with objects written in different languages is not possible.
RMI does not provide methods to use services offered by C++ or
Smalltalk objects. The integration of legacy code is a major problem for
pure RMI applications.
Today CORBA offers services that are not available in RMI. There is,
for example, no event support in RMI; a Java applet waiting for a
specific event notification has to poll its server frequently to get the
updates. The RMI naming service today is non-persistent and quite
primitive. If an object is changed, the rmiregistry daemon has to be
stopped, and the whole RMI subsystem must be restarted.
● RMI over IIOP. With the release of the Java 2 SDK comes the
support for RMI that to work on top of IIOP, thus providing the
following benefits to RMI:
The table in the above overhead summarizes the features of RMI and
JavaIDL. This course shows that the processes of building applications
using these technologies are fairly similar. Each has inherent
advantages the other does not match. Java RMI’s advantage of being
built right into the Java programming language, allowing it to exploit
the full capabilities of the Java programming language will never exist
in JavaIDL. The JavaIDL, though, has the advantage of working with
existing legacy code.
Since most people are familiar with request-reply, but not with
publish-subscribe, two publish-subscribe scenarios are shown on the
next two overheads. The first scenario is an application that is clearly
intended for a bus. The second scenario is an application that could be
solved (and typically is) with request-reply. This would be a case
where request-reply and publish-subscribe overlap.
The client application can be seen as a versatile tuner, which allows the
user to select relevant channels for display. More function-rich clients
are possible as well; for example, the hardware alerts could be
processed in a network management application.
On the overhead, the components are linked only to the bus. The order
entry components publish all the information about a newly entered
order onto a specific channel on the bus. Every component that needs
to know about orders is registered to this channel, and acts
accordingly. New functionality can be added by creating new
components and subscribing them to relevant channels.
Organizational changes can usually be dealt with by updating a few
components only. Other non-affected components never know about
the change, since the channel continues to deliver the expected
information.
Before continuing, check that you are able to accomplish the following:
A-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
A
The IDL-to-Java Compiler: idltojava
Syntax
idltojava [ options | flags ] filename.idl ...
Description
The idltojava utility compiles IDL source code into Java source code.
You then use the javac compiler to compile that source to Java
bytecodes. The IDL declarations from the named IDL files are
translated to Java programming language declarations according to
the mapping from IDL to the Java programming language.
Options
Options are used to pass some environment-specific information to the
idltojava utility. The following three options deal with preprocessor
directives:
Flags
Flags give instructions to the idltojava utility and can be turned on
or off. To turn on a flag, type the following:
idltojava -fflag-name.
For example, the following directs idltojava to print a list giving the
current state of each flag:
idltojava -flist-flags hello.idl
Each flag is set to a default value. Turning a flag off when it is already
off does nothing; similarly, turning a flag on when it is already turned
on does nothing.
The following are the flags you can use with idltojava:
● -fcp – When ON, runs the C/C++ preprocessor on the IDL file
supplied. Default is ON.
CPP – Set this environment variable to the full path name of the
preprocessor executable you want to use.
-f list-flag – When ON, requests that the current state of all the
-f flags be printed. Default is OFF.
● -f write-file – When ON, requests that the Java files that are
generated be written out. idltojava creates a directory named
after the module for the .idl file and puts the .java files in it.
This new directory is in the same directory as the .idl file.
Turning the flag off allows the programmer to validate the IDL
code before writing out the generated Java files. Default is ON.
B-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
B
SQL Commands
● CREATE – Builds a new table with the specified field names and
types
mSQL statements are not case sensitive, but the examples shown here
highlight the keywords with capital letters.
Syntax
The SELECT statement is the primary command used for data retrieval
from a SQL database. It supports the following:
● Joins
● ORDER BY clauses
Where
Note – You must qualify all column names with a table name. mSQL
does not support the concept of uniquely named columns spanning
multiple tables. You are forced to qualify every column name as soon
as you access more than one table in a single SELECT.
Note – Unlike ANSI SQL, you cannot nest a SELECT within an INSERT
(in other words, you cannot insert the data returned by a SELECT).
For example:
INSERT INTO emp_details ( first_name, last_name, dept,
salary)
VALUES ('David', 'Hughes', 'I.T.S.','12345')
Note – Single quotes are possible within a field item by escaping the
single quote: "\".
The DELETE statement is used to remove records from a SQL table. The
syntax for the mSQL DELETE clause is
DELETE FROM table_name
WHERE column OPERATOR value
[ AND | OR column OPERATOR value ]...
Where
● OPERATOR can be <, >, =, <=, >=, <>, or the keyword LIKE.
For example:
DELETE FROM emp_details WHERE emp_id = '12345'
The UPDATE statement is the SQL mechanism for changing the contents
of a SQL record. To change a particular record, you must identify what
record from the table you want to change. The mSQL UPDATE
statement cannot use a column name as a value. Only literal values
can by used as an UPDATE value. The syntax is
UPDATE table_name SET column=value [ , column=value ]...
WHERE column OPERATOR value
[ AND | OR column OPERATOR value ]...
Where
● OPERATOR can be <, >, =, <=, >=, <>, or the keyword LIKE.
For example:
UPDATE emp_details SET salary=30000 WHERE emp_id = '1234'
address
A location on a computer network, on a peripheral device, or in
computer memory.
address space
The range of memory locations to which a CPU can refer;
effectively, the amount of memory a CPU could use if all of the
memory were available.
applet
A Java program that can be included in an HTML page using
the applet tag.
application
Any specific use of the computer. The term is often used
synonymously with program.
application programmer’s interface (API)
The interface to a library or package of language-specific
functions or methods.
browser
A program used to view World Wide Web materials that is
capable of interpreting URLs and understanding different
Internet protocols.
Glossary-1
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
class loader
A class loader is the foundation of the Java virtual machine
(JVM). A class loader is an executable class object that converts
a named class into the bits that make up an implementation of
that class. Class loaders enable the JVM to load a class without
having to know anything about the underlying file system
semantics. Class loaders extend the abstract class
java.lang.ClassLoader and implement the loadClass
method at minimum.
client
A software program that requests information or services from
another software application (server). For example, a browser is
a client that accesses data from HTTP servers.
Common Object Request Broker Architecture (CORBA)
The architecture and specifications aimed at software
developers and designers who want to produce applications
that comply with OMG standards for the ORB.
content handler
A specialized Java program that enhances Java technology
functionality by providing a means to understand a new
content type; for example, email, video, or audio files of
nonsupported types. It is responsible for reading data from a
stream (provided by a protocol handler) and returning an object
representation of the stream’s content.
distributed application
A program that makes calls to other address spaces, possibly on
another physical machine.
distributed computing
The technique of allowing applications running on one machine
to access applications that are running on another machine.
That is, client programs make calls to programs in other address
spaces, either local or remote.
distributed object computing
An extension of distributed computing, where objects are
implemented in an address space separate from the client
program.
Glossary Glossary-3
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Java
An object-oriented programming language developed by Sun
Microsystems to solve a number of problems in modern
programming practice.
JDBC API
A set of interfaces designed to insulate a database application
developer from a specific database vendor.
JavaIDL API
A set of classes and interfaces that enables developers to define
a set of remote interfaces using the CORBA IDL standard, and
maps IDL constructs onto a set of stubs and skeletons that can
be used to create a CORBA implementation.
multicast
A special form of broadcast where copies of the packet are
delivered to only a subset of all possible destinations.
network
A group of connected computers.
NFS
A distributed application that enables remote file systems to be
accessed by the end-user in the same way that a user would
access a local file system.
Object Management Group (OMG)
A nonprofit international consortium dedicated to promoting
the theory and practice of object technology for the
development of distributed computing systems.
Object Request Broker (ORB)
A program that provides the communications infrastructure
that enables objects to transparently make and receive requests
and responses in a distributed environment.
Object Serialization API
A set of classes and interfaces that enables developers to write
Java code that creates persistent storage for Java objects.
one-tier database design
A database written as a single unit, with both the database
engine and the user interface tightly coupled.
protocol
An agreed convention for inter-computer communication.
Glossary Glossary-5
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
serializable
Java objects are serializable if they implement the
java.io.Serializable interface and do not contain references
to nonserializable objects (for example, java.lang.Thread,
java.io.FileOutputStream) unless these references are
marked with the transient keyword. An object that is
serializable may be serialized.
serializing or serialized
Java objects that are serializable can be sent as a stream of bytes
over any type of java.io.Output stream and retrieved using
any type of java.io.InputStream. This includes files, pipes,
and sockets. An object is said to be serialized when it is
converted from its internal in-memory format to the stream of
bytes that can be sent over the wire.
server
In the client-server model for file systems, the server is a
machine with compute resources (and is sometimes called the
compute server) and large memory capacity.
skeleton
A server-side entity that contains a method that dispatches calls
to the actual remote object implementation.
socket
A software endpoint for network communication. Two
programs on different machines each open a socket in order to
communicate over the network. This is the low-level
mechanism that supports most networking programs.
stub
A proxy for a remote object that is responsible for forwarding
method invocations on remote objects to the server where the
actual remote object implementation resides.
TCP
Transport Control Protocol. A virtual circuit protocol of the
Internet protocol family. It provides reliable, flow-controlled, in-
order, two-way transmission of data in a byte stream.
thread
In programming, a process that is part of a larger process or
program.
Glossary Glossary-7
Copyright 2000 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, March 2000, Revision C.1
Copyright 2000 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droits
réservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la
copie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune
forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.
Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un
copyright et licencié par des fournisseurs de Sun.
Sun, Sun Microsystems, le logo Sun, Java, Java 2, JDK, Solaris, JavaSoft, JDBC, JavaIDL, JavaBeans, Write Once Run
Anywhere, 100% Pure Java, et Java Web Server sont des marques de fabrique ou des marques déposées de Sun
Microsystems, Inc. aux Etats-Unis et dans d’autres pays.
Toutes les marques SPARC sont utilisées sous licence sont des marques de fabrique ou des marques déposées de SPARC
International, Inc. aux Etats-Unis et dans d’autres pays.
Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.
Netscape Navigator est une marque de Netscape Communications Corporation.
UNIX est une marques déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company,
Ltd.
L’interfaces d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses
utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour larecherche et le développement du concept
des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive
de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent
en place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
L’accord du gouvernement américain est requis avant l’exportation du produit.
Le système X Window est un produit de X Consortium, Inc.
LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET
GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA
LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE
MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.
Please
Recycle