Upload
others
View
10
Download
0
Embed Size (px)
Citation preview
Languages in Depth Series: Java Programming
Prof. Dr. Bertrand Meyer
Chair of Software Engineering
Java Middleware Patrick Eugster, Till Bay, Tomas Hruz
2 Languages in Depth series: Java Programming
Java Middleware
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate RPC in general
RMI GWT middleware
Publish/Subscribe JMS
Application servers
3 Languages in Depth series: Java Programming
RPC in General
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate
RPC in general RMI GWT middleware
Publish/Subscribe JMS
Application servers
4 Languages in Depth series: Java Programming
Remote Procedure Call (RPC) in General
Object has Interface (abstract type) Implementation (concrete type) Local reference, e.g., value of a monotonically increased
counter, memory address Remote » object has
Interface for remote invocations Described in the implementation language: 1st class
RPC Otherwise: described in a separate language Usually local interface limited to access inside the process Implementation Global reference, e.g., (host id, process id, obj id)
Invocation on the server side is synchronous with client call
6 Languages in Depth series: Java Programming
Stubs and Skeletons
Client side: stub/proxy Offers same interface
as server object: mimics the server
Usually bound to a single server
Marshals the request into a stream of bytes Method id (e.g.,
name) Arguments
Additional features: Caching of values Load balancing Statistics
Server side: skeleton Represents the server
object Bound to a single
server Unmarshals the request
and calls the corresponding method on the server object
Additional features: Persistence
7 Languages in Depth series: Java Programming
Interaction in Detail
Invocations Transformed to messages, and sent to the « other side
»(marshaling) The « other side »: skeleton
Server-side counterpart to the stub Extracts request arguments from message (unmarshaling)
and invokes the server object Marshals return value and sends it to the invoker side,
where stub unmarshals it and returns the result to invoker
8 Languages in Depth series: Java Programming
Interaction in Detail
Skeleton type Delegation: skeleton is separate object (of arbitrary type)
Associated with the effective server object (binding is usually made by application)
Inheritance: Developer subclasses a skeleton class generated for
the server object interface, e.g, public class SkeletonRemote implements
RemoteInterface{} public class RemoteServis extends SkeletonRemote
{…}
9 Languages in Depth series: Java Programming
Interaction in Detail
Marshaling Unbound objects: serialized and passed by value Primitive types: ditto Bound objects: passed by reference
Mainly bound objects remotely « visible » Stub creation
Received as argument/result of remote method invocation, or
From lookup service
10 Languages in Depth series: Java Programming
Further Concepts
Repositories Reference Repository
Find new remote objects (locate objects, i.e., bootstrapping) Interface Repository
Discover new remote object types (browse remote types) Object Repository
Initialize new remote objects (automatic server activation) Advanced concepts
Interception Threading Distributed garbage collection Calls from the server to client
Synchronous to original client->server call Asynchronous
11 Languages in Depth series: Java Programming
Java RMI
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate RPC in general
Java RMI GWT middleware
Publish/Subscribe JMS
Application servers
12 Languages in Depth series: Java Programming
Java RMI (RPC)
Java RMI: At a Glance Allows distributed Java objects to interact
Through (remote) method invocations, since Java 1.1 Invocations are synchronous (even if no reply)
1st class RPC package Fully integrated with Java language Remote interfaces are described through Java interfaces
Separate compilation Generate stubs and skeletons according to interfaces Compile application
14 Languages in Depth series: Java Programming
Stub/Skeleton Layer
Stub Has same interface as remote object Initializes call to remote object Marshals arguments to stream Passes stream to remote reference layer Unmarshals the return value Informs the remote reference layer that call is complete
Skeleton Unmarshals arguments from the stream Makes (up-)call to the remote object implementation Marshals the return value or an exception onto the stream
15 Languages in Depth series: Java Programming
Remote Reference Layer
Carries out remote reference protocol Independent of stubs/skeletons
Remote object implementation chooses invocation protocol Unicast point-to-point, extensions:
Replicated object group, Support for specific replication strategy
Support for persistent reference to remote object (automatic activation of remote object)
Reconnection strategies
16 Languages in Depth series: Java Programming
Transport Layer
Responsibilities Connection set-up to remote address space Managing connections Monitoring connection « liveness » Listening for incoming calls Maintaining a table of remote objects Connection set-up for incoming call Locating the dispatcher for the target of the remote call
Abstractions Endpoint: denotes an address space or JVM Channel: conduit between two address spaces, manages
connections Connection: data transfer (input/output) Transport: Manages channels
17 Languages in Depth series: Java Programming
Design a Java RMI Application
1. Write the interfaces of the remote (i.e., remotely accessible) objects: coarse grain
2. Write the implementations of the remote objects 3. Write other classes involved: fine grain 4. Compile the application with javac 5. Generate stubs and skeletons with rmic
18 Languages in Depth series: Java Programming
Declaring a Remote Interface
Objects are remotely accessible through their remote interface(s) only
Methods to be exported are declared in an interface that extends the java.rmi.Remote interface
Remote interfaces Must be public All methods must declare java.rmi.RemoteException in
throws list: represent exceptions due to distribution
19 Languages in Depth series: Java Programming
Hello World Remote Interface
import java.rmi.*; public interface Hello extends Remote {
public void print() throws RemoteException; }
21 Languages in Depth series: Java Programming
Implementing Remote Interface
Implement the Remote interface Abstract class java.rmi.server.RemoteObject implements
Remote Remote behavior for hashCode(), equals() and toString()
Abstract class java.rmi.server.RemoteServer extends RemoteObject Functions to export remote objects
Concrete class java.rmi.server.UnicastRemoteObject extends RemoteServer
Non-replicated remote object Support for point-to-point active object references
(invocations, parameters, and results) using TCP Inheritance: subclass UnicastRemoteObject
Note Own exceptions must not subtype RemoteException
22 Languages in Depth series: Java Programming
A Hello World Implementation
import java.rmi.*; import java.rmi.server.*; public class HelloImpl extends UnicastRemoteObject implements Hello {
public HelloImpl() throws RemoteException{ super(); } public void print() throws RemoteException { System.out.println("Hello World"); }
}
23 Languages in Depth series: Java Programming
Constructing a Remote Object
The Constructor Calls the no-argument constructor of the
UnicastRemoteObject class (implicitly or explicitly) Which exports a UnicastRemoteObject, making that
available to accept incoming requests by listening to calls from clients on an anonymous port
Throws RemoteException, since the constructor of UnicastRemoteObject might do so, if the object cannot be exported Communication resources are unavailable Stub class cannot be found, …
Alternative: Delegation Explicitly export the object
UnicastRemoteObject.exportObject()
24 Languages in Depth series: Java Programming
Starting a Server
rmiregistry &
public class HelloServer { public static void main(String[] args) { … Hello hello = new HelloImpl(); // Register object (e.g., naming service) Naming.rebind ("Hello", hello); // What’s up doc? … }
}
25 Languages in Depth series: Java Programming
Client
public class HelloClient { public static void main(String[] args) { … // Lookup object (e.g., naming service) Hello hello = (Hello) Naming.lookup ("//ethz.ch/Hello"); // Invoke the remote object hello.print(); // That’s all folks… }
}
26 Languages in Depth series: Java Programming
Parameters and Return Values
Can be Local objects
Primitive types (e.g., int, boolean, …) Serializable, i.e. implementing java.io.Serializable:fields
are copied (except static or transient) and serialized Remote Objects
Passed by reference Serialization
Can be overridden A copy of the object is created at the client side
27 Languages in Depth series: Java Programming
Exceptions
All RMI exceptions subclass RemoteException Examples
StubNotFoundException or SkeletonNotFoundException: forgot rmic?
ServerError: error while server executes remote method ServerException: remote exception in server’s remote
method call
28 Languages in Depth series: Java Programming
Distributed Garbage Collection
(Local) object garbage collected if No (local) reference to it exists
Remote object garbage collected if No local reference to it exists No remote reference to it exists
JVM keeps track of the # of refs to an object First reference triggers message send to JVM hosting the
object Discarding last reference triggers message send as well When no remote JVM references object anymore,
reference becomes « weak »
29 Languages in Depth series: Java Programming
More Information
Java site: http://java.sun.com Java RMI site: http://java.sun.com/products/jdk/rmi/ Tutorial: http://java.sun.com/j2se/1.5/docs/guide/rmi/ Specification:
http://java.sun.com/j2se/1.5/docs/guide/rmi/spec/rmiTOC.html
White Paper: http://java.sun.com/marketing/collateral/javarmi.html
30 Languages in Depth series: Java Programming
GWT Middleware
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate RPC in general
RMI
GWT middleware Publish/Subscribe
JMS Application servers
31 Languages in Depth series: Java Programming
GWT
Google Web Toolkit A Java based system to develop AJAX dynamic web
pages Consists of
A GUI Widget library in Java and in Javascript A Java compiler which is compiling to Javascript
Consequences The code is developed and tested in Java against Java
GWT library with all Java IDE tools The final product is compiled to a Javascript code
which can be used on compatible browsers The browser compatibility problem is solved in GWT
library
33 Languages in Depth series: Java Programming
More Information on GWT
http://code.google.com/webtoolkit/ http://code.google.com/webtoolkit/documentation
/com.google.gwt.doc.DeveloperGuide.RemoteProcedureCalls.html
34 Languages in Depth series: Java Programming
Publish/Subscribe
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate RPC in general
RMI GWT middleware
Publish/Subscribe JMS
Application servers
35 Languages in Depth series: Java Programming
Publish/Subscribe
Model Producers publish information Consumers subscribe to information Producers and Consumers communicate through logical
buses (or channels) Decoupling of participants
In time In space In flow
Enforces scalability Topic-based, content-based, type-based
Modern systems combine more of them
37 Languages in Depth series: Java Programming
Topic-Based Publish/Subscribe
A.k.a. subject-based publish/subscribe News-like approach
Messages are classified according to topic names, e.g., ETHZ
Topics can be seen as (dynamic) groups URL-like topic names for convenience
Topics arranged in a hierarchy, e.g., /ETHZ/CSE Automatic subscriptions to subtopics Wildcards Aliases
39 Languages in Depth series: Java Programming
Content-Based Publish/Subscribe
A.k.a. property-based publish/subscribe Events classified according to their properties
Consumers subscribe by specifying properties of events of interest
Application criteria are seen as subscription pattern Translated to filter, or predicate, matched against events
Classic approach Map event attributes to properties Subscription language and parser, E.g., "name == ‘Bob’"
41 Languages in Depth series: Java Programming
Type-Based Publish/Subscribe
Subscription criterion The type (its interface) of application-defined events Content-based queries based on methods
Combines static and dynamic schemes Static classification should be made as far as possible for
efficiency Filters for fine-grained content-based subscription increase
expressiveness if required Languages which support structural reflection
No need for specific events (e.g., Java introspection), In other languages, events can subtype an introspective
event type
43 Languages in Depth series: Java Programming
Java Middleware
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate RPC in general
RMI GWT middleware
Publish/Subscribe
JMS Application servers
44 Languages in Depth series: Java Programming
Java Message Service
The Java Message Service is only an API Standardized API for messaging in Java Implemented by most industrial solutions
TIBCO iBus Gryphon …
Two messaging styles: Publish/subscribe (topic-based & content-based) Point-to-point (message queuing)
45 Languages in Depth series: Java Programming
Benefit of JMS
Sun standard Ensures a certain degree of portability Integration with other Java concepts/services
Enterprise Java Beans (EJB): EJB Message Beans, the container invokes the beans if messages are available
Java Database Connectivity (JDBC) for database integration
Java Transaction Service (JTS) for messages as part of distributed transactions
Java Naming and Directory (JNDI) for object lookup API can be downloaded: package javax.jms
46 Languages in Depth series: Java Programming
JMS Event Model
General-purpose messages which require explicit marshalling
Message body can contain Stream Properties String Object Bytes
Additional attributes Message header: explicit messaging Message properties: for content-based filtering
47 Languages in Depth series: Java Programming
Message Attributes Message properties
Name-to-value properties provided by message producer
Property types (native Java types) Boolean Byte Short Int Long Float Double String
Note: attributes mapped to properties
Message header Assigned by service
upon send Destination Delivery mode
(PERSISTENT,
NON_PERSISTENT) Message ID Timestamp Priority Expiration
Provided by client Correlation ID, e.g.,
refer to other message
Type Reply destination
48 Languages in Depth series: Java Programming
Properties for Content-Based
Properties of messages are assigned explicitly Not java.util.Properties
Subscriber describes required properties Message selector = filter Subscription language: message selector is String Syntax specified by JMS Must be mapped to service provider’s subscription
language syntax E.g.,
"JMSType = ‘car’ AND color = ‘blue’ AND weight > 2500"
49 Languages in Depth series: Java Programming
Common Facilities
Destination Named object (topic, queue) obtained through JNDI: empty
interface ConnectionFactory
Obtained through JNDI, used to create Connection to a topic, queue: empty
Connection May require authentication Register ExceptionListener for problem detection Factory for Session
Session Required by client (producer/consumer) to interact with topic,
queue Creates MessageProducer (push), MessageConsumer (push
/pull) Single threaded. Transaction support
50 Languages in Depth series: Java Programming
Connections
public interface Connection { public String getClientID() throws JMSException; public void setClientID(String ID) throws …; public void setExceptionListener(ExceptionListener l) throws …; public ExceptionListener getExceptionListener() throws …; public void close() throws …; public start() throws …; public stop() throws …;
… /* (Sessions created through implementation classes) */ }
51 Languages in Depth series: Java Programming
Sessions
public interface Session { public void setMessageListener(MessageListener l) throws …; public MessageListener getMessageListener() throws …; public TextMessage createTextMessage() throws …; public StreamMessage createStreamMessage() throws …;
public MessageProducer createProducer(Destination destination) throws…; … public void close() throws …; public void recover() throws …; public void commit() throws …; public void rollback() throws …; …
}
52 Languages in Depth series: Java Programming
Message Producers
public interface MessageProducer { public void setDeliveryMode(int deliveryMode) throws …; public int getDeliveryMode() throws …; public void setPriority(int defaultPriority) throws …; public int getPriority() throws …; public void setTimeToLive(long ttl) throws …; public long getTimeToLive() throws …; … sent(…) throws …;
}
53 Languages in Depth series: Java Programming
Message Consumers
public interface MessageConsumer { /* Provide content-based filter */ public String getMessageSelector() throws …; /* Push model */ public void setMessageListener(MessageListener l) throws …; public MessageListener getMessageListener() throws …; /* Poll */ public Message receive() throws …; /* Blocking pull */ public Message receive(long timeout) throws …; …
}
54 Languages in Depth series: Java Programming
Point-To-Point (PTP)
Objects Queue represents a vendor-specific implementation TemporaryQueue is a temporary incarnation, bound to a
QueueConnection Created through a QueueConnectionFactory QueueSession, QueueReceiver (message consumer:
push/pull), QueueSender (message producer) QueueBrowser to query queue without removing
messages … Note
Message selector can be specified by consumer
55 Languages in Depth series: Java Programming
Queue
public interface Queue { public String getQueueName() throws …; public String toString() throws …;
} public interface QueueBrowser {
public Enumeration getEnumeration() throws …; public String getMessageSelector() throws …; public String getQueue() throws …; …
}
56 Languages in Depth series: Java Programming
Publish/Subscribe
Objects Topic gives access to pub/sub system: no naming
conventions TemporaryTopic, TopicConnectionFactory,
TopicConnection, TopicSession, as seen previously TopicSubscriber (message consumer) and TopicPublisher
(producer) Durable subscription
Client provides unique ID TopicRequestor
Use pub/sub to make request/replies Mixed topic/content-based
Client provides a message selector
57 Languages in Depth series: Java Programming
Topic
public interface Topic { public String getTopicName() throws …; public String toString() throws …;
} public class TopicRequestor {
public TopicRequestor(TopicSession session, Topic topic) throws … {…} public Message request(Message message) throws … {…} …
}
58 Languages in Depth series: Java Programming
JMS Exceptions
JMSException Root of exception hierarchy
Specific exceptions JMSSecurityException: authentication problem InvalidDestination: destination not understood by provider InvalidSelectorException: « syntax error » in filter MessageFormatException: e.g., unsupported payload
class …
59 Languages in Depth series: Java Programming
More Info on JMS
http://java.sun.com/products/jms/ http://www.tibco.com http://www.softwired-inc.com/products/mobile
/mobile.html
60 Languages in Depth series: Java Programming
Java Middleware
What is middleware Client-server communication and method invocation Provides a substrate on which distant modules can
transparently cooperate RPC in general
RMI GWT middleware
Publish/Subscribe JMS
Application servers
62 Languages in Depth series: Java Programming
Application Server
What the application server gives you: Design your application as a set of functional modules (in J2EE terminology –
Enterprise Java Beans EJBs) Concentrate on business logic programming The beans live in “Bean Containers”, containers provide various services for the
beans: Instance pooling and caching aka resource and lifecycle management Remote Accessibility Persistence on various levels of automation Security Messaging Concurrency control Clustering and load balancing
Your modules/services (beans) are efficiently managed by the application server administration tools You have means to manage a large number of beans (10^4) You have tools to deploy large systems You can manage your modules in run-time
Application server is a “small operating system” for your modules (beans) The price you pay:
You have to stick to the container rules You have to implement certain interfaces used by the container
64 Languages in Depth series: Java Programming
EJB Interface Groups
Home interfaces Remote interface Container interfaces
…
65 Languages in Depth series: Java Programming
Recent Development & References
Spring Framework Hibernate EJB 3.0 specification (JSR 220) More Info
http://java.sun.com/javaee/index.jsp http://www.bea.com/framework.jsp?CNT=index.htm&FP=
/content/products/weblogic&WT.ac=topnav_products_weblogic
http://www.jboss.org/ http://en.wikipedia.org/wiki/Ejb (Controversial)