Sunday, October 7, 2012

SOAP Basics


It has a clear purpose exchanging data over network ( via protocols like http , ftp , smtp etc ).


< ? xml version="1.0" encoding="UTF-8"? >
< soap : Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  < soap:Header >
    < !- - Header blocks go here - - >
  < / soap:Header >
  < soap:Body >
    < !- - Application data goes here - - >
  < / soap:Body >
< / soap:Envelope >

The Header element can contain XML elements that describe security credentials, transaction IDs, routing instructions, debugging information, payment tokens, or any other information about the message that is important in processing the data in the Body element.

< ? xml version="1.0" encoding="UTF-8"? >
soap : Envelope
 xmlns : soap="http://schemas.xmlsoap.org/soap/envelope/" >
  < soap : Body>
    < po : purchaseOrder orderDate="2003-09-22"
     xmlns : po=" http://www.Monson-Haefel.com/jwsbook/PO ">
      < po : accountName > Amazon.com< / po:accountName >
      < / po:purchaseOrder >
   </ soap : Body>
</ soap : Envelope >

Use of a name space 
1. basic thing like avoid collision
2. proper versioning
3. hence proper processing
4. As you can see from the previous examples, a SOAP message may contain many different namespaces, which makes SOAP messaging very modular. This modularity enables different parts of a SOAP message to be processed independently of other parts and to evolve separately.
5. Example :- The code that processes the element Envelope is independent of the code that processes the header blocks, which is independent of the code that processes application-specific data in the SOAP Body element

SOAP can be used with a variety of messaging systems (asynchronous, synchronous, RPC, One-Way, and others),


SOAP Over HTTP
It's possible to deliver SOAP messages using other protocols, such as SMTP and FTP as well, but details of these non-HTTP bindings are not specified by SOAP and are not supported by the BP
SOAP messages sent over HTTP are placed in the payload of an HTTP request or response.
There is nothing intrinsic to HTTP that limits it to requesting Web pages, but that's been its primary occupation for the past decade. Most HTTP traffic is composed of HTTP GET requests and HTTP replies. The HTTP GET request identifies the Web page requested and may include some parameters. An HTTP reply message returns the Web page to the requester as its payload.
While the HTTP GET request is perfectly suited for requesting Web pages, it doesn't have a payload area and therefore cannot be used to carry SOAP messages. The HTTP POST request, on the other hand, does have a payload area and is perfectly suited to carrying a SOAP message. HTTP reply messages, whether they are replies to GET or POST messages, follow the same format and carry a payload. Web services that use SOAP 1.1 with HTTP always use HTTP POST and not HTTP GET messages.


The HTTP POST message must contain a SOAPAction header field, but the value of this header field is not specified. The SOAPAction header field can improve throughput by providing routing information outside the SOAP payload. A node can then do some of the routing work using the SOAPAction, rather than having to parse the SOAP XML payload.

While the SOAPAction header field can improve efficiency, it's also the source of a lot of debate in the Web services industry. SOAP purists don't like the use of the SOAPAction HTTP header field because it expands the SOAP processing model to include the carrier protocol (in this case HTTP). They believe that all of the routing and payload should be contained in the SOAP document, so that SOAP messages are not dependent on the protocol over which they are delivered.

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.

You may have noticed that the Content-Type is text/xml, which indicates that the payload is an XML document. The WS-I Basic Profile 1.0 prefers that the text/xml Content-Type be used with SOAP over HTTP. It's possible to use others (for example, SOAP with Attachments would specify multipart/related) but it's not recommended.

Http Reply




Http Response Code : Success code
200 : ok
202 : Accepted This response code means that the request was processed successfully but that there is no SOAP response data. This type of SOAP operation is similar to a Java method that has a return type of void.

Http Response Code : Error code
400 Bad Request This error code is used to indicate that either the HTTP request or the XML in the SOAP message was not well formed.
405 Method Not Allowed If a Web service receives a SOAP message via any HTTP method other than HTTP POST, the service should return a 405 Method Not Allowed error to the sender.
415 Unsupported Media Type HTTP POST messages must include a Content-Type header with a value of text/xml. If it's any other value, the server must return a 415 Unsupported Media Type error.
500 Internal Server Error This code must be used when the response message in a Request/Response MEP is a SOAP fault.



Saturday, October 6, 2012

SOAP Vs REST : Making the Right choice

SOAP Vs REST

Often the question arises which one is better and which one should be used ? Here i attempt to answer the same

Difference


REST
SOAP
Basics
Exposes Resources which represents data
Exposes operations which exposes logic
Http Method
Uses HTTP verbs like GET / POST / DELETE
Uses HTTP Post (can't use Get) or any other protocol like smtp , ftp
Emphasis
Emphasis on simple point to point communication using HTTP.
Emphasis on loosely coupled distributed messaging.
Data Formats
Supports multiple data formats like XML , JSON
Supports only xml.
Stateless vs Stateful
Emphasizes stateless communication
Supports stateless and stateful  conversation and operations
Caching
Since HTTP based / Rest-ful APIs can be consumed using simple GET requests, intermediate proxy servers / reverse-proxies can cache their response very easily
SOAP requests use POST and require a complex XML request to be created which makes response-caching difficult.
Depending on protocol used may be more tough to cache.
Testing
It is also easy to test and troubleshoot an HTTP API since one can construct a call with nothing more than a browser and check the response inside the browser window itself.
There are special tools (SOAPUI) & libraries to test SOAP services hence a learning curve.
2 Phase commit
REST is limited by HTTP itself which can’t provide two-phase commit across distributed transactional resources
SOAP can. ( hence better choice for enterperise services )
Full form
REST (Representational State Transfer)
SOAP (Simple Object Access Protocol)


Supports asynchronous messaging


Strong typing, it has a fixed set of supported data types

Can easily do CRUD operations







When is REST Better than SOAP
  1. REST can be consumed by any client even a web browser with ajax and JavaScript.
  2. Rest is light weight
    1. Doesn't require xml parsing
    2. consumes less bandwidth - doesnt require a soap header for every msg
  3. REST is safe
    1. supports HTTPs
    2. -  aren't GET operations safe ? ( but they do expose params in url )


When is SOAP Better than REST
  1. Building a client for REST can be challenging
    1.   for soap can generate clients for wsdl
    2. dont have to write raw http calls
    3. SOAP can use own java exceptions , in REST look at the http response code
  2. REST only supports HTTP / HTTPs
  3. Parameter of REST will be exposed as a part of URI ( may be a security consideration ) 
  4. REST doesnt support reliable messaging 
  5. REST cannot be governed
    1.  how do i know who is consuming my WS w/o registry
    2.  how to discover a Restful WS





Good places to use REST
  1. Limited bandwidth
  2. Limited resources
  3. when ok to Expose URL data on web
  4. Combining content from many different sources on web ( mashups )


Good places to use SOAP
  1. Enterprise Services
    1. high reliability WS-RM :- Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.
    2. Transactions with WS-AT    :- Need ACID Transactions over a service, you’re going to need SOAP. While REST supports transactions, it isn’t as comprehensive and isn’t ACID compliant. 
    3. Security with WS-Security , adds enterprise level security , Supports identity through intermediaries, not just point to point . It also provides a standard implementation of data integrity and data privacy. 
  2. Asynchronous processing
  3. Stateful operation
  4. standard support interoperability with Buss apps
  5. Tooling support

Code Example And Performance
The above article gives simple code example and performance analysis for both

SOAP Disadvantages
1. Main use of SOAP is RPC ( generate proxy and use it to RPC ) but its not easy to pass even integers across two platforms
2. Strong typing is a bad choice for loosely coupled distributed systems. The moment you need to change anything, the type signature changes and all the clients that were built to your earlier protocol spec break. 


Saturday, June 16, 2012

Why two different web apps on same server have different class loaders ?

In Application server different classloaders are used to load different web application so that you can deploy and undeploy one application without affecting other application on same server

Wednesday, May 16, 2012

StringBuffer equals

Class stringBufferEqual
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Amit");
StringBuffer s2 = new StringBuffer("Amit");
System.out.println(s1.equals(s2));
}
}

It's false because that's how StringBuffer is defined. In fact, per my review of the API, it does not appear that StringBuffer overrides the equals method from Object as String does. If instead you want to compare Strings held by the two StringBuffers, you could do: 
System.out.println(sb1.toString().equals(sb2.toString())); 


StringBuffer VS StringBuilder

StringBuffer came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.


StringBuilder came later. Most of the uses of StringBuffer were single-thread and unnecessarily paying the cost of the synchronization.


Since StringBuilder is a drop-in replacement for StringBuffer without the synchronization, there would not be differences between any examples.


Simply use StringBuilder unless you really are trying to share a buffer between threads.


Tuesday, April 24, 2012

What will Class.forName do while loading drivers


Class.forName() returns a type of java.lang.class
It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
Supports Dynamic loading of Java classes at runtime. It provides the basis for application servers. ForName() method of java.lang.Class.

One of Java’s strongest features is its ability to dynamically load code given the name of the class to load, without having to know the actual classname until runtime. This allows Java developers to build flexible, dynamic systems that can grow and change without requiring complete recompilation.
In a program named DynamicLoader have line like …
Class toRun = Class.forName(args[0]);

This means we can run any compiled Java class through DynamicLoader without having to change DynamicLoader’s code.

java DynamicLoader Echo ONE TWO THREE

The classloader attempts to (i) Locate (ii) load and (iii) link the Driver class in the "org.gjt.mm.mysql" package and if successful, the static initializer is run.

To answer the question I started with the JavaDoc for the Class.forName() method. According to the documentation, the method:

... attempts to locate, load, and link the class or interface

I wasn't perfectly clear on what "locate, load, and link" meant, so I did a little digging through the Java Language Specification. According to chapter 12 of the JLS: 

Loading refers to the process of finding the binary form of a class or interface type with a particular name, perhaps by computing it on the fly, but more typically by retrieving a binary representation previously computed from source code by a compiler, and constructing, from that binary form, a Class object to represent the class or interface.

Next, again according to the JLS, it must be transformed from it's binary representation to something the Java virtual machine can use, this process is called linking. Finally, the class is initialized, which is the process that executes the static initializer and the initializers for static fields declared in the class. 

So then back to the original problem, when Class.forName() is called with an argument like this:

Class.forName("org.gjt.mm.mysql.Driver");

The classloader attempts to (i) load and (ii) link the Driver class in the "org.gjt.mm.mysql" package and if successful, the static initializer is run. The MySQL Driver (download the source code) static initializer looks like this:

static {
  try {
    java.sql.DriverManager.registerDriver(new Driver());
  } catch (SQLException E) {
    throw new RuntimeException("Can't register driver!");
  }
}

So it calls a static method in the java.sql.DriverManager class which apparently registers a copy of itself when it loads.

So now I understand the where and the how, what about why? To understand the why you have to look at the next line in the initial code example:

Connection con = DriverManager.getConnection(url,  "myLogin", "myPassword");
Conn.setAutoCommit(false);


How to count number of objects for a class in JVM

Simple ..


public class LikeThis {
  private static int numberOfObjectsCreated = 0;
 
   public  LikeThis() {
    numberOfObjectsCreated++;
    // other constructor business  
  }
}

what is difference between www and www2

We all know that “WWW” stands for World Wide Web, which is a kind of prefix before normal domain name. Web was created around 1990 in Geneva, Switzerland. But what is WWW1 or WWW2? 


You must noticed www1 or www2 once in a while when you are visiting a website. WWW1, WWW2 or even WWW3 is nothing but a mirror of the original web server which is typical WWW. Many websites like government, banks even major search engines like Google(www1.google.com or www2.google.com) and Yahoo(www1.yahoo.com or www2.yahoo.com)! uses www1 and www2. The main purpose of this techniques is to reduce server load. Sometimes the original server need to be updated or modified but major websites like .gov, .edu, google.com, yahoo.com cannot just shut their main server down for hours to update their system. Therefore, they need to use www1 or www2 duplication of their mainframe server. 


Sometimes this different servers used for the serving users based on their geographical location. Suppose, if someone typehttp://www.google.com form US, they might be taken to the original google server which means http://www.google.com but if someone type http://www.google.com from Africa, it might take them to www2.google.com or www1.google.com. 


I was surprised that not a lot of information showed up in Google or Yahoo when i was searching for it. If you know more about WWW2 or WWW1 please feel free to share with everyone here by adding your comment at the bottom. I was wondering if there is any security issue behind this mirror web server policy? 



http://en.wikipedia.org/wiki/WWW2