Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
1
Distributed Objects
分布对象(2)
Institute of Computer Software
Nanjing University
2017/5/6
摘要
2
More about RMI
J2EE/EJB
Institute of Computer Software
Nanjing University
2017/5/6
摘要
3
More about RMI
J2EE/EJB
Institute of Computer Software
Nanjing University
2017/5/6
RMI
4
Java语言之内,充分利用这一点!
Stub可下载!
可以传“对象”!
Garbage
Collection!
传“引用”
java.rmi.Remote
(RemoteException)
Institute of Computer Software
Nanjing University
2017/5/6
5
Institute of Computer Software
Nanjing University
2017/5/6
Some important parts of RMI
6
Stubs:
Serialization:
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.
Arguments and results have to be “marshalled”—converted to a
representation that can be sent over the Net. In general this is a nontrivial 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.
Institute of Computer Software
Nanjing University
2017/5/6
RMI Architecture overview
7
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).
Institute of Computer Software
Nanjing University
2017/5/6
Remote Reference Layer
8
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
Institute of Computer Software
Nanjing University
2017/5/6
Remote Reference Layer
9
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.
Institute of Computer Software
Nanjing University
2017/5/6
Using RMI
10
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.
Institute of Computer Software
Nanjing University
2017/5/6
Using RMI
11
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
Institute of Computer Software
Nanjing University
2017/5/6
Point 1 – Remote Interface
12
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)
Institute of Computer Software
Nanjing University
2017/5/6
Point 2 – Implementation
13
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
激活服务的目标:只有在需要时才启动服务进程
Institute of Computer Software
Nanjing University
2017/5/6
Dynamic stubs in Java 1.5
14
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).
Institute of Computer Software
Nanjing University
2017/5/6
Point 3 – Server
15
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).
Institute of Computer Software
Nanjing University
2017/5/6
Point 4 – Start RMI Register
16
rmiregistry <port>
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.
Institute of Computer Software
Nanjing University
2017/5/6
load classes dynamically
17
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?)
Institute of Computer Software
Nanjing University
2017/5/6
load classes dynamically
18
Start of server:
specify codebase for downloading class files
Start of client:
permission to access server has to be provided (due to security manager):
java -Djava.rmi.server.codebase=http://10.0.2.112:8080/calculator.jar
nju.ics.yuping.dc.rmi.CalculatorServer
java -Djava.security.policy=java.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.112:2001-", "connect,resolve";
};
Institute of Computer Software
Nanjing University
2017/5/6
Point 5 - Codebase
19
-Djava.rmi.server.codebase=file:///e:\course\code\rmi\server\
-Djava.rmi.server.codebase=http://10.0.2.112:8080/calculator.jar
Institute of Computer Software
Nanjing University
2017/5/6
Point 6 - Marshalling
20
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!)
Institute of Computer Software
Nanjing University
2017/5/6
Note on passing remote objects
21
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).
Institute of Computer Software
Nanjing University
2017/5/6
Callbacks
22
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.
Institute of Computer Software
Nanjing University
2017/5/6
Callback: How to
23
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.
Institute of Computer Software
Nanjing University
2017/5/6
Callback Example
24
Institute of Computer Software
Nanjing University
2017/5/6
摘要
25
More about RMI
J2EE/EJB
Institute of Computer Software
Nanjing University
2017/5/6
J2EE
26
JDBC
JNDI
EJB
RMI
Java IDL/CORBA
JSP
Java Servlet
XML
JMS
JTA
JavaMail
JAF
Institute of Computer Software
Nanjing University
2017/5/6
Application Servers
27
"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.)
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Application Servers
28
Major J2EE products:
BEA
WebLogic
IBM WebSphere
Borland AppServer
Sun/Oracle GlassFish
JBoss
Institute of Computer Software
Nanjing University
2017/5/6
Web Server and Application Server
29
App Server 1
Internet Browser
Web Server
(HTTP Server)
HTTP(S)
App Server 2
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Multi-tier Model
30
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Application Scenarios
31
Multi-tier typical application
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Application Scenarios
32
Stand-alone client
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Application Scenarios
33
Web-centric application
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Application Scenarios
34
Business-to-business
Institute of Computer Software
Nanjing University
2017/5/6
J2EE Architecture
35
Institute of Computer Software
Nanjing University
2017/5/6
Now
36
JEE 5
JEE 6
Homepage:
http://www.oracle.com/technetwork/java/javaee/tech
/index-jsp-142185.html
Institute of Computer Software
Nanjing University
2017/5/6
Main technologies
37
JavaServer Pages (JSP)
Servlet
Enterprise JavaBeans (EJB)
JSPs, servlets and EJBs are application components
Institute of Computer Software
Nanjing University
2017/5/6
JSP
38
Used for web pages with dynamic content
Processes HTTP requests (non-blocking call-andreturn)
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
Institute of Computer Software
Nanjing University
2017/5/6
Servlet
39
Used for web pages with dynamic content
Processes HTTP requests (non-blocking call-andreturn)
Written in Java; uses print statements to render
HTML
Loaded into memory once and then called many
times
Provides APIs for session management
Institute of Computer Software
Nanjing University
2017/5/6
EJB
40
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
Institute of Computer Software
Nanjing University
2017/5/6
EJB
41
EJB 1.1
EJB 2.0
EJB 2.1
EJB 3.0
EJB 3.1
更简单
Institute of Computer Software
Nanjing University
2017/5/6
EJB技术要解决的问题
42
EJB™ 技术的初衷是简化企业级应用的开发
通过EJB容器环境
提供可共享的服务:
Concurrency,Distribution,
Transactions,
EIS integration, Resource pooling,
Security, Persistence
提供EJB运行环境
减轻企业级应用开发人员的负担
Institute of Computer Software
Nanjing University
2017/5/6
EJB的相关概念
43
EJB容器:由厂商提供的位于EJB服务器上的实体,
管理EJB的系统级服务,控制EJB的生命周期。针
对每一种组件,都有相应的容器进行处理。
EJB服务器:作为容器和低层平台的桥梁管理着
EJB容器和函数,向EJB容器提供了访问系统服务
的能力。
EJB接口(2.x):Home接口,Remote接口,Local和
LocalHome接口
Institute of Computer Software
Nanjing University
2017/5/6
EJB分类
44
Session Bean
Stateless
同步通信
Stateful
Entity Bean
Message Driven Bean
异步通信
Institute of Computer Software
Nanjing University
2017/5/6
Session Bean
45
Stateless session bean:
Contains
no user-specific data
Business process that provides a generic service
Container can pool stateless beans
Example: shopping catalog
Institute of Computer Software
Nanjing University
2017/5/6
Session Bean
46
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
Institute of Computer Software
Nanjing University
2017/5/6
Entity Bean
47
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
Institute of Computer Software
Nanjing University
2017/5/6
Message-Driven Bean
48
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
Institute of Computer Software
Nanjing University
2017/5/6
EJB 2.x的问题
49
APIs设计的角度不对,多是为了容器正常工作设计,
较少考虑易用性
EJBHome interface
EJBObject interface
EnterpriseBean interfaces
JNDI interfaces
Deployment descriptor
…
解决了老问题,引入了新问题
程序复杂,臃肿,普及度不高。
Boiler Code
部署脚本
Institute of Computer Software
Nanjing University
2017/5/6
简单的EJB 2.x例子
50
// 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() {}
Institute of Computer Software
Nanjing University
2017/5/6
简单的EJB 2.x例子
51
// EJB 2.1 Stateless Session Bean: Bean Class (continued)
public void ejbCreate() {
...
Context initialCtx = new InitialContext();
payrollDB = (DataSource)initialCtx.lookup
(“java:com/env/jdbc/empDB”);
...
}
public void setTaxDeductions(int empId,int deductions){
...
Connection conn = payrollDB.getConnection();
Statement stmt = conn.createStatement();
...
}
}
Institute of Computer Software
Nanjing University
2017/5/6
简单的EJB 2.x例子
52
// 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);
}
Institute of Computer Software
Nanjing University
2017/5/6
简单的EJB 2.x例子
53
// EJB 2.1 Stateless Session Bean: Deployment Descriptor
<session>
<ejb-name>PayrollBean</ejb-name>
<local-home>com.example.PayrollHome</local-home>
<local>com.example.Payroll</local>
<ejb-class>com.example.PayrollBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<resource-ref>
<res-ref-name>jdbc/empDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</session>
Institute of Computer Software
Nanjing University
2017/5/6
简单的EJB 2.x例子
54
// Deployment Descriptor(continued)
<assembly-descriptor>
<method-permission>
<unchecked/>
<method>
<ejb-name>PayrollBean</ejb-name>
<method-name>*</method-name>
</method>
</method-permission>
<container-transaction>
<method>
<ejb-name>PayrollBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
Institute of Computer Software
Nanjing University
2017/5/6
为什么开发EJB 3.0?
55
简化EJB!
Institute of Computer Software
Nanjing University
2017/5/6
EJB类
56
POJO (Plain Old Java Object)
会话Bean和消息驱动Bean本身是普通的Java类
通过注解来指定EJB的类型
注解
用在类的级别上
@Stateless,
@Stateful, @MessageDriven
EJB 3.0取消实体Bean
JPA(Java
Persistence API)取而代之
通过@Entity注解
Institute of Computer Software
Nanjing University
2017/5/6
EJB 2.x中的EJB类
57
// 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) {
...
}
}
Institute of Computer Software
Nanjing University
2017/5/6
EJB 3.0中的EJB类
58
// EJB 3.0 Stateless Session Bean: Bean Class
@Stateless
public class PayrollBean implements Payroll {
public void setTaxDeductions(int empId,int
deductions){
...
}
}
Institute of Computer Software
Nanjing University
2017/5/6
EJB接口
59
接口就是最普通的接口
不再需要extend:
EJBObject, EJBHome
接口可以是local或remote
注解:@Local,
@Remote
Remote方法不需抛出RemoteException
Institute of Computer Software
Nanjing University
2017/5/6
EJB 2.x中的EJB接口
60
// 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);
}
Institute of Computer Software
Nanjing University
2017/5/6
EJB 3.0中的EJB接口
61
// Local Interface
@Local
public interface Payroll {
public void setTaxDeductions(int empId, int
deductions);
}
// Remote Interface
@Remote
public interface Payroll {
public void setTaxDeductions(int empId, int
deductions);
}
Institute of Computer Software
Nanjing University
2017/5/6
消息驱动Bean
62
注解
@MessageDriven
消息驱动Bean需要实现javax.jmx.MessageListener
onMessage(Message
msg)方法
Institute of Computer Software
Nanjing University
2017/5/6
消息驱动Bean的例子
63
// EJB 3.0 Message-driven bean: Bean Class
@MessageDriven
public class PayrollMDB implements
javax.jms.MessageListener {
public void onMessage(Message msg) {
...
}
}
Institute of Computer Software
Nanjing University
2017/5/6
调用资源
64
不再需要繁琐的JNDI Lookup。
资源注射
注解Instance
variable
注解setter方法
动态Lookup
注解class
Institute of Computer Software
Nanjing University
2017/5/6
注解
65
@Resource
For
connection factories, simple environment entries,
topics/queues, EJBContext, UserTransaction, etc.
@PersistenceContext
容器管理的EntityManager
@PersistenceUnit
EntityManagerFactory:获取非容器管理的
EntityManager
Institute of Computer Software
Nanjing University
2017/5/6
Dependency Injection
66
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 @PostConstruct method is called when
injection is complete
Institute of Computer Software
Nanjing University
2017/5/6
资源注射的例子
67
// EJB 3.0 Stateless Session Bean: Bean Class
// Data access using injection and Java Persistence API
@Stateless
public class PayrollBean implements Payroll {
@PersistenceContext EntityManager payrollMgr;
public void setTaxDeductions(int empId,int deductions){
payrollMgr.find(Employee.class,empId).
setTaxDeductions(deductions);
}
}
Institute of Computer Software
Nanjing University
2017/5/6
动态Lookup的例子
68
// EJB 3.0 Stateless Session Bean
// Using dynamic lookup
@PersistenceContext(name=”payrollMgr”)
@Stateless
public class PayrollBean implements Payroll {
@Resource SessionContext ctx;
public void setTaxDeductions(int empId,int deductions){
EntityManager payrollMgr = ctx.lookup(“payrollMgr”);
payrollMgr.find(Employee.class,
empId).setDeductions(deductions);
}
}
Institute of Computer Software
Nanjing University
2017/5/6
Bean Lifecycle Event
69
EJB 2.1需要实现EnterpriseBean接口,并重写
Lifecycle相关的方法
EJB 3.0通过注解指定需要的方法
注解:
@PostConstruct
@PreDestroy
@PostActivate
@PrePassivate
多个注解可用于同一个方法。
Institute of Computer Software
Nanjing University
2017/5/6
简化了EJB调用
70
使用资源注射的方式
不再需要Home interface
不再抛出RemoteException
Institute of Computer Software
Nanjing University
2017/5/6
EJB 2.x的调用
71
// EJB 2.1: Client View
...
Context initialContext = new InitialContext();
PayrollHome payrollHome = (PayrollHome)
initialContext.lookup(“java:comp/env/ejb/payroll”);
Payroll payroll = payrollHome.create();
...
// Use the bean
payroll.setTaxDeductions(1234, 3);
Institute of Computer Software
Nanjing University
2017/5/6
EJB 3.0的调用
72
// EJB 3.0: Client View
@EJB Payroll payroll;
// Use the bean
payroll.setTaxDeductions(1234, 3);
Institute of Computer Software
Nanjing University
2017/5/6
EJB 3.0 Summary
73
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
Institute of Computer Software
Nanjing University
2017/5/6
作业(本次作业不用提交)
74
Java 1.5对RMI做了哪些改进?
EJB 3.0相比EJB 2.1有哪些改进?
Institute of Computer Software
Nanjing University
2017/5/6