Thursday, November 13, 2008

Correlating Messages


Asynchronous messaging means that the sender doesn't receive an immediate reply or confirmation of receipt. After sending a message for processing by a remote service, most applications require at least confirmation that the message was received and acted upon, and often require the results of the remote process. Remember—in a normal application, even if a method doesn't return a value, the system at least knows that the method has had a chance to execute.

A reply message is a message received in response to another message. Reply messages are generally document or event messages, but are distinguished by being associated with a particular message. Typically, this association is accomplished by assigning each outgoing message a unique identifier (MOM systems do this automatically). If an incoming message is a reply, it includes a reference to the message the remote application is replying to.

JMS includes built-in functionality for associating a reply message with the original. Each JMS message, upon creation, is assigned a message ID, which is accessible via the JMSMessageID property of the Message class. Messages also have a JMSCorrelationID field, not set by default. When composing a reply message, it's standard practice to take the JMSMessageID and store it in the JMSCorrelationID field. Assuming that message and reply are valid JMS messages, and that reply is a response to message, this is how we'd set the correlation:

Command Message


Distributed applications can be a command and control nightmare. Multiple web applications expose different interfaces to the administrator, and actions that affect multiple systems need to be repeated. Tools like JMX (the Java Management Extensions) alleviate this problem to a degree, but only within controlled environments. It can be irritating, but the real challenge comes when disparate applications need to control each other. Since user interfaces are generally not designed to be used by other computers, some kind of remote command infrastructure is required.

A command message allows one system to control another application, or a series of other applications, by sending a specially formatted message to that system. A command message includes instructions to perform a specific action, either via headers and attributes, or as part of the message payload. The recipient performs the appropriate action when the message is received. Command messages are closely related to the Command pattern from GoF, which we discussed back in Chapter 3. They can be thought of, in fact, as a remote version of this pattern.

Security is a particular concern with command messages. MOM products provide a variety of mechanisms for securing a message channel. If these products are adequate for your needs (they often are), receipt of a command message can be treated much like an RPC call. If you're using a transport system that doesn't provide security guarantees, such as email, consider the security options we discussed for document messages.

Event Message


Event handling in Java should be familiar to you by now; but on the off chance that it isn't, here's the primer: an object can register itself with another object as an event listener. Once the listener has been registered, the target has a handle to the listener and can use callback methods to notify the listening object that a particular event has occurred. This process allows programmers to easily modify runtime behavior by plugging new listeners in at appropriate places. Swing is full of listeners, as is the Servlet API (ServletContextListener, etc.). The Gang of Four identified this behavior as Observer, in which the actor is the object or set of objects performing the main actions, and the observer is the listener.

An event message extends the Observer model to a set of distributed applications. The basic informational content of an event message is implicit in the fact that the message has been sent. Event messages can be sent from one system to another to provide notification of lifecycle events within an application, or to announce the status of particular activities. Applications for this pattern include enterprise monitoring (see the discussion of the control bus later in this chapter) and centralized logging.

An important characteristic of event messages is that they do not require a reply. In fact, one could go so far as to say there is no requirement that event messages be received, either. In some cases this is true, and in others it isn't: whether events must be received should influence your choice of message transport.

In JMS, an event message can be implemented with the user-defined headers of a message. The benefit of this approach is simplicity: applications only need to agree on header names, so there is no need to define a format for the message data. Performance improves, too, since JMS and most MOM packages provide built-in functionality to filter messages based on their headers.

Nonguaranteed messaging


Nonguaranteed messaging is like standard postal service. Your message will probably get there, but you don't know exactly when or in what condition. You also don't know if something goes wrong: there's no notification when your letter slips out of the bag and gets wedged in a corner of the Duluth post office.

Internet email, as defined by RFC 822, is the archetypical nonguaranteed messaging system. In fact, it's very consistent: messages sent to a valid address almost never get lost, and are delivered in a timely manner. In a controlled environment, receipt rates in the five-nines (99.999%) range aren't out of the question. Of course, delivery guarantees are only part of the issue. RFC 822 messaging provides no guarantee that a message will only be delivered and processed once, or that the message won't be changed in transport (corporate firewalls and virus detection packages frequently modify the format of a message). The application is responsible for verifying integrity and making sure that the order of processing is handled correctly. There are also no security guarantees; with SMTP, for instance, it is trivially easy to create a "spoof" message that appears to be from a particular source: receipt of a message provides no assurance that the message is genuine.

In return for a little extra work, you get the basic global infrastructure for free. Nonguaranteed messaging is often the only option when dealing with widely distributed sites, getting integrations up and running quickly with external partners, or when one actor in the messaging interaction is a human.

In J2EE, email integration is handled via the JavaMail API, which, out of the box, supports sending messages via SMTP and receiving them via POP3 or IMAP.[3] JavaMail is actually a generic messaging API, and additional plug-ins are available to support other messaging schemes, such as NNTP, the protocol behind Usenet.

Guaranteed messaging


Guaranteed messaging uses middleware to ensure that a message is properly delivered to its destination, both ungarbled and in a reasonably timely fashion. The middleware implementing the messaging framework guarantees a message sent to a valid destination eventually arrives, even if the destination is temporarily unreachable.

Guaranteed delivery doesn't imply complete certainty. Specifying a nonexistent destination won't get your message delivered, regardless of how expensive your middleware is. And if a destination system is unavailable for a long period of time, the middleware will probably return the message to its sender rather than wait indefinitely. What is guaranteed, however, is the contract between the messaging client and the server governing how a message will be handled. Undeliverable messages won't vanish into the night but will be handled according to a specific and well-known set of rules.

Message Oriented Middleware systems implement guaranteed messaging. Senders and recipients work through a MOM server, which is responsible for tracking all elements of the message lifecycle. MOM servers often provide a range of options for the message content itself: XML, Java objects, raw binary data, and so on. J2EE clients interact with MOM servers using JMS, the Java Message Service. JMS, which is part of J2EE 1.3, provides a standard programmatic interface to the different MOM implementations, much as JDBC does for database servers. Sonic Software's SonicMQ and IBM's MQSeries products are two of the leading MOM products

Interactions


A client calls a business method of the business delegate. The delegate locates the correct business service and connects to it. The business service grants the business delegate access to the relevant business objects. The business delegate manipulates the business objects and returns the result to the client.

Constant services locator

A typical ServiceLocator takes a JNDI directory name from the client and performs the requested lookup. This creates a coupling between all the various client calls to the locator and the directory structure—and when the directory structure changes, the client must be updated in many places. One variation of the ServiceLocator defines a constant set of services and lets clients access those services with a locator-specific name. This decouples the clients from the actual directory structure, allowing access to the new directory with only a single change to the locator.

Message Handler Pattern


All message clients perform two functions: they retrieve and process a message. It's possible to weave these two activities tightly together, but in more complex systems it can result in some pretty complex code. We want to isolate the latter function in a way that lets us share code across different message types. The Message Handler pattern abstracts the code responsible for receiving the actual message away from the code responsible for processing the message content.

This pattern allows us to change the method by which we receive a message without changing the code for processing the message. Changing message handling itself becomes easier, since we can drop message handlers in and out without major changes to the rest of the application (we can even do it dynamically). There's also a testing benefit, since you can write standalone test cases for an isolated handler method more easily than for an integrated component.

Types of Messaging


Deciding to use asynchronous messaging in your application is a big step, but it's by no means the last. There are a number of ways to implement asynchronous messaging, each involving a different Quality of Service guarantee. The U.S. Postal Service, for instance, promises to deliver a first class letter within four days, and makes their best effort to deliver the letter intact. Most letters duly arrive in the expected timeframe and in reasonable condition. However, some letters get lost, and others are damaged. Because this isn't good enough for every snail-mail enabled application, the USPS provides a set of additional delivery services: return receipts, certified mail, Priority Mail, and Express Mail. An Express Mail letter is all but certain to arrive at its destination the following day, in good condition.

Messaging middleware is the same. Depending on the sophistication and configuration of your messaging platform, you can achieve a variety of different service levels. The higher levels involve more maintenance and are generally more expensive to configure. In this chapter, we're going to talk about two different kinds of messaging. The first is guaranteed messaging, which is implemented via middleware and provides high reliability and control. We use JMS to handle guaranteed messaging in Java. The second is nonguaranteed messaging, which lacks the reliability and security of guaranteed messaging, but can be implemented with much less programmer time and less cost for external middleware.

processing

Many applications involve multiple processing. For example, placing an order might require reserving stock at the warehouse, processing payment, and shipping. In a fully integrated enterprise, you might be able to do all of this in one system and at one time, but most companies aren't entirely integrated. Reserving stock might require someone to physically visit the warehouse, and payment processing might involve purchase order approvals or lengthy credit checks. In these cases, it makes sense to decouple the activities into separate components and connect them with messaging.

Security


One of the features of Java is how easily code can be downloaded and composed into a running application. However, such code has the potential to execute critical operations that manipulate sensitive system data, so it is imperative to distinguish code that can be trusted from code that cannot. To this end, the Java security model is based on the origin of the running code. Sensitive operations are allowed or disallowed based on where the classes in the current call stack were loaded from and/or who signed them.

In a distributed system, code representing business operations is hosted on one or more servers. A client request acts as a trigger to execute server code that has the potential to perform critical operations that manipulate sensitive system data. It is important to distinguish requests that can be trusted from those that cannot. The server must enforce security based on who is attempting to run the code, and that means being able to verify the identity of the caller.

Ensuring security gets more complicated when client and server communicate over a public network where servers may be more easily spoofed. The client may also want some guarantee that the server is genuine before accepting or providing certain information. There are questions to be answered. How can the system tell which clients can be trusted? How is it possible to specify which clients can access which functionality? How can the clients tell which servers can be trusted? How can malicious persons be stopped from accessing the system or tampering with requests and responses?

seems

It seems that distributed computing technologies keep reinventing themselves every couple of years. From COBRA to COM to RMI, now XML Web Services is all the rage. Web Services is touted as a platform-independent integration technology that supports loose coupling. It promises universal interoperability and supports advanced messaging protocols. The Simple Object Access Protocol (SOAP) is the foundation for XML Web Services. Smart mobile clients that fit into the corporate Web Services infrastructure could prove crucial for any mobile enterprise solution.

In this chapter, I introduce an open source tool that supports Web Services clients on small wireless devices: the kSOAP parser. Through tutorial examples and source code analysis, we will not only learn how to program in kSOAP but also gain a deeper understanding of Web Services concepts and applications.

XML

XML is the foundation of componentized and interoperable Web Services. Java and XML are perfectly suited for each other, since Java provides code mobility while XML provides data mobility. In this chapter, we discuss why XML is so important, and we explore common XML parsing APIs on the Java platform and XML support on the J2ME platform. An example of Amazon XML Web Services demonstrates how to process real-world XML messages using different APIs. Finally, we learn about an RSS XML client, and the important concept of XML-based data aggregation is introduced.

Information

Information aggregation is one of the core functionalities of enterprise information systems. Disconnected mobile databases by themselves are not of much use. On one hand, field data from mobile users must be aggregated and incorporated into the enterprise system; on the other hand, mobile users must rely on the backend to keep up with latest updates. The best way to keep database contents up to date is through synchronization. Mobile database vendors offer proprietary synchronization solutions for their databases. This chapter explains the "disconnected but synchronized" mobile application architecture and discusses innovations from different vendors.

MIDP

On MIDP devices, full relational databases prove to be too expensive. The standard MIDP does not even support basic SQL types such as the Float type. On the other hand, the standard persistent storage facility (i.e., the RMS) on the MIDP is terribly inadequate for enterprise applications. RMS stores are very slow. They are neither indexable nor searchable. RMS's linear structure makes it a pain to handle relational or object data.

To address this problem, database vendors have developed simple database solutions on top of the RMS. Since those databases are extremely lightweight, full support for the JDBC API is not necessary. Each vendor provides its lightweight proprietary access APIs. In this chapter, we discuss those solutions and APIs.

Sun's

Sun's Java Blueprints is a program to promote good design practices among Java developers. The blueprints cover a wide range of Java technology application areas, including J2EE, Web Services, security, and mobility. The Wireless Blueprints contain a sample application and a design guidelines white paper for end-to-end mobile commerce solutions. The wireless blueprints' Java Smart Ticket sample application is a mobile movie ticket-ordering system with a J2ME/MIDP wireless front end and a J2EE application server back end. It showcases a number of important design patterns and best practices for end-to-end mobile applications. Using the Smart Ticket sample, we study the mobile design patterns in this chapter.

We start with a quickstart guide on how to install and run the sample application. Then, using the source code, we analyze the key architectural patterns and their benefits. In the last section of this chapter, we review important behavioral patterns and coding techniques used in the implementation.

J2ME

J2ME represents a new mobile application paradigm: smart clients. Smart clients, especially Java smart clients, have many advantages over competing solutions such as WAP/WML. In this chapter, I use a sample application, iFeedBack, the grand prize winner of 2003 NexTel/Sun/Motorola University Wireless Developer Contest, to illustrate the power of smart clients and the basic end-to-end architecture. We will focus on the overall design and briefly walk through the implementation.

Since this book targets advanced Java developers, I assume that you already have knowledge of J2ME application development and deployment. If you need to refresh your memory, a quick start guide is available in Appendix A. A list of entry level J2ME books and tutorials can also be found in the "Resources" section. Although the implementation details of the J2EE serverside components are not the focus of this book, knowledge on servlet, JDBC, JMS, JAX-RPC and EJB will greatly help you understand the sample applications. To run the sample applications, you also need to know how to deploy J2EE applications to your application server.

Mobile messaging

Mobile messaging applications have proven extremely successful in the consumer world to support flexible person-to-person communications. However, messaging is much more than interperson communications. The wide use of messaging-oriented middleware (MOM), such as the Java Messaging Service (JMS), has made messaging one of the most important person-to-machine or machine-to-machine integration schemes in modern enterprise applications. Compared with tightly integrated applications, messaging-based solutions are more reliable, flexible, and scalable. Those are critical advantages in the mobile enterprise world. Using iBus//Mobile and IBM WebSphere MQ Everyplace as examples, we discuss design principles of mobile MOM applications. We also walk through sample code for simple applications using both systems.

p2p

SMS-based peer-to-peer (P2P) mobile messaging is already a major revenue source for wireless carriers. It could become mobile commerce's killer application. In the past, SMS (Short Message Service) was a nonprogrammable device native feature. It was difficult to integrate SMS functionalities into custom mobile solutions. But with emerging tools on both the J2ME smart client side and the messaging server side, SMS is becoming increasingly available to enterprise mobile developers. This chapter focuses on the J2ME Wireless Messaging API (WMA), which standardizes SMS APIs for all J2ME platforms. We also discuss third-party tools to integrate SMS functionalities into your J2EE backend applications.

The limitation of SMS is that it works only on the wireless networks. As a result, mobile phone SMS messages cannot reach PDAs in a local WiFi network or PCs using popular Internet instant messaging (IM) systems (e.g., AOL, MSN, Yahoo! IM systems). We also discuss J2ME toolkits and clients for general IP network-based IM systems that can bridge this gap. In particular, a development library for Jabber is discussed.

prog

1 Given

11. public interface Status {

12. /* insert code here */ int MY_VALUE = 10;

13. }

Which three are valid on line 12? (Choose three.)

A. final

B. static

C. native

D. public

E. private

F. abstract

G. protected

Answer: ABD

2. Given:

10. public class Bar {

11. static void foo( int... x ) {

12. // insert code here

13. }

14. }

Which two code fragments, inserted independently at line 12, will allow the class to compile? (Choose two.)

A. foreach( x ) System.out.println(z);

B. for( int z : x ) System.out.println(z);

C. while( x.hasNext() ) System.out.println( x.next() );

D. for( int i=0; i<>

Answer: BD

A program

A programmer is designing a class to encapsulate the information about an inventory item. A JavaBeans component is needed to

do this. The InventoryItem class has private instance variables to store the item information:

10. private int itemId;

11. private String name;

12. private String description;

Which method signature follows the JavaBeans naming standards for modifying the itemId instance variable?

A. itemID(int itemId)

B. update(int itemId)

C. setItemId(int itemId)

D. mutateItemId(int itemId)

E. updateItemID(int itemId)

A Story

Love Good Reading? Click here to Join Group...


One fine day, an old couple around the age of 70, walks into a lawyer's office.


Apparently, they are there to file a divorce.Lawyer was very puzzled, after having a chat with them, he got their story....


This couple had been quarreling all their 40 over yrs of marriage nothing ever seems to go right.They hang on because of their children, afraid that it might affect their up-bringing. Now, all their children have already grown up, have their own family, there's nothing else the old couple have to worry about, all they wanted is to lead their own life free from all these years of unhappiness from their marriage, so both agree on a divorce....



Lawyer was having a hard time trying to get the papers done, because he felt that after 40 yrs of marriage at the age of 70, he couldn't understand why the old couple would still want a divorce..


While they were signing the papers, the wife told the husband..


"I really love u, but I really cant carry on anymore, I'm sorry.."


"Its o.k, I understand.." said the husband. Lookin at this, the lawyer suggested a dinner together, just 3 of them,wife thought, why not, since they are still gonna be friends..


At the dining table, there was a silence of awkardness.


The first dish was roasted chicken, immediately, the old man took the drumstick for the old lady.."take this, its your favourite.."


Looking at this, the lawyer thought maybe theres still a chance, but the wife was frowning when she answer.."This is always the problem, you always think so highly of yourself, never thought about how I feel, don't you know that I hate drumsticks?"


Little did she know that, over the years, the husband have been trying all ways to please her, little did she know that drumsticks was the husband's favourite. Little did he know that she never thought he understand her at all, little did he know that she hates drummsticks even though all he wants is the best for her.


That night, both of them couldn't sleep, toss and turn, toss and turn...after hours, the old man couldn't take it anymore, he knows that he still loves her, and he cant carry on life without her, he wants her back, he wants to tell her, he is sorry, he wanted to tell her "I love you"...


He picks up the phone, starting dialing her number....ringing never stops..he never stop dialing....On the other side, she was sad, she couldn't understand how come after all these years, he still doesn't understand her at all, she loves him a lot, but she just cant take it anymore....phone's ringing, she refuses to answer knowing that its him..."whats the point of talking now that its over...I have ask for it and now I wanna keep it this way, if not I will lose face.."she thought...still ringing...she have decided to pull out the cord... Little did she remember, he have heart problems...


The next day, she received news that he had passed away...she rushed down to his apartment, saw his body, lying on the couch still holding on to the phone...he had a heart attack when he was still trying to get through her phone line....


As sad as she could be...she will have to clear his belongings.. .when she was looking thru the drawers, she saw this insurance policy, dated from the day they got married, with the beneficiary being her... And together in those file, there was this note...



"To my dearest wife, by the time you're reading this, I'm sure I'm no longer around, I bought this policy for you, though the amount is only $100k, I hope it will be able to help me continue my promise that I have made when we got married, I might not be around anymore, I want this amount of money to continue taking care of you, just like the way I will if I could have live longer. I want you to know Iwill always be around, by your side... I love you"


Tears flowed like river......


"When you love someone, let them know... You never know what will happen the next minute.... Learn to build a life together.. Learn to love each other. For who they are.. Not what they are..."