Sunday, October 7, 2012

how WSDL tells if WebService is one way or two way.


The port type  should have input and output. input before ouptput indicates that in coming msg shud come before outgoing.

<portType name="BookQuote">
  <operation name="getBookPrice">
     <input name="isbn" message="mh:GetBookPriceRequest"/>
     <output name="price" message="mh:GetBookPriceResponse"/>
     <fault name="InvalidArgumentFault" message="mh:InvalidArgumentFault"/>
     <fault name="SecurityFault" message="mh:SecurityFault"/>
  </operation>
</portType>


and one way messaging is like

<portType name="SubmitPurchaseOrder_PortType">
  <operation name="SubmitPurchaseOrder">
     <input name="order" message="mh:SubmitPurchaseOrderMessage"/>
  </operation>
</portType>

WebService Synchronous & Asynchronous call,


In Synchronous call, if you are making any request, then you will have to wait till the response, you can't do any other thing until you will not get the response.

In Asynchronous call, if you are making any request, then you don't need to wait for the response and you can perform any other task. Whenever the response will come, you can receive in call back delegate.

SOAP With Attachments

SOAP message can handle attachments. there is another api for that SAAJ. SAAJ stands for the "SOAP with Attachments API for Java  -- an offshoot of the Java API for XML Messaging (JAXM) -- automates many of the required steps, such as creating connections or creating and sending the actual messages. This tip chronicles the creation and sending of a synchronous SOAP message.

The process involves five steps:
  1. Creating a SOAP connection
  2. Creating a SOAP message
  3. Populating the message
  4. Sending the message
  5. Retrieving the reply
The figure shows a high-level structure of a SOAP message that has two attachments.



Base on above figure we have following structure of java objects. defined by SAAJ Apis

I. SOAP message

     A. SOAP part

         1. SOAP envelope

              a. SOAP header (optional)

              b. SOAP body

Note: Many SAAJ API interfaces extend DOM interfaces. 

When you create a new SOAPMessage object, it will automatically have the parts that are required to be in a SOAP message. In other words, a newSOAPMessage object has a SOAPPart object that contains a SOAPEnvelope object. The SOAPEnvelope object in turn automatically contains an empty SOAPHeader object followed by an empty SOAPBody object. If you do not need the SOAPHeader object, which is optional, you can delete it. The rationale for having it automatically included is that more often than not you will need it, so it is more convenient to have it provided.

The SAAJ API provides the AttachmentPart class to represent an attachment part of a SOAP message. A SOAPMessage object automatically has a SOAPPart object and its required subelements, but because AttachmentPart objects are optional, you must create and add them yourself. 

If a SOAPMessage object has one or more attachments, each AttachmentPart object must have a MIME header to indicate the type of data it contains. It may also have additional MIME headers to identify it or to give its location. These headers are optional but can be useful when there are multiple attachments.

SAAJ and DOM

The SAAJ APIs extend their counterparts in the org.w3c.dom package:

  1. The Node interface extends the org.w3c.dom.Node interface.
  2. The SOAPElement interface extends both the Node interface and the org.w3c.dom.Element interface.
  3. The SOAPPart class implements the org.w3c.dom.Document interface.
  4. The Text interface extends the org.w3c.dom.Text interface.


public class SOAPTip {
    
   public static void main(String args[]) {
        
      try {
     
         // First create the connection
         SOAPConnectionFactory soapConnFactory =  SOAPConnectionFactory.newInstance();
         SOAPConnection connection =  soapConnFactory.createConnection();
         
         //Next, create the actual message
         MessageFactory messageFactory = MessageFactory.newInstance();
         SOAPMessage message = messageFactory.createMessage();
         
         //Create objects for the message parts            
         SOAPPart soapPart =     message.getSOAPPart();
         SOAPEnvelope envelope = soapPart.getEnvelope();
         SOAPBody body =         envelope.getBody();

//Populate the body
        //Create the main element and namespace
        SOAPElement bodyElement =   body.addChildElement(envelope.createName("getPrice" , 
                                                                "ns1", "urn:xmethods-BNPriceCheck"));
        //Add content
        bodyElement.addChildElement("isbn").addTextNode("0672324229");

//Populate the Message
        StreamSource preppedMsgSrc = new StreamSource( new FileInputStream("prepped.msg"));
        soapPart.setContent(preppedMsgSrc);

        //Save the message
        message.saveChanges();


        //Check the input
        System.out.println("\nREQUEST:\n");
        message.writeTo(System.out);
        System.out.println();
 
//Send the message and get a reply   
            
        //Set the destination
        String destination =  "http://services.xmethods.net:80/soap/servlet/rpcrouter";
        //Send the message
        SOAPMessage reply = connection.call(message, destination);
 
        //Check the output
        System.out.println("\nRESPONSE:\n");
        //Create the transformer
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer =  transformerFactory.newTransformer();
        //Extract the content of the reply
        Source sourceContent = reply.getSOAPPart().getContent();
        //Set the output for the transformation
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
        System.out.println();
 
         //Close the connection            
         connection.close();
            
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}


Difference between SOAP 1.1 and SOAP 1.2


1. Just as a person can perform one or more roles in a stage play, a node can play one or more roles in a SOAP message path. Unfortunately, the designers of SOAP 1.1 confused the words "actor" and "role"; they specified that you must identify the roles a node will play by declaring an actor attribute. They've recognized their mistake, and in SOAP 1.2 this attribute has been renamed role.

2. Neither SOAP 1.1 nor the BP explicitly prohibits intermediaries from modifying the contents of the Body element. As a result, the ultimate receiver has no way of knowing if the application-specific data has changed somewhere along the message path. SOAP 1.2 reduces this uncertainty by explicitly prohibiting certain intermediaries, called forwarding intermediaries, from changing the contents of the Body element and recommending that all other intermediaries, called active intermediaries, use a header block to document any changes to the Body element.

3. SOAP 1.2 will replace the SOAPAction header with the protocol-independent action media type (a parameter to the "application/soap+xml" MIME type), so dependency on this feature may result in forward-compatibility problems.

preferred protocol unidirectional SOAP messages


Http is not the best way.

Although a One-Way SOAP message is conceptually unidirectional, but when it's sent over HTTP some type of HTTP reply will be transmitted back to the receiver. One-Way SOAP messages do not return SOAP faults or results of any kind, so the HTTP 202 Accepted response code indicates only that the message made it to the receiver—it doesn't indicate whether the message was successfully processed

SOAP Faults

A SOAP message that contains a Fault element in the Body is called a fault message. When a fault message is generated, the Body of the SOAP message must contain only a single Fault element and nothing else. The Fault element itself must contain a faultcode element and a faultstring element, and optionally faultactor and detail elements.


<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote" >
  <soap:Body>
    <soap:Fault>
      <faultcode>soap:Client</faultcode>
      <faultstring>
        The ISBN value contains invalid characters
      </faultstring>
      <faultactor>http://www.xyzcorp.com</faultactor>
      <detail>
        <mh:InvalidIsbnFaultDetail>
          <offending-value>19318224-D</offending-value>
          <conformance-rules>
            The first nine characters must be digits. The last
            character may be a digit or the letter 'X'. Case is
            not important.
          </conformance-rules>
        </mh:InvalidIsbnFaultDetail>
      </detail>
    </soap:Fault>
  </soap:Body>
</soap:Envelope>


The faultcode element may use any of four standard SOAP fault codes to identify an error.
SOAP Standard Fault Codes

1.       Client - node that sent the SOAP message caused the error. receiver cannot process the SOAP message because there is something wrong with the message or its data, it's considered the fault of the client, the sender
When a node receives a fault message with a Client code, it should not attempt to resend the same message. It should take some action to correct the problem or abort completely.

2.       Server - the node that received the SOAP message malfunctioned or was otherwise unable to process the SOAP message.
In this case the sender can assume the SOAP message to be correct, and can redeliver it after pausing some period of time to give the receiver time to recover

3.       VersionMismatch - a SOAP 1.1 node will generate a fault with a VersionMismatch code if it receives a SOAP 1.2 message, because it finds an unexpected namespace in the Envelope.
The VersionMismatch fault applies only to the namespace assigned to the Envelope, Header, Body, and Fault elements. It does not apply to other parts of the SOAP message, like the header blocks, XML document version, or application-specific elements in the Body.
The VersionMismatch fault is also used in the unlikely event that the root element of a message is not Envelope, but something else. Sending a VersionMismatch fault message back to the sender in this case may not be helpful, however: The sender may be designed to handle a different protocol and doesn't understand SOAP faults.

4.       MustUnderstand

Although you're allowed to use arbitrary fault codes, you should use only the four standard codes listed.
The faultstring element is mandatory. It should provide a human-readable description of the fault. 

Although the faultstring element is required, the text used to describe the fault is not standardized
Optionally, the faultstring element can indicate the language of the text message using a special attribute, xml:lang.

The faultactor element indicates which node encountered the error and generated the fault (the faulting node). This element is required if the faulting node is an intermediary, but optional if it's the ultimate receiver.

The detail element of a fault message must be included if the fault was caused by the contents of the Body element, but it must not be included if the error occurred while processing a header block.

The detail element may contain any number of application-specific elements, which may be qualified or unqualified, according to their XML schema. In addition, the detail element itself may contain any number of qualified attributes, as long as they do not belong to the SOAP 1.1 namespace, "http://schemas.xmlsoap.org/soap/envelope".

Summary on Faults
This is probably a good time to recap. Faults result from one of several conditions:
  1. The message received by the receiver is improperly structured or contains invalid data.
  2. The incoming message is properly structured, but it uses elements and namespaces in the Body element that the receiver doesn't recognize.
  3. The incoming message contains a mandatory header block that the receiver doesn't recognize.
  4. The incoming message specifies an XML namespace for the SOAP Envelope and its children (Body, Fault, Header) that is not the SOAP 1.1 namespace.
  5. The SOAP receiver has encountered an abnormal condition that prevents it from processing an otherwise valid SOAP message.
The first two conditions generate what are considered Client faults, faults that relate to the contents of the message: The client has sent an invalid or unfamiliar SOAP message to the receiver. The third condition results in a MustUnderstand fault, and the fourth results in a VersionMismatch fault. The fifth condition is considered a Server fault, which means the error was unrelated to the contents of the SOAP message. A server fault is generated when the receiver cannot process a SOAP message because of an abnormal condition.

SOAP : More Details

Scenario
Consider a scenario in which SOAP message goes from sender to receiver via many intermediaries 


Intermediaries in a SOAP message path must not modify the application-specific contents of the SOAP Body element, but they may, and often do, manipulate the SOAP header blocks.


two relatively simple header blocks: message-id and processed-by. The processed-by header block keeps a record of the SOAP applications (nodes) that process a SOAP message on its way from the initial sender to the ultimate receiver. Like the message-id header, the processed-by header block is useful in debugging and logging

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:mi="http://www.Monson-Haefel.com/jwsbook/message-id"
 xmlns:proc="http://www.Monson-Haefel.com/jwsbook/processed-by">
  <soap:Header>
    <mi:message-id>11d1def534ea:b1c5fa:f3bfb4dcd7:-8000</mi:message-id>
    <proc:processed-by>
      <node>
        <time-in-millis>1013694680000</time-in-millis>
        <identity>http://www.customer.com</identity>
      </node>
      <node>
        <time-in-millis>1013694680010</time-in-millis>
        <identity>http://www.Monson-Haefel.com/sales</identity>
      </node>
      <node>
        <time-in-millis>1013694680020</time-in-millis>
        <identity>http://www.Monson-Haefel.com/AR</identity>
      </node>
      <node>
        <time-in-millis>1013694680030</time-in-millis>
        <identity>http://www.Monson-Haefel.com/inventory</identity>
      </node>
      <node>
        <time-in-millis>1013694680040</time-in-millis>
        <identity>http://www.Monson-Haefel.com/shipping</identity>
      </node>
    </proc:processed-by>
  </soap:Header>
  <soap:Body>
      <!-- Application-specific data goes here -->
  </soap:Body>
</soap:Envelope>

actor attribute
You use an actor attribute to identify a function to be performed by a particular node.

Just as a person can perform one or more roles in a stage play, a node can play one or more roles in a SOAP message path. Unfortunately, the designers of SOAP 1.1 confused the words "actor" and "role"; they specified that you must identify the roles a node will play by declaring an actor attribute. They've recognized their mistake, and in SOAP 1.2 this attribute has been renamed role.

The actor attribute is used in combination with the XML namespaces to determine which code module will process a particular header block. Conceptually, the receiving node will first determine whether it plays the role designated by the actor attribute, and then choose the correct code module to process the header block, based on the XML namespace of the header block. Therefore, the receiving node must recognize the role designated by the actor attribute assigned to a header block, as well as the XML namespace associated with the header block




<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
 xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:mi="http://www.Monson-Haefel.com/jwsbook/message-id"
 xmlns:proc="http://www.Monson-Haefel.com/jwsbook/processed-by">
  <soap:Header>
    <mi:message-id soap:actor="http://www.Monson-Haefel.com/logger" >
      11d1def534ea:b1c5fa:f3bfb4dcd7:-8000
    </mi:message-id>
    <proc:processed-by>
      <node>
        <time-in-millis>1013694680000</time-in-millis>
        <identity>http://www.customer.com</identity>
      </node>
    </proc:processed-by>
  </soap:Header>
  <soap:Body>
      <!-- Application-specific data goes here -->
  </soap:Body>
</soap:Envelope>

Only those nodes in the message path that identify themselves with the actor value "http://www.Monson-Haefel.com/logger" will process the message-id header block; all other nodes will ignore it

The actor attribute may have values like
  1. 1.       custom URIs like "http://www.Monson-Haefel.com/logger",
  2. 2.       two standard roles for the actor attribute: next
  3. 3.       and ultimate receiver.

The next role indicates that the next node in the message path must process the header. The next role has a designated URI, which must be used as the value of the actor attribute: "http://schemas.xmlsoap.org/soap/actor/next".

The ultimate receiver role indicates that only the ultimate receiver of the message should process the header block. The protocol doesn't specify an explicit URI for this purpose; it's the absence of an actor attribute in the header block that signals that the role is ultimate receiver

must understand attribute

In many cases we may not know the exact message path or the capabilities of all the nodes in a message path, which means we don't always know whether nodes can process header blocks correctly.  For example, the processed-by header block is targeted at the next role, which means the next node to receive it should process it. But what if the next node doesn't recognize that kind of header block?

The mustUnderstand attribute can have the value of either "1" or "0", to represent true and false, respectively. 0 is default.

The "understand" in mustUnderstand means that the node must recognize the header block by its XML structure and namespace, and know how to process it.

If a node doesn't understand a mandatory header block, it must generate a SOAP fault (similar to a remote exception in Java) and discard the message; it must not forward the message to the next node in the message path

Whether or not a fault is sent back to the sender depends on whether the messaging exchange pattern (MEP) is One-Way or Request/Response.

If the mustUnderstand attribute is "0", the processing requirements specified by SOAP are very different. If a node performs the role declared by a non-mandatory header block, and an application fails to understand the header (it doesn't recognize the XML structure or the namespace), it must remove the header block.
In other words, receivers should not attempt to determine whether a message was successfully processed by previous nodes in the path based on which header blocks are present

Note :- header element is optional but body is mandatory.

Neither SOAP 1.1 nor the BP explicitly prohibits intermediaries from modifying the contents of the Body element. As a result, the ultimate receiver has no way of knowing if the application-specific data has changed somewhere along the message path. SOAP 1.2 reduces this uncertainty by explicitly prohibiting certain intermediaries, called forwarding intermediaries, from changing the contents of the Body element and recommending that all other intermediaries, called active intermediaries, use a header block to document any changes to the Body element.


ok