J2EE documentation

What is what

The JAXM API conforms to the Simple Object Access Protocol (SOAP) 1.1 specification and the SOAP with Attachments specification. The complete JAXM API is presented in two packages:

  • javax.xml.soap – the package defined in the SOAP with Attachments API for Java (SAAJ) 1.1 specification. This is the basic package for SOAP messaging, which contains the API for creating and populating a SOAP message.
  • javax.xml.messaging – the package defined in the JAXM 1.1 specification. This package contains the API needed for using a messaging provider and thus for being able to send one-way messages.

JAX-RPC stands for Java API for XML-based RPC. It's an API for building Web services and clients that used remote procedure calls (RPC) and XML.

JMS

Sequence

  • Instantiate connection factory:
    QueueConnectionFactory myQConnFactory = new com.sun.messaging.QueueConnectionFactory();

    or locate in JNDI:

    Context ctx = new InitialContext();
    QueueConnectionFactory myQConnFactory = (QueueConnectionFactory) ctx.lookup("MyQueueConnectionFactory");
  • Create a connection to the message server:
    QueueConnection myQConn = myQConnFactory.createQueueConnection();
  • Create a session within the connection.
    QueueSession myQSess = myQConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
  • Instantiate a Message Queue administered object that corresponds to a queue destination in the message server:
    Queue myQueue = new com.sun.messaging.Queue("world");
  • Create message producer:
    QueueSender myQueueSender = myQSess.createSender(myQueue);
  • Create and send a message to the queue:
    TextMessage myTextMsg = myQSess.createTextMessage();
    myTextMsg.setText("Hello World");
    myQueueSender.send(myTextMsg);
  • Create message consumer:
    QueueReceiver myQueueReceiver = myQSess.createReceiver(myQueue);

    and start it

    myQConn.start();
  • Receive a message from the queue:
    Message msg = myQueueReceiver.receive();
  • Retrieve the contents of the message:
    TextMessage txtMsg = (TextMessage) msg;
    String text = txtMsg.getText();
  • Close the session and connection resources:
    myQSess.close();
    myQConn.close();

Types of domains

  • Publish/subscribe (Topic) domain (one-to-many broadcasting)
  • Point to point (Queue) domain (one-to-one queuing)
  • Unified domain (Topics and Queues)

Connection and session

A connection:

  • Is a relatively heavy-weight object
  • Manages authentication and communication setup that must be done when a connection is created

For this reason, it's a good idea to use as few connections as possible

A session:

  • The real allocation of work occurs in sessions, which are light-weight, single-threaded contexts for producing and consuming messages.
  • Is a factory for its message producers and consumers.
  • Supplies provider-optimized message factories.
  • Supports a single series of transactions that combine work spanning its producers and consumers into atomic units.
  • Defines a serial order for the messages it consumes and the messages it produces.
  • Retains messages until they have been acknowledged.
  • Serializes execution of message listeners registered with its message consumers.

JMS Threading Restrictions

The requirement that sessions be operated on by a single thread at a time places some restrictions on the combination of producers and consumers that can use the same session. In particular, if a session has an asynchronous consumer, it may not have any other synchronous consumers. The Java Messaging Specification mandates that a session not be operated on by more than one thread at a time. This leads to the following restrictions:

  • A session may not have an asynchronous consumer and a synchronous consumer.
  • A session that has an asynchronous consumer can only produce messages from within the onMessage() method (the message listener). The only call that you can make outside the message listener is to close the session.
  • A session may include any number of synchronous consumers, any number of producers, and any combination of the two. That is, the single-thread requirement cannot be violated by these combinations. However, performance may suffer.

Acknowledgement Modes

  • AUTO_ACKNOWLEDGE The system automatically acknowledges a message once the consumer has processed it. This mode guarantees at most one redelivered message after a provider failure.
  • CLIENT_ACKNOWLEDGE The application controls the point at which messages are acknowledged. All messages processed in that session since the previous acknowledgement are acknowledged. If the message server fails while processing a set of acknowledgments, one or more messages in that group might be redelivered. Using this mode is similar to using transactions, except there is no guarantee that all acknowledgments will be processed together if a provider fails during processing.
  • DUPS_OK_ACKNOWLEDGE This mode instructs the system to acknowledge messages in a lazy manner. Multiple messages can be redelivered after a provider failure.
  • NO_ACKNOWLEDGE In this mode, the broker considers a message acknowledged as soon as it has been written to the client. The broker does not wait for an acknowledgement from the receiving client. This mode is best used by typic subscribers who are not worried about reliability.

Types of subscriptions

  • Durable
    Persistent messages are only stored persistently for durable subscriptions, so that should a message server fail, the messages can still be delivered after recovery, when the corresponding consumer becomes active. The Message Queue message server must persistently store the list of messages assigned to each durable subscription so that should a message server fail, the list is available after recovery.
  • Non-Durable
    Persistent messages for non-durable subscriptions are not stored persistently (should a message server fail, the corresponding consumer connection is lost and the message would never be delivered).

Auto-Reconnect

  • Single-Broker Auto-Reconnect: specify one broker address
  • Parallel Broker Auto-Reconnect: specify several broker addresses
  • Clustered-Broker Auto-Reconnect: specify several broker addresses and AddressListBehavior=RANDOM

SOAP

SOAP is a protocol that allows the exchange of structured data between peers in a decentralized, distributed environment.

  • Use JAXMServlet to simplify SOAP service endpoint development
  • Use MessageTransformer.SOAPMessageIntoJMSMessage(SOAPMessage, Session) and MessageTransformer.SOAPMessageFromJMSMessage(Message, MessageFactory) to perform SOAP-to-JMS transformations.

See Creating a SOAP Web Service using Java6 for practical information.

SOAP Messaging Layers

  • The Transport Layer
    Although SOAP messages can be sent using any number of protocols, the SOAP specification defines only the binding with HTTP. SOAP uses the HTTP request/response message model.
  • The SOAP Layer
    This layer specifies the XML scheme used to identify the message parts: envelope, header, body, and attachments.
  • The Language Implementation Layer
    A language implementation allows you to create XML messages that conform to SOAP, using API calls.
  • The Profiles Layer
    A SOAP implementation can offer services that relate to message delivery. These could include reliability, persistence, security, and administrative control, and are typically delivered by a SOAP messaging provider. For example, messaging provider that is implemented to include ebXML capabilities on top of SOAP capabilities is said to support an ebXML profile.

SOAP Packaging Models

  • SOAP message without attachments: (SOAP Message (Envelope (Header, Body)))
  • SOAP message with attachments: (MIME Envelope (Part (Envelope (Header, Body))), (Attachment Part (SOAP Attachment))). Attachments are easy to be created using JAF (no need to define content type, which is auto-detected):
    soapMessage.addAttachmentPart(soapMessage.createAttachmentPart(new DataHandler(new URL("http://greatproducts.com/pics/img.jpg"))));
  • SOAP message with fault: (SOAP Message (Part (Envelope (Header, Body (Fault))))):
    soapBody.addFault().setFaultString("Message does not have necessary info");

Sending SOAP Message

  • If you are working without a messaging provider, you must do the following:
    • Create a SOAPConnectionFactory object.
    • Create a SOAPConnection object.
    • Create a MessageFactory object and use it to create a message.
    • Populate the message.
    • Send the message:
      SOAPMessage response = soapConnection.call(soapMessage, new URL("http://bat.server.com/service"));

      or

      SOAPMessage response = soapConnection.call(soapMessage, new javax.xml.messaging.URLEndpoint("http://somehost/myServlet"));

When the application should be written using the J2SE platform (it is not required to be deployed in J2EE container and no configuration is required), then it may not use messaging provider. Those clients that do not use a messaging provider can be further divided into those that run in a container and those that do not. A JAXM client that does not use a messaging provider and also does not run in a container is called a standalone client.

  • If you are working with a messaging provider, you must do the following:
    • Create a ProviderConnectionFactory object.
    • Get a ProviderConnection object from the provider connection factory.
    • Get a MessageFactory object from the provider connection and use it to create a message.
    • Populate the message.
    • Send the message:
      providerConnection.send(soapMessage);

Advantages of using message provider

  • Transparency
    Messaging provider receives the message and works with other parts of the communications infrastructure to perform various tasks, depending on what the message's header contains and how the messaging provider itself has been implemented. The message arrives at its final destination without your even knowing about the details involved in accomplishing the delivery.
  • Profiles
    Depending on the profile, a new SOAPMessage object will come with certain headers already set. Also a profile implementation may provide API that makes it easier to create a header and set its content. The JAXM reference implementation includes APIs for both the ebXML and SOAP-RP profiles:
    String[] supportedProfiles = providerConnection.getMetaData().getSupportedProfiles();
    if (supportedProfiles.length > 0 && "ebxml".equals(supportedProfiles[0]))
    {
      MessageFactory factory = pcCon.createMessageFactory(supportedProfiles[0]);
     
      com.sun.xml.messaging.ebxml.EbXMLMessageImpl /* is a part of JWSDP */ message = (com.sun.xml.messaging.ebxml.EbXMLMessageImpl) factory.createMessage();
    }
  • Continuously Active
    A JAXM client may make a connection with its provider, send one or more messages, and then close the connection. The provider will store the message and then send it. It will resend a message that was not successfully delivered until it is successfully delivered or until the limit for the number of resends is reached. Also, the provider will stay in a waiting state, ready to receive any messages that are intended for the client. The provider will store incoming messages so that when the client connects with the provider again, the provider will be able to forward the messages.
  • Intermediate Destinations
    When a messaging provider is used, a message can be sent to one or more intermediate destinations before going to the final recipient. These intermediate destinations, called actors, are specified in the message's SOAPHeader object.

JMS and transaction

JMS and JCA

JAX-RPC

JAX-RPC supported types

JAX-RPC supports all primitives except char and java.lang.Char, all collections and user types if user type confirm the following restrictions:

  • It must have a public default constructor.
  • It must not implement (either directly or indirectly) the java.rmi.Remote interface.
  • Its fields must be supported JAX-RPC types.

The class may contain public, private, or protected fields. For its value to be passed (or returned) during a remote call, a field must meet these requirements:

  • A public field cannot be final or transient.
  • A non-public field must have corresponding getter and setter methods.

JAX-RPC remote interface

A service definition interface (remote interface) declares the methods that a remote client may invoke on the service. The interface must conform to a few rules:

  • It extends the java.rmi.Remote interface.
  • It must not have constant declarations, such as public final static.
  • The methods must throw the java.rmi.RemoteException or one of its subclasses. The methods may also additionaly throw service-specific exceptions.
  • Method parameters and return types must be supported JAX-RPC types, mentioned above.

JAX-RPC client proxy types

  • Static stub
    Static stub is generated by wscompile before runtime.
    javax.xml.rpc.Stub stub = (javax.xml.rpc.Stub) (new MyHello_Impl().getHelloIFPort());
    HelloService hello = (HelloService) stub;
    System.out.println(hello.sayHello("Duke!"));

    The code in this example is implementation-specific and might not be portable.

  • Dynamic proxy
    Example calls a remote procedure through a dynamic proxy – a class that is created during runtime. Before creating the proxy class, the client gets information about the service by looking up its WSDL document.
    final String NS = "http://proxy.org/wsdl";
    final String SERVICE_NAME = "HelloWorld";
    final String PORT_NAME = "HelloPort";
    final URL HELLO_WSDL_URL = new URL("http://localhost:8080/ProxyHelloWorld.wsdl");
     
    javax.xml.rpc.Service helloService = javax.xml.rpc.ServiceFactory.newInstance().createService(HELLO_WSDL_URL, new QName(NS, SERVICE_NAME));
    HelloService myProxy = (HelloService) helloService.getPort(new javax.xml.namespace.QName(NS, PORT_NAME), HelloService.class);
    System.out.println(myProxy.sayHello("Duke!"));
  • Dynamic invocation interface
    With the dynamic invocation interface a client can call a remote procedure even if the signature of the remote procedure or the name of the service are unknown until runtime:
    final String ENDPOINT            = "http://localhost:8080/dynamic-jaxrpc/dynamic";
    final String SERVICE_NAME        = "Hello";
    final String PORT_NAME            = "HelloPort";
    final String BODY_NS            = "http://dynamic.org/wsdl";
    final String ENCODING_STYLE_PROPERTY    = "javax.xml.rpc.encodingstyle.namespace.uri";
    final String XSD_NS            = "http://www.w3.org/2001/XMLSchema";
    final String ENCODING_NS        = "http://schemas.xmlsoap.org/soap/encoding/";
     
    javax.xml.rpc.ServiceFactory factory = javax.xml.rpc.ServiceFactory.newInstance();
    javax.xml.rpc.Service service = factory.createService(new QName(SERVICE_NAME));
    javax.xml.rpc.Call call = service.createCall(new QName(PORT_NAME));
    call.setTargetEndpointAddress(ENDPOINT);
    call.setProperty(javax.xml.rpc.Call.SOAPACTION_USE_PROPERTY, new Boolean(true));
    call.setProperty(javax.xml.rpc.Call.SOAPACTION_URI_PROPERTY, "");
    call.setProperty(ENCODING_STYLE_PROPERTY, ENCODING_NS);
    QName QNAME_TYPE_STRING = new QName(XSD_NS, "string");
    call.setReturnType(QNAME_TYPE_STRING);
    call.setOperationName(new QName(BODY_NAMESPACE_VALUE, "sayHello"));
    call.addParameter("String_1", QNAME_TYPE_STRING, javax.xml.rpc.ParameterMode.IN);
    String[] params = { "Duke!" };
     
    System.out.println((String) call.invoke(params));
programming/java/j2ee.txt · Last modified: 2011/01/05 18:31 by dmitry
 
 
Recent changes RSS feed Driven by DokuWiki