Thursday, February 27, 2014

Tuesday, September 27, 2011

JMS - 1

Messaging systems are
composed of messaging clients and some kind of messaging middleware server. The clients send messages to the messaging server, which then distributes those messages
to other clients. The client is a business application or component that is using the
messaging API (in our case, JMS).


Centralized Architectures


Enterprise messaging systems that use a centralized architecture rely on a message
server. A message server, also called a message router or broker, is responsible for delivering messages from one messaging client to other messaging clients.


Decentralized Architectures


All decentralized architectures currently use IP multicast at the network level. A messaging system based on multicasting has no centralized server.

Messaging Models


JMS supports two types of messaging models: point-to-point and publish-andsubscribe.
These messaging models are sometimes referred to as messaging domains.
Point-to-point messaging and publish-and-subscribe messaging are frequently shortened
to p2p and pub/sub, respectively.

In the simplest sense, publish-and-subscribe is intended for a one-to-many broadcast
of messages, while point-to-point is intended for one-to-one delivery of messages.


From a JMS perspective, messaging clients are called JMS clients, and the messaging system is called the JMS provider. A JMS application is a business system composed of many JMS clients and, generally, one JMS provider.

In addition, a JMS client that produces a message is called a message producer, while a
JMS client that receives a message is called a message consumer. A JMS client can be both a message producer and a message consumer. When we use the term consumer or producer, we mean a JMS client that consumes messages or produces messages, respectively.

Point-to-Point


The point-to-point messaging model allows JMS clients to send and receive messages
both synchronously and asynchronously via virtual channels known as queues. In the point-to-point model, message producers are called senders and message consumers
are called receivers.

One of the distinguishing characteristics of point-to-point messaging is that messages sent to a queue are received by one and only one receiver, even though there may be many receivers listening on a queue for the same message.

Point-to-point messaging supports asynchronous “fire and forget” messaging as well
as synchronous request/reply messaging. Point-to-point messaging tends to be more
coupled than the publish-and-subscribe model in that the sender generally knows how
the message is going to be used and who is going to receive it.

Publish-and-Subscribe
In the publish-and-subscribe model, messages are published to a virtual channel called
a topic. Message producers are called publishers, whereas message consumers are called
subscribers. Unlike the point-to-point model, messages published to a topic using the publish-and-subscribe model can be received by multiple subscribers. This technique is sometimes referred to as broadcasting a message. Every subscriber receives a copy of
each message. The publish-and-subscribe messaging model is by and large a push-based
model, where messages are automatically broadcast to consumers without them having
to request or poll the topic for new messages.

There are many different types of subscribers within the pub/sub messaging model.
Nondurable subscribers are temporary subscriptions that receive messages only when
they are actively listening on the topic. Durable subscribers, on the other hand, will
receive a copy of every message published, even if they are “offline” when the message
is published. There is also the notion of dynamic durable subscribers and administered durable subscribers.

JMS General API



Within the JMS general API, there are seven main JMS API interfaces related to sending
and receiving JMS messages:
• ConnectionFactory
• Destination
• Connection
• Session
• Message
• MessageProducer
• MessageConsumer

In JMS, the Session object holds the transactional unit of work for messaging, not the
Connection object. This is different from JDBC, where the Connection object holds the
transactional unit of work. This means that when using JMS, an application will typically have only a single Connection object but will have a pool of Session objects.

Point-to-Point API


The interfaces used for sending and
receiving messages from a queue are as follows:
• QueueConnectionFactory
• Queue
• QueueConnection
• QueueSession
• Message
• QueueSender
• QueueReceiver


Publish-and-Subscribe API


The interfaces used within the pub/sub
messaging model are as follows:
• TopicConnectionFactory
• Topic
• TopicConnection
• TopicSession
• Message
• TopicPublisher
• TopicSubscriber


SOA has given rise to a new breed of middleware known as an Enterprise Service
Bus, or ESB.




An InitialContext is the starting point for any JNDI lookup—it’s similar in concept to the root of a filesystem. The InitialContext provides a network connection to the directory service that acts as a root for accessing JMS administered objects. The properties used to create an InitialContext depend on which JMS directory service you are using. You could configure the initial context properties using the Properties Object directly in your source code, or preferably using an external jndi.properties file located in the classpath of the application.

The corresponding source code using the properties object would be as follows:
Properties env = new Properties();
env.put(Context.SECURITY_PRINCIPAL, "system");
env.put(Context.SECURITY_CREDENTIALS, "manager");
env.put(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
env.put(Context.PROVIDER_URL, "tcp://localhost:61616");
InitialContext ctx = new InitialContext(env);


Once a JNDI InitialContext object is instantiated, it can be used to look up the Topic
ConnectionFactory in the messaging server’s naming service:
TopicConnectionFactory conFactory =
(TopicConnectionFactory)ctx.lookup(topicFactory);

The TopicConnectionFactory provides two overloaded versions of the createTopicCon
nection() method:

public TopicConnection createTopicConnection()
throws JMSException, JMSSecurityException;
public TopicConnection createTopicConnection(String username,
String password) throws JMSException, JMSSecurityException;


The TopicConnection is created by the TopicConnectionFactory:
// Look up a JMS connection factory and create the connection
TopicConnectionFactory conFactory =
(TopicConnectionFactory)ctx.lookup(topicFactory);
TopicConnection connection = conFactory.createTopicConnection();

The TopicConnection is an interface that extends javax.jms.Connection interface. It defines several generalpurpose methods used by clients of the TopicConnection. Among these methods are the start() , stop(), and close() methods:

public interface Connection {
public void start() throws JMSException;
public void stop() throws JMSException;
public void close() throws JMSException;
...
}

public interface TopicConnection extends Connection {
public TopicSession createTopicSession(boolean transacted,
int acknowledgeMode)
throws JMSException;


Closing a TopicConnection closes all the objects associated with the connection,
including the TopicSession, TopicPublisher, and TopicSubscriber.

After the TopicConnection is obtained, it’s used to create TopicSession objects:
// Create two JMS session objects
TopicSession pubSession = connection.createTopicSession(
false, Session.AUTO_ACKNOWLEDGE);
TopicSession subSession = connection.createTopicSession(
false, Session.AUTO_ACKNOWLEDGE);


The boolean parameter in the createTopicSession() method indicates whether the
Session object will be transacted.
The second parameter indicates the acknowledgment mode used by the JMS client. An
acknowledgment is a notification to the message server that the client has received the
message. In this case we chose AUTO_ACKNOWLEDGE, which means that the message is
automatically acknowledged after it is received by the client.

The TopicSession objects are used to create the TopicPublisher and TopicSubscriber.
The TopicPublisher and TopicSubscriber objects are created with a Topic identifier and
are dedicated to the TopicSession that created them; they operate under the control of
a specific TopicSession:
TopicPublisher publisher =
pubSession.createPublisher(chatTopic);
TopicSubscriber subscriber =
subSession.createSubscriber(chatTopic);


The TopicSession is also used to create the Message objects that are delivered to the
topic.
TextMessage message = pubSession.createTextMessage();

JNDI is used to locate a Topic object, which is an administered object like the Topic
ConnectionFactory:
InitialContext jndi = new InitialContext(env);
...
// Look up a JMS topic
Topic chatTopic = (Topic)jndi.lookup(topicName);

A Topic object is a handle or identifier for an actual topic, called a physical topic, on the messaging server. A physical topic is an electronic channel to which many clients can subscribe and publish.

The Topic object has one method, getName(), the name identifier for the physical topic it represents.

// Create a JMS publisher and subscriber
TopicSubscriber subscriber =
subSession.createSubscriber(chatTopic, null, true);

A TopicSubscriber receives messages from a specific topic. The Topic object argument
used in the createSubscriber() method identifies the topic from which the TopicSub
scriber will receive messages. The second argument contains the message selector used
to filter out only those messages we want to receive based on certain criteria. In this
case, we set this value to null, indicating that we want to receive all messages. The third argument contains a boolean value indicating whether or not we want to receive messages we publish ourselves. In this case, we are setting the value to true, indicating that, as a subscriber to the topic, we do not want to see messages we publish.

The pub/sub messaging model in JMS includes an in-process Java event model for
handling incoming messages. This is similar to the event-driven model used by Java-
Beans.‡ An object simply implements the listener interface, in this case the MessageLis
tener, and then is registered with the TopicSubscriber. A TopicSubscriber may have
only one MessageListener object. Here is the definition of the MessageListener

interface
used in JMS:
package javax.jms;
public interface MessageListener {
public void onMessage(Message message);
}

A message has three parts: a header, properties, and payload.

Message
This type has no payload. It is useful for simple event notification.

TextMessage
This type carries a java.lang.String as its payload. It is useful for exchanging
simple text messages and also for more complex character data, such as XML
documents.

ObjectMessage
This type carries a serializable Java object as its payload. It’s useful for exchanging
Java objects.

BytesMessage
This type carries an array of primitive bytes as its payload. It’s useful for exchanging
data in an application’s native format, which may not be compatible with other
existing Message types. It is also useful where JMS is used purely as a transport
between two systems, and the message payload is opaque to the JMS client.

StreamMessage
This type carries a stream of primitive Java types (int, double, char, etc.) as its
payload. It provides a set of convenience methods for mapping a formatted stream
of bytes to Java primitives. It’s an easy programming model when exchanging
primitive application data in a fixed order.

MapMessage
This type carries a set of name-value pairs as its payload. The payload is similar to
a java.util.Properties object, except the values must be Java primitives or their
wrappers. The MapMessage is useful for delivering keyed data.


JMS consumers
can choose to receive messages based on the values of certain headers and
properties, using a special filtering mechanism called message selectors.

Automatically assigned headers



There are two types of delivery modes in JMS: persistent and nonpersistent. A persistent message should be delivered once-and-only-once, which means that if the JMS provider fails, the message is not lost; it will be delivered after the server recovers. A nonpersistent message is delivered at-most-once, which means that it can be lost permanently if the JMS provider fails.

JMSDeliveryMode and the JMSPriority headers

int deliverymode = message.getJMSDeliveryMode();
if (deliverymode == javax.jms.DeliveryMode.PERSISTENT) {
...
} else { // equals DeliveryMode.NON_PERSISTENT
...
}

// Set the JMS delivery mode on the message producer
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

String messageid = message.getJMSMessageID();

long timestamp = message.getJMSTimestamp();

long timeToLive = message.getJMSExpiration();

TopicPublisher topicPublisher = topicSession.createPublisher(topic);
// Set time to live as 1 hour (1000 millis x 60 sec x 60 min)
topicPublisher.setTimeToLive(3600000);

boolean isRedelivered = message.getJMSRedelivered()

There are two categories of message priorities: levels 0–4 are gradations of normal priority, and levels 5–9 are gradations of expedited priority. The message servers may use a message’s priority to prioritize delivery of messages to consumers—messages with an expedited priority are delivered ahead of normal priority messages:
int priority = message.getJMSPriority();

The priority of messages can be declared by the JMS client using the setPriority()
method on the producer:

TopicPublisher topicPublisher = TopicSession.createPublisher(someTopic);
topicPublisher.setPriority(9);

Any direct programmatic invocation of the setJMSPriority() method will be ignored
when the message is sent.

Developer assigned headers


message.setJMSReplyTo(topic);
...
Topic topic = (Topic) message.getJMSReplyTo();

message.setJMSCorrelationID(identifier);
...
String correlationid = message.getJMSCorrelationID();

Properties



There are three basic categories of message properties: application-specific properties,JMS-defined properties, and provider-specific properties. Application properties are defined and applied to Message objects by the application developer; the JMS extension and provider-specific properties are additional headers that are, for the most part, automatically added by the JMS provider.

message.setStringProperty("username",username);
Property values can be any boolean, byte, short, int, long, float, double, or String.



Message
CF - connection - session - /_ MessageProducer ---|
\ MessageConsumer ---|
| |
| |
Destination --------------------------------------


Point-to-Point API
Message
QCF - Qconnection - Qsession - /_ QueueSender ---|
\ QueueReceiver--|
| |
| |
Queue -------------------------------------------

Publish-and-Subscribe API

Message
TCF - TConnection - TSession - /_ TopicPublisher--|
\ TopicSubscriber-|
| |
| |
Topic---------------------------------------------


public interface Message{
....
public short getShortProperty(String name)
throws JMSException, MessageFormatException;

public void setShortProperty(String name, short value)
throws JMSException, MessageNotWriteableException;

public Object getObjectProperty(String name)
throws JMSException, MessageFormatException;

public void setObjectProperty(String name, Object value)
throws JMSException, MessageNotWriteableException;

public void clearProperties()
throws JMSException;

public Enumeration getPropertyNames()
throws JMSException;

public boolean propertyExists(String name)
throws JMSException;
}

The properties can, however, be changed on that message by calling the method
clearProperties(), which removes all the properties from the message so that new ones
can be added.


Note that in the Message interface you will not find corresponding setJMSXERTY>() and getJMSX() methods defined; when used, they must be set in the
same manner as application-specified properties:

message.setStringProperty("JMSXGroupID", "ERF-001");
message.setIntProperty("JMSXGroupSeq", 3);

Provider-Specific Properties


Every JMS provider can define a set of proprietary properties that can be set by the
client or the provider automatically. Provider-specific properties must start with the
prefix JMS followed by the property name (JMS_). The purpose
of the provider-specific properties is to support proprietary vendor features.

Message Types


The six message interfaces are Message and its five subinterfaces:
TextMessage, StreamMessage, MapMessage, ObjectMessage, and BytesMessage.

-------------------
As shown below, the Message type can be created and
used as a JMS message with no payload:
// Create and deliver a Message
Message message = session.createMessage();
publisher.publish(message);
...
// Receive a message on the consumer
public void onMessage(Message message) {
// No payload, just process event notification
}

This type of message contains only JMS headers and properties and is used in event
notification.
-------------------
TextMessage textMessage = session.createTextMessage();
textMessage.setText("Hello!");
topicPublisher.publish(textMessage);
...

TextMessage textMessage = session.createTextMessage("Hello!");
queueSender.send(textMessage);
-------------------
// Order is a serializable object
Order order = new Order( );
...
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setObject(order);
queueSender.send(objectMessage);
...
ObjectMessage objectMessage = session.createObjectMessage(order);
topicPublisher.publish(objectMessage);

-------------------
BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.writeChar('R');
bytesMessage.writeInt(10);
bytesMessage.writeUTF("OReilly");
queueSender.send(bytesMessage);

On the surface, the StreamMessage strongly resembles the BytesMessage, but they are
not the same. The StreamMessage keeps track of the order and types of primitives written.For example, an exception would be
thrown if you tried to read a long value as a short:

-------------------
StreamMessage streamMessage = session.createStreamMessage();
streamMessage.writeLong(2938302);
// The next line throws a JMSException
short value = streamMessage.readShort()
-------------------
MapMessage mapMessage = session.createMapMessage();
mapMessage.setInt("Age", 88);
mapMessage.setFloat("Weight", 234);
mapMessage.setString("Name", "Smith");
mapMessage.setObject("Height", new Double(150.32));
....
int age = mapMessage.getInt("Age");
float weight = mapMessage.getFloat("Weight");
String name = mapMessage.getString("Name");
Double height = (Double)mapMessage.getObject("Height");

To avoid reading nonexistent name-value pairs, the MapMessage provides an
itemExists() test method. In addition, the getMapNames() method lets a JMS client
enumerate the names and use them to obtain all the values in the message. For example:

public void onMessage(Message message) {
MapMessage mapMessage = (MapMessage)message;
Enumeration names = mapMessage.getMapNames();
while(names.hasMoreElements()){
String name = (String)names.nextElement();
Object value = mapMessage.getObject(name);
System.out.println("Name = "+name+", Value = "+value);
}
}


Read Only Messages


There are three acknowledgment modes that may be set by the JMS consumer when its session is created: AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE, and CLIENT_ACKNOWLEDGE. Here is how a pub/sub consumer sets one of the three acknowledgment modes:

TopicSession topic = topicConnection.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);

In CLIENT_ACKNOWLEDGE mode, the JMS consumer (client) explicitly acknowledges each message as it is received. The acknowledge() method on the Message interface is used
for this purpose. For example:

public void onMessage(Message message) {
message.acknowledge();
...
}

Chapter 4 - Point-to-Point Messaging



Chapter 5 - Publish-and-Subscribe Messaging



Each message is delivered to multiple message consumers, called subscribers.
There are many types of subscribers, including durable, nondurable, and dynamic.

Another major difference between the pub/sub and p2p models is that, with the pub/
sub model, message selectors are applied when the message is copied to each subscriber;
whereas with the p2p model, message selectors are applied after the message has been
added to the queue.

The important point here is that multiple consumers may consume the message.

Monday, September 26, 2011

JWS - reference

Two ways to publish a web service using endpoint

Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());

Endpoint endpoint = Endpoint.create(new TimeServerImpl());
endpoint.publish(url);

2 ways to create a client:

QName qname = new QName("http://ts.ch01/", "TimeServerImplService");
Service service = Service.create(url, qname);
TimeServer eif = service.getPort(TimeServer.class);


or if you have already generated the artifacts with wsimport

TeamsService service = new TeamsService();
Teams port = service.getTeamsPort();


Document VS RPC
Under the rpc style, the messages are named but not explicitly typed; under the
document style, the messages are explicitly typed in an XSD document.

WRAPPED vs UNWRAPPED
The body of the unwrapped SOAP request envelope has two elements, named num1 and num2. These are numbers to be added. The SOAP body does not contain the name of the service operation that is to perform the addition and send the sum as a response. By contrast, the body of a wrapped SOAP request envelope has a single element named addNums, the name of the requested service operation, and two subelements, each holding a number to be added. The wrapped version makes the service operation explicit. The arguments for the operation are nested in an intuitive manner; that is, as subelements within the operation element addNums.

Guidelines for the wrapped document convention are straightforward. Here is a summary of the guidelines:

The SOAP envelope's body should have only one part, that is, it should contain a single XML element with however many XML subelements are required. For example, even if a service operation expects arguments and returns a value, the parameters and return value do not occur as standalone XML elements in the SOAP body but, rather, as XML subelements within the main element. Example 2-9 illustrates with the addNums element as the single XML element in the SOAP body and the pair num1 and num2 as XML subelements.

The relationship between the WSDL's XSD and the single XML element in the SOAP body is well defined. The document-style version of the TimeServer can be used to illustrate. In the XSD, there are four XSD complexType elements, each of which defines a data type. For example, there is a complexType with the name getTimeAsString and another with the name getTimeAsStringResponse. These definitions occur in roughly the bottom half of the XSD. In the top half are XML element definitions, each of which has a name and a type attribute. The complexTypes also have names, which are coordinated with the element names. For example, the complexType named getTimeAsString is matched with an element of the same name. Here is a segment of the XSD that shows the name coordination:

<xs:element name="getTimeAsString"
type="tns:getTimeAsString">
</xs:element>
<xs:element name="getTimeAsStringResponse"
type="tns:getTimeAsStringResponse">
</xs:element>
...
<xs:complexType name="getTimeAsString"></xs:complexType>
<xs:complexType name="getTimeAsStringResponse">
<xs:sequence>
<xs:element name="return"
type="xs:string" minOccurs="0">
</xs:element>
</xs:sequence>
</xs:complexType>

Further, each complexType is either empty (for instance, getTimeAsString) or contains an xs:sequence (for instance, getTimeAsStringResponse, which has an xs:sequence of one XML element). The xs:sequence contains typed arguments and typed returned values. The TimeServer example is quite simple in that the requests contain no arguments and the responses contain just one return value. Nonetheless, this segment of XSD shows the structure for the general case. For instance, if the getTimeAsStringResponse had several return values, then each would occur as an XML subelement within the xs:sequence. Finally, note that every XML element in this XSD segment (and, indeed, in the full XSD) is named and typed.

The XML elements in the XSD serve as the wrappers for the SOAP message body. For the ch01.ts.TimeServer, a sample wrapped document is:

<?xml version="1.0" ?>
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.or g/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soapenv:Body>
<ans:getTimeAsElapsedResponse xmlns:ans="http://ts.ch01/">
<return>1205030105192</return>
</ans:getTimeAsElapsedResponse>
</soapenv:Body>
</soapenv:Envelope>

This is the same kind of SOAP body generated for an rpc-style service, which is precisely the point. The difference, again, is that the wrapped document-style service, unlike its rpc-style counterpart, includes explicit type and format information in an XSD from the WSDL's types section.

The request wrapper has the same name as the service operation (for instance, addNums in Example 2-9), and the response wrapper should be the request wrapper's name with Response appended (for instance, addNumsResponse).

The WSDL portType section now has named operations (e.g., getTimeAsString) whose messages are typed. For instance, the input (request) message getTimeAsString has the type tns:getTimeAsString, which is defined as one of the four complexTypes in the WSDL's XSD. For the document-style version of the service, here is the portType segment:

<portType name="TimeServer">
<operation name="getTimeAsString">
<input message="tns:getTimeAsString"></input>
<output message="tns:getTimeAsStringResponse"></output>
</operation>
<operation name="getTimeAsElapsed">
<input message="tns:getTimeAsElapsed"></input>
<output message="tns:getTimeAsElapsedResponse"></output>
</operation>
</portType>

The wrapped document convention, despite its unofficial status, has become prevalent. JWS supports the convention. By default, a Java SOAP-based web service is wrapped doc/lit, that is, wrapped document style with literal encoding.

JAXB


JAX-B supports conversions between Java and XML types.

The @XmlType and @XmlRootElement annotations direct the marshaling of Skier objects, where marshaling is the process of encoding an in-memory object (for example, a Skier) as an XML document so that, for instance, the encoding can be sent across a network to be unmarshaled or decoded at the other end. In common usage, the distinction between marshal and unmarshal is very close and perhaps identical to the serialize/deserialize distinction. I use the distinctions interchangeably. JAX-B supports the marshaling of in-memory Java objects to XML documents and the unmarshaling of XML documents to in-memory Java objects.

The annotation @XmlType, applied in this example to the Person class, indicates that JAX-B should generate an XML Schema type from the Java type. The annotation @XmlRootElement, applied in this example to the Skier class, indicates that JAX-B should generate an XML document (outermost or root) element from the Java class. Accordingly, the resulting XML in this example is a document whose outermost element represents a skier; and the document has a nested element that represents a person.

Marshaling
JAXBContext ctx = JAXBContext.newInstance(Skier.class);
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

// Marshal a Skier object: 1st to stdout, 2nd to file
Skier skier = createSkier();
m.marshal(skier, System.out);


Unmarshaling
Unmarshaller u = ctx.createUnmarshaller();
Skier bd_clone = (Skier) u.unmarshal(new File(file_name));


@XmlRootElement(name = "getTimeAsElapsedResponse", namespace = "http://ts.ch02/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getTimeAsElapsedResponse", namespace = "http://ts.ch02/")
public class GetTimeAsElapsedResponse {
@XmlElement(name = "return", namespace = "")
private long _return;
public long get_return() { return this._return; }

public void set_return(long _return) { this._return = _return; }
}



The annotation in bold indicates that the field named _return will be marshaled and unmarshaled rather than a property defined with a get/set method pair that follows the usual JavaBean naming conventions.

Other annotation attributes can be set to override the default naming conventions. For example, if the annotation in the Skier class declaration is changed to:

@XmlRootElement(name = "NordicSkier")

then the resulting XML document begins:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<NordicSkier>

eclipse

syso

ctrl +1 - quick fix

Tuesday, September 20, 2011

JWS - week 3

So far web services have been deployed using either Endpoint, HttpsServer, or Tomcat.


A JAS is a: Web Container, Message-oriented middleware,
Enterprise Java Bean (EJB) container.

JMS topics implement the publisher/subscriber model of messaging, whereas JMS queues implement the point-to-point model.


The endpoint is different when deployed as an EJB
The endpoint URL for the EJB-based web service differs from WAR examples seen so far. For one thing, the name of the EAR file does not occur in the path as does the name of a WAR file. There are two pieces in the path section of the URL: the first is the SIB name with Service appended, giving FibEJBService in this example; the second is the SIB name, in this case FibEJB. The combination is shown in the URL below for the sample Perl client:

#!/usr/bin/perl -w
use SOAP::Lite;
use strict;
my $url = 'http://localhost:8081/FibEJBService/FibEJB?wsdl';
my $service = SOAP::Lite->service($url);
print $service->fib(7), "\n";

Monday, September 12, 2011

JWS - week 2

wsimport vs wsgen



The wsimport tool generates JAX-WS portable artifacts used in JAX-WS clients and services. The tool reads a WSDL and generates all the required artifacts for web service development, deployment, and invocation.



  • In the working directory, invoke the wsimport utility, which likewise comes with core Java 6:

    % wsimport -p teamsC -keep http://localhost:8888/teams?wsdl

    This utility generates various classes in the subdirectory teamsC (the -p flag stands for package). These classes make it easier to write a client against the service.


  • % wsimport

    displays a short report on how the utility can be used. The first example with wsimport produces client artifacts against the TimeServer service.

    After the ch01.ts.TimeServerPublisher application has been started, the command:
    % wsimport -keep -p client http://localhost:9876/ts?wsdl
    generates two source and two compiled files in the subdirectory client.


  • wsimport -keep -p client ts.wsdl






The wsgen tool reads a service endpoint implementation class and generates all of the portable artifacts for a JAX-WS web service..



  • The wsgen utility also can be used to generate a WSDL document for a web service. For example, the command:

    % wsgen -cp "." -wsdl ch01.ts.TimeServerImpl


  • The wsgen utility produces the classes required to build the WSDL, classes known as wsgen artifacts. The command:

    % wsgen -keep -cp . ch01.ts.TimeServerImpl



MessageContext, which is normally accessed in handlers: the subtypes SOAPMessageContext and LogicalMessageMessageContext are the parameter types, for example, in the handleMessage callbacks of SOAP and logical handlers, respectively.

In a handler or SIB, Java provides access to HTTP messages in a MessageContext. In a Java-based client, Java likewise gives access to the HTTP level but in this case through the BindingProvider and the request/response contexts, which are exposed as BindingProvider properties. The code examples illustrate application-level as opposed to handler-level access to transport messages.


SOAP Attachments


There are basically three options for SOAP attachments: SwA (SOAP with Attachments), the original SOAP specification for attachments; DIME (Direct Internet Message Encapsulation), a lightweight but by now old-fashioned encoding scheme for attachments; and MTOM (Message Transmission Optimization Mechanism), which is based on XOP (XML-Binary Optimized Packaging). JWS has a DIME extension whose main purpose is to interoperate with Microsoft clients. Up until the release of Microsoft Office 2003, a web service client written in Visual Basic for Applications (VBA) could handle only DIME rather than MTOM attachments. The SwA approach has drawbacks. For one, it is hard to use SwA with a document-style service, which is now the norm. Further, frameworks such as DotNet do not support SwA. MTOM has the W3C stamp of approval and enjoys widespread support; hence, MTOM is the efficient, modern, interoperable way to transmit binary data in SOAP-based web services.

REST


As Web-based informational items, resources are pointless unless they have at least one representation. In the Web, representations are MIME-typed. The most common type of resource representation is probably still text/html, but nowadays resources tend to have multiple representations.

The RESTful approach keeps the complexity out of the transport level, as a resource representation is transferred to the client as the body of an HTTP response message. By contrast, a SOAP-based service inevitably complicates the transport level because a SOAP message is encapsulated as the body of a transport message; for instance, an HTTP or SMTP message. SOAP requires messages within messages, whereas REST does not.

The @WebService annotation signals that the messages exchanged between the service and its clients will be SOAP envelopes. The @WebServiceProvider signals that the exchanged messages will be XML documents of some type, a notion captured in the phrase raw XML

A service annotated with @WebServiceProvider implements the Provider interface, which requires that the invoke method:

public Source invoke(Source request)

be defined. This method expects a Source of bytes (for instance, the bytes in an XML document that represents the service request) and returns a Source of bytes (the bytes in the XML response).

A RESTful Provider implements the method:

public Source invoke(Source request)

and a Dispatch object, sometimes described as a dynamic service proxy, provides an implementation of this method on the client side. Recall that a Source is a source of an XML document suitable as input to a Transform, which then generates a Result that is typically an XML document as well. The Dispatch to Provider relationship supports a natural exchange of XML documents between client and service:

The client invokes the Dispatch method invoke, with an XML document as the Source argument. If the request does not require an XML document, then the Source argument can be null.

The service-side runtime dispatches the client request to the Provider method invoke whose Source argument corresponds to the client-side Source.

The service transforms the Source into some appropriate Result (for instance, a DOM tree), processes this Result in an application-appropriate way, and returns an XML source to the client. If no response is needed, null can be returned.

The Dispatch method invoke returns a Source, sent from the service, that the client then transforms into an appropriate Result and processes as needed.

The fact that the Provider method invoke and the Dispatch method invoke have the same signature underscores the natural fit between them.

WADL stands for Web Application Description Language

JAX-RS (Java API for XML-RESTful Web Services)

For now, JAX-WS and For now, JAX-WS and JAX-RS are separate frameworks. It would not be surprising if, in the future, the two frameworks merged are separate frameworks. It would not be surprising if, in the future, the two frameworks merged.

Java Web Services Security


HTTPS (HyperText Transport Protocol over Secure Socket Layer)

Java has various packages that support SSL/TLS in general and HTTPS in particular. JSSE (Java Secure Sockets Extension) has been part of core Java since JDK 1.4.


  1. Peer authentication

    Alice needs Bob to authenticate himself so that she is sure about who is on the receiving end before she sends the secret message. Bob, too, needs Alice to authenticate herself so that he knows that the secret message is from her rather than an impostor such as Eve. This step also is described as mutual authentication or mutual challenge.


  2. Confidentiality

    Once Alice and Bob have authenticated each other, Alice needs to encrypt the secret message in such a way that only Bob can decrypt it. Even if Eve intercepts the encrypted message, she should not be able to decrypt the message because doing so requires enormous computational power or incredibly good luck.


  3. Integrity

    The message that Alice sends should be identical to the one that Bob receives. If not, an error condition should be raised. The received message might differ from the sent one for various reasons; for instance, noise in the communications channel or deliberate tampering by Eve. Any difference between the sent and the received message should be detected.



Symmetric Encryption/Decryption
Modern approaches to encryption follow two different approaches, symmetric and asymmetric. Under either approach, the bits to be encrypted (plain bits) are one input to an encryption engine and an encryption key is the other input (see Figure 5-3). The encrypted bits are the cipher bits. If the input bits represent text, then they are the plaintext and the output bits are the ciphertext. The cipher bits are one input to the decryption engine, and a decryption key is the other input. The decryption produces the original plain bits. In the symmetric approach, the same key—called the secret key or the single key—is used to encrypt and decrypt (see Figure 5-4). The symmetric approach has the advantage of being relatively fast, but the disadvantage of what is known as the key distribution problem. How is the secret key itself to be distributed to the sender and the receiver?

Asymmetric Encryption/Decryption
In the asymmetric approach, the starting point is a key pair, which consists of a private key and a public key. As the names suggest, the private key should not be distributed but safeguarded by whoever generated the key pair. The public key can be distributed freely and publicly. If message bits are encrypted with the public key, they can be decrypted only with the private key, and vice-versa. Figure 5-5 illustrates. The asymmetric approach solves the key distribution problem, but asymmetric encryption and decryption are roughly a thousand times slower than their symmetric counterparts.

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />

The clientAuth attribute is set to false, thereby indicating that Tomcat does not challenge the client. The default client behavior is to challenge the server.

Monday, September 5, 2011

JWS

WS

  • SOAP

  • REST



Simple Object Access Protocol (Service Oriented Architecture)
Representational State Transfer


A SOAP-based web service could be implemented as a single Java class but, following best practices, there should be an interface that declares the methods, which are the web service operations, and an implementation, which defines the methods declared in the interface. The interface is called the SEI: Service Endpoint Interface. The implementation is called the SIB: Service Implementation Bean


The other WSDL section of interest is the last, the service section, and in particular the service location, in this case the URL http://localhost:9876/ts. The URL is called the service endpoint and it informs clients about where the service can be accessed.


message exchange pattern (MEP)—request/response

WSDL - web service definition language

A SOAP-based web service should provide, as a WSDL document, a service contract for its potential clients. So far we have seen how a Perl, a Ruby, and a Java client can request the WSDL at runtime for use in the underlying SOAP libraries. Chapter 2 studies the WSDL more closely and illustrates how it may be used to generate client-side artifacts such as Java classes, which in turn ease the coding of web service clients. The Java clients in Chapter 2 will not be written from scratch, as is our first Java client. Instead such clients will be written with the considerable aid of the wsimport utility, as was the TeamClient shown earlier. Chapter 2 also introduces JAX-B (Java API for XML-Binding), a collection of Java packages that coordinate Java data types and XML data types. The wsgen utility generates JAX-B artifacts that play a key role in this coordination; hence, wsgen also will get a closer look.

XML-qualified name (a Java QName), which in turn consists of the service's local name (in this case, TimeServerImplService) and a namespace identifier (in this case, the URI http://ts.ch01/)

Building a client for the web service
wsimport -keep -p client http://localhost:9876/ts?wsdl
wsimport -keep -p client ts.wsdl

@WebMethod
@WebResult(partName = "time_response")
String getTimeAsString();


2.2 WSDL Structure
At a high level, a WSDL document is a contract between a service and its consumers. The contract provides such critical information as the service endpoint, the service operations, and the data types required for these operations. The service contract also indicates, in describing the messages exchanged in the service, the underlying service pattern, for instance, request/response or solicit/response. The outermost element (called the document or root element) in a WSDL is named definitions because the WSDL provides definitions grouped into the following sections:

The types section, which is optional, provides data type definitions under some data type system such as XML Schema. A particular document that defines data types is an XSD (XML Schema Definition). The types section holds, points to, or imports an XSD. If the types section is empty, as in the case of the TimeServer service, then the service uses only simple data types such as xsd:string and xsd:long.

Although the WSDL 2.0 specification allows for alternatives to XML Schema (see http://www.w3.org/TR/wsdl20-altschemalangs), XML Schema is the default and the dominant type system used in WSDLs. Accordingly, the following examples assume XML Schema unless otherwise noted.

The message section defines the messages that implement the service. Messages are constructed from data types either defined in the immediately preceding section or, if the types section is empty, available as defaults. Further, the order of the messages indicates the service pattern. Recall that, for messages, the directional properties in and out are from the service's perspective: an in message is to the service, whereas an out message is from the service. Accordingly, the message order in/out indicates the request/response pattern, whereas the message order out/in indicates the solicit/response pattern. For the TimeServer service, there are four messages: a request and a response for the two operations, getTimeAsString and getTimeAsElapsed. The in/out order in each pair indicates a request/response pattern for the web service operations.

The portType section presents the service as named operations, with each operation as one or more messages. Note that the operations are named after methods annotated as @WebMethods, a point to be discussed in detail shortly. A web service's portType is akin to a Java interface in presenting the service abstractly, that is, with no implementation details.

The binding section is where the WSDL definitions go from the abstract to the concrete. A WSDL binding is akin to a Java implementation of an interface (that is, a WSDL portType). Like a Java implementation class, a WSDL binding provides important concrete details about the service. The binding section is the most complicated one because it must specify these implementation details of a service defined abstractly in the portType section:

The transport protocol to be used in sending and receiving the underlying SOAP messages. Either HTTP or SMTP (Simple Mail Transport Protocol) may be used for what is called the application-layer protocol; that is, the protocol for transporting the SOAP messages that implement the service. HTTP is by far the more popular choice. The WSDL for the TimeServer service contains this segment:

transport="http://schemas.xmlsoap.org/soap/http">

The value of the transport attribute signals that the service's SOAP messages will be sent and received over HTTP, which is captured in the slogan SOAP over HTTP.

The style of the service, shown earlier as the value of the style attribute, takes either rpc or document as a value. The document style is the default, which explains why the SEI for the TimeServer service contains the annotation:

@SOAPBinding(style = Style.RPC)

This annotation forces the style attribute to have the value rpc in the Java-generated WSDL. The difference between the rpc and the document style will be clarified shortly.

The data format to be used in the SOAP messages. There are two choices, literal and encoded. These choices also will be clarified shortly.

The service section specifies one or more endpoints at which the service's functionality, the sum of its operations, is available. In technical terms, the service section lists one or more port elements, where a port consists of a portType (interface) together with a corresponding binding (implementation). The term port derives from distributed systems. An application hosted at a particular network address (for instance, 127.0.0.1) is available to clients, local or remote, through a specified port. For example, the TimeServer application is available to clients at port 9876.


By default, a Java SOAP-based web service is wrapped doc/lit, that is, wrapped document style with literal encoding.

The @XmlType and @XmlRootElement annotations direct the marshaling of Skier objects, where marshaling is the process of encoding an in-memory object (for example, a Skier) as an XML document so that, for instance, the encoding can be sent across a network to be unmarshaled or decoded at the other end. In common usage, the distinction between marshal and unmarshal is very close and perhaps identical to the serialize/deserialize distinction. I use the distinctions interchangeably. JAX-B supports the marshaling of in-memory Java objects to XML documents and the unmarshaling of XML documents to in-memory Java objects.

The annotation @XmlType, applied in this example to the Person class, indicates that JAX-B should generate an XML Schema type from the Java type. The annotation @XmlRootElement, applied in this example to the Skier class, indicates that JAX-B should generate an XML document (outermost or root) element from the Java class. Accordingly, the resulting XML in this example is a document whose outermost element represents a skier; and the document has a nested element that represents a person.

JAX-B JAVA To XML Binding

@XmlRootElement(name = "getTimeAsElapsedResponse", namespace = "http://ts.ch02/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getTimeAsElapsedResponse", namespace = "http://ts.ch02/")
public class GetTimeAsElapsedResponse {
@XmlElement(name = "return", namespace = "")
private long _return;
public long get_return() { return this._return; }

public void set_return(long _return) { this._return = _return; }
}


@XmlRootElement(name = "NordicSkier")

How the wsgen utility and the JAX-B packages interact in JWS now can be summarized. A Java web service in document rather than rpc style has a nonempty types section in its WSDL. This section defines, in the XML Schema language, the types required for the web service. The wsgen utility generates, from the SIB, Java classes that are counterparts of XSD types. These wsgen artifacts are available for the underlying JWS libraries, in particular for the JAX-B family of packages, to convert (marshal) instances of Java types (that is, Java in-memory objects) into XML instances of XML types (that is, into XML document instances that satisfy an XML Schema document). The inverse operation is used to convert (unmarshal) an XML document instance to an in-memory object, an object of a Java type or a comparable type in some other language. The wsgen utility thus produces the artifacts that support interoperability for a Java-based web service. The JAX-B libraries provide the under-the-hood support to convert between Java and XSD types. For the most part, the wsgen utility can be used without our bothering to inspect the artifacts that it produces. For the most part, JAX-B remains unseen infrastructure.

SOAP Message

Optional SOAP Header \_ SOAP Envelope
Required SOAP Body /

Optional SOAP attachments


SOAP handlers


Recall that a SOAP envelope has a required body, which may be empty, and an optional header. An intermediary should inspect and process only the elements in the SOAP header rather than anything in the SOAP body, which carries whatever cargo the sender intends for the ultimate receiver alone. The header, by contrast, is meant to carry whatever meta-information is appropriate for either the ultimate receiver or intermediaries.

JWS provides a handler framework that allows application code to inspect and manipulate outgoing and incoming SOAP messages. A handler can be injected into the framework in two steps:


  1. One step is to create a handler class, which implements the Handler interface in the javax.xml.ws.handler package. JWS provides two Handler subinterfaces, LogicalHandler and SOAPHandler. As the names suggest, the LogicalHandler is protocol-neutral but the SOAPHandler is SOAP-specific. A LogicalHandler has access only to the message payload in the SOAP body, whereas a SOAPHandler has access to the entire SOAP message, including any optional headers and attachments. The class that implements either the LogicalHandler or the SOAPHandler interface needs to define three methods for either interface type, including handleMessage, which gives the programmer access to the underlying message. The other two shared methods are handleFault and close. The SOAPHandler interface requires the implementation to define a fourth method, getHeaders.


  2. The other step is to place a handler within a handler chain. This is typically done through a configuration file, although handlers also can be managed through code.


JWS has two different ways to throw SOAP faults and the example illustrates both. The simplest way is to extend the Exception class (for example, with a class named FibException) and to throw the exception in a @WebMethod whenever appropriate. JWS then automatically maps the Java exception to a SOAP fault. The other way, which takes more work, is to throw a fault from a handler. In this case, a SOAPFaultException is created and then thrown.

The top-to-bottom sequence of the handlers in the configuration file determines the order in which handler methods of one type (e.g., SOAPHandler) execute. The runtime ordering may differ from the order given in the configuration file. Here is the reason:


  • For an outbound message (for instance, a client request under the request/response MEP), the handleMessage method or handleFault method in a LogicalHandler code execute before their counterparts in a SOAPHandler.



  • For an inbound message, the handleMessage method or handleFault method in a SOAPHandler code execute before their counterparts in a LogicalHandler.