Design of Distributed Software Chapter 3: Chapter 3: Middleware Services Middleware Services – part II – 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)
70
Embed
Design of Distributed Software Chapter 3: Middleware Services – part II Overview of 10 important middleware services and examples in CORBA, RMI, JEE, Web.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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.
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
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
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 {
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
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
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(); }}
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
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 {
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
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)
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