Transactional Interoperability Across Java EE and .NET


As it appears from this chapter's earlier discussion on individual platform transactional support, the .NET transaction model is not compatible with the transaction support in Java, which makes it difficult to achieve transactional interoperability. The next few sections explore various strategies on how to propagate a transactional context between Java EE and .NET, thus addressing the challenge of the transactional incompatibility between the two platforms. The first and recommended strategy at this point in time is based on messaging. The next strategy relies on a Web services-based solution. The final strategy explores custom, off-the-shelf, solutions to provide support for transactions.

Transaction Management Using Messaging

Depending on the individual integration scenario, support for transactions can be easily incorporated into a publish-and-subscribe or a point-to-point messaging-based solution. In the purchase order scenario there are two distinct services that communicate with each other. The Java-based Purchase Order management system, acting as a producer, can send an asynchronous request to the Inventory management system to create a purchase order. The .NET service, acting as a consumer, listens on a point-to-point queue or subscribes to a publish-and-subscribe topic. In the purchase order creation scenario, the point-to-point integration is quite appropriate. The publish-subscribe mechanism could be selected in a situation where an event has to be distributed to multiple recipients. For transaction management with the point-to-point application integration, Java EE and .NET components utilize a message queue. Hereafter, examples demonstrate how to implement transactional support using messaging with Java EE and C# components. Asynchronous Java EE-.NET integration with messaging middleware is discussed in Part III of this book, "Asynchronous Integration Solutions."

Messaging Support in Java EE Components

Session and Entity beans can use JMS to send messages, but their lifecycle model makes them inappropriate for receiving messages.

Instead, Java EE defines a special kind of enterprise bean, referred to as a message-driven bean, whose sole purpose is to asynchronously receive messages from the messaging middleware. Depending on point-to-point or publish-subscribe integration, javax.jms.Queue or javax.jms.Topic is utilized respectively. If the EJB application needs to receive messages, then a message-driven bean is appropriate (as a matter of fact, the only way to invoke a message-driven bean is by sending a JMS message to it).

This example involves a Java EE application that calls a .NET service. This means that the Java EE application is acting as the sender, so one wouldn't use a message-driven bean but a session EJB here. The session bean is called to check the inventory, and it delegates the call to .NET via a JMS message.

The example in Listing 12-7 demonstrates how to communicate with a JMS connection using a message queue.

Listing 12-7. POHandlerEJB Class

public class POHandlerEJB implements SessionBean {     EJBContext ejbContext;     public void sendCheckInventoryRequest(String productID,        int productCount) {        javax.transaction.UserTransaction userTxn;        javax.jms.QueueConnectionFactory connectionFactory;        javax.jms.QueueConnection connection;        javax.jms.Queue queue;        javax.jms.QueueSession session;        javax.jms.QueueSender sender;        javax.jms.MapMessage msg;      try{        InitialContext initialContext = new InitialContext();        // Createa JMS connection and set up Queue Session for        // transactions        connectionFactory =         (javax.jms.QueueConnectionFactory) initialContext.lookup                    ("java:comp/env/jms/QueueConnectionFactory");        connection = connectionFactory.createQueueConnection();        // Pass values for boolean transacted and int acknowledgeMode        session = connection.createQueueSession(true,0);        queue = (javax.jms.Queue)        initialContext.lookup("java:comp/env/jms/jmsQueue");        sender = session.createSender(queue);        msg = session.createMapMessage();        msg.setInt(productID, productCount);        //Get user transaction        userTxn = ejbContext.getUserTransaction();        //Start the transaction        userTxn.begin();        // Execute transaction        sender.send(msg);        //Commit the transaction        userTxn.commit();      } catch (SQLException exc) {          try {             userTxn.rollback();          } catch (Exception e){}      } finally {        //Release resources        sender.close();        session.close();        connection.close();      }   } } 

In Listing 12-8, the queue session, connection.createQueueSession(true, 0), is created with a transaction attribute set to true and acknowledgement mode set to zero. The reason for acknowledgement being zero is because the Java EE container ignores this method parameter in transactional use cases. The container handles transactional characteristics of this JMS session on behalf of a bean. Similarly, createTopicSession(true, 0) can be used to utilize a topic rather than a queue.

Architect's Note

It is important to mention the limitations of messaging-based Java EE .NET integration when it comes to transaction management. With the messaging-based communication, a transaction typically does not span across a messaging channel. In particular, the scope of a transaction is limited to only one party in the message chain. A rollback can only affect at the most one party in that chain. Additionally, transactional support in the messaging environment is not designed for a request-reply type of communication. It is impossible to receive a reply to a request as part of the same transaction. An attempt to do so always results in a time-out and a transaction rollback. The practical consequence of using messaging in the transaction context is to ensure that all of the following requirements are met:


  • No reply message is required within the scope of a transaction.

  • Once sent, a request is guaranteed to arrive at the recipient.

  • Upon arrival of the message, a recipient guarantees to process the message successfully.

Failure to meet one of these requirements can result in violations of the Atomic property, thus transaction management with messaging should be used with the proper care. Having said that, the chapter next explores what it takes to process a message by the .NET application.

Transaction Request Processing with .NET Messaging

On the .NET platform, transactions can be enabled with the System.Messaging.MessageQueueTransaction class and automatically managed by the MSMQ engine. Refer to Listing 12-8.

Listing 12-8. Enabling Transactions with System.Messaging.MessageQueueTransaction

// Check if the queue exists if ( MessageQueue.Exists(".\\inventoryQueue") {   // Look up the inventory queue   // Create new transaction   MessageQueueTransaction txn = new MessageQueueTransaction();   try {     // Begin transaction     txn.Begin()     // Receive the inventory check reques     Message msg = inventoryQueue.Receive(txn);     Sting request = (String)msg.Body;     // After checking the inventory, send the status back to the queue     inventoryQueue.Send("inventory status...", txn);     txn.Commit();   } catch ( MessageQueueException exp){     //abort the transaction     txn.Abort();   } } //End of if statement 

After sending a message to the queue, the status of the transaction can be verified with the MessageQueueTransactionStatus library to determine if a transaction has been committed, aborted, initialized, or if it is pending.

if (txn.Status = MessageQueueTransactionStatus.Aborted)   // Log the status 


If a transaction has been aborted, sent messages are removed from the queue.

Architect's Note

Messaging is a practical and mature solution for transactional interoperability across Java EE and .NET. While the Web services transactional support, discussed next, is still evolving, messaging is the most reliable way to ensure integrity of distributed transactions. A disadvantage of messaging pertains to its cost as compared to using Web services. Leveraging transactional characteristics of messaging would be more appropriate if Java EE and .NET applications already relied on messaging as an integration solution or if there were a messaging server already deployed in the company that could be leveraged for other purposes.


Web Services Transaction Strategy

In spite of the high value and simplicity of Web services-based Java EE and .NET component integration, support for distributed transactions with Web services is somewhat problematic. There is no de-facto standard adopted by the industry to address transactional interoperability, although a strong candidate specification has recently been published by a consortium of industry giantsWS-Transactions. However because this is a new evolution at the time of this writing, transactional characteristics of Java EE-.NET Web services integration are very limited and primarily embrace proprietary technologies. Most of today's Web services integrations rely on a simple request-response scenario or a reliable and secure message interchange for B2B transactions. Neither of these scenarios entails a request for distributed transactions.

In some cases, though, distributed transaction integration is necessary, and most of the industry players, realizing its potential value, released a set of specifications to accommodate support for Web services-based distributed transactions. Microsoft, IBM, IONA, Arjuna, and BEA released a proprietary trio of specifications for WS-Coordination, WS-AtomicTransaction, and WS-BusinessActivity, which were previously embraced under an umbrella of the WS-Transaction specification [WS-TX]. This specification set was officially published in version 1.0, open to the public as well as royalty-free to implement. Along the same line, Sun, Oracle, Iona, Arjuna Technologies, and Fujitsu, as part of the Organization for the Advancement of Structured Information Standards (OASIS), are working on the Web Services Composite Application Framework, a.k.a. WS-CAF specification. The OASIS WS-CAF technical committee will define a royalty-free, generic, and open to the public framework to manage Web service distributed transactions [SUNWSCAF]. From a technical standpoint, WS-CAF and WS-Transaction trio resemble each other greatly. Another standard in this space corresponds to OASIS' Business Transaction Process (BTP) standard that addresses distributed transaction across the long living B2B communication. A more detailed discussion of each of these standards follows, providing an understanding of how they can be leveraged for Java EE .NET transaction interoperability with Web services and dive a bit more into details with the WS-AtomicTransaction specification.

WS-Coordination, WS-AtomicTransaction, and WS-BusinessActivity

The industry is gaining momentum around this trio of specifications that defines how Web services can participate in the distributed transaction model, see [WSACOORD]. The first of the trio, WS-Coordination, provides a means to create, register, and coordinate distributed Web services. While WS-Coordination does not require transaction support to protect ACID properties, the latter are essential features of distributed collaborations. WS-AtomicTransaction extends the WS-Coordination specification with support for atomic, all-or-nothing transactions. This specification relies on a transaction coordinator to collaborate with each of the participants to agree on a transaction commit or rollback, thus following a classic two-phase-commit protocol. WS-AtomicTransactions can be used when heterogeneous applications and resources have to participate in a short-lived transaction and the level of trust among transaction participants is fairly high. The WS-BusinessActivity specification is the second type of the transaction coordination. WS-BusinessActivity is designed for a long living business transaction with a low level of trust, and aimed at facilitating transaction execution in a B2B scenario.

Achieving Transactional Interoperability with WS-AtomicTransaction

In light of Java EE .NET integration, this book primarily focuses on how to integrate two intranet applications, Java EE and .NET, and their underlying resources. This implies that a transaction the text is trying to portray is short-lived and is deployed within the boundaries of the same corporation. Therefore, it is expected that the level of trust among transaction participants is high. These characteristics point to the WS-AtomicTransaction as an adequate technology for needed requirements.

The first thing that needs to happen is the creation of a new transaction. In WS-AtomicTransaction, this is done via the Coordinator service. This is a Web service that runs either inside the Java EE server or as a separate Web service on the network. The Coordinator service needs a transaction type for the creation request (because the design of WS-Transactions allows multiple transaction types to be supported by the same Coordinator). For WS-AtomicTransaction, the type is identified by a schema, which can be found at [WS-AT].

As a result of the creation, the Coordinator returns a ticket (the so-called CoordinationContext, expressed in XML) that describes the transaction and can be passed along with the application-level requests. The fact that a request carries this context in its header signals that it is part of the corresponding transaction. An example of such a context is shown here in Listing 12-9.

Listing 12-9. Example of a Web Services Coordination Context

<wscoor:CoordinationContext>    <wsu:Identifier>http://theInventoryCheck.com</wsu:Identifier>    <wsu:Expires>2004-12-22T15:10:17-00:00</wsu:Expires>    <wscoor:CoordinationType>      http://schemas.xmlsoap.org/ws/2004200410/09/wsat    </wscoor:CoordinationType>    <wscoor:RegistrationService>      <wsu:Address>        http://RegistrationSrvice_uri      </wsu:Address>    </wscoor:RegistrationService>  </wscoor:CoordinationContext> 

Any invoked Web service that receives a request with a context header can use the context information to register with the Coordinator's RegistrationService (included in the context shown in Listing 12-9) so that the service becomes subject to two-phase commit termination at the end of the transaction. This registration is shown in Listing 12-10.

Listing 12-10. Registering a Database Resource in Web Services Coordination

<soapenv> <soapheader>      <!-- WS-Addressing headers to identify target service, and            the requesting service with its reply information. --> </soapheader> <soapbody>  <wscoor:Register>    <ProtocolIdentifier>       http://xxxx/AtomicTransaction/Completion      http://schemas.xmlsoap.org/ws/2004/10/wsat/Durable2PC    </ProtocolIdentifier>    <ParticipantProtocolService>        <Address>http://database_address</Address>     </ParticipantProtocolService>   </wscoor:Register>  </soapbody> </soapenv> 

Upon receiving a registration, the Coordinator (Registration) service returns a reference (address) of the coordination service to the registering party (not shown).

Services can register for two types of termination: Volatile2PC or Durable2PC. Services that register for the former will only receive a notification before 2PC really happens (this is useful for cache managers that only need to flush to other services that take care of the real persistence work). Services that register for the latter will receive full 2PC requests and should also respond accordingly. When the transaction ends, all remote business calls have been done, and consequently all participating services have registered. This means that at the time of termination, the coordinator service knows all the parties involved in the transaction.

To terminate the transaction, some part of the application has to indicate if it wants to commit or roll back. This happens via the Completion service, another service that is exposed by the Coordinator. Application services that want to trigger commit or rollback processing should first register for the Completion Protocol (with the Coordinator). The registration message is similar to the one for 2PC shown earlier; only the protocol URI differs, and the participant service contains the address of the service that wants to trigger termination. This extra registration is provided to allow a Web service other than the transaction creator to trigger the termination process.

Note

If the Coordinator is collocated with the transaction creator and the creator also triggers commit, then no extra SOAP message exchange may be neededinstead, an API call will typically do.


Once registration for Completion is finished, the registered application service can request commit or rollback. Assuming that commit is desired, the Coordinator starts the two-phase commit protocol. WS-AtomicTransaction describes the message format and state transitions for this protocol.

Architect's Note

With version 1.0 released in August 2005, WS-Coordination and WS-AtomicTransaction together standardize the protocol messages to be exchanged between cross-vendor, cross-platform Web service transactions. This minimal and yet unambiguous nature should make it a lot easier to achieve interoperability across vendors and platforms, since implementers are not bothered by unnecessary elements in the specification. WS-AtomicTransaction-compliant products are allowed to include proprietary (and purely supplementary) information to enhance the user experience when deployed in a network of single-vendor installations. However, if they follow the protocol guidelines, there should be no implications on interoperability.


Realistically speaking, as with all interoperability technologies, testing will have to make sure that message formats and content are really compliant across vendors. This is inevitable; the same problem exists even at the basic SOAP protocol level.

Web Services Composite Application Framework

This specification is more generic than WS-AtomicTransaction, WS-BusinessActivity, and WS-Coordination, although WS-CAF also addresses the same problem domain space of Web services distributed transaction support. The WS-CAF specification encompasses three specifications, all of which are still works in progress at the time of writing. The first one pertains to the Web Service Context (WS-CTX), which defines a means for Web services to manage, share, and access Web services contextfor instance, coordinating a state of a shopping cart across different Web services at the application level. Another example of the Web Service Context is to manage Web service transaction information at the system level. The second WS-CAF specification, Web Service Coordination Framework (WS-CF), coordinates distributed transaction support. For example, if a 2PC commit failed at one of the Web services, the coordinator is responsible for propagating the rollback across all participants. Finally, the Web Service Transaction Management (WS-TXM) defines a plug-in model for transaction managers.

Architect's Note

As a result of the fairly generic set of specifications, WS-CAF inevitably leads to added complexity, which, in turn, could complicate interoperability.


In addition to discussed specifications, there is a Business Transaction Processing Protocol (BTP), [BTP], which outlines a mechanism to conduct a business-to-business transaction across multiple parties.

Java Support of Web Services Transaction Standards

There are two Java Specification Requests, JSR 156 and JSR 95, that have been submitted to address Java EE support for distributed transactions using Web services.

  • JSR 156 XML Transactioning API for Java (JAXTX) This JSR intends to extend Java transactional support with Web services transaction models including OASIS BTP and WS-Transaction. Mapping of the transaction context between Java and SOAP message headers or Java and WS-Transaction would simplify transaction processing of loosely coupled applications.

  • JSR 95 Java EE Active Service for Extended Transactions This JSR intends to extend Java EE frameworks with support for activities, where an activity can be anything from an ACID transaction to a workflow task. This JSR extends JTA/JTS with support for OMG's Activity Service standard and is fairly generic (that is, very low-level and therefore probably not useful for mainstream Java EE application developers).

Web Services Transaction Support Future Directions

Considering Sun and Microsoft announcements regarding technology interoperability, it would not be surprising if Web services transactional interoperability improves. Once WS interoperability gets better, the distributed transaction design spanning across Java EE and .NET Web services will become easily realizable because there will be corresponding product support such as Java EE containers and .NET CLR. In this example, the PO Handler prepares to call the Inventory Handler Web service and initiates a transaction. At that point all members of the transaction register with the distributed transaction coordinator. The Java EE transaction coordinator coordinates the 2PC across different transaction managers. Figure 12-2 shows how distributed transaction can be achieved with Web services, once the interoperability is implemented in Java EE and .NET containers.

Figure 12-2. Web services distributed transaction


For additional information on Web services and transaction, please see [WSTXN].




Java EE and. Net Interoperability(c) Integration Strategies, Patterns, and Best Practices
Java EE and .NET Interoperability: Integration Strategies, Patterns, and Best Practices
ISBN: 0131472232
EAN: 2147483647
Year: N/A
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net