SlideShare a Scribd company logo
The Common Object Request
Broker Architecture (CORBA
Dr M.Rani Reddy
CORBA
 The Common Object Request Broker
Architecture (CORBA) is a standard
architecture for a distributed objects system.
 CORBA is designed to allow distributed
objects to interoperate in a heterogenous
environment, where objects can be
implemented in different programming
language and/or deployed on different
platforms
CORBA vs. Java RMI
 CORBA differs from the architecture of Java
RMI in one significant aspect:
 RMI is a proprietary facility developed by Sun
MicroSystems, Inc., and supports objects written
in the Java programming langugage only.
 CORBA is an architecture that was developed by
the Object Management Group (OMG), an
industrial consortium.
CORBA
 CORBA is not in inself a distributed objects facility;
instead, it is a set of protocols.
 A distributed object facility which adhere to these
protocols is said to be CORBA-compliant, and the
distributed objects that the facility support can
interoperate with objects supported by other CORBA-
compliant facilities.
 CORBA is a very rich set of protocols. We will
instead focus on the key concepts of CORBA related
to the distributed objects paradigm. We will also
study a facility based on CORBA: the Java IDL.
The Basic Architecture
object client
naming service
naming
lookup
stub
ORB
network
operating
system
object
implementation
skeleton
ORB
network
operating
system
logical data flow
physical data flow
CORBA Object Interface
 A distributed object is defined using a software file similar to
the remote interface file in Java RMI.
 Since CORBA is language independent, the interface is
defined using a universal language with a distinct syntax,
known as the CORBA Interface Definition Language (IDL).
 The syntax of CORBA IDL is similar to Java and C++.
However, object defined in a CORBA IDL file can be
implemented in a large number of diverse programming
languages, including C, C++, Java, COBOL, Smalltalk, Ada,
Lisp, Python, and IDLScript.
 For each of these languages, OMG has a standardized mapping
from CORBA IDL to the programming language, so that a
compiler can be used to process a CORBA interface to
generate the proxy files needed to interface with an object
implementation or an object client written in any of the
CORBA-compatible languages.
Cross-language CORBA application
object client written in Java
stub in Java generated by compiling
the CORBA object interface
ORB written in Java
object implementation written
in C++
skeleton in C++ generated by
compiling the CORBA object
interface
ORB written in C++
Inter-ORB Protocols
 To allow ORBs to be interoperable, the
OMG specified a protocol known as the
General Inter-ORB Protocol (GIOP), a
specification which “provides a general
framework for protocols to be built on top
of specific transport layers.”
 A special case of the protocol is the Inter-
ORB Protocol (IIOP), which is the GIOP
applied to the TCP/IP transport layer.
Inter-ORB Protocols
The IIOP specification includes the following elements:
1. Transport management requirements: specifies the
connection and disconnection requirements, and the
roles for the object client and object server in making
and unmaking connections.
2. Definition of common data representation: a coding
scheme for marshalling and unmarshalling data of each
IDL data type.
3. Message formats: different types of message format
are defined. The messages allow clients to send
requests to object servers and receive replies. A client
uses a Request message to invoke a method declared in
a CORBA interface for an object and receives a reply
message from the server.
Object Bus
An ORB which adheres to the specifications of the IIOP may
interoperate with any other IIOP-compliant ORBs over the
Internet. This gives rise to the term “object bus”, where the
Internet is seen as a bus that interconnects CORBA objects
The Internet
CORBA
object
CORBA
object
CORBA
object
ORB ORB ORB
...
ORB products
There are a large number of proprietary as well
as experimental ORBs available:
(See CORBA Product Profiles,
http://www.puder.org/corba/matrix/)
 Orbix IONA
 Borland Visibroker
 PrismTech’s OpenFusion
 Web Logic Enterprise from BEA
 Ada Broker from ENST
 Free ORBs
Object Servers and Object Clients
 As in Java RMI, a CORBA distributed object
is exported by an object server, similar to the
object server in RMI.
 An object client retrieves a reference to a
distributed object from a naming or directory
service, to be described, and invokes the
methods of the distributed object.
CORBA Object References
 As in Java RMI, a CORBA distributed object
is located using an object reference. Since
CORBA is language-independent, a CORBA
object reference is an abstract entity mapped to
a language-specific object reference by an
ORB, in a representation chosen by the
developer of the ORB.
 For interoperability, OMG specifies a protocol
for the abstract CORBA object reference
object, known as the Interoperable Object
Reference (IOR) protocol.
Interoperable Object Reference (IOR)
 For interoperability, OMG specifies a protocol
for the abstract CORBA object reference
object, known as the Interoperable Object
Reference (IOR) protocol.
 An ORB compatible with the IOR protocol
will allow an object reference to be registered
with and retrieved from any IOR-compliant
directory service. CORBA object references
represented in this protocol are called
Interoperable Object References (IORs).
Interoperable Object Reference (IOR)
An IOR is a string that contains encoding
for the following information:
 The type of the object.
 The host where the object can be found.
 The port number of the server for that object.
 An object key, a string of bytes identifying the
object.
The object key is used by an object server to
locate the object.
Interoperable Object Reference (IOR)
The following is an example of the string
representation of an IOR [5]:
IOR:000000000000000d49444c3a677269643a312e3000000
00000000001000000000000004c0001000000000015756c74
72612e6475626c696e2e696f6e612e6965000009630000002
83a5c756c7472612e6475626c696e2e696f6e612e69653a67
7269643a303a3a49523a67726964003a
The representation consists of the
character prefix “IOR:” followed by a
series of hexadecimal numeric characters,
each character representing 4 bits of
binary data in the IOR.
CORBA Naming Service
 CORBA specifies a generic directory service.
The Naming Service serves as a directory for
CORBA objects, and, as such, is platform
independent and programming language
independent.
 The Naming Service permits ORB-based clients
to obtain references to objects they wish to use.
It allows names to be associated with object
references. Clients may query a naming service
using a predetermined name to obtain the
associated object reference.
CORBA Naming Service
 To export a distributed object, a CORBA object
server contacts a Naming Service to bind a symbolic
name to the object The Naming Service maintains a
database of names and the objects associated with
them.
 To obtain a reference to the object, an object client
requests the Naming Service to look up the object
associated with the name (This is known as resolving
the object name.)
 The API for the Naming Service is specified in
interfaces defined in IDL, and includes methods that
allow servers to bind names to objects and clients to
resolve those names.
CORBA Naming Service
To be as general as possible, the CORBA object naming
scheme is necessary complex. Since the name space is
universal, a standard naming hierarchy is defined in a manner
similar to the naming hierarchy in a file directory
naming context1
naming context1 naming context2
naming context1 naming context1
object
name1
object
namen
...
...
...
...
A Naming Context
 A naming context correspond to a folder or directory
in a file hierarchy, while object names corresponds to
a file.
 The full name of an object, including all the
associated naming contexts, is known as a compound
name. The first component of a compound name
gives the name of a naming context, in which the
second component is accessed. This process
continues until the last component of the compound
name has been reached.
 Naming contexts and name bindings are created using
methods provided in the Naming Service interface.
A CORBA object name
The syntax for an object name is as follows:
<naming context > …<naming context><object name>
where the sequence of naming contexts
leads to the object name.
Example of a naming hierarchy
As shown, an object representing the men’s
clothing department is named
store.clothing.men, where store and clothing
are naming contexts, and men is an object
name.
store
clothing Appliances
women men
...
television
...
Interoperable Naming Service
The Interoperable Naming Service (INS) is a URL-
based naming system based on the CORBA Naming
Service, it allows applications to share a common
initial naming context and provide a URL to access a
CORBA object.
CORBA Object Services
CORBA specify services commonly needed in distributed
applications, some of which are:
 Naming Service:
 Concurrency Service:
 Event Service: for event synchronization;
 Logging Service: for event logging;
 Scheduling Service: for event scheduling;
 Security Service: for security management;
 Trading Service: for locating a service by the type (instead of by
name);
 Time Service: a service for time-related events;
 Notification Service: for events notification;
 Object Transaction Service: for transactional processing.
Each service is defined in a standard IDL that can be
implemented by a developer of the service object, and whose
methods can be invoked by a CORBA client.
Object Adapters
In the basic architecture of CORBA, the implementation of a
distributed object interfaces with the skeleton to interact with
the stub on the object client side. As the architecture evolved,
a software component in addition to the skeleton was needed
on the server side: an object adapter.
distributed object
implementation
object adapter
ORB
Object Adapter
 An object adapter simplifies the
responsibilities of an ORB by assisting an
ORB in delivering a client request to an object
implementation.
 When an ORB receives a client’s request, it
locates the object adapter associated with the
object and forwards the request to the adapter.
 The adapter interacts with the object
implementation’s skeleton, which performs
data marshalling and invoke the appropriate
method in the object.
The Portable Object Adapter
 There are different types of CORBA object
adapters.
 The Portable Object Adapter, or POA, is a
particular type of object adapter that is defined
by the CORBA specification. An object
adapter that is a POA allows an object
implementation to function with different
ORBs, hence the word portable.
The Java IDL (Java 1.4 version)
Java IDL – Java’s CORBA Facility
 IDL is part of the Java 2 Platform, Standard
Edition (J2SE).
 The Java IDL facility includes a CORBA
Object Request Broker (ORB), an IDL-to-Java
compiler, and a subset of CORBA standard
services.
 In addition to the Java IDL, Java provides a
number of CORBA-compliant facilities,
including RMI over IIOP, which allows a
CORBA application to be written using the
RMI syntax and semantics.
Key Java IDL Packages
 package org.omg.CORBA – contains interfaces and
classes which provides the mapping of the OMG
CORBA APIs to the Java programming language
 package org.omg.CosNaming - contains interfaces
and classes which provides the naming service for
Java IDL
 org.omg.CORBA.ORB - contains interfaces and
classes which provides APIs for the Object Request
Broker.
Java IDL Tools
Java IDL provides a set of tools needed for
developing a CORBA application:
 idlj - the IDL-to-Java compiler (called idl2java in
Java 1.2 and before)
 orbd - a server process which provides Naming
Service and other services
 servertool – provides a command-line interface for
application programmers to register/unregister an
object, and startup/shutdown a server.
 tnameserv – an olderTransient Java IDL Naming
Service whose use is now discouraged.
A Java IDL application example
The CORBA Interface file Hello.idl
01. module HelloApp
02. {
03. interface Hello
04. {
05. string sayHello();
06. oneway void shutdown();
07. };
08. };
Compiling the IDL file (using Java 1.4)
The IDL file should be placed in a directory dedicated to the
application. The file is compiled using the compiler idlj using
a command as follows:
idlj -fall Hello.idl
The –fall command option is necessary for the compiler to
generate all the files needed.
In general, the files can be found in a subdirectory named <some
name>App when an interface file named <some name>.idl is
compiled.
If the compilation is successful, the following files can be found
in a HelloApp subdirectory:
HelloOperations.java Hello.java
HelloHelper.java HelloHolder.java
_HelloStub.java HelloPOA.java
These files require no modifications.
The *Operations.java file
 There is a file HelloOperations.java
 found in HelloApp/ after you compiled using
idlj
 It is known as a Java operations interface in
general
 It is a Java interface file that is equivalent to
the CORBA IDL interface file (Hello.idl)
 You should look at this file to make sure that
the method signatures correspond to what you
expect.
HelloApp/HelloOperations.java
The file contains the methods specified in the original IDL
file: in this case the methods sayHello( ) and shutdown().
package HelloApp;
01. package HelloApp;
04. /**
05. * HelloApp/HelloOperations.java
06. * Generated by the IDL-to-Java compiler (portable),
07. * version "3.1" from Hello.idl
08. */
09.
10. public interface HelloOperations
11. {
12. String sayHello ();
13. void shutdown ();
14. } // interface HelloOperations
HelloApp/Hello.java
The signature interface file combines the characteristics of
the Java operations interface (HelloOperations.java) with
the characteristics of the CORBA classes that it extends.
01. package HelloApp;
03. /**
04. * HelloApp/Hello.java
05. * Generated by the IDL-to-Java compiler (portable),
06. * version "3.1" from Hello.idl
07. */
09. public interface Hello extends HelloOperations,
10. org.omg.CORBA.Object,
11. org.omg.CORBA.portable.IDLEntity
12. { …
13. } // interface Hello
HelloHelper.java, the Helper class
 The Java class HelloHelper (Figure
7d) provides auxiliary functionality needed to
support a CORBA object in the context of the
Java language.
 In particular, a method, narrow,allows a
CORBA object reference to be cast to its
corresponding type in Java, so that a CORBA
object may be operated on using syntax for
Java object.
HelloHolder.java, the Holder class
 The Java class called HelloHolder
(Figure 7e) holds (contains) a reference
to an object that implements the Hello
interface.
 The class is used to handle an out or an
inout parameter in IDL in Java syntax
( In IDL, a parameter may be declared to be
out if it is an output argument, and inout if the
parameter contains an input value as well as
carries an output value.)
_HelloStub.java
 The Java class HelloStub (Figure 7e) is
the stub file, the client-side proxy, which
interfaces with the client object.
 It extends
org.omg.CORBA.portable.ObjectImpl
and implements the Hello.java interface.
HelloPOA.java, the server skeleton
 The Java class HelloImplPOA (Figure
7f) is the skeleton, the server-side proxy,
combined with the portable object adapter.
 It extends org.omg.PortableServer.Servant,
and implements the InvokeHandler interface
and the HelloOperations interface.
The application
Server-side Classes
 On the server side, two classes need to be
provided: the servant and the server.
 The servant, HelloImpl, is the implementation
of the Hello IDL interface; each Hello object
is an instantiation of this class.
The Servant - HelloApp/HelloImpl.java
// The servant -- object implementation -- for the Hello
// example. Note that this is a subclass of HelloPOA,
// whose source file is generated from the
// compilation of Hello.idl using j2idl.
06. import HelloApp.*;
07. import org.omg.CosNaming.*;
08. import java.util.Properties; …
15. class HelloImpl extends HelloPOA {
16. private ORB orb;
18. public void setORB(ORB orb_val) {
19. orb = orb_val;
20. }
22. // implement sayHello() method
23. public String sayHello() {
24. return "nHello world !!n";
25. }
27. // implement shutdown() method
28. public void shutdown() {
29. orb.shutdown(false);
30. }
31. } //end class
The server - HelloApp/HelloServer.java
public class HelloServer {
public static void main(String args[]) {
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// get reference to rootpoa & activate the POAManager
POA rootpoa =
(POA)orb.resolve_initial_references("RootPOA");
rootpoa.the_POAManager().activate();
// create servant and register it with the ORB
HelloImpl helloImpl = new HelloImpl();
helloImpl.setORB(orb);
// get object reference from the servant
org.omg.CORBA.Object ref =
rootpoa.servant_to_reference(helloImpl);
// and cast the reference to a CORBA reference
Hello href = HelloHelper.narrow(ref);
HelloApp/HelloServer.java - continued
// get the root naming context
// NameService invokes the transient name service
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
// Use NamingContextExt, which is part of the
// Interoperable Naming Service (INS) specification.
NamingContextExt ncRef =
NamingContextExtHelper.narrow(objRef);
// bind the Object Reference in Naming
String name = "Hello";
NameComponent path[] = ncRef.to_name( name );
ncRef.rebind(path, href);
System.out.println
("HelloServer ready and waiting ...");
// wait for invocations from clients
orb.run();
The object client application
 A client program can be a Java application, an applet,
or a servlet.
 The client code is responsible for creating and
initializing the ORB, looking up the object using the
Interoperable Naming Service, invoking the narrow
method of the Helper object to cast the object
reference to a reference to a Hello object
implementation, and invoking remote methods using
the reference. The object’s sayHello method is
invoked to receive a string, and the object’s shutdown
method is invoked to deactivate the service.
// A sample object client application.
import HelloApp.*;
import org.omg.CosNaming.*; …
public class HelloClient{
static Hello helloImpl;
public static void main(String args[]){
try{
ORB orb = ORB.init(args, null);
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef =
NamingContextExtHelper.narrow(objRef);
helloImpl =
HelloHelper.narrow(ncRef.resolve_str(“Hello”));
System.out.println(helloImpl.sayHello());
helloImpl.shutdown();
Compiling and Running a Java IDL application
1. Create and compile the Hello.idl file on the server
machine:
idlj -fall Hello.idl
2. Copy the directory containing Hello.idl (including
the subdirectory generated by idlj) to the client
machine.
3. In the HelloApp directory on the client machine:
create HelloClient.java. Compile the *.java files,
including the stubs and skeletons (which are in the
directory HelloApp):
javac *.java HelloApp/*.java
Compiling and Running a Java IDL application
4. In the HelloApp directory on the server machine:
 Create HelloServer.java. Compile the .java files:
javac *.java HelloApp/*.java
 On the server machine: Start the Java Object Request
Broker Daemon, orbd, which includes a Naming Service.
To do this on Unix:
orbd -ORBInitialPort 1050 -ORBInitialHost
servermachinename&
To do this on Windows:
start orbd -ORBInitialPort 1050 -ORBInitialHost
servermachinename
Compiling and Running a Java IDL application
5. On the server machine, start the Hello server, as
follows:
java HelloServer –ORBInitialHost <nameserver host
name> -ORBInitialPort 1050
6. On the client machine, run the Hello application
client. From a DOS prompt or shell, type:
java HelloClient -ORBInitialHost nameserverhost
-ORBInitialPort 1050
all on one line.
Note that nameserverhost is the host on which the
IDL name server is running. In this case, it is the
server machine.
Compiling and Running a Java IDL application
7. Kill or stop orbd when finished. The name
server will continue to wait for invocations
until it is explicitly stopped.
8. Stop the object server.
JAVARMI
By
Dr M.Rani Reddy
Remote Method Invocation (RMI)
In Search of the Simplest Communication Form
Main Idea: Working with an object on a remote machine is made to look
like calling a procedure on the remote site, i.e.
• the application/client sends a message to the remote object
• the remote object receives message, does processing and sends back
message with results - the server side;
• the client receives message and uses/prints result
Server Side
send client data
(request)
receive server data/result
(reply)
Remote Object
runs procedure
Client Side
Why do we need yet another mechanism for remote object
communication?
We have sockets, and, if we find sockets tedious, there are intermediate
representations, such as name/value pairs or XML.
They would do the job, yes.
In the traditional client/server model the request is formulated or translated
into an intermediary language, e.g. name/value pairs, XML data. The
server parses the requests, translates it into its language, computes reply,
translates into intermediary languages, sends it to client, then client
repeats the process.
BUT in case of user defined structured data these mechanisms
• require a significant coding effort;
• are not very intuitive and not part of the basic vocabulary/concepts of
programming languages
As opposed to this RMI
• has a form that is familiar even to an entry level programmer;
• naturally extends the "everything is an object" principle to "objects can
be everywhere";
Goals of RMI
More specifically RMI specification goals are listed as follows
(http://java.sun.com/products/jdk/1.2/docs/guide/rmi/spec/rmi-title.doc.html)
• Support seamless remote invocations on objects in different JVMs.
• Support callbacks from servers to clients.
• Integrate the distributed object model into the Java programming language in a
natural way while retaining most of the language's object semantics.
• Make differences between the distributed object model and the java object model
apparent.
• Make writing distributed applications as simple as possible (certainly simpler
than with sockets).
• Preserve the safety provided by the Java run-time environment.
Flexibility and extensibility are provided by:
• Distributed garbage collection.
• Capability to support multiple transports
• Varying remote invocation mechanisms, such as unicast and multicast
Distributed Application Tasks
• Locate Remote Objects: Application can obtain references to remote
objects when
a) objects are registered with the RMI naming facility, the rmiregistry,
or
b) application can pass and return remote object references as part of its
normal operation
• Communicate with remote objects: handled by RMI; looks like standard
Java method invocation to the programmer
• Load class bytecodes for objects that are passed as parameters or return
values: Because RMI allows a caller to pass pure Java objects to remote
object, RMI provides the necessary mechanisms for loading an object's
code as well as transmitting its data
Using the Registry to obtain References to Remote Object
RMI
RMI
RMI
URL
protocol
URL
protocol
Client
Web Server
Registry
Web Server
Server
• Server calls registry to associate name with a remote object.
• Client looks up remote object by name in server's registry.
• Client invokes method on object
Note: The RMI system uses an existing web server to load Java class
bytecodes, from server to client and from client to server, when needed.
RMI can load class bytecodes using any URL protocol (e.g. HTTP, FTP,
file, etc.) that is supported by the Java system.
RMI Architecture
Server
Skeleton
Client
Stub
Remote Reference Layer
Transport Layer
The layers are independent. Each layer is defined by specific protocol
and built using specific interface. Any layer can be replaced by an
alternate implementation without affecting the others, e.g. the current
transport layer in RMI is TCP based, but can be substituted by a UDP
based transport layer
Application
Presentation
Session
Transport
OSI Model
RMI Architecture (continued)
Stub/Skeleton Layer: Interface of the application with the rest of the
system (standard mechanism used in RPC system). This layer transmits
the data to the remote reference layer via the abstraction of marshal
streams that use object serialization.
• A stub is a surrogate for the remote object, its representative on the
client side, that acts as a proxy for the remote object. It resides on the
client side (although it is generated on the server side) and handles all
the interaction with the remote object
• A skeleton handles the communication on the server side (not required
in JDK1.2-only environments)
Remote Reference Layer: responsible for providing ability to support
varying remote reference or invocation protocols independent of client
stubs and server skeletons.
Examples: unicast provides point-to-point invocation, multicast to groups
of objects; other protocols deal with replication strategies or persistent
references to the remote object, such as enabling remote object
activation (supported only by Java2)
RMI Architecture (continued)
Transport Layer: Low level layer that ships the marshal streams between
different address spaces. Responsible for managing connection:
• Setting up connections
• Listening to incoming calls
• Maintaining table of remote objects that reside in same address space
Remote object references are represented by an object identifier and end
point. This representation is called a live reference. Given a live
reference for a remote object the identifier looks up the targeted remote
object and the end point sets up the connection to the address space the
object resides
Distributed Garbage Collection
In stand-alone application object that are no longer referenced by any
client are automatically deleted.
RMI provides distributed garbage collector that automatically removes
objects that are no longer referenced by any client.
RMI uses a reference counting garbage collection that keeps track of all
live references of a given object on each JVM. When a live reference
enters a JVM its count is incremented, when it becomes unreferenced, its
count is decremented; when the count is 0 (no live reference) the object
can be garbage collected. As long as there is a local reference to a remote
object it cannot be garbage collected, since it can be passed to remote
server or returned to a client.
Parameter Marshalling and Unmarshalling
When a client code invokes a remote method on a remote object, it
actually calls an ordinary/local Java method encapsulated in the stub.
The stub encodes the parameters used in the remote method with a device-
independent encoding and transforms them in a format suitable for
transport. The process of encoding, writing to a stream and sending an
object is referred as parameter marshalling.
Thus the stub method on the client side builds an information block that
consists of:
• Identifier of remote object to be used;
• Name of the method to be called
• Marschalled parameters.
The reverse process of receiving, reading and decoding is called
parameter unmarshalling.
RMI in action
Client Stub Skeleton Server
local call to
stub method local call to
server method
Sending
marshalled
parameters
return value or
throw exception
Sending
marshalled return
value or exception
RMI in action (continued)
When a stub's method is invoked, it does the following:
• Initiates connection with the JVM on which remote object resides;
• Marshals the parameters
• Waits for result of method invocation
• Unmarshals the value or exception returned
• Returns value to caller
On the server side, the skeleton or receiver object
• Unmarshals the parameters of the remote method
• Locates object to be called
• Calls desired method on remote object implementation
• Captures and marshals return value or exception to the caller.
Anatomy of a simple RMI-based application
Example 1: Product Info Client-Server
Client Server
myProduct . getDescription()
calls remote / sends arguments
returns description
• Server program in class
ProductServer
• Remote Interface Product
• Interface Implementation in class
ProductImpl
• ProductImpl_Stub automatically
generated by the rmic compiler
from the ProductImpl class
• Client program in class
ProductClient
• Remote Interface Product
• ProductImpl_Stub automatically
generated by the rmic compiler
from the ProductImpl class
(HoCo 2002, Ch. 5, Examples 5-1,2,3,5, p. 343-347)
The Remote Interface
• The remote interface must be public (it cannot have package access, i.e
it cannot be "friendly"). Otherwise the client cannot load a remote
object that implements the remote interface
• The remote interface must extend the interface java.rmi.Remote.
• Each method in the remote interface must declare
java.rmi.RemoteException in its throw clause in addition to any
application-specific exceptions. This is necessary as remote methods
are inherently less reliable than local ones.
Example: remote interface Product
//The Product information remote interface
/**
*@(#) Product.java
*/
import java.rmi.*;
public interface Product extends Remote{
public String getDescription( ) throws RemoteException;
}
remote interface
must for all methods
in remote interface
Server Side: Implementing the Remote Interface: class
ProductImpl
/**
*@(#) ProductImpl.java
*/
import java.rmi.*;
import java.rmi.server.*;
public class ProductImpl
extends UnicastRemoteObject
implements Product {
//Constructor
public ProductImpl ( String n)
throws RemoteException {
//super(); called by default
name = n;
}
implements
remote interface
constructor must be explicitly
defined, even if it is just the
default, because it must throw the
RemoteException
must extend server subclass
UnicastRemoteObject, i.e. it
is a server class
Implementing the Remote Interface: class ProductImpl
(continued)
//implementation of remote interface method
public String getDescription( )
throws RemoteException {
return "I am an excellent " + name + ". Buy me!";
}
private String name;//product name
}
UnicastRemoteObject - API Specification
public class UnicastRemoteObject extends RemoteServer
• Concrete class;
• defines a non-replicated remote object whose references are valid only
while the server process is alive;
• provides support for point-to-point active object references (invocations,
parameters, and results) using TCP streams.
Object
RemoteObject
RemoteStub RemoteServer
(abstract class)
UnicastRemoteObject
Remote
Server Side Security
In the main( ) method of the server program (here implemented in class
ProductServer) :
• Create and install security manager to support RMI
System.setSecurityManager (new RMISecurityManager( ) );
Note: Server examples in the RMI tutorial documentation typically have a
security manager installed. However, it is the client not the server that is
more in need of a security manger, at it is the one downloading files. A
security manger on the server side is a must only if the server is in its turn
a client, or there is a special reason to put restrictions.
The Server creates and registers remote objects
• Create one or more instances of the remote object (ProductImpl);
• An application can bind, unbind, and rebind registry object references only
if it runs on the same host as the registry. This shields the registry from
hostile clients attempting to change registry information. However, any
client can lookup objects.
• Register at least one of the remote objects with the RMI remote object
registry. The server registers the object with the bootstrap registry service
and the client retrieves stubs to those objects. An object is registered by
giving the registry its reference and a name:
ProductImpl p = new ProductImpl("Laptop");
Naming. bind("//host/Laptop", p);
In general:
Naming. bind("//<hostName>/<ObjRegistryName>", <objReference>);
The RMI default port is 1099
The Server … (continued)
Optionally, one can also specify a port instead of the default through:
Naming. bind("//host:3000/Laptop", p);
In general:
Naming. bind (
"//<hostName:portnumber> /<ObjRegistryName>", <objReference>);
A remote object can have methods that produce references to other objects.
This allows setting it up so that the client goes to the registry only once. As
it is notoriously difficult to keep names unique (and the names objects are
registered with should be unique), one should register as few objects as
possible. If one tries to register an object with a name that is already taken,
one gets the AlreadyBoundException. To avoid this one can use rebind()
instead of bind(): rebind() either adds a new entry or replaces the existing
one.
The Client accesses remote objects
• The client gets access to a server object that implements the interface
Product by creating a variable of type interface Product. The value that
is looked up and returned by the server is stored in the variable of type
interface.
The Naming.lookup() method is called and the remote host and object
name are specified:
Product a = (Product) Naming.lookup(" rmi: //host/Laptop");
or
Product a = (Product) Naming.lookup(“rmi: //host:3000/Laptop");
• A method on the remote object is then called through
a . getDescription()
Note: the form of the remote call is exactly the same as the form of a local
call!!
optional
Interface Objects Access Remote Objects
The client variable a, making the remote call
a . getDescription()
is an object of type remote interface (Product), NOT an object of class remote
interface implementation (ProductImpl).
Why do we cast to the remote interface instead of to the class that implements it?
The simple answer is: because the client does not have the class that implements
the interface.
On the other hand interfaces are abstract entities that define methods only, not
objects. Thus whenever we have an object variable of some interface type, it
must be bound to a real object. This is where the stub class comes to the rescue!!
The interface object refers to a stub object, which is an actual object of the stub
class, i.e. when calling the remote method the remote interface object refers to the
stub object representing the remote interface implementation class. The client
does not actually know the type of the remote object. It relies on the stub that is
obtained by running a special compiler rmic on the remote interface
implementation class (ProductImpl.class), and is somehow (by hand, or through
another call) obtained from the server
The Server program: class ProductServer
/**
*@(#) ProductServer.java
*/
import java.rmi.*;
import java.rmi.server.*;
class ProductServer{
public static void main(String args[]) {
try{
System.setSecurityManager(new RMISecurityManager());
System.out.println("Starting server...");
System.out.println("Creating remote objects...");
ProductImpl p = new ProductImpl("Laptop");
ProductImpl q = new ProductImpl("Display");
System.out.println("Binding remote objects to registry...");
Naming.rebind("//host/Laptop", p);
Naming.rebind("//host/Display", q);
System.out.println("Waiting for client call...");
}catch (Exception e){
System.out.println("Server error:" + e);
}
}
}
The Client program: class ProductClient
//**
*@(#) ProductClient.java
*/
import java.rmi.*;
import java.net.*;
public class ProductClient {
public static void main(String args[]){
try{
Product a = (Product)Naming.lookup("//host/Laptop");
Product b = (Product)Naming.lookup("//host/Display");
System.out.println( a.getDescription( ) );
System.out.println(b.getDescription());
}catch (Exception e){
System.out.println("Client error:" + e);
}
System.exit(0);
}
}
Client should have security
manager to protect
Location of RMI class files
Server
• Server implementation classes
• Remote interface classes
• Remote interface implementation
class
• Stub classes
• Skeleton classes
Client
• Client implementation classes
• Remote interface classes
• Stub classes
When building an RMI application threr are basically five categories of
files that are generated
• Remote interface classes
• Client implementation classes
• Server implementation classes , including the remote interface
implementation class
• Stub classes
• Skeleton classes
To run the application these classes must be distributed as follows
Server Side Classes and Objects
interface <RemoteInterface> extends Remote
class <RemoteInterfaceImpl >
extends UnicastRemoteObject
implements RemoteInterface
//constructor
public <RemoteInterfaceImpl> throws RemoteException {…}
//implementation of RemoteInterface methods
public <remoteMethod> (…) throws RemoteException
class <RemoteInterfaceServer>
main()
create & set RMISecurityManager
create server objects <objRemoteInterfaceImpl > of type
<RemoteInterfaceImpl>
bind <objRemoteInterfaceImpl> through
Naming.rebind(" //<host>/<objName ", <objRemoteInterfaceImpl>)
class <RemoteInterfaceImpl>_Stub: automatically generated by rmic;
class <RemoteInterfaceImpl>_Skel: automatically generated by rmic;
not needed in JDK1.2s
Client Side Classes and Objects
interface <RemoteInterface> extends Remote
class <RemoteInterfaceClient>
main()
set RMISecurityManager
create client objects <objRemoteInterface> of type <RemoteInterface>
(note difference to server !!) through
<RemoteInterface> <objRemoteInterface> =
(<RemoteInterface>) Naming.lookup ("//<host>/<objName> ")
call remote method through
<objRemoteInterface> . <remoteMethod>(…)
class RemoteInterfaceImpl_Stub: automatically generated by rmic;
Location of RMI class files - Notes
• The stub classes are executed only by the client. However, they are also
needed by the server when it is exporting itself for remote access.
• Most RMI applications do not have a cleanly separated client and server
functionality, i.e. any participating site has elements of the server as well
as the client. Indeed , one of the great strength of RMI is that the server
can make remote method calls to the client. It is entirely possible to
create pure peer-to-peer RMI applications that have no distinction
between the their endpoints. In these cases, the site where a given remote
object resides should include all class files (thus being the “server” for
this object), while the site from which the object is remotely accessed
includes only the interface and the stub.
Testing the Distributed Application on a single machine
1. Create two separate directories for the client and the server and place the
corresponding *.java files in them.
2. Compile the source files for the interface, implementation, client and server
classes, e.g.
javac Product*.java
C:Coursescs667CompiledExamplesProductRMIProductClient>javac
ProductClient.java
C:Coursescs667CompiledExamplesProductRMIProductClient>dir
Directory of C:Coursescs667CompiledExamplesProductRMIProductClient
09/25/2002 05:20 PM 219 Product.class
10/11/2000 07:05 PM 227 Product.java
09/25/2002 05:20 PM 946 ProductClient.class
09/25/2002 02:42 PM 578 ProductClient.java
C:Coursescs667CompiledExamplesProductRMIProductServer>javac
ProductServer.java
C:Coursescs667CompiledExamplesProductRMIProductServer>dir
Directory of C:Coursescs667CompiledExamplesProductRMIProductServer
09/25/2002 05:30 PM 219 Product.class
02/04/2002 12:00 AM 230 Product.java
09/25/2002 05:30 PM 641 ProductImpl.class
02/04/2002 12:00 AM 643 ProductImpl.java
09/25/2002 05:30 PM 1,096 ProductServer.class
02/04/2002 12:00 AM 776 ProductServer.java
3. On server side: compile the <objRemoteInterfaceImpl> with the rmic compiler from
the command line (in DOS window), e.g.
rmic ProductImpl
This produces the stub and skeleton for the implementation:
ProductImpl_Stub.class and ProductImpl_Skel.class
There is an option for Java 2 compilation
rmic –v1.2 ProductImpl
that produces only ProductImpl_Stub.class (skeleton is not needed any more)
More generally: rmic <options> <ImplementationClassName>
(see documentation for rmic optional argument list)
C:Coursescs667CompiledExamplesProductRMIProductServer>rmic
ProductImpl
Directory of C:Coursescs667CompiledExamplesProductRMIProductServer
09/25/2002 05:30 PM 219 Product.class
02/04/2002 12:00 AM 230 Product.java
09/25/2002 05:30 PM 641 ProductImpl.class
02/04/2002 12:00 AM 643 ProductImpl.java
09/25/2002 05:35 PM 1,434 ProductImpl_Skel.class
09/25/2002 05:35 PM 2,876 ProductImpl_Stub.class
09/25/2002 05:30 PM 1,096 ProductServer.class
rmic Produces Stub and Skeletons
Stub Classes Needed by Server and Client
4. To perform a first test on a single machine without using automatic class
downloading place a copy of the stub class in the client directory. (If you did not
place and compile a <RemoteInterface>.java file in the client directory, now is
the time to place a copy of the <RemoteInterface>.class on the client side). If
you are working with projects in an IDE and are starting the server and client
from the project, you typically need to add the stubs and skeletons in the
corresponding projects.
Of course, when deploying a real application the stub and remote interface
classes will be always automatically downloaded. The above is for testing
purposes only.
Note: For the JDK1.1.1 localhost does not work with RMI and the name of the machine must be provided.
Under 32 bit Windows you can find the machine name as follows: go to Control Panel, select
“Network”, select “Identification” tab and you will see the Computer Name.
Start the RMI Registry
5. In the server directory start the RMI registry:
start rmiregistry or start rmiregistry 3000 for Windows
rmiregistry & or rmiregistry 3000& for Unix
Make sure you have an active TCP/IP connection, i.e. you must be connected to your
Internet service provider.
The registry is launched in separate window and bound to the specified port (default
1099) on machine executing the command. No text/message appears in the
command line registry window:
If you attempt to start the server before the rmiregistry is running the the
java.rmi.ConnectException is thrown.
C:Coursescs667CompiledExamplesProductRMIProductServer>start rmiregistry
Run the Server
6. Start server
start java ProductServer for Windows
(w/o start runs in same window)
java ProductServer & for Unix
Note: In Unix, if the process is not run in the background, it never finishes
normally. The main function exits immediately after registration as
expected. However, when an object of a class that extends
UnicastRemoteObject is created, a separate thread is started that keeps the
program alive indefinitely.
C:Courses667CompiledExamplesProductRMIProductServer> java ProductServer
Starting server...
Creating remote objects...
Binding remote objects to registry...
Waiting for client call...
Run the Client
7. Start the client, e.g.
start java ProductClient for Windows
java ProductClient for Unix
C:Coursescs667CompiledExamplesProductRMIProductClient>java
ProductClient
I am an excellent Laptop. Buy me!
I am an excellent Display. Buy me!
Naming Conventions for RMI classes
no suffix remote interface
e.g. Product
Impl suffix server class implementing interface
e.g. ProductImp
Server suffix server program that creates server objects
e.g. ProductServer
Client suffix client program that calls remote method
e.g. ProductClient
_Stub suffix stub class automatically generated by rmic
e.g. ProductImpl_Stub program
_Skel suffix skeleton class automatically generated by rmic
e.g. ProductImpl_Skel (needed for JDK 1.1, but nor for 1.2)
Example 2: Array Math
Client Server
myArrayMath . add(x, y)
calls remote / sends arrays x, y
x+y
returns result
• Server program
ArrayMathServer
• Remote Interface ArrayMath
• Interface Implementation
ArrayMathImpl
• Client program
ArrayMathClient
• Remote Interface ArrayMath
• ArrayMathImpl_Stub
Stub class of ArrayMathImpl
(Mah 2000, p. 115, modified)
Example 2: Array Math Client-Server - interface ArrayMath
/**
*@(#) ArrayMath.java
*/
public interface ArrayMath
extends java.rmi.Remote {
int[] addArray(int a[], int b[]) throws java.rmi.RemoteException;
}
Example 2: class ArrayMathImpl
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
/**
* @(#) ArrayMathImpl.java
*/
public class ArrayMathImpl
extends UnicastRemoteObject
implements ArrayMath{
private String objectName;
public ArrayMathImpl (String s) throws RemoteException{
//super( ); called by default
objectName = s;
}
public int[] addArray(int a[], int b[] ) throws RemoteException{
int sum[] = new int[16];
for(int i=0; i<sum.length; i++)
sum[i] = a[i] + b[i];
return sum;
}
}
Example 2: class ArrayMathServer
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.net.*;
/**
* @(#) ArrayMathServer.java
*/
class ArrayMathServer{
public static void main (String argv[]) {
System.setSecurityManager(new RMISecurityManager());
try{
ArrayMathImpl ams = new ArrayMathImpl("ArrayMathServer");
Naming.rebind("//host/ArrayMathServer", ams);
System.out.println("ArrayMathServer bound in registry");
}catch (Exception e){
System.out.println("ArrayMathServer error"+ e.getMessage());
e.printStackTrace();
}
}
}
Example 2: class ArrayMathClient
import java.rmi.*;
import java.net.*;
/**
*@(#) ArrayMathClient.java
*/
public class ArrayMathClient {
public static void main(String argv[]){
int x[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int y[]={2,2,2,2,2,2,2,2,2,2, 2, 2, 2, 2, 2, 2};
int result[]= new int[16];
try{
ArrayMath ams =
(ArrayMath)Naming.lookup("//host/ArrayMathServer");
result = ams.addArray(x,y);
}catch(Exception e){
System.out.println("ArrayMathClient: "+ e.getMessage());
e.printStackTrace();
}
Example 2: class ArrayMathClient (continued)
System.out.println("The two arrays are ");
for(int j=0; j<x.length; j++)
System.out.print(x[j] + " ");
System.out.println();
for(int k=0; k<y.length; k++)
System.out.print(y[k] + " ");
System.out.println();
System.out.println("The sum is ");
for(int i=0; i<result.length; i++)
System.out.print(result[i] + " ");
System.out.println();
}
}
Java Servlets
By
Dr Rani Reddy
What Are Servlets?
 Basically, a java program that runs on the
server
 Creates dynamic web pages
What Do They Do?
 Handle data/requests sent by users
(clients)
 Create and format results
 Send results back to user
Who Uses Servlets?
 Servlets are useful in many business
oriented websites
 … and MANY others
History
 Dynamic websites were often created with
CGI
 CGI: Common Gateway Interface
 Poor solution to today’s needs
 A better solution was needed
Servlets vs. CGI
 Servlet Advantages
 Efficient
 Single lightweight java thread handles multiple requests
 Optimizations such as computation caching and keeping
connections to databases open
 Convenient
 Many programmers today already know java
 Powerful
 Can talk directly to the web server
 Share data with other servlets
 Maintain data from request to request
 Portable
 Java is supported by every major web browser (through plugins)
 Inexpensive
 Adding servlet support to a server is cheap or free
Servlets vs. CGI
 CGI Advantages
 CGI scripts can be written in any language
 Does not depend on servlet-enabled server
What Servlets Need
 JavaServer Web Development Kit (JSWDK)
 Servlet capable server
 Java Server Pages (JSP)
 Servlet code
Java Server Web Development Kit
 JSWDK
 Small, stand-alone server for testing servlets
and JSP pages
 The J2EE SDK
 Includes Java Servlets 2.4
Servlet capable server
Apache
 Popular, open-source server
 Tomcat
 A “servlet container” used with Apache
Other servers are available
Java Server Pages
 Lets you mix regular, static HTML pages with
dynamically-generated HTML
 Does not extend functionality of Servlets
 Allows you to separate “look” of the site from
the dynamic “content”
 Webpage designers create the HTML
 Servlet programmers create the dynamic content
 Changes in HTML don’t effect servlets
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>
<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>
<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>
<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
<head>
</head>
<body>
<%
// jsp sample code
out.println(" JSP, ASP, CF, PHP - you name it, we support it!");
%>
</body>
</html>
<html>
<head>
</head>
<body>
<b>
JSP, ASP, CF, PHP - you name it, we support it!
</b>
</body>
</html>
</font>
Servlet Code
 Written in standard Java
 Implement the javax.servlet.Servlet
interface
package servlet_tutorials.PhoneBook;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.net.*;
public class SearchPhoneBookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String query = null;
String where = null;
String firstname = null;
String lastname = null;
ResultSet rs = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// check which if any fields in the submitted form are empty
if (req.getParameter("FirstName").length() > 0)
firstname = req.getParameter("FirstName");
else firstname = null;
}
Main Concepts of Servlet
Programming
 Life Cycle
 Client Interaction
 Saving State
 Servlet Communication
 Calling Servlets
 Request Attributes and Resources
 Multithreading
Life Cycle
 Initialize
 Service
 Destroy
Life Cycle: Initialize
 Servlet is created when servlet container
receives a request from the client
 Init() method is called only once
Life Cycle: Service
 Any requests will be forwarded to the
service() method
 doGet()
 doPost()
 doDelete()
 doOptions()
 doPut()
 doTrace()
Life Cycle: Destroy
 destroy() method is called only once
 Occurs when
 Application is stopped
 Servlet container shuts down
 Allows resources to be freed
Client Interaction
 Request
 Client (browser) sends a request containing
 Request line (method type, URL, protocol)
 Header variables (optional)
 Message body (optional)
 Response
 Sent by server to client
 response line (server protocol and status code)
 header variables (server and response information)
 message body (response, such as HTML)
 Thin clients (minimize download)
 Java all “server side”
Client
Server
Servlets
Saving State
 Session Tracking
 A mechanism that servlets use to maintain
state about a series of requests from the
same user (browser) across some period of
time.
 Cookies
 A mechanism that a servlet uses to have
clients hold a small amount of state-
information associated with the user.
Servlet Communication
 To satisfy client requests, servlets
sometimes need to access network
resources: other servlets, HTML pages,
objects shared among servlets at the
same server, and so on.
Calling Servlets
 Typing a servlet URL into a browser
window
 Servlets can be called directly by typing their
URL into a browser's location window.
 Calling a servlet from within an HTML
page
 Servlet URLs can be used in HTML tags,
where a URL for a CGI-bin script or file URL
might be found.
Request Attributes and Resources
 Request Attributes
 getAttribute
 getAttributeNames
 setAttribute
 Request Resources - gives you access to
external resources
 getResource
 getResourceAsStream
Multithreading
 Concurrent requests for a servlet are handled by
separate threads executing the corresponding
request processing method (e.g. doGet or
doPost). It's therefore important that these
methods are thread safe.
 The easiest way to guarantee that the code is
thread safe is to avoid instance variables
altogether and instead use synchronized blocks.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 public class SimpleCounter extends HttpServlet {
 int count = 0;
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
 res.setContentType("text/plain");
 PrintWriter out = res.getWriter();
 count++;
 out.println("This servlet has been accessed " + count + " times since
loading");
 }
 }
Simple Counter Example
MultiThread Problems
 Problem - Synchronization between threads
count++; // by thread1
count++; // by thread2
out.println.. // by thread1
out.println.. // by thread2
Two Requests will
get the same
value of counter
 Solution - Use Synchronized Block!
 Synchronized Block
 Lock(Monitor)
Better Approach
 The approach would be to synchronize only the section
of code that needs to be executed automically:
PrintWriter out = res.getWriter();
synchronized(this)
{
count++;
out.println("This servlet has been accessed " +
count + "times since loading");
}
This reduces the amount of time the servlet spends in its
synchronized block, and still maintains a consistent
count.
Example: On-line Phone Book
 Design
Example: On-line Phone Book
Search Form
<html>
<head>
<title>Search Phonebook</title>
</head>
<body bgcolor="#FFFFFF"> <p><b>
Search Company Phone Book</b></p>
<form name="form1" method="get"
action="servlet/servlet_tutorials.PhoneBook.SearchPhoneBookServlet">
<table border="0" cellspacing="0" cellpadding="6"> <tr> <td >Search by</td>
<td>
</td> </tr> <tr> <td><b>
First Name
</b></td> <td>
<input type="text" name="FirstName"> AND/OR</td> </tr> <tr> <td ><b>
Last Name
</b></td> <td >
<input type="text" name="LastName"></td> </tr> <tr> <td ></td> <td >
<input type="submit" name="Submit" value="Submit">
</td> </tr> </table>
</form>
</body>
</html>
Java server Page
Search_phone_book.jsp
Example: On-line Phone Book
Display Results
<html>
<%@page import ="java.sql.*" %>
<jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/>
<%@ page buffer=35 %>
<%@ page errorPage="error.jsp" %>
<html>
<head>
<title>Phone Book Search Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head>
<body bgcolor="#FFFFFF"> <b>Search Results</b> <p>
<% String q = request.getParameter("query");
ResultSet rs = phone.getResultSet(q);
%>
<% if (rs.wasNull()) {
%>
"NO RESULTS FOUND"
<%
} else
%>
<table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div align="center">Last
Name</font></b></div> </td> <td> <div align="center">Phone Number</font></b></div> </td> <td>
<div align="center">Email</font></b></div> </td> </tr>
<% while(rs.next()) { %> <tr> <td>
<%= rs.getString("first_name") %></td> <td><%= rs.getString("last_name") %></td>
<td><%= rs.getString("phone_number") %>
</td> <td>
<%= rs.getString("e_mail") %>
</td> </tr>
<% } %>
</table>
Java Server Page
Display_search_results.jsp
Servlet
Listing 2 SearchPhoneBookServlet.java
package servlet_tutorials.PhoneBook;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.net.*;
public class SearchPhoneBookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String query = null;
String where = null;
String firstname = null;
String lastname = null;
ResultSet rs = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// check which if any fields in the submitted form are empty
if (req.getParameter("FirstName").length() > 0)
firstname = req.getParameter("FirstName");
else firstname = null;
if (req.getParameter("LastName").length() > 0)
lastname = req.getParameter("LastName");
else lastname = null;
// Build sql query string
if ((firstname != null) && (lastname != null)){
where = "first_name ='";
where += firstname;
where += "' AND ";
where += "last_name ='";
where += lastname;
where += "'";
}
else if ((firstname == null) && (lastname != null)){
where = "last_name ='";
where += lastname;
where += "'";
}
Java Bean & Database linked
Listing 4 PhoneBookBean.java
package servlet_tutorials.PhoneBook;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
public class PhoneBookBean {
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
private String query = null;
public PhoneBookBean() {}
public ResultSet getResultSet(String query) {
// grab a connection to the database
con = ConnectDB.getConnection();
try{
stmt = con.createStatement();
// run the sql query to obtain a result set
rs = stmt.executeQuery(query);
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
catch (RuntimeException rex) {
rex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace(); }
return rs;
}
}
Listing 5 ConnectDB.java
package servlet_tutorials.PhoneBook;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
/**
* Re-usable database connection class
*/
public class ConnectDB {
// setup connection values to the database
static final String DB_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
static final String URL = "jdbc:odbc:PhoneBook";
static final String USERNAME = "anon_user";
static final String PASSWORD = "";
// Load the driver when this class is first loaded
static {
try {
Class.forName(DB_DRIVER).newInstance();
}
catch (ClassNotFoundException cnfx) {
cnfx.printStackTrace();
}
catch (IllegalAccessException iaex){
iaex.printStackTrace();
}
catch(InstantiationException iex){
iex.printStackTrace ();
}
}
/**
* Returns a connection to the database
*/
public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
return con;
Conclusion
Questions? Comments?
References
 http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html
 www.cis.upenn.edu/~matuszek/ cit597-2004/Lectures/21-servlets.ppt
 http://learning.unl.ac.uk/im269/lectures/week6servletsp1.ppt
 http://java.sun.com/docs/books/tutorialNB/download/tut-servlets.zip
 http://www.webdevelopersjournal.com/articles/intro_to_servlets.html
Processing XML with Java
BY
Dr Rani Reddy
DBI – Representation and
Management of Data on the Internet
XML
• XML is eXtensible Markup Language
• It is a metalanguage:
– A language used to describe other languages using
“markup” tags that describe properties of the data
• Designed to be structured
– Strict rules about how data can be formatted
• Designed to be extensible
– Can define own terms and markup
XML Family
• XML is an official recommendation of
the W3C
• Aims to accomplish what HTML cannot
and be simpler to use and implement than
SGML
HTML XML
SGML
XHTML
The Essence of XML
• Syntax
– The permitted arrangement or structure of letters and
words in a language as defined by a grammar (XML)
• Semantics
– The meaning of letters or words in a language
• XML uses Syntax to add Semantics to the
documents
Using XML
• In XML there is a separation of the content
from the display
• XML can be used for:
– Data representation
– Data exchenge
Databases and XML
• Database content can
be presented in XML
– XML processor can
access DBMS or file
system and convert
data to XML
– Web server can serve
content as either XML
or HTML
HTML vs. XML
<OL>
<LI>HTML allows <B><I>improper nesting</B></I>.
<LI>HTML allows start tags, without end tags, like the
<BR> tag.
<LI>HTML allows <FONT COLOR=#9900CC>attribute
values</FONT> without quotes
<li>HTML is case-insensitive
<LI>White space is not important in HTML
</OL>
<OL>
<LI>XML requires <B><I>proper nesting</I></B>.</LI>
<LI>XML requires empty tags to be identified with
a trailing slash, as in <BR/>.</LI>
<LI>XML requires <FONT COLOR="#9900CC">quoted attribute
values</FONT>.</LI>
<LI>XML is case-sensitive
<LI>White space is important in XML
</OL>
Some Basic Rules for XML
• All tags must be balanced - <TAG>...</TAG>
• Empty tags expressed - <EMPTY_TAG/>
• Tags must be nested - <B><I>…</I></B>
• All element attributes must be quoted -
<TAG name=“value”>
• Text is case-sensitive - <TAG> != <Tag>
• Comments are allowed - <!-- … -->
• Must begin - <?xml version=‘1.0’ ?>
• Special characters must be escaped (e.g., &gt; for >)
SAX Parser
• Set of interfaces implemented by an
application
• The application
– reads in an XML file
– generates events when it encounters items in
the XML file
SAX Parser Events
• A SAX parser generates events
– at the start and end of a document,
– at the start and end of an element,
– when it finds characters inside an element, and
at several other points
• User writes the Java code
that handles each event, and decides what to
do with the information from the parser
ADVANCED JAVA MODULE III & IV.ppt
When to (not) use SAX
• Ideal for simple operations on XML files
– E.g. reading and extracting elements
• Good for very large XML files (c.f. DOM)
• Not good if we want to manipulate XML
structure
• Not designed for writing out XML
DOM
• Document Object Model
• Set of interfaces for an application that
reads an XML file into memory and stores
it as a tree structure
• The abstract API allows for constructing,
accessing and manipulating the structure
and content of XML and HTML documents
What a DOM Parser Gives
• When you parse an XML document with a
DOM parser, you get back a tree structure
that contains all of the elements of your
document
• The DOM provides a variety of functions
you can use to examine the contents and
structure of the document
ADVANCED JAVA MODULE III & IV.ppt
Why to Use DOM
• Task of writing parsers is reduced to coding
against an API for the document structure
• Domain-specific frameworks will be written
on top of DOM
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
DOM vs. SAX
• If your document is very large and you only
need a few elements - use SAX
• If you need to process many elements and
perform manipulations on XML - use DOM
• If you need to access the XML many times -
use DOM
What Would You Choose for
• Processing an XML document in a server?
• Processing an XML document in a remote
client?
• Direct access to element in the XML file
(e.g., index based on paths)
• A visual tool for traversal over the
document tree?
XML Parsers
XML Parsers
• There are several different ways to
categorise parsers:
– Validating versus non-validating parsers
– Parsers that support the Document Object
Model (DOM)
– Parsers that support the Simple API for XML
(SAX)
– Parsers written in a particular language (Java,
C++, Perl, etc.)
Non-Validating Parsers
• Speed and efficiency
– It takes a significant amount of effort for an
XML parser to process a DTD and make sure
that every element in an XML document
follows the rules of the DTD.
• If we only want to find tags and extract
information – we should use a non-
validating parser
Using an XML Parser
• Three basic steps in using an XML parser
– Creating a parser object
– Passing the XML document to the parser
– Processing the results
• Generally, writing out XML is not in the
scope of parsers (though some may
implement proprietary mechanisms)
SAX – Simple API for XML
The SAX Parser
• SAX parser is an event-driven API
– An XML document is sent to the SAX parser
– The XML file is read sequentially
– The parser notifies the class when events
happen, including errors
– The events are handled by the implemented
API methods to handle events that the
programmer implemented
SAX Parser
• A SAX parser generates events
– At the start and end of a document
– At the start and end of an element
– When it finds characters inside an element
– Upon encountering errors
– Upon encountering negligible whitespace
– and at several other points
• It uses a callback mechanism to notify the
application
• Java code that handles each event implements the
events handling
The org.xml.sax.* Package
• SAX Interfaces and Classes
– Parser
– DocumentHandler
– DTDHandler
– ErrorHandler
– EntityResolver
– AttributeList
– Locator
The Apache XML Parser (xerces)
import org.xml.sax.*;
import org.apache.parsers.*;
class MyClass {
SAXParser myParser;
…
try {
myParser.parse("file:/myFile.xml");
} catch (SAXException err) {…}
…
}
The Parser Interface
• Registers other objects for callbacks
– void setDocumentHandler(DocumentHandler handler)
– void setDTDHandler(DTDHandler handler)
– void setErrorHandler(ErrorHandler handler)
– void setEntityResolver(EntityResolver resolver)
• Starts parsing with parse() method call
• When the parser hits a significant item, it stops
reading and calls a registered object
• The parser continues reading the XML file once
the called method has returned
The DocumentHandler Interface
• This interface is used to receive basic markup
events from the parser
• It is usually implemented by a class that activates
the parser
class myClass implements DocumentHandler
{
…
myParser.setDocumentHandler(this);
…
}
DocumentHandler Methods
• void startDocument()
• void endDocument()
• void startElement(String name,
AttributeList attrs)
• void endElement(String name)
• void characters(char[] ch,
int start,
int length)
• void ignorableWhitespace(char[] ch,
int start,
int length)
• void processingInstruction(String target,
String data)
Bachelor Tags
• What happen when the parser parses a
bachelor tag?
<dbi id=‘1’/>
AttributeList Interface
• Elements may have attributes
– We have a wrapper object for all attribute
details that implements the AttributeList
interface
– It cannot distinguish attributes that are defined
explicitly from those that are specified in the
DTD
AttributeList Interface (cont.)
int getLength();
String getName(int i);
String getType(int i);
String getValue(int i);
String getType(String name);
String getValue(String name);
Attributes Types
• The following are possible types for
attributes:
– "CDATA",
– "ID",
– "IDREF", "IDREFS",
– "NMTOKEN", "NMTOKENS",
– "ENTITY", "ENTITIES",
– "NOTATION"
AttributeListImpl
• The class is in the package
org.xml.sax.helpers.*
• Include methods such as:
– addAtrribute, removeAttribute
– clear
– getName, getType, getValue
– getLength
By name
or by index
ErrorHandler Interface
• If we want to know about warnings and
errors
– We implement the ErrorHandler interface
and register it with the parser class
– The handler does not report where the error
occurred
• We have three levels of exception:
void error(SAXParseException ex);
void fatalError(SAXParserExcpetion ex);
void warning(SAXParserException ex);
Locator Interface
• Associates a SAX event with a document
location
– The parser can inform
• the application of the entity,
• line number and character number of a warning or
error,
– if it is a class implementing the Locator
interface and it is registered with the
DocumentHandler
Locator Methods
int getLineNumber();
int getColumnNumber();
String getSystemId();
(i.e., return the URL)
String getPublicId();
DTDHandler Interface
• Provides callback methods to receive
notification of DTD events
• It is a mechanism to inform an application
about any binary entity that the parser
encounters
DTD Handler
notationDecl(String name,
String publicId,
String systemId);
unparsedEntityDecl(String name,
String publicId,
String systemId,
String notationName);
InputSource Class
• Possible to specify a byte or character
stream for the input to the parser
• The InputSource class contains
methods that specify the exact nature of the
data source
EntityResolver Interface
• The application is not aware of the physical
structure of the XML data
• The parser contains an entity manager that
hides the complexity from the application
which sees the data as a single stream
• Can intercept references to entities by
implementing the EntityResolver
interface
EntityResolver Interface (2)
• When the parser encounters an entity, it
passes the system and/or public identifier to
the application
– Return value is ‘null’ or new InputSource
EntityResolver Interface (2)
public InputSource resolveEntity(String publicID,
String systemID) {
if (systemID.equals("Disclaimer") ||
publicID.equals
("-//EBI//TEXT Disclaimer//EN"))
return (new
InputSource(file:/xml/disc.xml));
}
}
HandlerBase Class
• This class implements SAX interfaces in a
sensible, default way
DocumentHandler, DTDHandler,
EntityResolver and ErrorHandler
• Can be used for partial implementation of the
interfaces
• This class can be extended:
import org.xml.sax.HandlerBase;
public class myHandler extends HandlerBase() {
…
}
ParserFactory Class
• A helper class
– Provides convenient methods for dynamically
loading SAX parsers
makeParser() (Uses org.xml.sax.parser system property)
makeParser(String className)
Example
• An example of indenting an XML
document (as part of a server)
XMLIndent.java
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
ADVANCED JAVA MODULE III & IV.ppt
DOM – Document Object Model
DOM Standards
• DOM 1.0 standard from www.w3.org
• Assumes an object-oriented approach
• Composed of number of interfaces
– org.w3c.dom.*
• Central class is 'Document' (DOM tree)
• Standard does not include
– Tree walking
– Writing out XML format
Creating a DOM Tree
• A DOM implementation has a method to
pass an XML file to a factory object
• The factory object returns a Document
object that represents the root element of a
whole document
• On the Document objects, DOM standard
interface can be used to interact with XML
structure
Line Of Work
DOM Parser DOM Tree
XML File
A
P
I
Application
DOM Tree
Document
Document Type Element
Attribute Element Element
Attribute Text
Element
Text Entity Reference Text
Text
Text
Comment
Normalizing a Tree
• Normalizing a DOM Tree has two effects:
– Combine adjacent textual nodes
– Eliminate empty textual nodes
– We can apply a normalize() method to the
document element
DOMParser
• DOMParser extends XMLParser
– Important Methods:
• void parse(InputSource source)
Parses the specified input source
• void parse(java.lang.String systemId)
Parses the input source specified by the given
system identifier
• Document getDocument()
Returns the document
DOMParser
parse(xml-file) getDocument()
Document
getChildNodes()
NodeList …
Creating a DOM Tree (2)
import java.io.*; import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import org.apache.xerces.parsers.*;
public class myClass {
DOMParser parser = new DOMParser();
try {
parser.parse(“file:/doc.xml”);
} ccatch (IOException err) {…}
catch (SAXException err) {…}
catch (DOMException err) {…}
Document document = parser.getDocument();…
DOM Interfaces and Classes
DocumentFragment
Document
CharacterData
Text
Comment
CDATASection
Attr
Element
DocumentType
Notation
Entity
EntityReference
ProcessingInstruction
Node
NodeList
NamedNodeMap
DocumentType
Figure as from “The XML Companion” - Neil Bradle
DOM Interfaces
• The DOM defines several Java interfaces
– Node The base data type of the DOM
– Element Represents element
– Attr Represents an attribute of an element
– Text The content of an element or attribute
– Document Represents the entire XML
document. A Document object is
often referred to as a DOM tree
Node Interface
• Basic object of DOM (single node in tree)
• Nodes describe
• Node collections
– NodeList, NamedNodeMap, DocumentFragment
• Several nodes extend the Node interface
Elements
Attributes
Text
Comments
CDATA sections
Entity declarations
Entity references
Notation declarations
Entire documents
Processing instructions
Node Methods
• Three categories of methods
– Node characteristics
• name, type, value
– Contextual location and access to relatives
• parents, siblings, children, ancestors, descendants
– Node modification
• Edit, delete, re-arrange child nodes
Node Methods (2)
short getNodeType();
String getNodeName();
String getNodeValue()
throws DOMException;
void setNodeValue(String value)
throws DOMException;
boolean hasChildNodes();
NamedNodeMap getAttributes();
Document getOwnerDocument();
Node Types - getNodeType()
ELEMENT_NODE = 1
ATTRIBUTE_NODE = 2
TEXT_NODE = 3
CDATA_SECTION_NODE = 4
ENTITY_REFERENCE_NODE = 5
ENTITY_NODE = 6
PROCESSING_INSTRUCTION_NODE = 7
COMMENT_NODE = 8
DOCUMENT_NODE = 9
DOCUMENT_TYPE_NODE = 10
DOCUMENT_FRAGMENT_NODE = 11
NOTATION_NODE = 12
if (myNode.getNodeType() == Node.ELEMENT_NODE) {
//process node
…
}
Node Names and Values
• Every node has a name and possibly a value
• Name is not a unique identifier (only location)
Type Interface Name Name Value
ATTRIBUTE_NODE Attr Attribute name Attribute value
DOCUMENT_NODE Document #document NULL
DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment NULL
DOCUMENT_TYPE_NODE DocumentType DOCTYPE name NULL
CDATA_SECTION_NODE CDATASection #cdata-section CDATA content
COMMENT_NODE Comment Entity name Content string
ELEMENT_NODE Element Tag name NULL
ENTITY_NODE Entity Entity name NULL
ENTITY_REFERENCE_NODE EntityReference Entity name NULL
NOTATION_NODE Notation Notation name NULL
PROCESSING_INSTRUCTION_
NODE
ProcessingInstruction Target string Content string
TEXT_NODE Text #text Text string
Table as from “The XML Companion” - Neil Bradle
Type Interface Name Name Value
ATTRIBUTE_NODE Attr Attribute name Attribute value
DOCUMENT_NODE Document #document NULL
DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment NULL
DOCUMENT_TYPE_NODE DocumentType DOCTYPE name NULL
CDATA_SECTION_NODE CDATASection #cdata-section CDATA content
COMMENT_NODE Comment Entity name Content string
ELEMENT_NODE Element Tag name NULL
ENTITY_NODE Entity Entity name NULL
ENTITY_REFERENCE_NODE EntityReference Entity name NULL
NOTATION_NODE Notation Notation name NULL
PROCESSING_INSTRUCTION_
NODE
ProcessingInstruction Target string Content string
TEXT_NODE Text #text Text string
Child Nodes
• Most Nodes cannot have children, except
– Document, DocumentFragment,
Element
• Can check for presence of children
– if (myNode.hasChildNodes()) {
//process children of myNode
…
}
Node Navigation
• Every node has a specific location in tree
• Node interface specifies methods to find
surrounding nodes
– Node getFirstChild();
– Node getLastChild();
– Node getNextSibling();
– Node getPreviousSibling();
– Node getParentNode();
– NodeList getChildNodes();
Node Navigation (2)
getFirstChild()
getPreviousSibling()
getChildNodes()
getNextSibling()
getLastChild()
getParentNode()
Node parent = myNode.getParentNode();
if (myNode.hasChildren()) {
NodeList children = myNode.getChildNodes();
}
Figure as from “The XML Companion” - Neil Bradle
Node Manipulation
• Children of a node in a DOM tree can be
manipulated - added, edited, deleted,
moved, copied, etc.
Node removeChild(Node old) throws DOMException;
Node insertBefore(Node new, Node ref) throws DOMException;
Node appendChild(Node new) throws DOMException;
Node replaceChild(Node new, Node old) throws DOMException;
Node cloneNode(boolean deep);
Node Manipulation (2)
Ref
New
insertBefore
Old
New
replaceChild
cloneNode
Shallow 'false'
Deep 'true'
Figure as from “The XML Companion” - Neil Bradle
Document::Node Interface
• Represents entire XML document (tree root)
• Methods
//Information from DOCTYPE - See 'DocumentType'
DocumentType getDocumentType();
//Information about capabilities of DOM implementation
DOMImplementation getImplementation();
//Returns reference to root node element
Element getDocumentElement();
//Searches for all occurrences of 'tagName' in nodes
NodeList getElementsByName(String tagName);
Document::Node Interface (2)
• Factory methods for node creation
Element createElement(String tagName) throws DOMException;
DocumentFragment createDocumentFragment();
Text createTextNode(String data);
Comment createComment(String data);
CDATASection createCDATASection(String data) throws
DOMException;
ProcessingInstruction createProcessingInstruction(
String target, String data) throws DOMException;
Attr createAttribute(String name) throws DOMException;
EntityReference createEntityReference(String name)
throws DOMException;
DocumentType::Node Interface
• Information about document encapsulated
in DTD representation
• DOM 1.0 doesn’t allow editing of this node
//Returns name of document
String getName();
//Returns general entities declared in DTD
NamedNodeList getEntities();
//Returns notations declared in DTD
NamedNodeList getNotations();
Element::Node Interface
• Two categories of methods
– General element methods
– Attribute management methods
String getTagName();
NodeList getElementsByTagName();
void normalize();
String getAttribute(String name);
void setAttribute(String name, String value)
throws DOMException;
void removeAttribute(String name)
throws DOMException;
Attr getAttributeNode(String name);
void setAttributeNode(Attr new)
throws DOMException;
void removeAttributeNode(Attr old)
throws DOMException;
Element::Node Interface (2)
• Only Element objects have attributes but attribute
methods of Element are simple
– Need name of attribute
– Cannot distinguish between default value specified in
DTD and given in XML file
– Cannot determine attribute type [String]
• Instead use getAttributes() method of Node
– Returns Attr objects in a NamedNodeMap
Attr::Node Interface
• Interface to objects holding attribute data
• Entity ref's are children of attribute's
//Get name of attribute
String getName();
//Get value of attribute
String getValue();
//Change value of attribute
void setValue(String value);
//if 'true' - attribute defined in element, else in DTD
boolean getSpecified();
Attr::Node Interface (2)
• Attributes not considered part of DOM
– parentNode, previousSibling and
nextSibling have null value for Attr object
• Create attribute objects using factory method
of Document
//Create the empty Attribute node
Attr newAttr = myDoc.createAttribute("status");
//Set the value of the attribute
newAttr.setValue("secret");
//Attach the attribute to an element
myElement.setAttributeNode(newAttr);
CharacterData::Node Interface
• Useful general methods for dealing with text
• Not used directly
– sub-classed to Text and Comment Node types
String getData() throws DOMException;
void setData(String data) throws DOMException;
int getLength();
void appendData(String data) throws DOMException;
String substringData(int offset, int length)
throws DOMException;
void insertData(int offset, String data)
throws DOMException;
void deleteData(int offser, int length)
throws DOMException;
void replaceData(int offset, int length, String data)
throws DOMException;
Text::Node Interface
• Represents textual content of Element or Attr
– Usually children of these nodes
• Always leaf nodes
• Single method added to CharacterData
– Text splitText(int offset) throws DOMException
• Factory method in Document for creation
• Calling normalize() on an Element merges
its Text objects
CDATASection::Text Interface
• Represents CDATA that is not to be interpreted as
markup (the only delimiter recognised is the "]]>"
string that ends the CDATA section)
• The DOMString attribute of the Text node holds
the text of the CDATA section
• No methods added to CharacterData
• Factory method in Document for creation
– CDATASection newCDATA =
myDoc.createDATASection("press <<<ENTER>>>");
Comment::Text Interface
• Represents comments
• all the characters between starting '<!--'
and ending '-->'
• No methods added to CharacterData
• Factory method in Document for creation
– Comment newComment =
myDoc.createComment(" my comment "); //Note
spaces
ProcessingInstruction::Node
Interface
• Represent processing instruction declarations
– Name of node is target application name
– Value of node is target application command
• Factory method in Document for creation
– ProcessingInstruction newPI =
myDoc.createProcessingInstruction(“myProgs/ghostview”,
“page.ps”);
//Get the content of the processing instruction
String getData()
//Set the content of the processing instruction
void setData(String data)
//The target of this processing instruction
String getTarget();
EntityReference::Node Interface
• DOM includes interfaces for handling
notations, entities and entity references
– If the entities have not been replaced by the
parser
Element Text
Text
EntityReference Text
An
value
xml
eXtensible
Markup
Language
<!ENTITY xml "eXtensible Markup Language">
<para>An &xml; value</para>
value
name
Figure as from “The XML Companion” - Neil Bradle
Entity::Node Interface
• Represents an entity, either parsed or unparsed, in
an XML document
– Parser may replace entity references, or create
EntityReference nodes
• Must retain Entity for non-parsable data
• Extends Node interface and adds methods
• For non-parsable entities - can get notation name
String getPublicId();
String getSystemId();
String getNotationName();
Entity::Node Interface (2)
• A parsable Entity may have children that
represent the replacement value of the entity
• All entities of a Document accessed with
getEntities() method in DocumentType
<!ENTITY MyBoat PUBLIC "BOAT" SYSTEM "boat.gif" NDATA GIF>
String publicId = ent.getPublicId(); //BOAT
String systemId = ent.getSystemId(); //boat.gif
String notation = ent.getNotationName(); //GIF
Figure as from “The XML Companion” - Neil Bradle
Notation::Node Interface
• Each notation declaration in DTD represented by a
Notation node
• Methods added to Node interface
• All notations of a Document accessed with
getNotations() method in DocumentType
object
//Returns content of PUBLIC identifier
String getPublicId();
//Returns content of SYSTEM identifier
String getSystemId();
NodeList Interface
• Holds collection of ordered Node objects
• Two methods
//Find number of Nodes in NodeList
int getLength();
//Return the i-th Node
Node item(int index);
-------------------------------------------------
Node child;
NodeList children = element.getChildNodes()'
for (int i = 0; i < children.getLength(); i++) {
child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(child.getNodeName());
}
}
NamedNodeMap Interface
• Holds collection of unordered Node objects
– E.g. Attribute, Entity and Notation
• Unique names are essential as nodes are
accessed by name
NamedNodeMap myAttributes = myElement.getAttributes();
NamedNodeMap myEntities = myDocument.getEntities();
NamedNodeMap myNotations = myDocument.getNotations();
------------------------------------------------------
int getLength();
Node item(int index);
Node getNamedItem(String name);
Node setNamedItem(Node node) throws DOMException;//Node!
Node removeNamedItem(String name) throws DOMException;
DocumentFragment::Node
Interface
• Fragment of Document can be temporarily
stored in DocumentFragment node
– Lightweight object, e.g. for 'cut-n-paste'
• When attached to another Node - destroys
itself (very useful for adding siblings to tree)
DocumentFragment
DOM tree
New DOM tree
Figure as from “The XML Companion” - Neil Bradle
DOMImplementation Interface
• Interface to determine level of support in
DOM parser
– hasFeature(String feature, String version);
– if (theParser.hasFeature("XML", "1.0") {
//XML is supported
…
}
DOM Objects
• DOM object  compiled XML
• Can save time and effort if send and receive
DOM objects instead of XML source
– Saves having to parse XML files into DOM at
sender and receiver
– But, DOM object may be larger than XML
source
Examples
• DOMTest
• DTD
• XML
• Counting Result
ADVANCED JAVA MODULE III & IV.ppt
Java + XML = JDOM
What is JDOM?
• JDOM is a way to represent an XML document
for easy and efficient reading, manipulation, and
writing
– Straightforward API
– Lightweight and fast
– Java-optimized
• Despite the name similarity, it's not build on DOM
or modeled after DOM
– Although it integrates well with DOM and SAX
• An open source project with an Apache-style
license
The JDOM Philosophy
• JDOM should be straightforward for Java
programmers
– Use the power of the language (Java 2)
– Take advantage of method overloading, the Collections
APIs, reflection, weak references
– Provide conveniences like type conversions
• JDOM should hide the complexities of XML
wherever possible
– An Element has content, not a child Text node with
content
– Exceptions should contain useful error messages
– Give line numbers and specifics, use no SAX or DOM
specifics
More JDOM Philosophy
• JDOM should integrate with DOM and
SAX
– Support reading and writing DOM documents
and SAX events
– Support runtime plug-in of any DOM or SAX
parser
– Easy conversion from DOM/SAX to JDOM
– Easy conversion from JDOM to DOM/SAX
The Historical Alternatives:
DOM
• DOM is a large API designed for complex
environments
– A W3C standard, developed by W3C working groups
– Implemented by products like Xerces
– Represents a document tree fully held in memory
– Has to have the same API on multiple languages
– Reading and changing the document is non-intuitive
– Fairly heavyweight to load and store in memory
– http://www.w3.org/DOM
The Historical Alternatives: SAX
• SAX is a lightweight API designed for fast
reading
– Public domain API from David Megginson and XML-
DEV mailing list
– Implemented by products like Xerces
– Callback mechanism reports when document elements
are encountered
– Lightweight since the document is never entirely in
memory
– Does not support modifying the document
– Does not support random access to the document
– Fairly steep learning curve to use correctly
Do you need JDOM?
• JDOM is a lightweight API
– Its design allows it to hold less in memory
• JDOM can represent a full document
– Not all must be in memory at once
• JDOM supports document modification
– And document creation from scratch, no
"factory"
For More Information
• To get more information on JDOM, see:
http://www.jdom/org
Ad

More Related Content

Similar to ADVANCED JAVA MODULE III & IV.ppt (20)

CORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBACORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBA
Priyanka Patil
 
Corba and-java
Corba and-javaCorba and-java
Corba and-java
afreen58
 
Chapter2
Chapter2Chapter2
Chapter2
Namomsa Amanuu
 
Corba in power system
Corba in power systemCorba in power system
Corba in power system
PROTIM PAUL
 
Unit iv
Unit ivUnit iv
Unit iv
selva kumar
 
Corba
CorbaCorba
Corba
Sanoj Kumar
 
MIDELWARE TECH
MIDELWARE TECHMIDELWARE TECH
MIDELWARE TECH
muthahar.sk
 
corba-151024114450-lva1-app6891.pptx
corba-151024114450-lva1-app6891.pptxcorba-151024114450-lva1-app6891.pptx
corba-151024114450-lva1-app6891.pptx
AasimAbdul
 
Chapter10
Chapter10Chapter10
Chapter10
lopjuan
 
Common Object Request Broker Architecture
Common Object Request Broker ArchitectureCommon Object Request Broker Architecture
Common Object Request Broker Architecture
OECLIB Odisha Electronics Control Library
 
Distributed computing - november 2006
Distributed computing  - november 2006Distributed computing  - november 2006
Distributed computing - november 2006
achraf_ing
 
kanchana .R.pptx.........................
kanchana .R.pptx.........................kanchana .R.pptx.........................
kanchana .R.pptx.........................
hanamshettyvani
 
CORBA.ppt
CORBA.pptCORBA.ppt
CORBA.ppt
rameshwarchintamani
 
Distributed systems corba remote connection
Distributed systems corba remote connectionDistributed systems corba remote connection
Distributed systems corba remote connection
MohammedAkramMohiudd
 
CORBA - Introduction and Details
CORBA - Introduction and DetailsCORBA - Introduction and Details
CORBA - Introduction and Details
dgsdg2websd
 
EAI and Attachmate Pt. 2 9-00
EAI and Attachmate Pt. 2  9-00EAI and Attachmate Pt. 2  9-00
EAI and Attachmate Pt. 2 9-00
Jeff Krukin
 
Middleware1
Middleware1Middleware1
Middleware1
bhumi109
 
Distributing computing.pptx
Distributing computing.pptxDistributing computing.pptx
Distributing computing.pptx
Kaviya452563
 
Learning activity 3
Learning activity 3Learning activity 3
Learning activity 3
Aileen Banaguas
 
Corba model ppt
Corba model pptCorba model ppt
Corba model ppt
Saransh Garg
 
CORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBACORBA Basic and Deployment of CORBA
CORBA Basic and Deployment of CORBA
Priyanka Patil
 
Corba and-java
Corba and-javaCorba and-java
Corba and-java
afreen58
 
Corba in power system
Corba in power systemCorba in power system
Corba in power system
PROTIM PAUL
 
MIDELWARE TECH
MIDELWARE TECHMIDELWARE TECH
MIDELWARE TECH
muthahar.sk
 
corba-151024114450-lva1-app6891.pptx
corba-151024114450-lva1-app6891.pptxcorba-151024114450-lva1-app6891.pptx
corba-151024114450-lva1-app6891.pptx
AasimAbdul
 
Chapter10
Chapter10Chapter10
Chapter10
lopjuan
 
Distributed computing - november 2006
Distributed computing  - november 2006Distributed computing  - november 2006
Distributed computing - november 2006
achraf_ing
 
kanchana .R.pptx.........................
kanchana .R.pptx.........................kanchana .R.pptx.........................
kanchana .R.pptx.........................
hanamshettyvani
 
Distributed systems corba remote connection
Distributed systems corba remote connectionDistributed systems corba remote connection
Distributed systems corba remote connection
MohammedAkramMohiudd
 
CORBA - Introduction and Details
CORBA - Introduction and DetailsCORBA - Introduction and Details
CORBA - Introduction and Details
dgsdg2websd
 
EAI and Attachmate Pt. 2 9-00
EAI and Attachmate Pt. 2  9-00EAI and Attachmate Pt. 2  9-00
EAI and Attachmate Pt. 2 9-00
Jeff Krukin
 
Middleware1
Middleware1Middleware1
Middleware1
bhumi109
 
Distributing computing.pptx
Distributing computing.pptxDistributing computing.pptx
Distributing computing.pptx
Kaviya452563
 
Learning activity 3
Learning activity 3Learning activity 3
Learning activity 3
Aileen Banaguas
 
Corba model ppt
Corba model pptCorba model ppt
Corba model ppt
Saransh Garg
 

More from rani marri (20)

express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvcexpress.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
rani marri
 
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjjNagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
rani marri
 
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchcLecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
rani marri
 
git.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internetgit.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internet
rani marri
 
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjjEJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
rani marri
 
Containers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptxContainers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptx
rani marri
 
JSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and expertsJSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and experts
rani marri
 
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.pptCSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
rani marri
 
nodejs tutorial foor free download from academia
nodejs tutorial foor free download from academianodejs tutorial foor free download from academia
nodejs tutorial foor free download from academia
rani marri
 
NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
must.pptx
must.pptxmust.pptx
must.pptx
rani marri
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvcexpress.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
express.js.pptxgghhhhhhnnbvcdssazxvuyiknvc
rani marri
 
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjjNagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
NagiOs.pptxhjkgfddssddfccgghuikjhgvccvvhjj
rani marri
 
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchcLecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
Lecture7.pptxhfjgjgjghcgzgzfzfzvzgxhchchc
rani marri
 
git.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internetgit.ppt.pptx power point presentation got Google internet
git.ppt.pptx power point presentation got Google internet
rani marri
 
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjjEJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
rani marri
 
Containers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptxContainers Orchestration using kubernates.pptx
Containers Orchestration using kubernates.pptx
rani marri
 
JSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and expertsJSP.pptx programming guide for beginners and experts
JSP.pptx programming guide for beginners and experts
rani marri
 
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.pptCSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
CSC128_Part_1_WrapperClassesAndStrings_CenBNcj.ppt
rani marri
 
nodejs tutorial foor free download from academia
nodejs tutorial foor free download from academianodejs tutorial foor free download from academia
nodejs tutorial foor free download from academia
rani marri
 
NAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptxNAAC PPT M.B.A.pptx
NAAC PPT M.B.A.pptx
rani marri
 
must.pptx
must.pptxmust.pptx
must.pptx
rani marri
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
oops with java modules iii & iv.pptx
oops with java modules iii & iv.pptxoops with java modules iii & iv.pptx
oops with java modules iii & iv.pptx
rani marri
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
rani marri
 
software engineering modules iii & iv.pptx
software engineering  modules iii & iv.pptxsoftware engineering  modules iii & iv.pptx
software engineering modules iii & iv.pptx
rani marri
 
software engineering module i & ii.pptx
software engineering module i & ii.pptxsoftware engineering module i & ii.pptx
software engineering module i & ii.pptx
rani marri
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
rani marri
 
data structures module III & IV.pptx
data structures module III & IV.pptxdata structures module III & IV.pptx
data structures module III & IV.pptx
rani marri
 
data structures module I & II.pptx
data structures module I & II.pptxdata structures module I & II.pptx
data structures module I & II.pptx
rani marri
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
Ad

Recently uploaded (20)

Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Ad

ADVANCED JAVA MODULE III & IV.ppt

  • 1. The Common Object Request Broker Architecture (CORBA Dr M.Rani Reddy
  • 2. CORBA  The Common Object Request Broker Architecture (CORBA) is a standard architecture for a distributed objects system.  CORBA is designed to allow distributed objects to interoperate in a heterogenous environment, where objects can be implemented in different programming language and/or deployed on different platforms
  • 3. CORBA vs. Java RMI  CORBA differs from the architecture of Java RMI in one significant aspect:  RMI is a proprietary facility developed by Sun MicroSystems, Inc., and supports objects written in the Java programming langugage only.  CORBA is an architecture that was developed by the Object Management Group (OMG), an industrial consortium.
  • 4. CORBA  CORBA is not in inself a distributed objects facility; instead, it is a set of protocols.  A distributed object facility which adhere to these protocols is said to be CORBA-compliant, and the distributed objects that the facility support can interoperate with objects supported by other CORBA- compliant facilities.  CORBA is a very rich set of protocols. We will instead focus on the key concepts of CORBA related to the distributed objects paradigm. We will also study a facility based on CORBA: the Java IDL.
  • 5. The Basic Architecture object client naming service naming lookup stub ORB network operating system object implementation skeleton ORB network operating system logical data flow physical data flow
  • 6. CORBA Object Interface  A distributed object is defined using a software file similar to the remote interface file in Java RMI.  Since CORBA is language independent, the interface is defined using a universal language with a distinct syntax, known as the CORBA Interface Definition Language (IDL).  The syntax of CORBA IDL is similar to Java and C++. However, object defined in a CORBA IDL file can be implemented in a large number of diverse programming languages, including C, C++, Java, COBOL, Smalltalk, Ada, Lisp, Python, and IDLScript.  For each of these languages, OMG has a standardized mapping from CORBA IDL to the programming language, so that a compiler can be used to process a CORBA interface to generate the proxy files needed to interface with an object implementation or an object client written in any of the CORBA-compatible languages.
  • 7. Cross-language CORBA application object client written in Java stub in Java generated by compiling the CORBA object interface ORB written in Java object implementation written in C++ skeleton in C++ generated by compiling the CORBA object interface ORB written in C++
  • 8. Inter-ORB Protocols  To allow ORBs to be interoperable, the OMG specified a protocol known as the General Inter-ORB Protocol (GIOP), a specification which “provides a general framework for protocols to be built on top of specific transport layers.”  A special case of the protocol is the Inter- ORB Protocol (IIOP), which is the GIOP applied to the TCP/IP transport layer.
  • 9. Inter-ORB Protocols The IIOP specification includes the following elements: 1. Transport management requirements: specifies the connection and disconnection requirements, and the roles for the object client and object server in making and unmaking connections. 2. Definition of common data representation: a coding scheme for marshalling and unmarshalling data of each IDL data type. 3. Message formats: different types of message format are defined. The messages allow clients to send requests to object servers and receive replies. A client uses a Request message to invoke a method declared in a CORBA interface for an object and receives a reply message from the server.
  • 10. Object Bus An ORB which adheres to the specifications of the IIOP may interoperate with any other IIOP-compliant ORBs over the Internet. This gives rise to the term “object bus”, where the Internet is seen as a bus that interconnects CORBA objects The Internet CORBA object CORBA object CORBA object ORB ORB ORB ...
  • 11. ORB products There are a large number of proprietary as well as experimental ORBs available: (See CORBA Product Profiles, http://www.puder.org/corba/matrix/)  Orbix IONA  Borland Visibroker  PrismTech’s OpenFusion  Web Logic Enterprise from BEA  Ada Broker from ENST  Free ORBs
  • 12. Object Servers and Object Clients  As in Java RMI, a CORBA distributed object is exported by an object server, similar to the object server in RMI.  An object client retrieves a reference to a distributed object from a naming or directory service, to be described, and invokes the methods of the distributed object.
  • 13. CORBA Object References  As in Java RMI, a CORBA distributed object is located using an object reference. Since CORBA is language-independent, a CORBA object reference is an abstract entity mapped to a language-specific object reference by an ORB, in a representation chosen by the developer of the ORB.  For interoperability, OMG specifies a protocol for the abstract CORBA object reference object, known as the Interoperable Object Reference (IOR) protocol.
  • 14. Interoperable Object Reference (IOR)  For interoperability, OMG specifies a protocol for the abstract CORBA object reference object, known as the Interoperable Object Reference (IOR) protocol.  An ORB compatible with the IOR protocol will allow an object reference to be registered with and retrieved from any IOR-compliant directory service. CORBA object references represented in this protocol are called Interoperable Object References (IORs).
  • 15. Interoperable Object Reference (IOR) An IOR is a string that contains encoding for the following information:  The type of the object.  The host where the object can be found.  The port number of the server for that object.  An object key, a string of bytes identifying the object. The object key is used by an object server to locate the object.
  • 16. Interoperable Object Reference (IOR) The following is an example of the string representation of an IOR [5]: IOR:000000000000000d49444c3a677269643a312e3000000 00000000001000000000000004c0001000000000015756c74 72612e6475626c696e2e696f6e612e6965000009630000002 83a5c756c7472612e6475626c696e2e696f6e612e69653a67 7269643a303a3a49523a67726964003a The representation consists of the character prefix “IOR:” followed by a series of hexadecimal numeric characters, each character representing 4 bits of binary data in the IOR.
  • 17. CORBA Naming Service  CORBA specifies a generic directory service. The Naming Service serves as a directory for CORBA objects, and, as such, is platform independent and programming language independent.  The Naming Service permits ORB-based clients to obtain references to objects they wish to use. It allows names to be associated with object references. Clients may query a naming service using a predetermined name to obtain the associated object reference.
  • 18. CORBA Naming Service  To export a distributed object, a CORBA object server contacts a Naming Service to bind a symbolic name to the object The Naming Service maintains a database of names and the objects associated with them.  To obtain a reference to the object, an object client requests the Naming Service to look up the object associated with the name (This is known as resolving the object name.)  The API for the Naming Service is specified in interfaces defined in IDL, and includes methods that allow servers to bind names to objects and clients to resolve those names.
  • 19. CORBA Naming Service To be as general as possible, the CORBA object naming scheme is necessary complex. Since the name space is universal, a standard naming hierarchy is defined in a manner similar to the naming hierarchy in a file directory naming context1 naming context1 naming context2 naming context1 naming context1 object name1 object namen ... ... ... ...
  • 20. A Naming Context  A naming context correspond to a folder or directory in a file hierarchy, while object names corresponds to a file.  The full name of an object, including all the associated naming contexts, is known as a compound name. The first component of a compound name gives the name of a naming context, in which the second component is accessed. This process continues until the last component of the compound name has been reached.  Naming contexts and name bindings are created using methods provided in the Naming Service interface.
  • 21. A CORBA object name The syntax for an object name is as follows: <naming context > …<naming context><object name> where the sequence of naming contexts leads to the object name.
  • 22. Example of a naming hierarchy As shown, an object representing the men’s clothing department is named store.clothing.men, where store and clothing are naming contexts, and men is an object name. store clothing Appliances women men ... television ...
  • 23. Interoperable Naming Service The Interoperable Naming Service (INS) is a URL- based naming system based on the CORBA Naming Service, it allows applications to share a common initial naming context and provide a URL to access a CORBA object.
  • 24. CORBA Object Services CORBA specify services commonly needed in distributed applications, some of which are:  Naming Service:  Concurrency Service:  Event Service: for event synchronization;  Logging Service: for event logging;  Scheduling Service: for event scheduling;  Security Service: for security management;  Trading Service: for locating a service by the type (instead of by name);  Time Service: a service for time-related events;  Notification Service: for events notification;  Object Transaction Service: for transactional processing. Each service is defined in a standard IDL that can be implemented by a developer of the service object, and whose methods can be invoked by a CORBA client.
  • 25. Object Adapters In the basic architecture of CORBA, the implementation of a distributed object interfaces with the skeleton to interact with the stub on the object client side. As the architecture evolved, a software component in addition to the skeleton was needed on the server side: an object adapter. distributed object implementation object adapter ORB
  • 26. Object Adapter  An object adapter simplifies the responsibilities of an ORB by assisting an ORB in delivering a client request to an object implementation.  When an ORB receives a client’s request, it locates the object adapter associated with the object and forwards the request to the adapter.  The adapter interacts with the object implementation’s skeleton, which performs data marshalling and invoke the appropriate method in the object.
  • 27. The Portable Object Adapter  There are different types of CORBA object adapters.  The Portable Object Adapter, or POA, is a particular type of object adapter that is defined by the CORBA specification. An object adapter that is a POA allows an object implementation to function with different ORBs, hence the word portable.
  • 28. The Java IDL (Java 1.4 version)
  • 29. Java IDL – Java’s CORBA Facility  IDL is part of the Java 2 Platform, Standard Edition (J2SE).  The Java IDL facility includes a CORBA Object Request Broker (ORB), an IDL-to-Java compiler, and a subset of CORBA standard services.  In addition to the Java IDL, Java provides a number of CORBA-compliant facilities, including RMI over IIOP, which allows a CORBA application to be written using the RMI syntax and semantics.
  • 30. Key Java IDL Packages  package org.omg.CORBA – contains interfaces and classes which provides the mapping of the OMG CORBA APIs to the Java programming language  package org.omg.CosNaming - contains interfaces and classes which provides the naming service for Java IDL  org.omg.CORBA.ORB - contains interfaces and classes which provides APIs for the Object Request Broker.
  • 31. Java IDL Tools Java IDL provides a set of tools needed for developing a CORBA application:  idlj - the IDL-to-Java compiler (called idl2java in Java 1.2 and before)  orbd - a server process which provides Naming Service and other services  servertool – provides a command-line interface for application programmers to register/unregister an object, and startup/shutdown a server.  tnameserv – an olderTransient Java IDL Naming Service whose use is now discouraged.
  • 32. A Java IDL application example
  • 33. The CORBA Interface file Hello.idl 01. module HelloApp 02. { 03. interface Hello 04. { 05. string sayHello(); 06. oneway void shutdown(); 07. }; 08. };
  • 34. Compiling the IDL file (using Java 1.4) The IDL file should be placed in a directory dedicated to the application. The file is compiled using the compiler idlj using a command as follows: idlj -fall Hello.idl The –fall command option is necessary for the compiler to generate all the files needed. In general, the files can be found in a subdirectory named <some name>App when an interface file named <some name>.idl is compiled. If the compilation is successful, the following files can be found in a HelloApp subdirectory: HelloOperations.java Hello.java HelloHelper.java HelloHolder.java _HelloStub.java HelloPOA.java These files require no modifications.
  • 35. The *Operations.java file  There is a file HelloOperations.java  found in HelloApp/ after you compiled using idlj  It is known as a Java operations interface in general  It is a Java interface file that is equivalent to the CORBA IDL interface file (Hello.idl)  You should look at this file to make sure that the method signatures correspond to what you expect.
  • 36. HelloApp/HelloOperations.java The file contains the methods specified in the original IDL file: in this case the methods sayHello( ) and shutdown(). package HelloApp; 01. package HelloApp; 04. /** 05. * HelloApp/HelloOperations.java 06. * Generated by the IDL-to-Java compiler (portable), 07. * version "3.1" from Hello.idl 08. */ 09. 10. public interface HelloOperations 11. { 12. String sayHello (); 13. void shutdown (); 14. } // interface HelloOperations
  • 37. HelloApp/Hello.java The signature interface file combines the characteristics of the Java operations interface (HelloOperations.java) with the characteristics of the CORBA classes that it extends. 01. package HelloApp; 03. /** 04. * HelloApp/Hello.java 05. * Generated by the IDL-to-Java compiler (portable), 06. * version "3.1" from Hello.idl 07. */ 09. public interface Hello extends HelloOperations, 10. org.omg.CORBA.Object, 11. org.omg.CORBA.portable.IDLEntity 12. { … 13. } // interface Hello
  • 38. HelloHelper.java, the Helper class  The Java class HelloHelper (Figure 7d) provides auxiliary functionality needed to support a CORBA object in the context of the Java language.  In particular, a method, narrow,allows a CORBA object reference to be cast to its corresponding type in Java, so that a CORBA object may be operated on using syntax for Java object.
  • 39. HelloHolder.java, the Holder class  The Java class called HelloHolder (Figure 7e) holds (contains) a reference to an object that implements the Hello interface.  The class is used to handle an out or an inout parameter in IDL in Java syntax ( In IDL, a parameter may be declared to be out if it is an output argument, and inout if the parameter contains an input value as well as carries an output value.)
  • 40. _HelloStub.java  The Java class HelloStub (Figure 7e) is the stub file, the client-side proxy, which interfaces with the client object.  It extends org.omg.CORBA.portable.ObjectImpl and implements the Hello.java interface.
  • 41. HelloPOA.java, the server skeleton  The Java class HelloImplPOA (Figure 7f) is the skeleton, the server-side proxy, combined with the portable object adapter.  It extends org.omg.PortableServer.Servant, and implements the InvokeHandler interface and the HelloOperations interface.
  • 42. The application Server-side Classes  On the server side, two classes need to be provided: the servant and the server.  The servant, HelloImpl, is the implementation of the Hello IDL interface; each Hello object is an instantiation of this class.
  • 43. The Servant - HelloApp/HelloImpl.java // The servant -- object implementation -- for the Hello // example. Note that this is a subclass of HelloPOA, // whose source file is generated from the // compilation of Hello.idl using j2idl. 06. import HelloApp.*; 07. import org.omg.CosNaming.*; 08. import java.util.Properties; … 15. class HelloImpl extends HelloPOA { 16. private ORB orb; 18. public void setORB(ORB orb_val) { 19. orb = orb_val; 20. } 22. // implement sayHello() method 23. public String sayHello() { 24. return "nHello world !!n"; 25. } 27. // implement shutdown() method 28. public void shutdown() { 29. orb.shutdown(false); 30. } 31. } //end class
  • 44. The server - HelloApp/HelloServer.java public class HelloServer { public static void main(String args[]) { try{ // create and initialize the ORB ORB orb = ORB.init(args, null); // get reference to rootpoa & activate the POAManager POA rootpoa = (POA)orb.resolve_initial_references("RootPOA"); rootpoa.the_POAManager().activate(); // create servant and register it with the ORB HelloImpl helloImpl = new HelloImpl(); helloImpl.setORB(orb); // get object reference from the servant org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl); // and cast the reference to a CORBA reference Hello href = HelloHelper.narrow(ref);
  • 45. HelloApp/HelloServer.java - continued // get the root naming context // NameService invokes the transient name service org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); // Use NamingContextExt, which is part of the // Interoperable Naming Service (INS) specification. NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // bind the Object Reference in Naming String name = "Hello"; NameComponent path[] = ncRef.to_name( name ); ncRef.rebind(path, href); System.out.println ("HelloServer ready and waiting ..."); // wait for invocations from clients orb.run();
  • 46. The object client application  A client program can be a Java application, an applet, or a servlet.  The client code is responsible for creating and initializing the ORB, looking up the object using the Interoperable Naming Service, invoking the narrow method of the Helper object to cast the object reference to a reference to a Hello object implementation, and invoking remote methods using the reference. The object’s sayHello method is invoked to receive a string, and the object’s shutdown method is invoked to deactivate the service.
  • 47. // A sample object client application. import HelloApp.*; import org.omg.CosNaming.*; … public class HelloClient{ static Hello helloImpl; public static void main(String args[]){ try{ ORB orb = ORB.init(args, null); org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); helloImpl = HelloHelper.narrow(ncRef.resolve_str(“Hello”)); System.out.println(helloImpl.sayHello()); helloImpl.shutdown();
  • 48. Compiling and Running a Java IDL application 1. Create and compile the Hello.idl file on the server machine: idlj -fall Hello.idl 2. Copy the directory containing Hello.idl (including the subdirectory generated by idlj) to the client machine. 3. In the HelloApp directory on the client machine: create HelloClient.java. Compile the *.java files, including the stubs and skeletons (which are in the directory HelloApp): javac *.java HelloApp/*.java
  • 49. Compiling and Running a Java IDL application 4. In the HelloApp directory on the server machine:  Create HelloServer.java. Compile the .java files: javac *.java HelloApp/*.java  On the server machine: Start the Java Object Request Broker Daemon, orbd, which includes a Naming Service. To do this on Unix: orbd -ORBInitialPort 1050 -ORBInitialHost servermachinename& To do this on Windows: start orbd -ORBInitialPort 1050 -ORBInitialHost servermachinename
  • 50. Compiling and Running a Java IDL application 5. On the server machine, start the Hello server, as follows: java HelloServer –ORBInitialHost <nameserver host name> -ORBInitialPort 1050 6. On the client machine, run the Hello application client. From a DOS prompt or shell, type: java HelloClient -ORBInitialHost nameserverhost -ORBInitialPort 1050 all on one line. Note that nameserverhost is the host on which the IDL name server is running. In this case, it is the server machine.
  • 51. Compiling and Running a Java IDL application 7. Kill or stop orbd when finished. The name server will continue to wait for invocations until it is explicitly stopped. 8. Stop the object server.
  • 53. Remote Method Invocation (RMI) In Search of the Simplest Communication Form Main Idea: Working with an object on a remote machine is made to look like calling a procedure on the remote site, i.e. • the application/client sends a message to the remote object • the remote object receives message, does processing and sends back message with results - the server side; • the client receives message and uses/prints result Server Side send client data (request) receive server data/result (reply) Remote Object runs procedure Client Side
  • 54. Why do we need yet another mechanism for remote object communication? We have sockets, and, if we find sockets tedious, there are intermediate representations, such as name/value pairs or XML. They would do the job, yes. In the traditional client/server model the request is formulated or translated into an intermediary language, e.g. name/value pairs, XML data. The server parses the requests, translates it into its language, computes reply, translates into intermediary languages, sends it to client, then client repeats the process. BUT in case of user defined structured data these mechanisms • require a significant coding effort; • are not very intuitive and not part of the basic vocabulary/concepts of programming languages As opposed to this RMI • has a form that is familiar even to an entry level programmer; • naturally extends the "everything is an object" principle to "objects can be everywhere";
  • 55. Goals of RMI More specifically RMI specification goals are listed as follows (http://java.sun.com/products/jdk/1.2/docs/guide/rmi/spec/rmi-title.doc.html) • Support seamless remote invocations on objects in different JVMs. • Support callbacks from servers to clients. • Integrate the distributed object model into the Java programming language in a natural way while retaining most of the language's object semantics. • Make differences between the distributed object model and the java object model apparent. • Make writing distributed applications as simple as possible (certainly simpler than with sockets). • Preserve the safety provided by the Java run-time environment. Flexibility and extensibility are provided by: • Distributed garbage collection. • Capability to support multiple transports • Varying remote invocation mechanisms, such as unicast and multicast
  • 56. Distributed Application Tasks • Locate Remote Objects: Application can obtain references to remote objects when a) objects are registered with the RMI naming facility, the rmiregistry, or b) application can pass and return remote object references as part of its normal operation • Communicate with remote objects: handled by RMI; looks like standard Java method invocation to the programmer • Load class bytecodes for objects that are passed as parameters or return values: Because RMI allows a caller to pass pure Java objects to remote object, RMI provides the necessary mechanisms for loading an object's code as well as transmitting its data
  • 57. Using the Registry to obtain References to Remote Object RMI RMI RMI URL protocol URL protocol Client Web Server Registry Web Server Server • Server calls registry to associate name with a remote object. • Client looks up remote object by name in server's registry. • Client invokes method on object Note: The RMI system uses an existing web server to load Java class bytecodes, from server to client and from client to server, when needed. RMI can load class bytecodes using any URL protocol (e.g. HTTP, FTP, file, etc.) that is supported by the Java system.
  • 58. RMI Architecture Server Skeleton Client Stub Remote Reference Layer Transport Layer The layers are independent. Each layer is defined by specific protocol and built using specific interface. Any layer can be replaced by an alternate implementation without affecting the others, e.g. the current transport layer in RMI is TCP based, but can be substituted by a UDP based transport layer Application Presentation Session Transport OSI Model
  • 59. RMI Architecture (continued) Stub/Skeleton Layer: Interface of the application with the rest of the system (standard mechanism used in RPC system). This layer transmits the data to the remote reference layer via the abstraction of marshal streams that use object serialization. • A stub is a surrogate for the remote object, its representative on the client side, that acts as a proxy for the remote object. It resides on the client side (although it is generated on the server side) and handles all the interaction with the remote object • A skeleton handles the communication on the server side (not required in JDK1.2-only environments) Remote Reference Layer: responsible for providing ability to support varying remote reference or invocation protocols independent of client stubs and server skeletons. Examples: unicast provides point-to-point invocation, multicast to groups of objects; other protocols deal with replication strategies or persistent references to the remote object, such as enabling remote object activation (supported only by Java2)
  • 60. RMI Architecture (continued) Transport Layer: Low level layer that ships the marshal streams between different address spaces. Responsible for managing connection: • Setting up connections • Listening to incoming calls • Maintaining table of remote objects that reside in same address space Remote object references are represented by an object identifier and end point. This representation is called a live reference. Given a live reference for a remote object the identifier looks up the targeted remote object and the end point sets up the connection to the address space the object resides
  • 61. Distributed Garbage Collection In stand-alone application object that are no longer referenced by any client are automatically deleted. RMI provides distributed garbage collector that automatically removes objects that are no longer referenced by any client. RMI uses a reference counting garbage collection that keeps track of all live references of a given object on each JVM. When a live reference enters a JVM its count is incremented, when it becomes unreferenced, its count is decremented; when the count is 0 (no live reference) the object can be garbage collected. As long as there is a local reference to a remote object it cannot be garbage collected, since it can be passed to remote server or returned to a client.
  • 62. Parameter Marshalling and Unmarshalling When a client code invokes a remote method on a remote object, it actually calls an ordinary/local Java method encapsulated in the stub. The stub encodes the parameters used in the remote method with a device- independent encoding and transforms them in a format suitable for transport. The process of encoding, writing to a stream and sending an object is referred as parameter marshalling. Thus the stub method on the client side builds an information block that consists of: • Identifier of remote object to be used; • Name of the method to be called • Marschalled parameters. The reverse process of receiving, reading and decoding is called parameter unmarshalling.
  • 63. RMI in action Client Stub Skeleton Server local call to stub method local call to server method Sending marshalled parameters return value or throw exception Sending marshalled return value or exception
  • 64. RMI in action (continued) When a stub's method is invoked, it does the following: • Initiates connection with the JVM on which remote object resides; • Marshals the parameters • Waits for result of method invocation • Unmarshals the value or exception returned • Returns value to caller On the server side, the skeleton or receiver object • Unmarshals the parameters of the remote method • Locates object to be called • Calls desired method on remote object implementation • Captures and marshals return value or exception to the caller.
  • 65. Anatomy of a simple RMI-based application Example 1: Product Info Client-Server Client Server myProduct . getDescription() calls remote / sends arguments returns description • Server program in class ProductServer • Remote Interface Product • Interface Implementation in class ProductImpl • ProductImpl_Stub automatically generated by the rmic compiler from the ProductImpl class • Client program in class ProductClient • Remote Interface Product • ProductImpl_Stub automatically generated by the rmic compiler from the ProductImpl class (HoCo 2002, Ch. 5, Examples 5-1,2,3,5, p. 343-347)
  • 66. The Remote Interface • The remote interface must be public (it cannot have package access, i.e it cannot be "friendly"). Otherwise the client cannot load a remote object that implements the remote interface • The remote interface must extend the interface java.rmi.Remote. • Each method in the remote interface must declare java.rmi.RemoteException in its throw clause in addition to any application-specific exceptions. This is necessary as remote methods are inherently less reliable than local ones.
  • 67. Example: remote interface Product //The Product information remote interface /** *@(#) Product.java */ import java.rmi.*; public interface Product extends Remote{ public String getDescription( ) throws RemoteException; } remote interface must for all methods in remote interface
  • 68. Server Side: Implementing the Remote Interface: class ProductImpl /** *@(#) ProductImpl.java */ import java.rmi.*; import java.rmi.server.*; public class ProductImpl extends UnicastRemoteObject implements Product { //Constructor public ProductImpl ( String n) throws RemoteException { //super(); called by default name = n; } implements remote interface constructor must be explicitly defined, even if it is just the default, because it must throw the RemoteException must extend server subclass UnicastRemoteObject, i.e. it is a server class
  • 69. Implementing the Remote Interface: class ProductImpl (continued) //implementation of remote interface method public String getDescription( ) throws RemoteException { return "I am an excellent " + name + ". Buy me!"; } private String name;//product name }
  • 70. UnicastRemoteObject - API Specification public class UnicastRemoteObject extends RemoteServer • Concrete class; • defines a non-replicated remote object whose references are valid only while the server process is alive; • provides support for point-to-point active object references (invocations, parameters, and results) using TCP streams. Object RemoteObject RemoteStub RemoteServer (abstract class) UnicastRemoteObject Remote
  • 71. Server Side Security In the main( ) method of the server program (here implemented in class ProductServer) : • Create and install security manager to support RMI System.setSecurityManager (new RMISecurityManager( ) ); Note: Server examples in the RMI tutorial documentation typically have a security manager installed. However, it is the client not the server that is more in need of a security manger, at it is the one downloading files. A security manger on the server side is a must only if the server is in its turn a client, or there is a special reason to put restrictions.
  • 72. The Server creates and registers remote objects • Create one or more instances of the remote object (ProductImpl); • An application can bind, unbind, and rebind registry object references only if it runs on the same host as the registry. This shields the registry from hostile clients attempting to change registry information. However, any client can lookup objects. • Register at least one of the remote objects with the RMI remote object registry. The server registers the object with the bootstrap registry service and the client retrieves stubs to those objects. An object is registered by giving the registry its reference and a name: ProductImpl p = new ProductImpl("Laptop"); Naming. bind("//host/Laptop", p); In general: Naming. bind("//<hostName>/<ObjRegistryName>", <objReference>); The RMI default port is 1099
  • 73. The Server … (continued) Optionally, one can also specify a port instead of the default through: Naming. bind("//host:3000/Laptop", p); In general: Naming. bind ( "//<hostName:portnumber> /<ObjRegistryName>", <objReference>); A remote object can have methods that produce references to other objects. This allows setting it up so that the client goes to the registry only once. As it is notoriously difficult to keep names unique (and the names objects are registered with should be unique), one should register as few objects as possible. If one tries to register an object with a name that is already taken, one gets the AlreadyBoundException. To avoid this one can use rebind() instead of bind(): rebind() either adds a new entry or replaces the existing one.
  • 74. The Client accesses remote objects • The client gets access to a server object that implements the interface Product by creating a variable of type interface Product. The value that is looked up and returned by the server is stored in the variable of type interface. The Naming.lookup() method is called and the remote host and object name are specified: Product a = (Product) Naming.lookup(" rmi: //host/Laptop"); or Product a = (Product) Naming.lookup(“rmi: //host:3000/Laptop"); • A method on the remote object is then called through a . getDescription() Note: the form of the remote call is exactly the same as the form of a local call!! optional
  • 75. Interface Objects Access Remote Objects The client variable a, making the remote call a . getDescription() is an object of type remote interface (Product), NOT an object of class remote interface implementation (ProductImpl). Why do we cast to the remote interface instead of to the class that implements it? The simple answer is: because the client does not have the class that implements the interface. On the other hand interfaces are abstract entities that define methods only, not objects. Thus whenever we have an object variable of some interface type, it must be bound to a real object. This is where the stub class comes to the rescue!! The interface object refers to a stub object, which is an actual object of the stub class, i.e. when calling the remote method the remote interface object refers to the stub object representing the remote interface implementation class. The client does not actually know the type of the remote object. It relies on the stub that is obtained by running a special compiler rmic on the remote interface implementation class (ProductImpl.class), and is somehow (by hand, or through another call) obtained from the server
  • 76. The Server program: class ProductServer /** *@(#) ProductServer.java */ import java.rmi.*; import java.rmi.server.*; class ProductServer{ public static void main(String args[]) { try{ System.setSecurityManager(new RMISecurityManager()); System.out.println("Starting server..."); System.out.println("Creating remote objects..."); ProductImpl p = new ProductImpl("Laptop"); ProductImpl q = new ProductImpl("Display"); System.out.println("Binding remote objects to registry..."); Naming.rebind("//host/Laptop", p); Naming.rebind("//host/Display", q); System.out.println("Waiting for client call..."); }catch (Exception e){ System.out.println("Server error:" + e); } } }
  • 77. The Client program: class ProductClient //** *@(#) ProductClient.java */ import java.rmi.*; import java.net.*; public class ProductClient { public static void main(String args[]){ try{ Product a = (Product)Naming.lookup("//host/Laptop"); Product b = (Product)Naming.lookup("//host/Display"); System.out.println( a.getDescription( ) ); System.out.println(b.getDescription()); }catch (Exception e){ System.out.println("Client error:" + e); } System.exit(0); } } Client should have security manager to protect
  • 78. Location of RMI class files Server • Server implementation classes • Remote interface classes • Remote interface implementation class • Stub classes • Skeleton classes Client • Client implementation classes • Remote interface classes • Stub classes When building an RMI application threr are basically five categories of files that are generated • Remote interface classes • Client implementation classes • Server implementation classes , including the remote interface implementation class • Stub classes • Skeleton classes To run the application these classes must be distributed as follows
  • 79. Server Side Classes and Objects interface <RemoteInterface> extends Remote class <RemoteInterfaceImpl > extends UnicastRemoteObject implements RemoteInterface //constructor public <RemoteInterfaceImpl> throws RemoteException {…} //implementation of RemoteInterface methods public <remoteMethod> (…) throws RemoteException class <RemoteInterfaceServer> main() create & set RMISecurityManager create server objects <objRemoteInterfaceImpl > of type <RemoteInterfaceImpl> bind <objRemoteInterfaceImpl> through Naming.rebind(" //<host>/<objName ", <objRemoteInterfaceImpl>) class <RemoteInterfaceImpl>_Stub: automatically generated by rmic; class <RemoteInterfaceImpl>_Skel: automatically generated by rmic; not needed in JDK1.2s
  • 80. Client Side Classes and Objects interface <RemoteInterface> extends Remote class <RemoteInterfaceClient> main() set RMISecurityManager create client objects <objRemoteInterface> of type <RemoteInterface> (note difference to server !!) through <RemoteInterface> <objRemoteInterface> = (<RemoteInterface>) Naming.lookup ("//<host>/<objName> ") call remote method through <objRemoteInterface> . <remoteMethod>(…) class RemoteInterfaceImpl_Stub: automatically generated by rmic;
  • 81. Location of RMI class files - Notes • The stub classes are executed only by the client. However, they are also needed by the server when it is exporting itself for remote access. • Most RMI applications do not have a cleanly separated client and server functionality, i.e. any participating site has elements of the server as well as the client. Indeed , one of the great strength of RMI is that the server can make remote method calls to the client. It is entirely possible to create pure peer-to-peer RMI applications that have no distinction between the their endpoints. In these cases, the site where a given remote object resides should include all class files (thus being the “server” for this object), while the site from which the object is remotely accessed includes only the interface and the stub.
  • 82. Testing the Distributed Application on a single machine 1. Create two separate directories for the client and the server and place the corresponding *.java files in them. 2. Compile the source files for the interface, implementation, client and server classes, e.g. javac Product*.java C:Coursescs667CompiledExamplesProductRMIProductClient>javac ProductClient.java C:Coursescs667CompiledExamplesProductRMIProductClient>dir Directory of C:Coursescs667CompiledExamplesProductRMIProductClient 09/25/2002 05:20 PM 219 Product.class 10/11/2000 07:05 PM 227 Product.java 09/25/2002 05:20 PM 946 ProductClient.class 09/25/2002 02:42 PM 578 ProductClient.java C:Coursescs667CompiledExamplesProductRMIProductServer>javac ProductServer.java C:Coursescs667CompiledExamplesProductRMIProductServer>dir Directory of C:Coursescs667CompiledExamplesProductRMIProductServer 09/25/2002 05:30 PM 219 Product.class 02/04/2002 12:00 AM 230 Product.java 09/25/2002 05:30 PM 641 ProductImpl.class 02/04/2002 12:00 AM 643 ProductImpl.java 09/25/2002 05:30 PM 1,096 ProductServer.class 02/04/2002 12:00 AM 776 ProductServer.java
  • 83. 3. On server side: compile the <objRemoteInterfaceImpl> with the rmic compiler from the command line (in DOS window), e.g. rmic ProductImpl This produces the stub and skeleton for the implementation: ProductImpl_Stub.class and ProductImpl_Skel.class There is an option for Java 2 compilation rmic –v1.2 ProductImpl that produces only ProductImpl_Stub.class (skeleton is not needed any more) More generally: rmic <options> <ImplementationClassName> (see documentation for rmic optional argument list) C:Coursescs667CompiledExamplesProductRMIProductServer>rmic ProductImpl Directory of C:Coursescs667CompiledExamplesProductRMIProductServer 09/25/2002 05:30 PM 219 Product.class 02/04/2002 12:00 AM 230 Product.java 09/25/2002 05:30 PM 641 ProductImpl.class 02/04/2002 12:00 AM 643 ProductImpl.java 09/25/2002 05:35 PM 1,434 ProductImpl_Skel.class 09/25/2002 05:35 PM 2,876 ProductImpl_Stub.class 09/25/2002 05:30 PM 1,096 ProductServer.class rmic Produces Stub and Skeletons
  • 84. Stub Classes Needed by Server and Client 4. To perform a first test on a single machine without using automatic class downloading place a copy of the stub class in the client directory. (If you did not place and compile a <RemoteInterface>.java file in the client directory, now is the time to place a copy of the <RemoteInterface>.class on the client side). If you are working with projects in an IDE and are starting the server and client from the project, you typically need to add the stubs and skeletons in the corresponding projects. Of course, when deploying a real application the stub and remote interface classes will be always automatically downloaded. The above is for testing purposes only. Note: For the JDK1.1.1 localhost does not work with RMI and the name of the machine must be provided. Under 32 bit Windows you can find the machine name as follows: go to Control Panel, select “Network”, select “Identification” tab and you will see the Computer Name.
  • 85. Start the RMI Registry 5. In the server directory start the RMI registry: start rmiregistry or start rmiregistry 3000 for Windows rmiregistry & or rmiregistry 3000& for Unix Make sure you have an active TCP/IP connection, i.e. you must be connected to your Internet service provider. The registry is launched in separate window and bound to the specified port (default 1099) on machine executing the command. No text/message appears in the command line registry window: If you attempt to start the server before the rmiregistry is running the the java.rmi.ConnectException is thrown. C:Coursescs667CompiledExamplesProductRMIProductServer>start rmiregistry
  • 86. Run the Server 6. Start server start java ProductServer for Windows (w/o start runs in same window) java ProductServer & for Unix Note: In Unix, if the process is not run in the background, it never finishes normally. The main function exits immediately after registration as expected. However, when an object of a class that extends UnicastRemoteObject is created, a separate thread is started that keeps the program alive indefinitely. C:Courses667CompiledExamplesProductRMIProductServer> java ProductServer Starting server... Creating remote objects... Binding remote objects to registry... Waiting for client call...
  • 87. Run the Client 7. Start the client, e.g. start java ProductClient for Windows java ProductClient for Unix C:Coursescs667CompiledExamplesProductRMIProductClient>java ProductClient I am an excellent Laptop. Buy me! I am an excellent Display. Buy me!
  • 88. Naming Conventions for RMI classes no suffix remote interface e.g. Product Impl suffix server class implementing interface e.g. ProductImp Server suffix server program that creates server objects e.g. ProductServer Client suffix client program that calls remote method e.g. ProductClient _Stub suffix stub class automatically generated by rmic e.g. ProductImpl_Stub program _Skel suffix skeleton class automatically generated by rmic e.g. ProductImpl_Skel (needed for JDK 1.1, but nor for 1.2)
  • 89. Example 2: Array Math Client Server myArrayMath . add(x, y) calls remote / sends arrays x, y x+y returns result • Server program ArrayMathServer • Remote Interface ArrayMath • Interface Implementation ArrayMathImpl • Client program ArrayMathClient • Remote Interface ArrayMath • ArrayMathImpl_Stub Stub class of ArrayMathImpl (Mah 2000, p. 115, modified)
  • 90. Example 2: Array Math Client-Server - interface ArrayMath /** *@(#) ArrayMath.java */ public interface ArrayMath extends java.rmi.Remote { int[] addArray(int a[], int b[]) throws java.rmi.RemoteException; }
  • 91. Example 2: class ArrayMathImpl import java.rmi.*; import java.rmi.server.UnicastRemoteObject; /** * @(#) ArrayMathImpl.java */ public class ArrayMathImpl extends UnicastRemoteObject implements ArrayMath{ private String objectName; public ArrayMathImpl (String s) throws RemoteException{ //super( ); called by default objectName = s; } public int[] addArray(int a[], int b[] ) throws RemoteException{ int sum[] = new int[16]; for(int i=0; i<sum.length; i++) sum[i] = a[i] + b[i]; return sum; } }
  • 92. Example 2: class ArrayMathServer import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import java.net.*; /** * @(#) ArrayMathServer.java */ class ArrayMathServer{ public static void main (String argv[]) { System.setSecurityManager(new RMISecurityManager()); try{ ArrayMathImpl ams = new ArrayMathImpl("ArrayMathServer"); Naming.rebind("//host/ArrayMathServer", ams); System.out.println("ArrayMathServer bound in registry"); }catch (Exception e){ System.out.println("ArrayMathServer error"+ e.getMessage()); e.printStackTrace(); } } }
  • 93. Example 2: class ArrayMathClient import java.rmi.*; import java.net.*; /** *@(#) ArrayMathClient.java */ public class ArrayMathClient { public static void main(String argv[]){ int x[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; int y[]={2,2,2,2,2,2,2,2,2,2, 2, 2, 2, 2, 2, 2}; int result[]= new int[16]; try{ ArrayMath ams = (ArrayMath)Naming.lookup("//host/ArrayMathServer"); result = ams.addArray(x,y); }catch(Exception e){ System.out.println("ArrayMathClient: "+ e.getMessage()); e.printStackTrace(); }
  • 94. Example 2: class ArrayMathClient (continued) System.out.println("The two arrays are "); for(int j=0; j<x.length; j++) System.out.print(x[j] + " "); System.out.println(); for(int k=0; k<y.length; k++) System.out.print(y[k] + " "); System.out.println(); System.out.println("The sum is "); for(int i=0; i<result.length; i++) System.out.print(result[i] + " "); System.out.println(); } }
  • 96. What Are Servlets?  Basically, a java program that runs on the server  Creates dynamic web pages
  • 97. What Do They Do?  Handle data/requests sent by users (clients)  Create and format results  Send results back to user
  • 98. Who Uses Servlets?  Servlets are useful in many business oriented websites  … and MANY others
  • 99. History  Dynamic websites were often created with CGI  CGI: Common Gateway Interface  Poor solution to today’s needs  A better solution was needed
  • 100. Servlets vs. CGI  Servlet Advantages  Efficient  Single lightweight java thread handles multiple requests  Optimizations such as computation caching and keeping connections to databases open  Convenient  Many programmers today already know java  Powerful  Can talk directly to the web server  Share data with other servlets  Maintain data from request to request  Portable  Java is supported by every major web browser (through plugins)  Inexpensive  Adding servlet support to a server is cheap or free
  • 101. Servlets vs. CGI  CGI Advantages  CGI scripts can be written in any language  Does not depend on servlet-enabled server
  • 102. What Servlets Need  JavaServer Web Development Kit (JSWDK)  Servlet capable server  Java Server Pages (JSP)  Servlet code
  • 103. Java Server Web Development Kit  JSWDK  Small, stand-alone server for testing servlets and JSP pages  The J2EE SDK  Includes Java Servlets 2.4
  • 104. Servlet capable server Apache  Popular, open-source server  Tomcat  A “servlet container” used with Apache Other servers are available
  • 105. Java Server Pages  Lets you mix regular, static HTML pages with dynamically-generated HTML  Does not extend functionality of Servlets  Allows you to separate “look” of the site from the dynamic “content”  Webpage designers create the HTML  Servlet programmers create the dynamic content  Changes in HTML don’t effect servlets
  • 106. <head> </head> <body> <% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> </body> </html> <html> <head> </head> <body> <b> JSP, ASP, CF, PHP - you name it, we support it! </b> </body> </html> </font>
  • 107. <head> </head> <body> <% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> </body> </html> <html> <head> </head> <body> <b> JSP, ASP, CF, PHP - you name it, we support it! </b> </body> </html> </font>
  • 108. <head> </head> <body> <% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> </body> </html> <html> <head> </head> <body> <b> JSP, ASP, CF, PHP - you name it, we support it! </b> </body> </html> </font>
  • 109. <head> </head> <body> <% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> </body> </html> <html> <head> </head> <body> <b> JSP, ASP, CF, PHP - you name it, we support it! </b> </body> </html> </font>
  • 110. Servlet Code  Written in standard Java  Implement the javax.servlet.Servlet interface
  • 111. package servlet_tutorials.PhoneBook; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.net.*; public class SearchPhoneBookServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String query = null; String where = null; String firstname = null; String lastname = null; ResultSet rs = null; res.setContentType("text/html"); PrintWriter out = res.getWriter(); // check which if any fields in the submitted form are empty if (req.getParameter("FirstName").length() > 0) firstname = req.getParameter("FirstName"); else firstname = null; }
  • 112. Main Concepts of Servlet Programming  Life Cycle  Client Interaction  Saving State  Servlet Communication  Calling Servlets  Request Attributes and Resources  Multithreading
  • 113. Life Cycle  Initialize  Service  Destroy
  • 114. Life Cycle: Initialize  Servlet is created when servlet container receives a request from the client  Init() method is called only once
  • 115. Life Cycle: Service  Any requests will be forwarded to the service() method  doGet()  doPost()  doDelete()  doOptions()  doPut()  doTrace()
  • 116. Life Cycle: Destroy  destroy() method is called only once  Occurs when  Application is stopped  Servlet container shuts down  Allows resources to be freed
  • 117. Client Interaction  Request  Client (browser) sends a request containing  Request line (method type, URL, protocol)  Header variables (optional)  Message body (optional)  Response  Sent by server to client  response line (server protocol and status code)  header variables (server and response information)  message body (response, such as HTML)
  • 118.  Thin clients (minimize download)  Java all “server side” Client Server Servlets
  • 119. Saving State  Session Tracking  A mechanism that servlets use to maintain state about a series of requests from the same user (browser) across some period of time.  Cookies  A mechanism that a servlet uses to have clients hold a small amount of state- information associated with the user.
  • 120. Servlet Communication  To satisfy client requests, servlets sometimes need to access network resources: other servlets, HTML pages, objects shared among servlets at the same server, and so on.
  • 121. Calling Servlets  Typing a servlet URL into a browser window  Servlets can be called directly by typing their URL into a browser's location window.  Calling a servlet from within an HTML page  Servlet URLs can be used in HTML tags, where a URL for a CGI-bin script or file URL might be found.
  • 122. Request Attributes and Resources  Request Attributes  getAttribute  getAttributeNames  setAttribute  Request Resources - gives you access to external resources  getResource  getResourceAsStream
  • 123. Multithreading  Concurrent requests for a servlet are handled by separate threads executing the corresponding request processing method (e.g. doGet or doPost). It's therefore important that these methods are thread safe.  The easiest way to guarantee that the code is thread safe is to avoid instance variables altogether and instead use synchronized blocks.
  • 124. import java.io.*; import javax.servlet.*; import javax.servlet.http.*;  public class SimpleCounter extends HttpServlet {  int count = 0;  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {  res.setContentType("text/plain");  PrintWriter out = res.getWriter();  count++;  out.println("This servlet has been accessed " + count + " times since loading");  }  } Simple Counter Example
  • 125. MultiThread Problems  Problem - Synchronization between threads count++; // by thread1 count++; // by thread2 out.println.. // by thread1 out.println.. // by thread2 Two Requests will get the same value of counter  Solution - Use Synchronized Block!  Synchronized Block  Lock(Monitor)
  • 126. Better Approach  The approach would be to synchronize only the section of code that needs to be executed automically: PrintWriter out = res.getWriter(); synchronized(this) { count++; out.println("This servlet has been accessed " + count + "times since loading"); } This reduces the amount of time the servlet spends in its synchronized block, and still maintains a consistent count.
  • 127. Example: On-line Phone Book  Design
  • 129. Search Form <html> <head> <title>Search Phonebook</title> </head> <body bgcolor="#FFFFFF"> <p><b> Search Company Phone Book</b></p> <form name="form1" method="get" action="servlet/servlet_tutorials.PhoneBook.SearchPhoneBookServlet"> <table border="0" cellspacing="0" cellpadding="6"> <tr> <td >Search by</td> <td> </td> </tr> <tr> <td><b> First Name </b></td> <td> <input type="text" name="FirstName"> AND/OR</td> </tr> <tr> <td ><b> Last Name </b></td> <td > <input type="text" name="LastName"></td> </tr> <tr> <td ></td> <td > <input type="submit" name="Submit" value="Submit"> </td> </tr> </table> </form> </body> </html> Java server Page Search_phone_book.jsp
  • 131. Display Results <html> <%@page import ="java.sql.*" %> <jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/> <%@ page buffer=35 %> <%@ page errorPage="error.jsp" %> <html> <head> <title>Phone Book Search Results</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF"> <b>Search Results</b> <p> <% String q = request.getParameter("query"); ResultSet rs = phone.getResultSet(q); %> <% if (rs.wasNull()) { %> "NO RESULTS FOUND" <% } else %> <table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div align="center">Last Name</font></b></div> </td> <td> <div align="center">Phone Number</font></b></div> </td> <td> <div align="center">Email</font></b></div> </td> </tr> <% while(rs.next()) { %> <tr> <td> <%= rs.getString("first_name") %></td> <td><%= rs.getString("last_name") %></td> <td><%= rs.getString("phone_number") %> </td> <td> <%= rs.getString("e_mail") %> </td> </tr> <% } %> </table> Java Server Page Display_search_results.jsp
  • 132. Servlet Listing 2 SearchPhoneBookServlet.java package servlet_tutorials.PhoneBook; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import java.net.*; public class SearchPhoneBookServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String query = null; String where = null; String firstname = null; String lastname = null; ResultSet rs = null; res.setContentType("text/html"); PrintWriter out = res.getWriter(); // check which if any fields in the submitted form are empty if (req.getParameter("FirstName").length() > 0) firstname = req.getParameter("FirstName"); else firstname = null; if (req.getParameter("LastName").length() > 0) lastname = req.getParameter("LastName"); else lastname = null; // Build sql query string if ((firstname != null) && (lastname != null)){ where = "first_name ='"; where += firstname; where += "' AND "; where += "last_name ='"; where += lastname; where += "'"; } else if ((firstname == null) && (lastname != null)){ where = "last_name ='"; where += lastname; where += "'"; }
  • 133. Java Bean & Database linked Listing 4 PhoneBookBean.java package servlet_tutorials.PhoneBook; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; public class PhoneBookBean { private Connection con = null; private Statement stmt = null; private ResultSet rs = null; private String query = null; public PhoneBookBean() {} public ResultSet getResultSet(String query) { // grab a connection to the database con = ConnectDB.getConnection(); try{ stmt = con.createStatement(); // run the sql query to obtain a result set rs = stmt.executeQuery(query); } catch(SQLException sqlex){ sqlex.printStackTrace(); } catch (RuntimeException rex) { rex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } return rs; } } Listing 5 ConnectDB.java package servlet_tutorials.PhoneBook; import java.io.*; import java.net.*; import java.sql.*; import java.util.*; /** * Re-usable database connection class */ public class ConnectDB { // setup connection values to the database static final String DB_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver"; static final String URL = "jdbc:odbc:PhoneBook"; static final String USERNAME = "anon_user"; static final String PASSWORD = ""; // Load the driver when this class is first loaded static { try { Class.forName(DB_DRIVER).newInstance(); } catch (ClassNotFoundException cnfx) { cnfx.printStackTrace(); } catch (IllegalAccessException iaex){ iaex.printStackTrace(); } catch(InstantiationException iex){ iex.printStackTrace (); } } /** * Returns a connection to the database */ public static Connection getConnection() { Connection con = null; try { con = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } finally { return con;
  • 136. References  http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Overview.html  www.cis.upenn.edu/~matuszek/ cit597-2004/Lectures/21-servlets.ppt  http://learning.unl.ac.uk/im269/lectures/week6servletsp1.ppt  http://java.sun.com/docs/books/tutorialNB/download/tut-servlets.zip  http://www.webdevelopersjournal.com/articles/intro_to_servlets.html
  • 137. Processing XML with Java BY Dr Rani Reddy DBI – Representation and Management of Data on the Internet
  • 138. XML • XML is eXtensible Markup Language • It is a metalanguage: – A language used to describe other languages using “markup” tags that describe properties of the data • Designed to be structured – Strict rules about how data can be formatted • Designed to be extensible – Can define own terms and markup
  • 139. XML Family • XML is an official recommendation of the W3C • Aims to accomplish what HTML cannot and be simpler to use and implement than SGML HTML XML SGML XHTML
  • 140. The Essence of XML • Syntax – The permitted arrangement or structure of letters and words in a language as defined by a grammar (XML) • Semantics – The meaning of letters or words in a language • XML uses Syntax to add Semantics to the documents
  • 141. Using XML • In XML there is a separation of the content from the display • XML can be used for: – Data representation – Data exchenge
  • 142. Databases and XML • Database content can be presented in XML – XML processor can access DBMS or file system and convert data to XML – Web server can serve content as either XML or HTML
  • 143. HTML vs. XML <OL> <LI>HTML allows <B><I>improper nesting</B></I>. <LI>HTML allows start tags, without end tags, like the <BR> tag. <LI>HTML allows <FONT COLOR=#9900CC>attribute values</FONT> without quotes <li>HTML is case-insensitive <LI>White space is not important in HTML </OL> <OL> <LI>XML requires <B><I>proper nesting</I></B>.</LI> <LI>XML requires empty tags to be identified with a trailing slash, as in <BR/>.</LI> <LI>XML requires <FONT COLOR="#9900CC">quoted attribute values</FONT>.</LI> <LI>XML is case-sensitive <LI>White space is important in XML </OL>
  • 144. Some Basic Rules for XML • All tags must be balanced - <TAG>...</TAG> • Empty tags expressed - <EMPTY_TAG/> • Tags must be nested - <B><I>…</I></B> • All element attributes must be quoted - <TAG name=“value”> • Text is case-sensitive - <TAG> != <Tag> • Comments are allowed - <!-- … --> • Must begin - <?xml version=‘1.0’ ?> • Special characters must be escaped (e.g., &gt; for >)
  • 145. SAX Parser • Set of interfaces implemented by an application • The application – reads in an XML file – generates events when it encounters items in the XML file
  • 146. SAX Parser Events • A SAX parser generates events – at the start and end of a document, – at the start and end of an element, – when it finds characters inside an element, and at several other points • User writes the Java code that handles each event, and decides what to do with the information from the parser
  • 148. When to (not) use SAX • Ideal for simple operations on XML files – E.g. reading and extracting elements • Good for very large XML files (c.f. DOM) • Not good if we want to manipulate XML structure • Not designed for writing out XML
  • 149. DOM • Document Object Model • Set of interfaces for an application that reads an XML file into memory and stores it as a tree structure • The abstract API allows for constructing, accessing and manipulating the structure and content of XML and HTML documents
  • 150. What a DOM Parser Gives • When you parse an XML document with a DOM parser, you get back a tree structure that contains all of the elements of your document • The DOM provides a variety of functions you can use to examine the contents and structure of the document
  • 152. Why to Use DOM • Task of writing parsers is reduced to coding against an API for the document structure • Domain-specific frameworks will be written on top of DOM
  • 155. DOM vs. SAX • If your document is very large and you only need a few elements - use SAX • If you need to process many elements and perform manipulations on XML - use DOM • If you need to access the XML many times - use DOM
  • 156. What Would You Choose for • Processing an XML document in a server? • Processing an XML document in a remote client? • Direct access to element in the XML file (e.g., index based on paths) • A visual tool for traversal over the document tree?
  • 158. XML Parsers • There are several different ways to categorise parsers: – Validating versus non-validating parsers – Parsers that support the Document Object Model (DOM) – Parsers that support the Simple API for XML (SAX) – Parsers written in a particular language (Java, C++, Perl, etc.)
  • 159. Non-Validating Parsers • Speed and efficiency – It takes a significant amount of effort for an XML parser to process a DTD and make sure that every element in an XML document follows the rules of the DTD. • If we only want to find tags and extract information – we should use a non- validating parser
  • 160. Using an XML Parser • Three basic steps in using an XML parser – Creating a parser object – Passing the XML document to the parser – Processing the results • Generally, writing out XML is not in the scope of parsers (though some may implement proprietary mechanisms)
  • 161. SAX – Simple API for XML
  • 162. The SAX Parser • SAX parser is an event-driven API – An XML document is sent to the SAX parser – The XML file is read sequentially – The parser notifies the class when events happen, including errors – The events are handled by the implemented API methods to handle events that the programmer implemented
  • 163. SAX Parser • A SAX parser generates events – At the start and end of a document – At the start and end of an element – When it finds characters inside an element – Upon encountering errors – Upon encountering negligible whitespace – and at several other points • It uses a callback mechanism to notify the application • Java code that handles each event implements the events handling
  • 164. The org.xml.sax.* Package • SAX Interfaces and Classes – Parser – DocumentHandler – DTDHandler – ErrorHandler – EntityResolver – AttributeList – Locator
  • 165. The Apache XML Parser (xerces) import org.xml.sax.*; import org.apache.parsers.*; class MyClass { SAXParser myParser; … try { myParser.parse("file:/myFile.xml"); } catch (SAXException err) {…} … }
  • 166. The Parser Interface • Registers other objects for callbacks – void setDocumentHandler(DocumentHandler handler) – void setDTDHandler(DTDHandler handler) – void setErrorHandler(ErrorHandler handler) – void setEntityResolver(EntityResolver resolver) • Starts parsing with parse() method call • When the parser hits a significant item, it stops reading and calls a registered object • The parser continues reading the XML file once the called method has returned
  • 167. The DocumentHandler Interface • This interface is used to receive basic markup events from the parser • It is usually implemented by a class that activates the parser class myClass implements DocumentHandler { … myParser.setDocumentHandler(this); … }
  • 168. DocumentHandler Methods • void startDocument() • void endDocument() • void startElement(String name, AttributeList attrs) • void endElement(String name) • void characters(char[] ch, int start, int length) • void ignorableWhitespace(char[] ch, int start, int length) • void processingInstruction(String target, String data)
  • 169. Bachelor Tags • What happen when the parser parses a bachelor tag? <dbi id=‘1’/>
  • 170. AttributeList Interface • Elements may have attributes – We have a wrapper object for all attribute details that implements the AttributeList interface – It cannot distinguish attributes that are defined explicitly from those that are specified in the DTD
  • 171. AttributeList Interface (cont.) int getLength(); String getName(int i); String getType(int i); String getValue(int i); String getType(String name); String getValue(String name);
  • 172. Attributes Types • The following are possible types for attributes: – "CDATA", – "ID", – "IDREF", "IDREFS", – "NMTOKEN", "NMTOKENS", – "ENTITY", "ENTITIES", – "NOTATION"
  • 173. AttributeListImpl • The class is in the package org.xml.sax.helpers.* • Include methods such as: – addAtrribute, removeAttribute – clear – getName, getType, getValue – getLength By name or by index
  • 174. ErrorHandler Interface • If we want to know about warnings and errors – We implement the ErrorHandler interface and register it with the parser class – The handler does not report where the error occurred • We have three levels of exception: void error(SAXParseException ex); void fatalError(SAXParserExcpetion ex); void warning(SAXParserException ex);
  • 175. Locator Interface • Associates a SAX event with a document location – The parser can inform • the application of the entity, • line number and character number of a warning or error, – if it is a class implementing the Locator interface and it is registered with the DocumentHandler
  • 176. Locator Methods int getLineNumber(); int getColumnNumber(); String getSystemId(); (i.e., return the URL) String getPublicId();
  • 177. DTDHandler Interface • Provides callback methods to receive notification of DTD events • It is a mechanism to inform an application about any binary entity that the parser encounters
  • 178. DTD Handler notationDecl(String name, String publicId, String systemId); unparsedEntityDecl(String name, String publicId, String systemId, String notationName);
  • 179. InputSource Class • Possible to specify a byte or character stream for the input to the parser • The InputSource class contains methods that specify the exact nature of the data source
  • 180. EntityResolver Interface • The application is not aware of the physical structure of the XML data • The parser contains an entity manager that hides the complexity from the application which sees the data as a single stream • Can intercept references to entities by implementing the EntityResolver interface
  • 181. EntityResolver Interface (2) • When the parser encounters an entity, it passes the system and/or public identifier to the application – Return value is ‘null’ or new InputSource
  • 182. EntityResolver Interface (2) public InputSource resolveEntity(String publicID, String systemID) { if (systemID.equals("Disclaimer") || publicID.equals ("-//EBI//TEXT Disclaimer//EN")) return (new InputSource(file:/xml/disc.xml)); } }
  • 183. HandlerBase Class • This class implements SAX interfaces in a sensible, default way DocumentHandler, DTDHandler, EntityResolver and ErrorHandler • Can be used for partial implementation of the interfaces • This class can be extended: import org.xml.sax.HandlerBase; public class myHandler extends HandlerBase() { … }
  • 184. ParserFactory Class • A helper class – Provides convenient methods for dynamically loading SAX parsers makeParser() (Uses org.xml.sax.parser system property) makeParser(String className)
  • 185. Example • An example of indenting an XML document (as part of a server) XMLIndent.java
  • 189. DOM – Document Object Model
  • 190. DOM Standards • DOM 1.0 standard from www.w3.org • Assumes an object-oriented approach • Composed of number of interfaces – org.w3c.dom.* • Central class is 'Document' (DOM tree) • Standard does not include – Tree walking – Writing out XML format
  • 191. Creating a DOM Tree • A DOM implementation has a method to pass an XML file to a factory object • The factory object returns a Document object that represents the root element of a whole document • On the Document objects, DOM standard interface can be used to interact with XML structure
  • 192. Line Of Work DOM Parser DOM Tree XML File A P I Application
  • 193. DOM Tree Document Document Type Element Attribute Element Element Attribute Text Element Text Entity Reference Text Text Text Comment
  • 194. Normalizing a Tree • Normalizing a DOM Tree has two effects: – Combine adjacent textual nodes – Eliminate empty textual nodes – We can apply a normalize() method to the document element
  • 195. DOMParser • DOMParser extends XMLParser – Important Methods: • void parse(InputSource source) Parses the specified input source • void parse(java.lang.String systemId) Parses the input source specified by the given system identifier • Document getDocument() Returns the document
  • 197. Creating a DOM Tree (2) import java.io.*; import org.w3c.dom.*; import org.apache.xerces.dom.*; import org.apache.xerces.parsers.*; public class myClass { DOMParser parser = new DOMParser(); try { parser.parse(“file:/doc.xml”); } ccatch (IOException err) {…} catch (SAXException err) {…} catch (DOMException err) {…} Document document = parser.getDocument();…
  • 198. DOM Interfaces and Classes DocumentFragment Document CharacterData Text Comment CDATASection Attr Element DocumentType Notation Entity EntityReference ProcessingInstruction Node NodeList NamedNodeMap DocumentType Figure as from “The XML Companion” - Neil Bradle
  • 199. DOM Interfaces • The DOM defines several Java interfaces – Node The base data type of the DOM – Element Represents element – Attr Represents an attribute of an element – Text The content of an element or attribute – Document Represents the entire XML document. A Document object is often referred to as a DOM tree
  • 200. Node Interface • Basic object of DOM (single node in tree) • Nodes describe • Node collections – NodeList, NamedNodeMap, DocumentFragment • Several nodes extend the Node interface Elements Attributes Text Comments CDATA sections Entity declarations Entity references Notation declarations Entire documents Processing instructions
  • 201. Node Methods • Three categories of methods – Node characteristics • name, type, value – Contextual location and access to relatives • parents, siblings, children, ancestors, descendants – Node modification • Edit, delete, re-arrange child nodes
  • 202. Node Methods (2) short getNodeType(); String getNodeName(); String getNodeValue() throws DOMException; void setNodeValue(String value) throws DOMException; boolean hasChildNodes(); NamedNodeMap getAttributes(); Document getOwnerDocument();
  • 203. Node Types - getNodeType() ELEMENT_NODE = 1 ATTRIBUTE_NODE = 2 TEXT_NODE = 3 CDATA_SECTION_NODE = 4 ENTITY_REFERENCE_NODE = 5 ENTITY_NODE = 6 PROCESSING_INSTRUCTION_NODE = 7 COMMENT_NODE = 8 DOCUMENT_NODE = 9 DOCUMENT_TYPE_NODE = 10 DOCUMENT_FRAGMENT_NODE = 11 NOTATION_NODE = 12 if (myNode.getNodeType() == Node.ELEMENT_NODE) { //process node … }
  • 204. Node Names and Values • Every node has a name and possibly a value • Name is not a unique identifier (only location) Type Interface Name Name Value ATTRIBUTE_NODE Attr Attribute name Attribute value DOCUMENT_NODE Document #document NULL DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment NULL DOCUMENT_TYPE_NODE DocumentType DOCTYPE name NULL CDATA_SECTION_NODE CDATASection #cdata-section CDATA content COMMENT_NODE Comment Entity name Content string ELEMENT_NODE Element Tag name NULL ENTITY_NODE Entity Entity name NULL ENTITY_REFERENCE_NODE EntityReference Entity name NULL NOTATION_NODE Notation Notation name NULL PROCESSING_INSTRUCTION_ NODE ProcessingInstruction Target string Content string TEXT_NODE Text #text Text string Table as from “The XML Companion” - Neil Bradle
  • 205. Type Interface Name Name Value ATTRIBUTE_NODE Attr Attribute name Attribute value DOCUMENT_NODE Document #document NULL DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment NULL DOCUMENT_TYPE_NODE DocumentType DOCTYPE name NULL CDATA_SECTION_NODE CDATASection #cdata-section CDATA content COMMENT_NODE Comment Entity name Content string ELEMENT_NODE Element Tag name NULL ENTITY_NODE Entity Entity name NULL ENTITY_REFERENCE_NODE EntityReference Entity name NULL NOTATION_NODE Notation Notation name NULL PROCESSING_INSTRUCTION_ NODE ProcessingInstruction Target string Content string TEXT_NODE Text #text Text string
  • 206. Child Nodes • Most Nodes cannot have children, except – Document, DocumentFragment, Element • Can check for presence of children – if (myNode.hasChildNodes()) { //process children of myNode … }
  • 207. Node Navigation • Every node has a specific location in tree • Node interface specifies methods to find surrounding nodes – Node getFirstChild(); – Node getLastChild(); – Node getNextSibling(); – Node getPreviousSibling(); – Node getParentNode(); – NodeList getChildNodes();
  • 208. Node Navigation (2) getFirstChild() getPreviousSibling() getChildNodes() getNextSibling() getLastChild() getParentNode() Node parent = myNode.getParentNode(); if (myNode.hasChildren()) { NodeList children = myNode.getChildNodes(); } Figure as from “The XML Companion” - Neil Bradle
  • 209. Node Manipulation • Children of a node in a DOM tree can be manipulated - added, edited, deleted, moved, copied, etc. Node removeChild(Node old) throws DOMException; Node insertBefore(Node new, Node ref) throws DOMException; Node appendChild(Node new) throws DOMException; Node replaceChild(Node new, Node old) throws DOMException; Node cloneNode(boolean deep);
  • 210. Node Manipulation (2) Ref New insertBefore Old New replaceChild cloneNode Shallow 'false' Deep 'true' Figure as from “The XML Companion” - Neil Bradle
  • 211. Document::Node Interface • Represents entire XML document (tree root) • Methods //Information from DOCTYPE - See 'DocumentType' DocumentType getDocumentType(); //Information about capabilities of DOM implementation DOMImplementation getImplementation(); //Returns reference to root node element Element getDocumentElement(); //Searches for all occurrences of 'tagName' in nodes NodeList getElementsByName(String tagName);
  • 212. Document::Node Interface (2) • Factory methods for node creation Element createElement(String tagName) throws DOMException; DocumentFragment createDocumentFragment(); Text createTextNode(String data); Comment createComment(String data); CDATASection createCDATASection(String data) throws DOMException; ProcessingInstruction createProcessingInstruction( String target, String data) throws DOMException; Attr createAttribute(String name) throws DOMException; EntityReference createEntityReference(String name) throws DOMException;
  • 213. DocumentType::Node Interface • Information about document encapsulated in DTD representation • DOM 1.0 doesn’t allow editing of this node //Returns name of document String getName(); //Returns general entities declared in DTD NamedNodeList getEntities(); //Returns notations declared in DTD NamedNodeList getNotations();
  • 214. Element::Node Interface • Two categories of methods – General element methods – Attribute management methods String getTagName(); NodeList getElementsByTagName(); void normalize(); String getAttribute(String name); void setAttribute(String name, String value) throws DOMException; void removeAttribute(String name) throws DOMException; Attr getAttributeNode(String name); void setAttributeNode(Attr new) throws DOMException; void removeAttributeNode(Attr old) throws DOMException;
  • 215. Element::Node Interface (2) • Only Element objects have attributes but attribute methods of Element are simple – Need name of attribute – Cannot distinguish between default value specified in DTD and given in XML file – Cannot determine attribute type [String] • Instead use getAttributes() method of Node – Returns Attr objects in a NamedNodeMap
  • 216. Attr::Node Interface • Interface to objects holding attribute data • Entity ref's are children of attribute's //Get name of attribute String getName(); //Get value of attribute String getValue(); //Change value of attribute void setValue(String value); //if 'true' - attribute defined in element, else in DTD boolean getSpecified();
  • 217. Attr::Node Interface (2) • Attributes not considered part of DOM – parentNode, previousSibling and nextSibling have null value for Attr object • Create attribute objects using factory method of Document //Create the empty Attribute node Attr newAttr = myDoc.createAttribute("status"); //Set the value of the attribute newAttr.setValue("secret"); //Attach the attribute to an element myElement.setAttributeNode(newAttr);
  • 218. CharacterData::Node Interface • Useful general methods for dealing with text • Not used directly – sub-classed to Text and Comment Node types String getData() throws DOMException; void setData(String data) throws DOMException; int getLength(); void appendData(String data) throws DOMException; String substringData(int offset, int length) throws DOMException; void insertData(int offset, String data) throws DOMException; void deleteData(int offser, int length) throws DOMException; void replaceData(int offset, int length, String data) throws DOMException;
  • 219. Text::Node Interface • Represents textual content of Element or Attr – Usually children of these nodes • Always leaf nodes • Single method added to CharacterData – Text splitText(int offset) throws DOMException • Factory method in Document for creation • Calling normalize() on an Element merges its Text objects
  • 220. CDATASection::Text Interface • Represents CDATA that is not to be interpreted as markup (the only delimiter recognised is the "]]>" string that ends the CDATA section) • The DOMString attribute of the Text node holds the text of the CDATA section • No methods added to CharacterData • Factory method in Document for creation – CDATASection newCDATA = myDoc.createDATASection("press <<<ENTER>>>");
  • 221. Comment::Text Interface • Represents comments • all the characters between starting '<!--' and ending '-->' • No methods added to CharacterData • Factory method in Document for creation – Comment newComment = myDoc.createComment(" my comment "); //Note spaces
  • 222. ProcessingInstruction::Node Interface • Represent processing instruction declarations – Name of node is target application name – Value of node is target application command • Factory method in Document for creation – ProcessingInstruction newPI = myDoc.createProcessingInstruction(“myProgs/ghostview”, “page.ps”); //Get the content of the processing instruction String getData() //Set the content of the processing instruction void setData(String data) //The target of this processing instruction String getTarget();
  • 223. EntityReference::Node Interface • DOM includes interfaces for handling notations, entities and entity references – If the entities have not been replaced by the parser Element Text Text EntityReference Text An value xml eXtensible Markup Language <!ENTITY xml "eXtensible Markup Language"> <para>An &xml; value</para> value name Figure as from “The XML Companion” - Neil Bradle
  • 224. Entity::Node Interface • Represents an entity, either parsed or unparsed, in an XML document – Parser may replace entity references, or create EntityReference nodes • Must retain Entity for non-parsable data • Extends Node interface and adds methods • For non-parsable entities - can get notation name String getPublicId(); String getSystemId(); String getNotationName();
  • 225. Entity::Node Interface (2) • A parsable Entity may have children that represent the replacement value of the entity • All entities of a Document accessed with getEntities() method in DocumentType <!ENTITY MyBoat PUBLIC "BOAT" SYSTEM "boat.gif" NDATA GIF> String publicId = ent.getPublicId(); //BOAT String systemId = ent.getSystemId(); //boat.gif String notation = ent.getNotationName(); //GIF Figure as from “The XML Companion” - Neil Bradle
  • 226. Notation::Node Interface • Each notation declaration in DTD represented by a Notation node • Methods added to Node interface • All notations of a Document accessed with getNotations() method in DocumentType object //Returns content of PUBLIC identifier String getPublicId(); //Returns content of SYSTEM identifier String getSystemId();
  • 227. NodeList Interface • Holds collection of ordered Node objects • Two methods //Find number of Nodes in NodeList int getLength(); //Return the i-th Node Node item(int index); ------------------------------------------------- Node child; NodeList children = element.getChildNodes()' for (int i = 0; i < children.getLength(); i++) { child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { System.out.println(child.getNodeName()); } }
  • 228. NamedNodeMap Interface • Holds collection of unordered Node objects – E.g. Attribute, Entity and Notation • Unique names are essential as nodes are accessed by name NamedNodeMap myAttributes = myElement.getAttributes(); NamedNodeMap myEntities = myDocument.getEntities(); NamedNodeMap myNotations = myDocument.getNotations(); ------------------------------------------------------ int getLength(); Node item(int index); Node getNamedItem(String name); Node setNamedItem(Node node) throws DOMException;//Node! Node removeNamedItem(String name) throws DOMException;
  • 229. DocumentFragment::Node Interface • Fragment of Document can be temporarily stored in DocumentFragment node – Lightweight object, e.g. for 'cut-n-paste' • When attached to another Node - destroys itself (very useful for adding siblings to tree) DocumentFragment DOM tree New DOM tree Figure as from “The XML Companion” - Neil Bradle
  • 230. DOMImplementation Interface • Interface to determine level of support in DOM parser – hasFeature(String feature, String version); – if (theParser.hasFeature("XML", "1.0") { //XML is supported … }
  • 231. DOM Objects • DOM object  compiled XML • Can save time and effort if send and receive DOM objects instead of XML source – Saves having to parse XML files into DOM at sender and receiver – But, DOM object may be larger than XML source
  • 232. Examples • DOMTest • DTD • XML • Counting Result
  • 234. Java + XML = JDOM
  • 235. What is JDOM? • JDOM is a way to represent an XML document for easy and efficient reading, manipulation, and writing – Straightforward API – Lightweight and fast – Java-optimized • Despite the name similarity, it's not build on DOM or modeled after DOM – Although it integrates well with DOM and SAX • An open source project with an Apache-style license
  • 236. The JDOM Philosophy • JDOM should be straightforward for Java programmers – Use the power of the language (Java 2) – Take advantage of method overloading, the Collections APIs, reflection, weak references – Provide conveniences like type conversions • JDOM should hide the complexities of XML wherever possible – An Element has content, not a child Text node with content – Exceptions should contain useful error messages – Give line numbers and specifics, use no SAX or DOM specifics
  • 237. More JDOM Philosophy • JDOM should integrate with DOM and SAX – Support reading and writing DOM documents and SAX events – Support runtime plug-in of any DOM or SAX parser – Easy conversion from DOM/SAX to JDOM – Easy conversion from JDOM to DOM/SAX
  • 238. The Historical Alternatives: DOM • DOM is a large API designed for complex environments – A W3C standard, developed by W3C working groups – Implemented by products like Xerces – Represents a document tree fully held in memory – Has to have the same API on multiple languages – Reading and changing the document is non-intuitive – Fairly heavyweight to load and store in memory – http://www.w3.org/DOM
  • 239. The Historical Alternatives: SAX • SAX is a lightweight API designed for fast reading – Public domain API from David Megginson and XML- DEV mailing list – Implemented by products like Xerces – Callback mechanism reports when document elements are encountered – Lightweight since the document is never entirely in memory – Does not support modifying the document – Does not support random access to the document – Fairly steep learning curve to use correctly
  • 240. Do you need JDOM? • JDOM is a lightweight API – Its design allows it to hold less in memory • JDOM can represent a full document – Not all must be in memory at once • JDOM supports document modification – And document creation from scratch, no "factory"
  • 241. For More Information • To get more information on JDOM, see: http://www.jdom/org