Showing posts with label soap. Show all posts
Showing posts with label soap. Show all posts

Sunday, June 19, 2011

Interview Question: Compare two web services type SOAP and RESTful (SOAP Vs RESTful)

Here are the differences between SOAP and Restful web services :





Criteria SOAP RESTful Comments
Orientation Wraps business logic Accesses resources/data
Developer View Object oriented Resource Oriented
Language Independence Yes Yes
Platform Independence Yes Yes
Simplicity No Yes
Standards Based Yes No SOAP web services are based on SOAP and WS-* specifications
Security SSL, WS-Security SSL WS-Security provides end-to-end security covering message integrity and authentication
Transactions WS-AtomicTransaction No
Reliability WS-ReliableMessaging Application specific
Performance Good Better Caching and lower message payload makes RESTful web services performance efficient and scalable
Caching No GET operations can be cached
Transport protocol support HTTP, SMTP, JMS HTTP Multiple transport protocol support makes SOAP Web Services flexible
Message Size Heavy, has SOAP and WS-* specific markup Lightweight, no extra xml markup
Message Communication protocol XML XML, JSON, other valid MIME type This flexibility of REST makes its extremely useful in providing consumer need specific message payloads
Message Encoding Yes No SOAP Web Services support text and binary encoding, RESTful encoding is limited to text
Service Description WSDL No formal contract definition In REST, no formal way to describe a service interface means more dependence on written documentation
Human intelligible Payload No Yes
Developer Tooling Yes Minimal or none Complexity of SOAP Web Services dictates the need for using frameworks to facilitate rapid application development. REST on the other hand due to its simplicity can be developed without any framework


Now we come to most important stage of deciding which type to select. There is no one answer for selecting either SOAP based or RESTful Web Services. Neither is the right choice for every situation. The choice is dependant upon specific needs and which solution addresses them best. An architect should ask the following questions and the responses should assist him/her in making an informed decision:
  • Does the service expose data or business logic? (REST can be a good choice for exposing data, SOAP/WS-* might be a better choice for logic)
  • Does the service need the capabilities of WS-*, or is a simpler RESTful approach sufficient?
  • What’s best for the developers who will build clients for the service?
Areas where RESTful WebServices are a great choice:
  • Limited bandwidth and resources: Remember the return structure is really in any format (developer defined). Plus, any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE verbs. Again, remember that REST can also use the XMLHttpRequest object that most modern browsers support today, which adds an extra bonus of AJAX.
  • Totally stateless operations: If an operation needs to be continued, then REST is not the best approach and SOAP may fit it better. However, if you need stateless CRUD (Create, Read, Update, and Delete) operations, then REST is suitable.
  • Caching situations: If the information can be cached because of the totally stateless operation of the REST approach, this is perfect.
Areas where SOAP based WebServices is a great solution:
  • Asynchronous processing and invocation: If application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Things like WSRM – WS-Reliable Messaging etc.
  • Formal contracts: If both sides (provider and consumer) have to agree on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction.
  • Stateful operations: If the application needs contextual information and conversational state management then SOAP 1.2 has the additional specification in the WS* structure to support those things (Security, Transactions, Coordination, etc). Comparatively, the REST approach would make the developers build this custom plumbing.
I have used a lot of information from resources generously shared by fellow bloggers. It would inconsiderate in case I do not mention them. The resources are:
  1. REST and SOAP: When to use each (or both)?
  2. SOAP vs REST: Complements or Competitors
  3. Introduction to Web APIs: REST vs SOAP



Friday, April 8, 2011

Sending a soap message from soap client in java

Sending a soap message requires a server name, like --
http://localhost:13000/myservicename
13000 is port no.
Now just create a connection and write soap message to it.
We are using following imports:
import java.net.*;
import java.io.*;
Now just write the code:
URL u = new URL(server);
      URLConnection uc = u.openConnection();
      HttpURLConnection connection = (HttpURLConnection) uc;
      
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("SOAPAction", SOAP_ACTION);
      
      OutputStream out = connection.getOutputStream();
      Writer wout = new OutputStreamWriter(out);
      
      wout.write("<?xml version='1.0'?>\r\n");  
      wout.write("<SOAP-ENV:Envelope ");
      wout.write("xmlns:SOAP-ENV=");
      wout.write(
        "'http://schemas.xmlsoap.org/soap/envelope/' "
      );
      wout.write("xmlns:xsi=");
      wout.write(
        "'http://www.w3.org/2001/XMLSchema-instance'>\r\n"); 
      wout.write("  <SOAP-ENV:Body>\r\n");
      wout.write("    <calculateFibonacci ");
      wout.write(
    "xmlns='http://namespaces.cafeconleche.org/xmljava/ch3/'\r\n"
      ); 
      wout.write("    type='xsi:positiveInteger'>" + input 
       + "</calculateFibonacci>\r\n"); 
      wout.write("  </SOAP-ENV:Body>\r\n"); 
      wout.write("</SOAP-ENV:Envelope>\r\n"); 
      
      wout.flush();
      wout.close();
      
      InputStream in = connection.getInputStream();
      int c;
      while ((c = in.read()) != -1) System.out.write(c);
      in.close();

Creating a soap message in java using SAAJ

Installation issues
Setting up the Java Web Services Developer Pack 1.2 is easy -- as long as you send your messages through the included Tomcat Web server. To send messages through a standalone application, as I do here, you need to take the following steps:
  1. Download the JWSDP 1.2 from http://java.sun.com/webservices/downloads/webservicespack.html.
  2. Follow the instructions and install.
Example of soap message to be created : 

<SOAP-ENV:Envelope 
        xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" 
        xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" 
        xmlns:xsd="http://www.w3.org/1999/XMLSchema"> 
    <SOAP-ENV:Header />
    <SOAP-ENV:Body> 
        <ns1:Price xmlns:ns1="urn:xmethods-BNPriceCheck" >340
        </ns1:Price>
         <AuthorName>
           <FirstName>Rajesh</FirstName>
           <LastName>Thakur</LastName>
        </AuthorName>
    </SOAP-ENV:Body> 
</SOAP-ENV:Envelope>

Now it has 2 parts - name and price , which it wants to submit to the service.
Notice the structure of the message. The Envelope contains the Header and Body elements, and all three are part of the http://schemas.xmlsoap.org/soap/envelope/ namespace. The application sends the message using a SOAPConnection.

Creating the message object
//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();

First, you create the message itself by using the MessageFactory. This message already contains empty versions of the basic parts, such as the envelope and header. The SOAPPart contains the envelope, and the envelope contains the body. Create references to the needed objects, such as the SOAPBody.

Populating the body:
The body of the SOAP message is just like any other XML element in that you can add a child element, such as Price.
//Populate the body
        //Create the main element and namespace
        SOAPElement bodyElement = 
                  body.addChildElement(envelope.createName("Price" , 
                                                                "ns1", 
                                          "urn:xmethods-BNPriceCheck")).addTextNode("340");
        
      SOAPElement authorElement = body.addChildElement(envelope.createName("AuthorName");
      authorElement.addChildElement("FirstName").addTextNode("Rajesh");
      authorElement.addChildElement("LastName").addTextNode("Thakur");
                                                    
        //Save the message
       message.saveChanges();


        //Check the input
        System.out.println("\nREQUEST:\n");
        message.writeTo(System.out);
        System.out.println();
So this is how our message is prepared and now we can send it as request.

Chitika