design of distributed software chapter 3: middleware services – part ii overview of 10 important...
TRANSCRIPT
Design of Distributed Software
Chapter 3: Middleware Chapter 3: Middleware Services – part IIServices – part II
Overview of 10 important middleware services and examples in CORBA, RMI, JEE, Web Services and .NET
(During the lesson, it will be indicated which parts are highly important and which are not important for the exam)
Design of Distributed Software 2
OverviewOverview
Naming Service Event and Notification Service Messaging Service Persistence Service Transaction Service Activation Service Loadbalancing Service Session Tracking Security Service Dynamic Invocation Service
Design of Distributed Software
3.5 Transaction 3.5 Transaction ServiceService
Design of Distributed Software 4
IntroductionIntroduction
Set of operations need to move data from one consistent state to another
The set of operations should be indivisible If one or more operations fail, the entire set should be undone
Facade
Account 1
Account 2
History
5. Transactions
Design of Distributed Software 5
Possible ApproachPossible Approach
By means of exception handling: Catch all possible exceptions of involved methods In case of exceptions: undo already finished operation
Drawbacks: Code spread across many exception handlers
Less readable Less maintainable
In case of network failures Has the operation been completed or not ? Remote object should roll back automatically if the network
becomes unavailable
=> Use of transactions
5. Transactions
Design of Distributed Software 6
What is a Transaction?What is a Transaction?
A transaction is a set of operations that moves data from one consistent state to another
If one or more operations fail, the entire set is undone Success: the transaction "commits" Failure: the transaction "rolls back"
For example:
begin transactiondebit checking accountcredit savings accountupdate history log
commit transaction
5. Transactions
Design of Distributed Software 7
Transaction DefinitionsTransaction Definitions
Transactional Object: An object which is used (methods invoked) within a transaction
Can only be associated with one transaction at a time
EJBs can be transactional objects Transactional Client: A program which invokes
methods on transactional objects Transaction Manager: A program that
coordinates transaction processing
5. Transactions
Design of Distributed Software 8
The Transaction ContextThe Transaction Context
A single transaction can involve multiple objects and operations
A transaction context represents the transaction shared by all these participants
By default, it is automatically propagated between transactional objects (EJBs).
5. Transactions
Design of Distributed Software 9
Java APIs for TransactionsJava APIs for Transactions
The Java Transaction API (JTA) is used by application developers Specifies the interface between the transaction manager and
all involved objects Main class: the UserTransaction interface.
The Java Transaction Service (JTS) is used by developers of transaction managers
Developers of application servers, EJB containers, etc. Not used by application developers
5. Transactions
Design of Distributed Software 10
Transaction Types with EJBsTransaction Types with EJBs
Normally, : use container-managed transactions (CMT) The EJB container manages transactions automatically
Interaction with databases Starting and ending transactions Creating and propagating the transaction context Even two-phase commit (2PC)
For databases with JDBC drivers that support XA You can dictate the transactional behavior of specific methods
No programming required -- just edit the deployment descriptor XML
In addition, bean-managed transactions (BMT) and client-managed transactions are also available.
5. Transactions
Design of Distributed Software 11
Container Managed TransactionsContainer Managed Transactions
Can be used with both session and entity beans.
The container begins a transaction immediately before an enterprise bean method starts (if declared to be transactional).
The transaction is committed before the method exits
Not all methods should be associated with transactions
=> Use of transaction attributesat deployment time
5. Transactions
Design of Distributed Software 12
Transaction Attribute ValuesTransaction Attribute Values
When using CMT, beans (or specific methods within beans) have a transaction attribute
Attribute controls scope of transaction One of six possible values:
Required RequiresNew Mandatory Never NotSupported Supports
5. Transactions
Design of Distributed Software 13
Transaction AttributesTransaction Attributes
.
.methodA() {
.
.Bean2.methodB();.
}
Bean1
.
.methodB() {
.
.
.
}
Bean2
TX1 TX?
methodB() part of TX1 ?
5. Transactions
Design of Distributed Software 14
RequiredRequired
Required If the invoker has a transaction context, it is propagated to the bean If not, the container creates a new transaction context I.e., the method always executes within a transaction context, but does
not create a new transaction needlessly This is the default value
Bean1 methodA() Bean2 methodB()Transactional TX1 TX1Context None TX2
5. Transactions
Design of Distributed Software 15
RequiresNewRequiresNew
RequiresNew If the invoker has a transaction context, it is suspended for the
duration of this method's execution Either way, a new transaction context is created Use when you want the method to execute within a transaction,
but you do not want failure to roll back the whole transaction
Bean1 methodA() Bean2 methodB()
Transactional TX1 TX2Context None TX2
5. Transactions
Design of Distributed Software 16
MandatoryMandatory
Mandatory If the invoker has a transaction context, it is propagated to the
bean Otherwise, an exception is thrown
TransactionRequiredException Use when you want the invoker to provide the transaction
Does not necessarily imply BMT or client managed transactions: the invoker can be a different method in the same EJB
Bean1 methodA() Bean2 methodB()Transactional TX1 TX1
Context None EXCEPTION
5. Transactions
Design of Distributed Software 17
NeverNever
Never If the invoker has a transaction context, an exception is thrown
RemoteException or EJBException Otherwise, the method proceeds normally, without a context Used for non-transactional resources
Bean1 methodA() Bean2 methodB()
Transactional TX1 EXCEPTIONContext None None
5. Transactions
Design of Distributed Software 18
NotSupportedNotSupported
NotSupported If the invoker has a transaction context, it is suspended for the
duration of this method's execution If not, no transaction context is used Either way, the method executes without transaction context For performance optimization
Bean1 methodA() Bean2 methodB()
Transactional TX1 TX1 suspendedContext None None
5. Transactions
Design of Distributed Software 19
SupportsSupports
Supports If the invoker (client, or a different method) has a transaction
context, it is propagated to the bean If not, no transaction context is used Use this for "don't care" situations
Bean1 methodA() Bean2 methodB()Transactional TX1 TX1
Context None None
5. Transactions
Design of Distributed Software 20
Transaction Attribute Values: SummaryTransaction Attribute Values: Summary
Invoker's transaction context Method's action
Supports T1 Use T1
None Work with no transaction context
NotSupported T1 T1 suspended
None Work with no transaction context
Required T1 Use T1
None Create and use T2
RequiresNew T1 T1 suspended, create and use T2
None Create and use T2
Mandatory T1 Use T1
None Throw exception
Never T1Throw exception
None Work with no transaction context
5. Transactions
Design of Distributed Software 21
Exceptions and TransactionsExceptions and Transactions
An application exception does not abort the transaction However, note that if the exception causes the method that
initiated the transaction to end, then the transaction will be stopped
If the client invokes m1, m1 initiates the transaction (due to its Requires attribute) and invokes m2, and m2 throws an application exception, then m1 can try to continue the transaction
If m1 throws (or does not catch) an application exception, the transaction will roll back
A system exception aborts the transaction The container will log the error and mark the transaction
"rollback only" Any attempt to proceed with the transaction would be futile
5. Transactions
Design of Distributed Software 22
Rolling back a TransactionRolling back a Transaction
1. By the container: if a system exception is thrown
2. The bean method can instruct the container to roll back a transaction
By invoking setRollBackOnly on its EJB context object
Usually done before throwing an application exception
5. Transactions
Design of Distributed Software 23
Roll back exampleRoll back example
public void transferToSaving(double amount) throwsInsufficientBalanceException {
checkingBalance -= amount;savingBalance += amount;try {
updateChecking(checkingBalance);if (checkingBalance < 0.00) {context.setRollbackOnly();throw new InsufficientBalanceException();}updateSaving(savingBalance);
} catch (SQLException ex) {throw new EJBException("Transaction failed due to SQLException: "+
ex.getMessage());}
} System exception : automatic roll back
Application exception : explicit roll back
5. Transactions
Design of Distributed Software 24
Java 5 Annotations ExampleJava 5 Annotations Example
@Stateless@TransactionManagement(TransactionManagementType.CONTAINER)
public class OrderManagerBean {
@Resourceprivate SessionContext context;...@TransactionAttribute(TransactionAttributeType.REQUIRED)public void placeOrder(Item item, Customer customer){
try {if (!bidsExisting(item)){validateCredit(customer);chargeCustomer(customer, item);removeItemFromBidding(item);}
} catch (CreditValidationException cve) {context.setRollbackOnly();
} catch (CreditProcessingException cpe){context.setRollbackOnly();
} catch (DatabaseException de) {context.setRollbackOnly();
}}
}
5. Transactions
Design of Distributed Software 25
@ApplicationException@ApplicationExceptionpublic void placeOrder(Item item, Customer customer) throws CreditValidationException,
CreditProcessingException, DatabaseException {
if (!bidsExisting(item)){validateCredit(customer);chargeCustomer(customer, item);removeItemFromBidding(item);
}}...@ApplicationException(rollback=true)public class CreditValidationException extends Exception {...@ApplicationException(rollback=true)public class CreditProcessingException extends Exception {...@ApplicationException(rollback=false)public class DatabaseException extends RuntimeException {...
5. Transactions
Design of Distributed Software 26
Roll back of Instance variablesRoll back of Instance variables
Container always undoes the changes to DB data, made by SQL calls within a transaction
Only in entity beans the container will undo changes to instance variables By ejbLoad method
Session beans must explicitly reset any instance variables changed within a transaction
=> Use of SessionSynchronization interface
5. Transactions
Design of Distributed Software 27
The SessionSynchronization InterfaceThe SessionSynchronization Interface Stateful session EJBs (only) that use container-managed
transactions can request notifications for transaction events Enables the bean to maintain a cache that will remain
synchronized with the DB To do this, the bean should simply implement
SessionSynchronization interface There are three methods in this interface:
afterBegin Load instance variables from database
beforeCompletion Possibility to abort the transaction by calling setRollbackOnly on the session context
afterCompletion(boolean) The parameter indicates commit (true) or rollback
5. Transactions
Design of Distributed Software 28
SessionSynchronization : exampleSessionSynchronization : example
public void afterBegin() {System.out.println("afterBegin()");try {
checkingBalance = selectChecking();savingBalance = selectSaving();
} catch (SQLException ex) {throw new EJBException("afterBegin
Exception: " + ex.getMessage());}
}
public void afterCompletion(boolean committed) {System.out.println("afterCompletion: " + committed);if (committed == false) {try {
checkingBalance = selectChecking();savingBalance = selectSaving();
} catch (SQLException ex) {throw new EJBException("afterCompletion SQLException:" +
ex.getMessage());}
}
5. Transactions
Design of Distributed Software 29
Bean-Managed TransactionsBean-Managed Transactions
NOT ALLOWED for Entity Beans A business method can use JTA create a new UserTransaction
object (effectively initiating a transaction), and use it as its own transaction context
UserTransaction methods : begin, commit, rollback, setRollbackOnly
This method will be propagated when invoking method on other EJBs (depending on the invoked methods' settings)
The bean that created the transaction is responsible for committing/rolling it back
In stateless session beans, the method that initiated the transaction must end it.
An instance that starts a transaction must complete it before starting a new one.
5. Transactions
Design of Distributed Software 30
JDBC TransactionsJDBC Transactions
• controlled by the transaction manager of the DBMS• use methods of the java.sql.Connection interface• transaction start is implicit• typical structure
try {Connection con=makeConnection();con.setAutoCommit(false); // explicit commit !// call methods that update/query DB
con.commit();} catch(Exception ex) {
try {
con.rollback();throw new EJBException(“Transaction failed.”);
} catch (SQLException sqx) {throw new EJBException(“Rollback failed.”);
}} finally {
releaseConnection();}
5. Transactions
Design of Distributed Software 31
JTA TransactionsJTA Transactions
• controlled by the J2EE container transaction manager• can control transactions involving different DB systems• NO nested transactions• explicit demarcation of transaction
call begin, commit, rollbackon javax.transaction.UserTransaction interface
5. Transactions
Design of Distributed Software 32
JTA TransactionsJTA Transactions
typical structure
UserTransaction ut = context.getUserTransaction();
try {ut.begin();// business logic ut.commit();
} catch (Exception ex) {try {
ut.rollback();} catch (SystemException syex) {
throw new EJBException("Rollback failed: " + syex.getMessage());
}throw new EJBException
("Transaction failed: " + ex.getMessage());}
5. Transactions
Design of Distributed Software 33
Transaction scopeTransaction scope
Stateless SB transaction limited to method scope !
Stateful SB JDBC :
when commit encountered when connection to DB closed
JTA : when commit encountered
5. Transactions
Design of Distributed Software 34
Recommended PracticesRecommended Practices
Always prefer container managed transactions. Prefer Required, RequiresNew and Mandatory over
other options Supports, NotSupported and Never are not
implemented by all containers - compromises portability
5. Transactions
Design of Distributed Software
3.6 Activation Service3.6 Activation Service
Design of Distributed Software 36
Activation ServiceActivation Service
responsible for activating objects when requests arrive passivating objects when they are idle for some time
Java RMI Activatable server objects: extend from the java.rmi.activation.Activatable class constructor with two arguments should be available: an
ActivationID and a MarshalledObject
CORBA Implementation Repository Functionality offered by JEE application server
Design of Distributed Software 37
CORBA : architectureCORBA : architecture
ORB Core ORB Core
client server
ab
proxy_bdispatcher
skeletonObject Adapter
Implementation Repository
ImR : 1. contains location information about CORBA objects 2. can activate objects that are not running
Design of Distributed Software 38
Implementation RepositoryImplementation Repository
Responsible for activating registered servers on demand locating servers that are currently running
Object Adapter name is used for registration and activation
Implementation Repository entry:
Object Adapter Name Pathname of Object Implementation Host name and port number of server
Extra information : access control information
Design of Distributed Software 39
Implementation RepositoryImplementation Repository On ImR machine: start ImR
$ imr –p 2446 –f /etc/imr.db –i /etc/imr/ior_file
On participating hosts: startup daemon
$ imr_ssd
Register a program:$ imr_mg add “echoServer” –c “java echoServer” $ imr_mg add “echoServer” –c “xterm –e java echoServer”
Automatic creation of new entries when activating objects:$ imr –p 2446 –f /etc/imr.db –i /etc/imr/ior_file –a
Design of Distributed Software
3.7 Loadbalancing 3.7 Loadbalancing ServiceService
Design of Distributed Software 41
Loadbalancing ServiceLoadbalancing Service Goal: transparent distribution of load between the available
servers i.e. without need for programmers’ intervention
Broker component is often used for this purpose: component with the same interface as the replicated service instead of executing the service, the broker forwards an incoming
request to one of the available servers. server selection can be performed in a random way, round robin, or
based on the load of the available servers. two ways a server can keep track of the load of the available servers:
•the broker maintains a list of forwarded requests to each of the server, with the aim to provide them with an as even load as possible;
the servers report their load to the broker (i) on a regular basis or (ii) when a threshold is exceeded.
often used in combination with a naming service communication via servlets: HTTP redirect option application servers:
HA (High Availability) option FT (Fault Tolerance) option
Design of Distributed Software
3.8 Session Tracking3.8 Session Tracking
Design of Distributed Software 43
Session Tracking Service Session Tracking Service
Goal: track user sessions without having to manually program it
JEE web centric architecture: HTTP is a stateless protocol, in that when a client accesses
a server, the next time the same client accesses the server, the server cannot know that it is the same client.
HTTP has no direct means to maintain a client session
Support in JEE architecture Explained on next slides
Design of Distributed Software 44
How to track sessions ?How to track sessions ?
HTML tricks• add hidden field in form to submit
<INPUT TYPE=“HIDDEN” NAME=“session” VALUE=“1234”>requires dynamic generation of each page
• URL rewritingappend data to URL identifying sessionuse HttpServletResponse methods
public void String encodeURL(String url)public void String encodeRedirectURL(String url)
• use secure sockets• use cookies
ServletHttpSession object
-> managed by web container-> uses HTML trick
Design of Distributed Software 45
CookiesCookies• string sent to client, to be resent in any further requests• users often/sometimes reluctant to accept cookies• many Cookies can be sent to client
Creating a Cookie
Retrieving info from a Cookie
Cookie c=new Cookie(“userName”,”10001”);res.addCookie(c); // content type already set
Cookie[ ] c=req.getCookies();if(c!=null) for(int i=0;i<c.length;i++)
if(c[i].getName().equalsIgnoreCase(“userName”)) {userName=c[i].getValue();i=c.length;
}
public String getValue()public void setValue(String val)public void setMaxAge(int expire)
//maximum age before destruction of Cookie//value 0 destroys Cookie immediately
public int getMaxAge()// -1 indicates persistence until browser shutdown
Design of Distributed Software 46
CookiesCookiesServlet to count number visits for single user (session)
public class Counter extends HttpServlet { private int num=0; private synchronized void inc() {num++;} private synchronized int getNum() {return num;} public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println("<HTML><HEAD><TITLE>Counter Output</TITLE></HEAD>"); inc(); out.println("<BODY>You have visited this site : "+getNum()+" times.<BR>"); out.println("<A HREF=\"http://localhost:8080/counter/count1\">This site</A>"); out.println("</BODY></HTML>"); out.close(); } public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { doGet(req,res); }}
Shows total number of visits
Design of Distributed Software 47
CookiesCookiesVisit count per user : Cookie solution
public class CounterCookie extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { Cookie numCookie=null; res.setContentType("text/html"); PrintWriter out=res.getWriter(); Cookie[] c=req.getCookies(); if(c!=null) { for(int i=0;i<c.length;i++) if(c[i].getName().equalsIgnoreCase("num")) { numCookie=c[i];i=c.length; } } else { numCookie=new Cookie("num","0"); } numCookie.setValue(""+(Integer.parseInt(numCookie.getValue())+1)); numCookie.setMaxAge(-1);res.addCookie(numCookie); out.println("<HTML><HEAD><TITLE>Counter Output</TITLE></HEAD>"); out.println("<BODY>You have visited this site : "+numCookie.getValue()+" times.<BR>"); out.println("<A HREF=\"http://localhost:8080/counter/count2\">This site</A>"); out.println("</BODY></HTML>"); out.close(); }}
Design of Distributed Software 48
HttpSessionHttpSession
• binds client to servlet over multiple requests• supported by cookies or URL rewriting• retrieved from HttpServletRequest object
public HttpSession getSession(boolean create)
• can be used to store session scope attributes
public Object getAttribute(String name)public Enumeration getAttributeNames()public void removeAttribute(String name)public void setAttribute(String name,Object obj)
public long getCreationTime()public long getLastAccessedTime()public int getMaxInactiveInterval() //session timeout in spublic void setMaxInactiveInterval()public void invalidate() // session no longer validpublic int getID() //unique session ID
Same as for context and request object,But for Session Scope attributes
Design of Distributed Software 49
HttpSessionHttpSession
public class CounterSession extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); HttpSession session=req.getSession(true); int num=0; if(session.getAttribute("num")!=null) num=Integer.parseInt((String)(session.getAttribute("num"))); session.setAttribute("num",""+(num+1)); out.println("<HTML><HEAD><TITLE>Counter Output</TITLE></HEAD>"); out.println("<BODY>You have visited this site : "+session.getAttribute("num")+" times.<BR>"); out.println("<A HREF=\"http://localhost:8080/counter/count3\">This site</A>"); out.println("</BODY></HTML>"); out.close(); }}
Visit count per user : Session solution
Design of Distributed Software
3.9 Security3.9 Security
Design of Distributed Software 51
J2EE Security Terminology (1)J2EE Security Terminology (1)
A principal is “something” that can be authenticated For example, a user or a server
Each principal has an associated set of security attributes Used to identify which resources the principal can access
A principal is identified using credentials A credential contains or references security attributes Credentials are acquired via authentication Credentials can also be acquired through delegation from
another principal
5. EJB Security
Design of Distributed Software 52
J2EE Security Terminology (2)J2EE Security Terminology (2)
Group: A set of authenticated users, defined in the Application Server.
Role: An abstract name for the permission to access a particular set of resources in an application. A role can be compared to a key that can open a lock. Many people might have a copy of the key. The lock
doesn’t care who you are, only that you have the right key.
5. EJB Security
Design of Distributed Software 53
Two possible waysTwo possible ways
Declarative security: defined using deployment descriptors Includes definition of security roles, access control rules and
authentication requirements Mapped by the application deployer to the specific runtime
environment Programmatic security: explicit use of security APIs by application
code Provides increased flexibility
e.g., the same method can function differently for different pricipals
Key methods: getCallerPrincipal and isCallerInRole, defined in EJBContext.
5. EJB Security
Design of Distributed Software 54
Authentication in J2EEAuthentication in J2EE
J2EE does not dictate any authentication method Each implementation should provide its own
authentication tools Common solutions include authentication via HTTP,
HTTPS (HTTP over SSL), and form-based authentication There are also solutions for non-web-based
authentication An implementation could rely on OS-provided
authentication services e.g., user login under Unix or NT
5. EJB Security
Design of Distributed Software 55
Declarative exampleDeclarative example
@DeclareRoles("BIDDER", "CSR", "ADMIN")@Statelesspublic class BidManagerBean implements BidManager {
@RolesAllowed("CSR, ADMIN")public void cancelBid(Bid bid, Item item) {...}
@PermitAllpublic List<Bid> getBids(Item item) {...}}
5. EJB Security
Design of Distributed Software 56
Programmatic exampleProgrammatic example
@Statelesspublic class BidManagerBean implements BidManager {
@Resource SessionContext context;...public void cancelBid(Bid bid, Item item) {
if (!context.isCallerInRole("CSR")) {throw new SecurityException("No permissions to cancel bid");
}...
}...}
5. EJB Security
Design of Distributed Software 57
The Bean Provider's RoleThe Bean Provider's Role
Security mechanisms should not be implemented in EJBs
Security policies should not be hard-coded The same application, when deployed by different
companies, could use different policies Conclusion: The bean provider should not be involved
in EJB security. The bean provider can convey security requirements
(e.g., what roles he assumes are defined) via the deployment descriptors
5. EJB Security
Design of Distributed Software 58
APIs Available for the Bean ProviderAPIs Available for the Bean Provider getCallerPrincipal returns the current caller's
principal name Can be used for logging, or as a key for accessing
database information No assumptions should be made regarding specific
names i.e., avoid code like if (principal.equals("root")) ...
isCallerInRole(String roleName) allows the bean provider to code security checks that cannot be defined using method permissions
A method that will behave differently for different users In many cases, it is better to simply provide different methods,
each with its own role requirements
5. EJB Security
Design of Distributed Software 59
Method PermissionsMethod Permissions The application assembler (or deployer) can specify
which methods can be invoked by which roles Example:
<method-permissions><role-name>client</role-name><method>
<ejb-name>Account</ejb-name><method-name>getBalance</method-name>
</method>... more methods ...
</method-permissions><method-permissions>
<role-name>clerk</role-name><method>
<ejb-name>Account</ejb-name><method-name>*</method-name>
</method></method-permissions>
5. EJB Security
Design of Distributed Software 60
Security Service in other technologiesSecurity Service in other technologies
The .NET framework provides a comparable security service and offers also support for declarative and programmatic security.
Corba defines a security service with support for: Identification and authentication of principals Authorization, i.e. deciding whether a principal can access an object or
operation on an object Security of communication between objects through encryption and
exchange of certificates WS-Security (Web Services Security) is a communications
protocol for applying security to Web services. originally developed by IBM, Microsoft, and VeriSign, and released in
2006. WS-Security describes how to attach signatures and encryption
headers to SOAP messages and how to attach security tokens to messages.
Design of Distributed Software
3.10 Dynamic 3.10 Dynamic Invocation ServiceInvocation Service
Design of Distributed Software 62
Dynamic Invocation Service
Goal: support for invoking an object whose interface is not known at compile time, but all at runtime the interface can be discovered.
Java offers the Reflection API for the other technologies another approach is needed.
CORBA provides support for dynamic invocation through the Interface Repository.
For designing web services, dynamic invocations are also possible (through WSDL retrieval and consequent construction of messages).
Design of Distributed Software 63
CORBA : architectureCORBA : architecture
ORB Core ORB Core
client server
ab
proxy_bdispatcher
skeletonObject Adapter
Interface Repository
or dynamic invocation or dynamic skeleton
IR : allows to request, inspect and modify IDL type information dynamically
Design of Distributed Software 64
Interface RepositoryInterface Repository
Provide information about registered IDL interfaces
Can supply the names of the methods the corresponding names and types of arguments and
exceptions Reflection facility Useful when client has no proxy for object
Not required when static invocation with client stubs and IDL skeletons
Design of Distributed Software 65
Dynamic InvocationDynamic Invocation
Dynamic Invocation Interface Useful when new objects are added dynamically NO run time downloads of classes for proxies
(cfr Java RMI) Clients obtain from the interface repository the
necessary information Invocation with required arguments is constructed and
sent to the server Dynamic Skeleton Interface
Allows to accept invocations on an interface for which there is no skeleton
Inspects the request: discovers target object and invokes the target
Design of Distributed Software 66
Static Stub Clients JAX-RPC Static Stub Clients JAX-RPC 3. Java WS
Uses automatically generated stub classes
package randomclient;
import javax.xml.rpc.*;import javax.xml.namespace.*;import javax.naming.*;import java.net.*;import random.*;
public class RandomServiceStaticStubClient { public static void main(String[ ] args) { try {
Stub stub=(Stub)(new RandomService_Impl().getRandomServiceIFPort()); // 1stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY,
"http://localhost:8080/random/rs"); // 2RandomServiceIF proxy=(RandomServiceIF)stub; //3 System.out.println(proxy.sayHello("student"));
for(int i=0;i<5;i++) System.out.println(""+i+" -> "+proxy.getRandomNumber(10)); } catch (Exception e) {e.printStackTrace();} }}
RandomServiceStaticStubClient.java
1. Create Stub-object2. Set endpoint address for the stub3. Cast the stub to correct runtime type4. Use the stub as local proxy
Design of Distributed Software 67
Dynamic Proxy Clients JAX-RPC Dynamic Proxy Clients JAX-RPC 3. Java WS
Client retrieves WSDL-document at runtime and creates proxy class dynamically
package randomclient;
import javax.xml.rpc.*;import javax.xml.namespace.*;import javax.naming.*;import java.net.*;import random.*;
public class RandomServiceDynamicStubClient { public static void main(String[ ] args) { try { String UrlString = "http://localhost:8080/random/rs?wsdl"; String nameSpaceUri="urn:RandomService"; String serviceName="RandomService"; String portName="RandomServiceIFPort"; URL randomWsdlUrl=new URL(UrlString); ServiceFactory serviceFactory = ServiceFactory.newInstance(); // 1 Service randomService=serviceFactory.createService(randomWsdlUrl,new QName(nameSpaceUri,serviceName));// 2 RandomServiceIF proxy=(RandomServiceIF)(randomService.getPort(
new QName(nameSpaceUri,portName),RandomServiceIF.class)); // 3 System.out.println(proxy.sayHello("student2")); for(int i=0;i<5;i++) System.out.println(""+i+" -> "+proxy.getRandomNumber(10)); } catch (Exception e) {e.printStackTrace();} }}
RandomServiceStaticStubClient.java
1. Create Service-factory object2. Create Service-object (= factory for proxies)3. Create proxy, specifying dynamic IF-type4. Use the proxy as before (i.e. static stubs)
Design of Distributed Software 68
Dynamic Invocation Interface ClientDynamic Invocation Interface Client3. Java WS
Service name unknown until runtimeService method signature unknown until runtimeUses reflection-type of approach
package randomclient;
import javax.xml.rpc.*;import javax.xml.namespace.*;
public class RandomServiceDIIClient {public static void main(String[ ] args) {
String qnameService = "RandomService"; String qnamePort = "RandomSerivceIF"; String bodyNameSpaceValue="urn:RandomService"; String encodingStyleProperty="javax.xml.rpc.encodingstyle.namespace.uri"; String nsXsd="http://www.w3.org/2001/XMLSchema"; String uriEncoding="http://schemas.xmlsoap.org/soap/encoding/";
// …
RandomServiceDIIClient.java
Design of Distributed Software 69
Dynamic Invocation Interface ClientDynamic Invocation Interface Client3. Java WS
try { ServiceFactory serviceFactory = ServiceFactory.newInstance(); // 1 Service service=serviceFactory.createService(new QName(qnameService)); // 2 QName port = new QName(qnamePort); Call call1 = service.createCall(port); // 3 call1.setTargetEndpointAddress("http://localhost:8080/random/rs"); // 4 call1.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true)); // 5 call1.setProperty(Call.SOAPACTION_URI_PROPERTY,""); // 5 call1.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,uriEncoding); // 5 QName qnameTypeString = new QName(nsXsd,"string"); call1.setReturnType(qnameTypeString); // 6 call1.setOperationName(new QName(bodyNameSpaceValue,"sayHello")); // 6 call1.addParameter("String_1",qnameTypeString,ParameterMode.IN); // 6 String[] params1 = {"student"}; // 7 System.out.println(call1.invoke(params1)); // 8
1. Create Service-factory object2. Create Service-object (= factory for proxies)3. Create generic proxy : Call-object4. Set endpoint for call5. Set SOAP-related properties6. Set method signature7. Define actual parameters8. Invoke the WS through the call-object
Design of Distributed Software 70
Dynamic Invocation Interface ClientDynamic Invocation Interface Client3. Java WS
Call call2 = service.createCall(port); call2.setTargetEndpointAddress("http://localhost:8080/random/rs"); call2.setProperty(Call.SOAPACTION_USE_PROPERTY,new Boolean(true)); call2.setProperty(Call.SOAPACTION_URI_PROPERTY,""); call2.setProperty(Call.ENCODINGSTYLE_URI_PROPERTY,uriEncoding); QName qnameTypeInt = new QName(nsXsd,"int"); call2.setReturnType(qnameTypeInt); call2.setOperationName(new QName(bodyNameSpaceValue,"getRandomNumber")); call2.addParameter("int_1",qnameTypeInt,ParameterMode.IN); Object[] params2 = {new Integer(10)}; for(int i=0;i<5;i++) System.out.println(""+i+" -> "+call2.invoke(params2)); } catch (Exception e) {e.printStackTrace();} }}
RandomServiceDIIClient.java
Code does NOT contain static type info concerning WSUsed in discovery-based invocations