Title: Java EE Programming
1Java EE Programming
2Topics
- Networking and Internetworking
- Inter-process communication
- Distributed objects and remote invocation
- UDP TCP
- Javas RMI
3Networking Issues for Distributed Systems
- Previous networks had to meet simple application
requirements - File transfer, remote login, e-mail and
newsgroups - With the growth of the Internet, more stringent
requirements are necessary - New modes of use
- Additional and more stringent requirements
4Current Networking Requirements Terms
- Performance
- Speed with which individual messages can be
transferred between two interconnected computers - Latency is the delay that occurs after a send
operation is executed before data starts to
arrive at the destination computer (network
latency) - Data transfer rate is the speed at which data
can be transferred between two computers in the
network once the transmission has begun - Bits per second
- Message transmission time
- latency length/data transfer rate
5Current Networking Requirements Terms
- Scalability
- The potential future size of the Internet is
commensurate with the population of the planet - Indicates size and load of the Internet
- Networks must scale
6Current Networking Requirements Terms
- Reliability
- The degree in which an application can recover
from communication failures - Security
- Techniques for achieving security in distributed
systems - Firewalls creates a protection boundary between
an organizations intranet and the rest of the
Internet - Distributed systems need a secure network
environment with end-to-end authentication,
privacy, and security - Example - encryption
7Current Networking Requirements Terms
- Mobility
- Wireless networks provide connectivity to devices
such as laptops, cell phones, PDAs - Addressing and routing schemes of Internet were
developed before the advent of wireless devices
so are not well-adapted to their intermittent
connection to many different subnets - Quality of service
- Applications that transmit multimedia data
require guaranteed bandwidth and latencies
8Current Networking Requirements Terms
- Multicasting
- One-to-many communication
- Needed in distributed systems
9Types of Networks in Distributed Systems
- PAN Personal area network
- Various digital devices carried by a user are
connected to a low-cost, low-energy network - LAN Local area network
- Carry messages at high speed between computers
connected by a single communication medium - Twisted copper wire, coaxial cable, fiber optics
- WAN Wide area network
- Carry messages a lower speeds between nodes that
are often in different organizations and may be
separated by large distances - Uses routers to route the messages
- MAN Metropolitan area network
- High speed network installed in towns/cities for
transmission of data and video - DSL and Cable modem connections
10Types of Networks in Distributed Systems
- WLAN Wireless local area network
- Used in place of wired LANs for wireless mobile
devices - IEEE 802.11 (WiFi) standard protocol
- WMAN Wireless metropolitan area network
- Supercedes 802.11
- IEEE 802.16 WiMAX protocol
11Types of Networks in Distributed Systems
- Internetworks communication subsystem in which
several networks are linked together to provide
common data communication facilities - Overlay the technologies and protocols of the
individual component networks and methods used
for their interconnection - Needed for the development of extensible, open
distributed systems - Example Internet
12Network performance
13Network Protocols
- Protocol refers to a well-known set of rules
and formats to be used for communication between
processes in order to perform a given task - Two parts
- a specification of the sequence of messages that
must be exchanged - a specification of the format of the data in the
messages
14Conceptual Layering of Protocol Software
15Protocol Layers
- Network software is arranged in a hierarchy of
layers - Each layer presents an interface to the layers
above it and below it - Sending side each layer (except top) accepts
items of data in a specified format from the
layer above it and applies transformations to
encapsulate the data in the format specified for
that layer - Receiving side converse transformations are
applied to data items received from the layer
below before being passed to layer above
16Encapsulation as it is applied in Layered
Protocols
The tags in the headers are the protocol type for
the layer above, needed for the receiving
protocol stack to correctly unpack the packets
17Protocol Suites
- Complete set of protocol layers is referred to as
a protocol suite or protocol stack - Reference Model for Open Systems Interconnection
(OSI) - Protocol layering brings substantial benefits in
simplifying and generalizing the software
interfaces for access to the communication
services of networks - Also carries significant performance costs
- Why do you think this is so?
18Protocol layers in the ISO Open Systems
Interconnection (OSI) model
19OSI Protocol Summary
20Internet Protocols
- TCP/IP Transmission Control Protocol/Internet
Protocol - Grown now to over 60 million hosts
- Example application services protocols based in
TCP/IP - Web (HTTP)
- email (SMTP, POP)
- netnews (NNTP)
- file transfer (FTP)
- Telnet (telnet)
21TCP/IP Layers
22TCP/IP Layers
- Two transport protocols
- TCP reliable connection-oriented protocol
- UDP datagram protocol that does not guarantee
reliable transmission - Internet Protocol (IP) is the underlying
network protocol - IP datagrams provide the basic transmission
mechanism for the Internet and other TCP/IP
networks - Internet protocols are usually layered over other
network technologies - i.e, Ethernet
23Encapsulation in a message transmitted via TCP
over an Ethernet
24The programmer's conceptual view of a TCP/IP
Internet
25IP Addressing
- Scheme chosen for naming and addressing hosts and
routing IP packets to their destination - Assigns an IP address to each host in the
Internet a 32-bit numeric identifier
containing - network identifier uniquely identifies one of
the subnetworks in the Internet - host identifier uniquely identifies the hosts
connection to that network
26Internet Address Space
Class A is reserved for very large networks
(i.e.,US NSFNet) Class B is used for
organizations that operate networks likely to
contain more than 255
computers Class C is allocated to all other
network operators Class D is reserved for
Internet multittask communication Class E
contains a range of unallocated addresses
reserved for future use
27TCP and UDP
- Provide the communication capabilities of the
Internet in a form that is useful for application
programs - TCP and UDP are transport protocols and must
provide process-to-process communication - Accomplished by using ports
- Port numbers are used for addressing messages to
processes within a particular computer and are
only valid for that computer - Once an IP packet has been delivered to its
destination host, the TCP- or UDP-layer software
dispatches it to a process via a specific port at
that host
28UDP Features
- UDP datagram is encapsulated inside an IP packet
- Short header with source and destination port
numbers, length field and a checksum - UDP does NOT guarantee delivery
- Adds no additional reliability mechanisms except
for checksum (which is optional) - Use is restricted to applications and services
that do not require reliable delivery of single
or multiple messages -
29TCP Features
- TCP provides a much more sophisticated transport
service - Provides reliable delivery of a long sequences of
bytes - Guarantees the delivery to the receiving process
of all the data presented to the TCP software by
the sending process in the same order - Provides retransmission if necessary
- Done when the it does not receive an
acknowledgement from the receiving process within
a specified timeout
30Middleware
- Looking at IPC from the Programmers point of
view - Remote Method Invocation (RMI)
- Remote Procedure Call (RPC)
31Interprocess Communication(IPC)
- Distributed Systems
- rely on exchanging data and achieving
synchronization amongst autonomous distributed
processes - Inter process communication (IPC)
- shared variables
- message passing
- message passing in concurrent programming
languages - language extensions
- API calls
- Principles of IPC
- (Concurrent programs collections of two or more
sequential programs executing concurrently - Concurrent processes collection of two or more
sequential programs in operation, executing
concurrently
32IPC Characteristics
- Message passing between pairs of processes can be
supported by two message communication
operations - send
- receive
- In order for one process to communicate with
another, one process sends a message (sequence of
bytes) to a destination and another process at
the destination receives the message
33Types of Communication
- Synchronous
- Sending and receiving process synchronize at
every message - Both send and receive are blocking operations
- Whenever a send is issued, the sending process
(or thread) is blocked until the corresponding
receive is issued - Whenever a receive is issued, the process (or
thread) blocks until a message arrives
34Types of Communication
- Asynchronous
- Send is non-blocking sending process is allowed
to proceed as soon as the message has been copied
to a local buffer - Receive operation can have blocking and
non-blocking variants - Non-blocking receiving process proceeds with
its program after issuing a receive operation
which provides a buffer to be filled in the
background - Must separately receive notification that is
buffer has been filled by polling or interrupt - Todays systems do not generally provide the
non-blocking form of receive because it adds
complexity to the application
35Sockets
- Both UDP and TCP use socket abstraction
- Provides an endpoint for communication between
processes - Originated from BSD UNIX but in all Unix flavors
(i.e., Linux) - IPC consists of transmitting a message between a
socket in one process and a socket in another
process
36Sockets and Ports
37Sockets and Ports
- For a process to receive messages, its socket
must be bound to a local port and one of the
Internet addresses of the computer on which it
runs - Messages sent to a particular Internet address
and port number can be received only by a process
whose socket is associated with that Internet
address and port number - Processes may use the same socket for sending and
receiving messages
38Moving from Interprocess to Distributed
Communication
- A distributed system breaks up a previously
monolithic application into different components
and then proceeds to place them on different
systems (i.e. tiers). - We are decoupling the consumer and the supplier
we are spreading the activities of an application
onto team players (systems)
39Moving from Interprocess to Distributed
Communication
- Analogy
- Let us imagine for a moment a small business run
by a single entrepreneur. This one person,
Suzette Sellers, does everything, much like a
monolithic application. She sells to customers,
orders new product, manages the books, pays the
bills, and does anything else. Internally, she
has compartmentalized her job function (much like
we program in a modular fashion) selling,
ordering, and administration. There is no
overhead associated with external communication
she does everything. - When her store becomes successful, she finds that
she simply cannot do it all and requires
assistance. Suzette hires Henry Helpers, a
capable and likeable chap. This is now similar
to our two-tier architecture. Because Suzette
and Henry work in the same physical location,
this is a logical two-tier system. Communication
is quick and easy. - Think about two programs on a computer they can
communicate via files, shared memory, pipes, or
other constructs. - If you are familiar with processing on a UNIX- or
Linix-based system, multiple commands are often
strung together with pipes.
40Moving from Interprocess to Distributed
Communication
- Suzettes store does so well that she moves her
office into another building to increase the
amount of retail floor space in her original
store. Now Suzette and Henry are in different
physical locations but still need to complete the
same tasks of selling, ordering, and
administration. We have moved into a physical
two tier distributed system and things just
become more complicated. Suzette and Henry still
need to communicate but the previous methods will
no longer work. - The obvious solution is the telephone, but this
changes the dynamic of the entire conversation - In our computer analogy, we now have a client and
a server tier where the previous solutions of
files, shared memory, or pipes are no longer
solutions as they only work within a single
system.
41Moving from Interprocess to Distributed
Communication
- Suzette and Henry must now specifically locate
each other (i.e. phone numbers) before
communicating. - Conversations will be slower (network latency).
- Data will need to be shared in different ways
(difficult to draw a picture on the phonethe
crayon keeps breaking on the handset). - And finally, the phone lines can go down or have
interference (network errors or corruption).
42Moving from Interprocess to Distributed
Communication
- Yes, we have gained some benefits by spreading
out Suzette and Henry (more retail floor space)
but we have introduced complexity and latency
into the business. - Similarly, when a distributed application is
placed on different systems (whether physically
or logically separated), we also introduce
complexity and latency into the application. - However, the ability to take advantage of
multiple computers is such a powerful incentive
that we have devised many ways to accommodate our
new problems - The stage is now set to discover how to implement
this distributed communication.
43Middleware Layer
- By choosing Java, we are explicitly ignoring the
platform because Java (in theory) runs exactly
the same on any platform that has a
Java-compatible runtime environment. - We are not yet concerned with what capabilities
an application will exhibit other than we will
create a server component that holds the
desired properties and a client component that
requests these capabilities. - Assume that our distributed Java-based
application will communicate via the TCP/IP
protocol
44UDP Communication
- Basis of TCP/IP protocol stack is the Internet
Protocol (IP) data packet - IP is a connectionless and stateless protocol
(fire and forget) - Once a IP packet is sent, the sender simply does
not care about it anymore - IP packet can become lost, destroyed, misplaced,
or corrupted on its way to its destination - If multiple IP packets are sent they can arrive
out of order - IP is quick to use but not reliable
- Think of IP as simple postal envelopes they can
be easily damaged, lost, and delivered out of
order. - However, IP envelopes are cheap and convenient.
(The analogy to a postal service is very
appropriate as the cost is low per message and
the service is usually reliable but there is no
capability to trace a wayward envelope.)
45UDP Communication
- The User Datagram Protocol (UDP) is implemented
on top of IP layer. - UDP is still a fairly lightweight protocol which
means that most of its effort is spent on
delivering data. - UDP adds two important features larger
payloads and data integrity. - If a message is larger than the size of a single
IP envelope, UDP will split the message into
multiple IP envelopes, taking care to remember
how it split up the original message. - UDP guarantees that the data in a single UDP
packet in the will arrive exactly as it was sent.
- What happens if one of the IP packets that made
up the UDP packet is lost? Then UDP discards the
rest of the IP packets and thus the entire UDP
packet rather than deliver a damaged UDP packet.
- This is analogous to sending a four page letter
in separate envelopes if envelope 3 does not
arrive, then UDP will throw array the remaining
envelopes that did arrive as it has no way to
reconstruct the original four page letter.
46UDP Communication
- UDP is also a stateless and connectionless
protocol - Stateless means that once a message is sent, the
sender does not care about it anymore. - If the message arrives, then that is fine. If it
does not arrive, we do not feel any grief - Connectionless means that there is no continued
conversation. - The message is complete in and of itself.
- Think about sending postcards. If we send one
postcard from Europe and another from South
America, neither of the postcards depend upon
each other. They are separate communications
47UDP Design Considerations
- For client-server applications that transfer
relatively small amounts of data, UDP is
acceptable - For the simplest application, a client will send
a single message to the server and expect a
response - If the client does not receive a response within
a pre-determined amount of time, the client may
send the request again. - This is similar to asking a person to repeat an
answer. Of course, after asking for the answer
so many times, it is likely that we (the client)
will just give up. - If a DNS server does not respond after a couple
of seconds, a client will simply accept that no
answer is forthcoming and either ask another DNS
server or return an error.
48UDP Example
- UDP communications can be implemented in Java
quite easily - However, it should be pointed out that UDP is
simply a service to ferry data from point A to
point B. - UDP does not understand data types or other Java
constructs, such as objects. - To accommodate this understanding, we will use
the capability of the String class to convert
itself into an array of bytes and back. - We are implicitly relying on the String class to
correctly convert an array of bytes using the
correct code set. - Both the server and client will perform many of
the same operations but the server has the
additional task of existing in a state where it
can receive requests at any time and must respond
to them. A client, on the other hand, will only
be executed on demand and exit as soon as it
receives a response.
49UDP Server
- The UDP server may look complicated but there is
actually very little to it. - The server first creates a socket, which is a
logical construct that we may attach to an actual
port. - We have hard-coded the port upon which our server
will listen, 7777. - You may choose any port between 1024 and 65535
(assuming that it is not already in use). - The server attaches to the port and then performs
an endless loop of listening for any incoming
message and sending the same message (known as a
datagram) back to its sender. - The effect is similar to a mirror
- See UDPServerSimple.java
50UDP Client
- The UDP client seems to be much longer in length
but that is because we have added in the ability
to specify the message to send, the server name,
and the port on which the UDP server is listening
on the command line, rather than hard-coding it.
- This approach should allow you to run the program
as-is, even though you will run it on your system
(which has a different network name and IP
address than everybody elses system). - The client, similar to the server, first creates
a socket that can be bound to a network port. - However, we will not bind it to a particular port
because we do not carejust as when you send a
letter, the mailbox you use is irrelevant to the
receiver.
51UDP Client
- The client program then resolves the name of the
server (first argument) to an IP address, which
is what the UDP protocol requires. - The second argument is the port that the UDP
server is listening on, and the third argument is
the actual message (remember to enclose it in
double quotes if it contains a space). - A datagram message is then created and sent to
the server. - Immediately after sending the message, the client
then acts like the server, waiting for a reply. - Although the client did not request a specific
port, the port that was automatically assigned is
included in the outgoing message so that the
server can successfully respond back to us. - See UDPClientSimple.java
52UDP Example In Action
- We first start the UDP server which opens the
port and waits for the first incoming message. - It will wait until the program is terminated
- Although not shown, the UDP server is running on
a system with the name Alpha (as in the first
Greek letter).
53UDP Example In Action
- The server gets up and running quickly and then
immediately starts waiting for eternity - Then run the UDP client which sends a message and
then itself waits for a reply.
54UDP Example In Action
- Notice that the client runs and then exits.
- This is typical of most client-server
communications where the client makes a request,
receives a reply from the server and is done.
55UDP Example In Action
- Meanwhile, the server has recorded the incoming
message, responded to it, and begun waiting for
another incoming request.
56TCP Communication
- TCP network communication is similar to UDP but
it fixes the flaws inherent in UDP by providing
message delivery guarantee and concurrency. - TCP goes a step beyond UDP and is a stateful and
connection-oriented protocol. - Stateful means that the TCP remembers what it has
sent and ensures that it arrives in the same
order - Connection-oriented means that each packet sent
is actually part of a larger conversation, or
stream.
57TCP Communication
- A TCP-based server differs from a UDP-based
server in that a single thread does not perform
all of the communication. - The usual solution to handle TCP communications
is to create a new thread that is dedicated to
incoming requests from a particular client. - A server can distinguish multiple requests from
the multiple clients on the same client system
because each client will be forced to use a
different port
58TCP Example
- The programs for the TCP client and server are
similar in nature although the details vary a
bit. - Because TCP is stateful, we actually open up two
streams one inbound and one outbound - These act like conveyor belts for data to flow
between the client and the server. - From a programming standpoint, we no longer have
to use datagrams but can simply read and write a
simple data type or a string object.
59TCP Server
- For the server, the largest change is that
additional of threads in order to maintain each
connection as a separate conversation. - However, once inside of a thread, the commands
are simply reading and writing data. - See TCPServer.java
60TCP Client
- The TCP client is very similar to the UDP client
except that instead of sending datagrams, we hook
up to the streams-based plumbing. - However, the rest of the logic is pretty much the
same. - See TCPClient.java
61TCP Example in Action
- Set CLASSPATH first!
- Start with the server first
62TCP Example in Action
- Next we invoke the TCP client to send a simple
message. - We can see that the client was able to acquire a
port to communicate out and received a reply that
was different than what was originally sent,
proving that something happened.
63TCP Example in Action
- The server first received a connection from the
remote port of 4304 (the client). - It then created new clientConnection object (the
two lines with the word setup in the brackets)
and then went back to listening for more
connection requests. - Meanwhile, the new thread was run and it picked
up the message sent by the client and then sent
it back with the prefix Received.
64Remote Method Invocation (RMI)
- Provides for communication between distributed
objects by means of remote method invocation - RMI objects that can receive remote method
invocations are called remote objects and they
implement a remote interface - Is an extension of local method invocation that
allows an object living in one process to invoke
methods of an object living in another process
65Middleware Layer for RMI
66Interfaces in Distributed Systems
- An interface specifies the procedures and
variables that can be accessed from other modules - Modules are implemented so as to hide all the
information about them except that which is
available through its interface. - As long as the interface does NOT change,
implementations may change without affecting the
users of the module - In a distributed program, the modules can run in
separate processes. - Cannot access the variables in a module in
another process not direct variable access
67Interfaces in Distributed Systems
- Other differences
- Parameter-passing mechanisms (i.e., call by
value, call by reference) used in local procedure
calls do not work in a distributed system - Uses input and output parameters that are passed
between processes - Pointers in one process are not valid in another
process on a remote computer - No pointer passing allowed
68Remote and Local Method Invocations
69Java RMI
- Java RMI provides an adapter that effectively
hides the network from us, instead allowing us to
simply lookup functionality that we want
(regardless of where it actually exists) and use
it as if it was locally available. - The level of complexity definitely increases once
we decide to distribute the objects in a Java
system. - Assuming that we started with two Java programs,
with one calling the other, we now introduce the
following elements - an interface that explicitly states what
functionality is remotely available - a server that provides access to the remote
object - the RMI registry that links up requests from a
client to a remote object
70Overview of RMI Interfaces and Classes
71Java RMI Example Foundation
- We will start with two Java classes that are not
RMI-enabled and then adapt them to operate with
RMI so we can see exactly what changes are
needed. - Let us imagine that we have devised an automated
registration process class which, upon knowing
which class for which we want to register, will
tell us if we are registered or if the class is
full.
72AskTheRegistrar.java
public class AskTheRegistrar private String theClass public AskTheRegistrar ( String in_whichClass ) theClass in_whichClass public String getRegistrationStatus() if ( theClass.toUpperCase().indexOf( "CS483" ) gt 0 ) return "You are registered" else return "There are no positions available to be registered"
If the class includes the word CS483 (case
sensitive) then the class must have some spots
open. Otherwise, the class is full.
73Java Application to Invoke the Functionality
LocalStudent.java
class LocalStudent public static void main( String args ) System.out.println() System.out.println( "LocalStudent running..." ) System.out.println( "--------------------------" ) System.out.println() String studentClass if ( args.length lt 1 ) studentClass "CS483" else studentClass args0 AskTheRegistrar currentRegistrationStatus new AskTheRegistrar(studentClass) System.out.println( "The registration status for " studentClass " is") System.out.println(" gt currentRegistrationStatus.getRegistrationStatus()) System.out.println() System.out.println( "--------------------------" ) System.out.println( "LocalStudent finished." )
In order to work, both classes just need to be
in a directory within the current CLASSPATH
environment variable
74Result when run...
- By passing the argument CS483, the
AskTheRegistrar service concludes that the
student is registered
75Java RMI Example (with a server)
- We now seek to move the AskTheRegistrar service
to a remote server so that it can be accessed
from multiple locations within the university. - The first step is to decide what functionality
should be made available. - Currently, the AskTheRegistrar class has two
member functions the constructor and
getRegistrationStatus. - The constructor will not be available remotely
and so we need to create an alternative method to
set the location. - These two functions, setClass and
getRegistrationStatus, will be available to
remote invocation and we can now create an
interface detailing this decision. - Need to enhance the object AskTheRegistrar so
that it can be remotely used
76RMI Server Example Sequence Diagram
77AskTheRegistrarInterface.java
import java.rmi. public interface AskTheRegistrarInterface extends Remote public void setClass( String in_whichClass ) throws RemoteException public String getRegistrationStatus( ) throws RemoteException
Remember an interface is a contract that a class
can choose to implement so there is no actual
code in the interface itself
78New Version of AskTheRegistrar
- See AskTheRegistrarRemote.java
- Imported java.rmi and java.rmi.server packages to
enable remote invocation capability - Class inherits from the UnicaseRemoteObject
parent class - This object means that a single instance (as
opposed to one instance per request) of the
AskRemoteRegistrarRemote object will be enabled
to be called remotely - Provides methods outlined in the interface
- Added an additional constructor that takes no
arguments and sets the private theClass variable
79RMI Registry
- A client wishing to use a remote object will need
to know exactly where it is located - RMI registry
- Coordinated phone book that records every
objects name and address - Publishes objects info in a well-known location
- rmiregistry.exe
- In the same directory as other java executables
- Can be run by itself as a background process
- We will run in its own command window
80RMI Registry
- RMI Registry starts off with an empty directory
- Has no way of actually invoking any objects
- Its only job is to provide locations to any
program that asks (like directory assistance)
81RMI Server Example
- We now need a Java program similar to our UDP
server that accepts requests for a remote object - This server program must also communicate to the
RMI registry that it exists so clients can find it
82AskTheRegistrarServer.java
import java.rmi. import java.rmi.server. class AskTheRegistrarServer public static void main ( String args ) try Naming.rebind("//localhost/AskTheRegistrar", new AskTheRegistrarRemote()) System.out.println("AskTheRegistrar Server is ready.") System.out.println() catch (Exception e) System.out.println("AskTheRegistrar Server unexpectedly quit. "Exception message " e.getMessage()) //end try //end main //end class
83RMI Server Example
- This seems like a very small amount of code
compared to our previous UDP server. - The magic happens on a single line
. . . Naming.rebind( "//localhost/AskTheRegistrar", new AskTheRegistrarRemote() ) . . .
84RMI Server Example
- The rebind command is what actually informs the
RMI registry that a remote object is now
available for remote invocation. - The first argument is the remote objects name in
the directory as well as which RMI registry will
be informed. - In our example, we are contacting the registry on
the local server (i.e. localhost). - If the registry was on a port other than its
default 1098, this could be specified by placing
a colon and the new port number directly after
the server name. - The identifier after the server is the name that
the object will be listed as in the registry. - This directory name does not have to be the same
as the actual remote object.
85RMI Server Example
- The second argument creates the actual remote
object that will accept requests from clients. - Because we are unsure of what location a client
will specify, we invoke the no-argument version
of the constructor which will set the internal
location to an empty string (and thus require the
client to specify an actual location later). - Most important point to heed is that in our
non-RMI setup (previous example), each instance
of the client application (LocationStudent)
created its own instance of the AskTheRegistrar
service class. - In the RMI version, we have a single instance of
the AskTheRegistrar class that will be used by
any and all clients.
86RMI Server Example
- Before we can run the server, we need to generate
a stub class for the remote object that will be
used by the server. - We use the rmic utility to do this.
- Server does not exit RMI registry still has an
open reference to it continuously available to
any incoming requests - Now that we have a server, we run it from the
command line like so
87Client Example
- Create a client that accesses the AskTheRegistrar
remote object - Two critical lines
. . . AskTheRegistrarInterface theRegistrar (AskTheRegistrarInterface) Naming.lookup ( "//" remoteServer "/AskTheRegistrar" ) . . . System.out.println( " gt " theRegistrar.getRegistrationStatus()) . . .
88Client Example
- The first uses the same class, Naming, that the
server did to contact the RMI registry. - In this case, we are asking the registry for the
location of a remote object that should be known
as AskTheRegistrar. - Note that what is returned is a reference to the
interface we initially created. - This interface hides the fact that there is no
code locally but simply provides some stubs that
will make a call to the remote object to perform
the actual work. - The second line uses the resulting object
reference as if it were localwhich was our
original intent
. . . AskTheRegistrarInterface theRegistrar (AskTheRegistrarInterface) Naming.lookup ( "//" remoteServer "/AskTheRegistrar" ) . . . System.out.println( " gt " theRegistrar.getRegistrationStatus()) . . .
89Client Example
- We can now see the result of running the client
90Server Output
- This is the activity on the server
- Server displays the callers (client) IP address
91 Java RMI Example (with a daemon)
- The previous example requires us to run a
separate Java application in a server capacity to
register and make a remote object available. - If we wish to make multiple objects available as
remote objects, we will either need to run a
separate server for each or create super-server
that registers one of each object. - To solve this problem use the RMI daemon
(background process), or rmid. - This one process will replace all of the other
server processes and allow any remote object to
be dynamically invoked - No adjustments to the interface or the client
code are required.
92Java RMI with the Daemon Sequence Diagram
93Java RMI Example (with a daemon)
- The remote object that we created in
AskTheRegistrarRemote last time needs to be
modified to inherit from a different, but related
objectthe Activatable object (which implies that
the remote object may be activated on demand). - For clarity, we will rename the class
AskTheRegistrarRemote to AskTheRegistrarActivation
.
94import java.rmi. import java.rmi.server. import java.rmi.activation. public class AskTheRegistrarActivation extends Activatable implements AskTheRegistrarInterface private String theClass // This constructor (which was not required when // we used the server-based form of RMI) will // be automatically called by the RMI daemon. // public AskTheRegistrarActivation( ActivationID id, MarshalledObject data ) throws RemoteException // Register the object with the activation system // then export it on an anonymous port // super(id, 0) // Here is our additional code. theClass "(No class set)" . . .
AskTheRegistrarActivation.java
95Java RMI Example (with a daemon)
- Instead of inheriting from UnicastRemoteObject,
the remote object now inherits from Activatable. - Both of the constructors that previously existed
have been removed and replaced with one that has
two arguments Activation ID MarshalledObject
- Any initialization code we need is placed after
the parent constructor is called. Other than
those changes, the code for the remote object is
the same. - What has changed the most is that instead of a
server process, we only need to register the
object as available for remote invocation and
then create a stub for use with the new daemon
process.
96Java RMI Example (with a daemon)Server
Application
- See AskTheRegistrarRMIDSetup.java
- The server application has undergone some
dramatic change. - The first statement inside the main class
provides the first hint of the alterations. - We are now operating with enhanced security
restrictions that we will need to alter in order
for our remote object to accept any connections
(a remote object that communicates with nobody is
not very useful).
97Java RMI Example (with a daemon)Server
Application
- To accomplish these alterations, we need a
security manager to be available like so
. . . System.setSecurityManager( new RMISecurityManager()) . . .
98Java RMI Example (with a daemon)Server
Application
- Next, we need to associate a security policy file
with the remote object when it is activated. - The policy file simply states that the remote
object is allowed to accept connections via the
network from any address as long as the
originating port is unprivileged (i.e. above
1023). - It should be noted that although the policy file
kind of looks like Java code, it is a
configuration file and not compiled it remains a
text file called AskTheRegistrarActivation.policy
grant // This allows the remote AskTheRegistrar object to accept // incoming connections from anywhere, as long as it is on // an unprivileged port (which is normally the case). // permission java.net.SocketPermission "1024-", "accept"
99Java RMI Example (with a daemon)
- The RMI registry is still operating as it was
previously therefore it must be run first of all
the server-based processes. - The RMI daemon must be run next.
- However, it will default to being very
restrictive with any of the remote objects that
will be registered with it as available to be
activated. - So, we must define a security policy for the RMI
daemon itself that allows future remote objects
to be allowed to register their own security
policy. - This could potentially open the door for
arbitrary permissions which is why this step is
explicitly required.
100Java RMI Example (with a daemon)
- Our security policy will look like the following
RMID.policy - This policy has only one purpose future remote
objects that will be registered may use the
security policy located in a file
Z\CS483\AskTheRegistrarActivation.policy. Any
other request for elevated permissions will be
expressly denied.
grant // This allows the remote AskTheRegistrar object to // request the security policy in the file // Z\CS483\AskTheRegistrar.policy. // If this is not allowed, then the remote AskTheRegistrar // object will either not be allowed to registered, or // will be registered with no ability to make network // connections. // permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policyZ/CS483/AskTheRegistrarActivation.policy"
101Run the daemon
- By default, the RMI daemon uses a security policy
of none (which is like selling a padlock with
no key) so we must change this when running the
daemon process. - Start the daemon
Cgt JAVAHOME\rmid J-Djava.security.policyRMID.policy
102Java RMI Example (with a daemon)
- Next, we must register the AskTheRegistrar remote
object with the daemon and registry. - The registration program itself needs permission
to contact both the daemon and the registry. - Here is its policy file
grant // This allows the AskTheRegistrar setup to connect to // the RMI registry. // permission java.net.SocketPermission "Alpha1098", "connect" // This allows the AskTheRegistrar setup to connect to // the RMI daemon (background process). // permission java.net.SocketPermission "Alpha1099", "connect"
103Java RMI Example (with a daemon)
- Assuming that the remote AskTheRegistrar object
will reside on the server known as Alpha, the
policy file allows the setup program to contact
the registry on the default port 1098 and the
daemon on the default port of 1099 - If the registration succeeds like we sincerely
hope it will, we should get two status messages
Cgt java -Djava.security.policyAskTheRegistrarRMIDSetup.policy AskTheRegistrarRMIDSetup
104Java RMI Example (with a daemon)
- It is worthwhile to note here that the remote
object, AskTheRegistrarActivation, has not yet
been instantiated and will remain so until the
first request. - This is one of the main benefits of the daemon
implementation in that it conserves resources
until they are required.
105Java RMI Example (with a daemon)
- We need to make two more adjustments.
- First, we need to provide the client with a
stub copy of the remote object (in addition to
the compiled interface definition). - After compiling the remote object (which is
AskTheRegistrarActivation in our example), we
employ the remote invocation compiler to whittle
it down to just a stub.
Cgt JAVAHOME\rmic AskTheRegistrarActivation
106Java RMI Example (with a daemon)
- This will produce a file named AskTheRegistrarActi
vation_stub.class that needs to be distributed
with the client application (in addition to the
AskTheRegistrarInterface.class and
LocalStudentClient.class files). - Secondly, while the client is unchanged, it now
requires a security policy file in order to
access the RMI daemon and registry
grant // This allows the local client permission to use the network // and make outbound connections to the "Alpha" server on any // unprivileged port. // permission java.net.SocketPermission "Alpha1024-", "connect,resolve"
107Java RMI Example (with a daemon)
- The policy file for the client says that
connections may be made to any non-privileged
port on the server that contains the remote
object. - When executing the client application, we now
need to include a reference to the security
policy file.
Cgt java -Djava.security.policyLocalStudentClient.policy LocalStudentClient Alpha "CS483"
108Executed Client Applicationwith Reference to
Policy File
109LocalStudent Client
- Our invocation of a remote object is now
functional again! - That was certainly a lot of work just to learn
that we are registered for CS483. - If we look back at the RMI daemon, we note that
the status messages are displayed, with some
extra logging information about execution groups
(which we did not cover).
110RMI Daemon
- Again, the benefit to this setup is that we can
run with just the daemon and dynamically register
objects with the daemon and the object will be
immediately available for use by clients.
111Java RMI Resources
- http//java.sun.com/docs/books/tutorial/rmi/index.
html - http//java.sun.com/j2se/1.5.0/docs/guide/rmi/inde
x.html - http//java.sun.com/j2se/1.5.0/docs/guide/rmi/spec
/rmiTOC.html - http//java.sun.com/j2se/1.5.0/docs/tooldocs/windo
ws/rmic.html