Title: Distributed Objects
1Distributed Objects
2??
3??
4RMI
- Java????,???????!
- Stub???!
- ?????!
- Garbage Collection!
- ???
- java.rmi.Remote (RemoteException)
5(No Transcript)
6Some important parts of RMI
- Stubs
- Each remote object class has an associated stub
class, which implements the same remote
interfaces. An instance of the stub class is
needed on each client. Client-side remote
invocations are actually local invocations on
the stub class. - Serialization
- Arguments and results have to be
marshalledconverted to a representation that
can be sent over the Net. In general this is a
non-trivial transformation for Java objects.
Serialization is also used for distributing
stubs. - The Server-side Run-time System
- This is responsible for listening for invocating
requests on suitable IP ports, and dispatching
them to the proper, local resident, remote object.
7RMI Architecture overview
- RMI Layers
- Stub/skeleton layer
- objects used by client and server applications
- Remote reference layer
- creation/management of remote references
- distributed garbage collection
- Transport protocol layer
- binary data protocol
- By using a layered architecture each layer could
be enhanced or replaced without affecting the
rest of the system ? transport layer UDP/IP
layer or secure sockets (SSL).
8Remote Reference Layer
- RemoteRef
- Interprets and manages references to remote
objects. The stub objects use the invoke() method
in RemoteRef to forward the method call. The
RemoteRef object understands the invocation
semantics for remote services. - Leasing for distributed garbage collection
- Naming/Registry Service -- rmiregistry
9Remote Reference Layer
- Invocation Semantics
- v1.1 unicast / point-to-point.
- v1.2 support for activation of dormant remote
service objects - Remote Object Activation
- RMI will instantiate a dormant object and restore
its state from disk. - As now No multicast semantics.
10Using RMI
- 1. Define interfaces for remote classes
- 2. Create and compile implementation of the
remote classes - 3. Create stub and skeleton classes using the
rmic compiler - No longer necessary in Java 1.5 because Java 1.5
adds support for the dynamic generation of stub
classes at runtime. - rmic must still be used to pre-generate stub
classes for remote objects that need to support
clients running on Java versions 1.4.
11Using RMI
- 4. Create and compile the server application
(registration) - 5. Create and compile a client program to access
the remote objects - 6. Start the RMI Registry and the server
application - 7. Test the client
12Point 1 Remote Interface
- Remote
- All remote interfaces must extend the interface
java.rmi.Remote (tagging interface) - All methods must throw a java.rmi.RemoteException
(extension of java.io.IOException)
13Point 2 Implementation
- UnicastRemoteObject
- Application must implement the defined remote
interface - Application extends class UnicastRemoteObject or
calls explicitly UnicastRemoteObject.exportObject
- link to RMI system
- base class performs RMI linking and remote object
initialization - constructor may throw a RemoteException
- Activatable
- Base class to be used for activatable objects
- ????????????????????
14Dynamic stubs in Java 1.5
- Dynamic Proxies
- Implemented using java.lang.reflect.Proxy (where
the implementation is based on a
RemoteObjectInvocationHandler) - Dynamic proxy is only used if no pre-generated
stub class is available or if the system property
java.rmi.server.ignoreStubClasses true. - It is only possible if clients run on Java 5.
- Notice If a remote object has pre-1.5 clients,
then that remote object should use a stub class
pre-generated with rmic. There are two stub
class. - protocols v1.1 / v1.2 (default).
15Point 3 Server
- RMI service must be hosted in a server process
whose job is - to create an instance
- to register the object with the naming service.
- Naming/Registry service
- RMI can use different naming services
- (i) Simple service RMI Registry
- (ii) JNDI (Java Naming and Directory interface).
16Point 4 Start RMI Register
- rmiregistry ltportgt
- default port 1099
- error if port is already used by another process
(e.g. another rmiregistry) - daemon has to be started in directory which
contains used classes or the classes have to be
on the CLASSPATH - Code Base You must specify where are the class
files. - Security policy file You must give permission to
use port 1099.
17load classes dynamically
- Required classes can be loaded over the network
- e.g. provided by a web server via http
- other protocols are also possible (file//,
ftp//, .) - RMI class loading and security. Two conditions
must be met - 1. a special class loader is provided
RMIClassLoader - 2. a security manager has to support remote class
loading - System.setSecurityManager(new RMISecurityManager()
) - Start of RMI-Registry in this case
- rmiregistry must not contain the needed classes
in its path (otherwise what is the point of
dynamically load the classes?)
18load classes dynamically
- Start of server
- specify codebase for downloading class files
- java -Djava.rmi.server.codebasehttp//10.0.2.112
8080/calculator.jar nju.ics.yuping.dc.rmi.Calculat
orServer - Start of client
- permission to access server has to be provided
(due to security manager) - java -Djava.security.policyjava.policy
nju.ics.yuping.dc.rmi.CalculatorClient - Policy file
- grant
- // connect to or accept connections on
unprivileged ports - // (ports greater than 1024) on host
loki.cs.fh-aargau.ch - permission java.net.SocketPermission
- 10.0.2.1122001-", "connect,resolve"
-
19Point 5 - Codebase
-Djava.rmi.server.codebasefile///e\course\code\
rmi\server\ -Djava.rmi.server.codebasehttp//10.0
.2.1128080/calculator.jar
20Point 6 - Marshalling
- How are parameters transferred to remote objects?
- Primitive Parameters
- passed by value, in a machine-independent format
- Serializable Objects
- serializable objects are copied ? call by value
- Remote Object Parameters
- only the reference to the remote object is
passed, i.e. a new proxy is generated ? call by
reference - Non-Serializable/Remote Objects
- cannot be transferred
- checked at runtime (not by rmic!)
21Note on passing remote objects
- Remote objects are commonly defined as parameters
and return types. - Example of usage
- ? Callbacks
- ? Factory classes that create remote references
- Reminder Remote objects are passed by reference.
- When Remote exported objects are passed to a
client, RMI substitutes the reference with that
of the Remote proxy (stub).
22Callbacks
- In many cases, applications require more complex
bi-directional interactions. Servers may wish to
make calls to the client (this is known as a
callback). Why? - ? Error or problem reporting
- ? Periodic updating and progress reports
- ? UI notification (Observer pattern ! )
- In OO programs the role of clients and servers
are not always clear cut. - Client-server applications often operate in a
peer-to-peer manner. At different stages an
object may either act as a server or as a client.
23Callback How to
- How do you create a callback?
- ? Make your client into a server!
- 1. Make your client implement a Remote interface
- ? Define a client remote interface
- 2. Make it available as a server (export your
client interface as a Remote object) - ? extend UnicastRemoteObject
- ? or use UnicastRemoteObject.exportObject(Remote)
- 3. Pass a client Remote reference to the server.
The server can then use this reference to make
calls on the client.
24Callback Example
25??
26J2EE
- JDBC
- JNDI
- EJB
- RMI
- Java IDL/CORBA
- JSP
- Java Servlet
27Application Servers
- "The Multi- tier applications" have several
independent components - An application server provides the infrastructure
and services to run such applications - Application server products can be separated into
3 categories - J2EE-based solutions
- Non-J2EE solutions (PHP, ColdFusion, Perl, etc.)
- And the Microsoft solution (ASP/COM and now .NET
with ASP.NET, VB.NET, C, etc.)
28J2EE Application Servers
- Major J2EE products
- BEA WebLogic
- IBM WebSphere
- Borland AppServer
- Sun/Oracle GlassFish
- JBoss
29Web Server and Application Server
App Server 1
Internet Browser
Web Server(HTTP Server)
HTTP(S)
App Server 2
30J2EE Multi-tier Model
31J2EE Application Scenarios
- Multi-tier typical application
32J2EE Application Scenarios
33J2EE Application Scenarios
34J2EE Application Scenarios
35J2EE Architecture
36Now
- JEE 5
- JEE 6
- Homepage http//www.oracle.com/technetwork/java/j
avaee/tech/index-jsp-142185.html
37Main technologies
- JavaServer Pages (JSP)
- Servlet
- Enterprise JavaBeans (EJB)
- JSPs, servlets and EJBs are application
components
38JSP
- Used for web pages with dynamic content
- Processes HTTP requests (non-blocking
call-and-return) - Accepts HTML tags, special JSP tags, and
scriptlets of Java code - Separates static content from presentation logic
- Can be created by web designer using HTML tools
39Servlet
- Used for web pages with dynamic content
- Processes HTTP requests (non-blocking
call-and-return) - Written in Java uses print statements to render
HTML - Loaded into memory once and then called many
times - Provides APIs for session management
40EJB
- EJBs are distributed components used to implement
business logic (no UI) - Developer concentrates on business logic
- Availability, scalability, security,
interoperability and integrability handled by the
J2EE server - Client of EJBs can be JSPs, servlets, other EJBs
and external aplications - Clients see interfaces
41EJB
- EJB 1.1
- EJB 2.0
- EJB 2.1
- EJB 3.0
- EJB 3.1
???
42EJB????????
- EJB ????????????????
- ??EJB????
- ????????
- Concurrency,Distribution, Transactions,
- EIS integration, Resource pooling,
- Security, Persistence
- ??EJB????
- ??????????????
43EJB?????
- EJB??????????EJB???????,??EJB??????,??EJB????????
?????,???????????? - EJB??????????????????EJB?????,?EJB???????????????
- EJB??(2.x)Home??,Remote??,Local?LocalHome??
44EJB??
- Session Bean
- Stateless
- Stateful
- Entity Bean
- Message Driven Bean
????
????
45Session Bean
- Stateless session bean
- Contains no user-specific data
- Business process that provides a generic service
- Container can pool stateless beans
- Example shopping catalog
46Session Bean
- Stateful session bean
- Retains conversational state (data) on behalf of
an individual client - If state changed during this invocation, the same
state will be available upon the following
invocation - Example shopping cart
47Entity Bean
- Represents business data stored in a database
persistent object - Underlying data is normally one row of a table
- A primary key uniquely identifies each bean
instance - Allows shared access from multiple clients
- Can live past the duration of client' s session
- Example shopping order
48Message-Driven Bean
- Message consumer for a JMS queue or topic
- Benefits from EJB container services that are not
available to standard JMS consumers - Has no home or remote interface
- Example Order processing stock info
49EJB 2.x???
- APIs???????,????????????,???????
- EJBHome interface
- EJBObject interface
- EnterpriseBean interfaces
- JNDI interfaces
- Deployment descriptor
-
- ??????,??????
- ????,??,??????
- Boiler Code
- ????
50???EJB 2.x??
- // EJB 2.1 Stateless Session Bean Bean Class
- public class PayrollBean implements
javax.ejb.SessionBean - SessionContext ctx
- DataSource payrollDB
- public void setSessionContext(SessionContext
ctx) - this.ctx ctx
-
- public void ejbActivate()
- public void ejbPassivate()
- public void ejbRemove()
51???EJB 2.x??
- // EJB 2.1 Stateless Session Bean Bean Class
(continued) -
- public void ejbCreate()
- ...
- Context initialCtx new InitialContext()
- payrollDB (DataSource)initialCtx.lookup
- (javacom/env/jdbc/empDB)
- ...
-
- public void setTaxDeductions(int empId,int
deductions) - ...
- Connection conn payrollDB.getConnection()
- Statement stmt conn.createStatement()
- ...
-
52???EJB 2.x??
- // EJB 2.1 Stateless Session Bean Interfaces
- public interface PayrollHome
- extends javax.ejb.EJBLocalHome
- public Payroll create() throws CreateException
-
- public interface Payroll
- extends javax.ejb.EJBLocalObject
- public void setTaxDeductions(int empID, int
- deductions)
53???EJB 2.x??
- // EJB 2.1 Stateless Session Bean Deployment
Descriptor - ltsessiongt
- ltejb-namegtPayrollBeanlt/ejb-namegt
- ltlocal-homegtcom.example.PayrollHomelt/local-homegt
- ltlocalgtcom.example.Payrolllt/localgt
- ltejb-classgtcom.example.PayrollBeanlt/ejb-classgt
- ltsession-typegtStatelesslt/session-typegt
- lttransaction-typegtContainerlt/transaction-typegt
- ltresource-refgt
- ltres-ref-namegtjdbc/empDBlt/res-ref-namegt
- ltres-typegtjavax.sql.DataSourcelt/res-typegt
- ltres-authgtContainerlt/res-authgt
- lt/resource-refgt
- lt/sessiongt
54???EJB 2.x??
- // Deployment Descriptor(continued)
- ltassembly-descriptorgt
- ltmethod-permissiongt
- ltunchecked/gt
- ltmethodgt
- ltejb-namegtPayrollBeanlt/ejb-namegt
- ltmethod-namegtlt/method-namegt
- lt/methodgt
- lt/method-permissiongt
- ltcontainer-transactiongt
- ltmethodgt
- ltejb-namegtPayrollBeanlt/ejb-namegt
- ltmethod-namegtlt/method-namegt
- lt/methodgt
- lttrans-attributegtRequiredlt/trans-attributegt
- lt/container-transactiongt
- lt/assembly-descriptorgt
55?????EJB 3.0?
56EJB?
- POJO (Plain Old Java Object)
- ??Bean?????Bean??????Java?
- ???????EJB???
- ??
- ???????
- _at_Stateless, _at_Stateful, _at_MessageDriven
- EJB 3.0????Bean
- JPA(Java Persistence API)????
- ??_at_Entity??
57EJB 2.x??EJB?
- // EJB 2.1 Stateless Session Bean Bean Class
- public class PayrollBean implements
javax.ejb.SessionBean - SessionContext ctx
- public void setSessionContext(SessionContext
ctx) - this.ctx ctx
-
- public void ejbCreate() ...
- public void ejbActivate()
- public void ejbPassivate()
- public void ejbRemove()
- public void setTaxDeductions(int empId, int
deductions) - ...
-
58EJB 3.0??EJB?
- // EJB 3.0 Stateless Session Bean Bean Class
- _at_Stateless
- public class PayrollBean implements Payroll
- public void setTaxDeductions(int empId,int
deductions) - ...
-
59EJB??
- ??????????
- ????extend EJBObject, EJBHome
- ?????local?remote
- ??_at_Local, _at_Remote
- Remote??????RemoteException
60EJB 2.x??EJB??
- // EJB 2.1 Stateless Session Bean Interfaces
- public interface PayrollHome extends
javax.ejb.EJBLocalHome - public Payroll create() throws CreateException
-
- public interface Payroll extends
javax.ejb.EJBLocalObject - public void setTaxDeductions(int empId, int
- deductions)
61EJB 3.0??EJB??
- // Local Interface
- _at_Local
- public interface Payroll
- public void setTaxDeductions(int empId, int
- deductions)
-
- // Remote Interface
- _at_Remote
- public interface Payroll
- public void setTaxDeductions(int empId, int
- deductions)
62????Bean
- ??
- _at_MessageDriven
- ????Bean????javax.jmx.MessageListener
- onMessage(Message msg)??
63????Bean???
- // EJB 3.0 Message-driven bean Bean Class
- _at_MessageDriven
- public class PayrollMDB implements
javax.jms.MessageListener - public void onMessage(Message msg)
- ...
-
64????
- ???????JNDI Lookup?
- ????
- ??Instance variable
- ??setter??
- ??Lookup
- ??class
65??
- _at_Resource
- For connection factories, simple environment
entries, topics/queues, EJBContext,
UserTransaction, etc. - _at_PersistenceContext
- ?????EntityManager
- _at_PersistenceUnit
- EntityManagerFactory????????EntityManager
66Dependency Injection
- Bean instance is supplied with references to
resources in environment - Occurs when instance of bean class is created
- No assumptions as to order of injection
- Optional _at_PostConstruct method is called when
injection is complete
67???????
- // EJB 3.0 Stateless Session Bean Bean Class
- // Data access using injection and Java
Persistence API - _at_Stateless
- public class PayrollBean implements Payroll
- _at_PersistenceContext EntityManager payrollMgr
- public void setTaxDeductions(int empId,int
deductions) - payrollMgr.find(Employee.class,empId).
- setTaxDeductions(deductions)
-
68??Lookup???
- // EJB 3.0 Stateless Session Bean
- // Using dynamic lookup
- _at_PersistenceContext(namepayrollMgr)
- _at_Stateless
- public class PayrollBean implements Payroll
- _at_Resource SessionContext ctx
- public void setTaxDeductions(int empId,int
deductions) - EntityManager payrollMgr ctx.lookup(payrollMg
r) - payrollMgr.find(Employee.class,
- empId).setDeductions(deductions)
-
69Bean Lifecycle Event
- EJB 2.1????EnterpriseBean??,???Lifecycle?????
- EJB 3.0???????????
- ??
- _at_PostConstruct
- _at_PreDestroy
- _at_PostActivate
- _at_PrePassivate
- ?????????????
70???EJB??
- ?????????
- ????Home interface
- ????RemoteException
71EJB 2.x???
- // EJB 2.1 Client View
- ...
- Context initialContext new InitialContext()
- PayrollHome payrollHome (PayrollHome)
- initialContext.lookup(javacomp/env/ejb/payroll)
- Payroll payroll payrollHome.create()
- ...
- // Use the bean
- payroll.setTaxDeductions(1234, 3)
72EJB 3.0???
- // EJB 3.0 Client View
- _at_EJB Payroll payroll
- // Use the bean
- payroll.setTaxDeductions(1234, 3)
73EJB 3.0 Summary
- Major simplification of EJB technology for
developers - Beans are plain Java classes with plain Java
interfaces - APIs refocused on ease of use for developer
- Easy access to container services and environment
- Deployment descriptors available, but generally
unneeded - EJB 3.0 components interoperate with existing
components/applications - Gives developer powerful and easy-to-use
functionality
74??(????????)
- Java 1.5?RMI???????
- EJB 3.0??EJB 2.1??????