Friday, 27 March 2015

Hibernate first level cache and second level cache

What is the difference between first level cache and second level cache?


First Level Cache
Second Level Cache
First Level Cache is associated with Session.
Second Level Cache is associated with SessionFactory.
It is enabled by default.
It is not enabled by default.


Hibernate Caching




























Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications.
Caching is important to Hibernate as well which utilizes a multilevel caching schemes as explained below:

First-level cache:

The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.
If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database.

Second-level cache:

Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions.
Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider interface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation.

Query-level cache:

Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache.
This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.

The Second Level Cache:

Hibernate uses first-level cache by default and you have nothing to do to use first-level cache. Let's go straight to the optional second-level cache. Not all classes benefit from caching, so it's important to be able to disable the second-level cache
The Hibernate second-level cache is set up in two steps. First, you have to decide which concurrency strategy to use. After that, you configure cache expiration and physical cache attributes using the cache provider.

Concurrency strategies:

A concurrency strategy is a mediator which responsible for storing items of data in the cache and retrieving them from the cache. If you are going to enable a second-level cache, you will have to decide, for each persistent class and collection, which cache concurrency strategy to use.
  • Transactional: Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.
  • Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.
  • Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern.
  • Read-only: A concurrency strategy suitable for data which never changes. Use it for reference data only.
If we are going to use second-level caching for our Employee class, let us add the mapping element required to tell Hibernate to cache Employee instances using read-write strategy.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <cache usage="read-write"/>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>
The usage="read-write" attribute tells Hibernate to use a read-write concurrency strategy for the defined cache.

Cache provider:

Your next step after considering the concurrency strategies you will use for your cache candidate classes is to pick a cache provider. Hibernate forces you to choose a single cache provider for the whole application.
S.N.Cache NameDescription
1EHCacheIt can cache in memory or on disk and clustered caching and it supports the optional Hibernate query result cache.
2OSCacheSupports caching to memory and disk in a single JVM, with a rich set of expiration policies and query cache support.
3warmCacheA cluster cache based on JGroups. It uses clustered invalidation but doesn't support the Hibernate query cache
4JBoss CacheA fully transactional replicated clustered cache also based on the JGroups multicast library. It supports replication or invalidation, synchronous or asynchronous communication, and optimistic and pessimistic locking. The Hibernate query cache is supported
Every cache provider is not compatible with every concurrency strategy. The following compatibility matrix will help you choose an appropriate combination.
Strategy/ProviderRead-onlyNonstrictread-writeRead-writeTransactional
EHCacheXXX
OSCacheXXX
SwarmCacheXX
JBoss CacheXX
You will specify a cache provider in hibernate.cfg.xml configuration file. We choose EHCache as our second-level cache provider:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <property name="hibernate.dialect">
      org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>

   <!-- Assume students is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/test
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      root123
   </property>
   <property name="hibernate.cache.provider_class">
      org.hibernate.cache.EhCacheProvider
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
Now, you need to specify the properties of the cache regions. EHCache has its own configuration file,ehcache.xml, which should be in the CLASSPATH of the application. A cache configuration in ehcache.xml for the Employee class may look like this:
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<cache name="Employee"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
That's it, now we have second-level caching enabled for the Employee class and Hibernate now hits the second-level cache whenever you navigate to a Employee or when you load a Employee by identifier.
You should analyze your all the classes and choose appropriate caching strategy for each of the classes. Sometime, second-level caching may downgrade the performance of the application. So it is recommended to benchmark your application first without enabling caching and later on enable your well suited caching and check the performance. If caching is not improving system performance then there is no point in enabling any type of caching.

The Query-level Cache:

To use the query cache, you must first activate it using the hibernate.cache.use_query_cache="true"property in the configuration file. By setting this property to true, you make Hibernate create the necessary caches in memory to hold the query and identifier sets.
Next, to use the query cache, you use the setCacheable(Boolean) method of the Query class. For example:
Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
List users = query.list();
SessionFactory.closeSession();
Hibernate also supports very fine-grained cache support through the concept of a cache region. A cache region is part of the cache that's given a name.
Session session = SessionFactory.openSession();
Query query = session.createQuery("FROM EMPLOYEE");
query.setCacheable(true);
query.setCacheRegion("employee");
List users = query.list();
SessionFactory.closeSession();
This code uses the method to tell Hibernate to store and look for the query in the employee area of the cache.




















Second level cache implementation:

1) Add 2 configuration setting in hibernate.cfg.xml file

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">database</property>
<property name="connection.password">database</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="show_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<mapping resource="com/ibm/hbm/Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>

2) Add cache usage setting in hbm file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ibm.beans.Employee" table="EMP">
<cache usage="read-only" />
<id name="employeeNo" column="ENO">
<generator class="assigned" />
</id>
<property name="employeeName" column="ENAME" />
<property name="employeeSalary" column="SALARY" />
</class>
</hibernate-mapping>


3) Create ehcache.xml file
<?xml version="1.0"?>
<ehcache>
<defaultCache maxElementsInMemory="100" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="200" />

<cache name="com.ibm.beans.Employee" maxElementsInMemory="100"
eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="200" />
</ehcache>  

4) Create Employee.java file
package com.ibm.beans;


public class Employee
{
private Integer employeeNo;
private String employeeName;
private Double employeeSalary;
public Integer getEmployeeNo()
{
return employeeNo;
}

public void setEmployeeNo(Integer employeeNo)
{
this.employeeNo = employeeNo;
}

public String getEmployeeName()
{
return employeeName;
}

public void setEmployeeName(String employeeName)
{
this.employeeName = employeeName;
}

public Double getEmployeeSalary()
{
return employeeSalary;
}

public void setEmployeeSalary(Double employeeSalary)
{
this.employeeSalary = employeeSalary;
}

}


5. Main method:
/**
 *******************************************************************************
 * Licensed Materials - Property of IBM                                        *
 * © Copyright IBM 2007 All Rights Reserved                                 *
 * Created on 05-Apr-2015                                                          *
 *******************************************************************************
 * Please do not makes any changes to this file without first                  *
 * updating the revision history below, under description                      *
 * please include relevant CRs or defect ids that required the change          *
 *******************************************************************************
 * Revision History:                                                           *
 *                                                                             *
 * Date        Name              Reference   Description                       *
 * ----------  ----------------  --------------------------------------------- *
 * 05-Apr-2015    Chandra            created                              *
 *******************************************************************************
 */

package com.ibm.beans;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author Chandrahasa
 * 
 */
public class Main
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        Configuration cfg = new Configuration().configure();
        SessionFactory factory = cfg.buildSessionFactory();

        Session session1 = factory.openSession();
        Employee emp1 = (Employee) session1.get(Employee.class, 1);
        System.out.println(emp1.getEmployeeNo() + " " + emp1.getEmployeeName() + " " + emp1.getEmployeeSalary());
        session1.close();

        Session session2 = factory.openSession();
        Employee emp2 = (Employee) session2.get(Employee.class, 2);
        System.out.println(emp2.getEmployeeNo() + " " + emp2.getEmployeeName() + " " + emp2.getEmployeeSalary());
        session2.close();
        
        Session session3 = factory.openSession();
        Employee emp3 = (Employee) session3.get(Employee.class, 1);
        System.out.println(emp3.getEmployeeNo() + " " + emp3.getEmployeeName() + " " + emp3.getEmployeeSalary());
        session3.close();

        Session session4 = factory.openSession();
        Employee emp4 = (Employee) session4.get(Employee.class, 2);
        System.out.println(emp4.getEmployeeNo() + " " + emp4.getEmployeeName() + " " + emp4.getEmployeeSalary());
        session4.close();

    }

}


Output of above program:
Hibernate: select employee0_.ENO as ENO0_0_, employee0_.ENAME as ENAME0_0_, employee0_.SALARY as SALARY0_0_ from EMP employee0_ where employee0_.ENO=?
1 chandra 20000.0
Hibernate: select employee0_.ENO as ENO0_0_, employee0_.ENAME as ENAME0_0_, employee0_.SALARY as SALARY0_0_ from EMP employee0_ where employee0_.ENO=?
2 chandra 20000.0
1 chandra 20000.0
2 chandra 20000.0


As we can see here, hibernate does not fire query twice. If you don't use second level cache, hibernate will fire query twice because both query uses different session objects.

get and load

The differences between get() and load() methods are given below.
No.get()load()
1)Returns null if object is not found.Throws ObjectNotFoundException if object is not found.
2)get() method always hit the database.load() method doesn't hit the database.
3)It returns real object not proxy.It returns proxy object.
4)It should be used if you are not sure about the existence of instance.It should be used if you are sure that instance exists.

Save, Update, SaveOrUpdate, persist, merge

save:
Save method stores an object into the database. That means it insert an entry if the identifier doesn’t exist, else it will throw error. If the primary key already present in the table, it cannot be inserted.

update:
Update method in the hibernate is used for updating the object using identifier. If the identifier is missing or doesn’t exist, it will throw exception.

saveOrUpdate:
This method calls save() or update() based on the operation. If the identifier exists, it will call update method else the save 

persist:
Make a transient instance persistent

merge:
suppose we create a session and load an object. Now object in session cache. If we close the session at this point and we edit state of object and tried to save using update() it will throw exception. To make object persistent we need to open another session. Now we load same object again in current session. So if we want to update present object with previous object changes we have to use merge() method. Merge method will merge changes of both states of object and will save in database. 

Hibernate Architecture

The Hibernate architecture includes many objects persistent object, session factory, transaction factory, connection factory, session, transaction etc.

There are 4 layers in hibernate architecture java application layer, hibernate framework layer, backhand api layer and database layer.Let's see the diagram of hibernate architecture:
This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects session factory, session, transaction etc. alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API) and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture

For creating the first hibernate application, we must know the elements of Hibernate architecture. They are as follows:

SessionFactory

The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.

Session

The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction interface provides methods for transaction management.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is optional.

TransactionFactory


It is a factory of Transaction. It is optional.

Monday, 23 March 2015

Hibernate without Cfg file

public class ConfigurationClass
{
    private static SessionFactory sf;
    private static final Properties properties;

    static
    {
        properties = new Properties();
        properties.setProperty("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
        properties.setProperty("hibernate.connection.url", "jdbc:oracle:thin:@localhost:1521:xe");
        properties.setProperty("hibernate.connection.username", "sql");
        properties.setProperty("hibernate.connection.password", "sql");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle9Dialect");
        sf = new AnnotationConfiguration().setProperties(properties).addAnnotatedClass(Employee.class).buildSessionFactory();
    }

    private ConfigurationClass()
    {

    }

    public static SessionFactory getSessionFactoryObject()
    {
        if (sf != null)
        {
            return sf;
        }
        return new AnnotationConfiguration().setProperties(properties).addAnnotatedClass(Employee.class).buildSessionFactory();
    }

}

Saturday, 14 March 2015

Web service interview questions and answers

What is a Web service?
Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system. 
XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications. 
Beyond this basic definition, a Web service may also have two additional (and desirable) properties: 
First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). (See FAQ number 7.) 
Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration. (See FAQ number 8.) 
Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems. For a quick look at the range of Web services currently available, check out the XMethods directory of Web services.
What is new about Web services? 
People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP. 
So, what is really new about Web services? The answer is XML. 
XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories. 
Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well. 
By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting.
I keep reading about Web services, but I have never actually seen one. Can you show me a real Web service in action? 
If you want a more intuitive feel for Web services, try out the IBM Web Services Browser, available on the IBM Alphaworks site. The browser provides a series of Web services demonstrations. Behind the scenes, it ties together SOAP, WSDL, and UDDI to provide a simple plug-and-play interface for finding and invoking Web services. For example, you can find a stock-quote service, a traffic-report service, and a weather service. Each service is independent, and you can stack services like building blocks. You can, therefore, create a single page that displays multiple services--where the end result looks like a stripped-down version of my.yahoo or my.excite.
What is the Web service protocol stack?
The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers: 
Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP). 
XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP. 
Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL.
Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI. 
Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language). For an overview of these protocols, check out Pavel Kulchenko's article, Web Services Acronyms, Demystified, on XML.com. 
Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.
What is XML-RPC? 
XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response. 
More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls. 
Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server. 
To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted): 
<?xml version="1.0" encoding="ISO-8859-1"?>
<methodCall>
<methodName>weather.getWeather</methodName>
<params>
<param><value>10016</value></param>
</params>
</methodCall>
The request consists of a simple element, which specifies the method name (getWeather) and any method parameters (zip code).

Here is a sample XML-RPC response from the weather service:

<?xml version="1.0" encoding="ISO-8859-1"?>
<methodResponse>
<params>
<param>
<value><int>65</int></value>
</param>
</params>
</methodResponse>
The response consists of a single element, which specifies the return value (the current temperature). In this case, the return value is specified as an integer. 
In many ways, XML-RPC is much simpler than SOAP, and therefore represents the easiest way to get started with Web services. 
The official XML-RPC specification is available at XML-RPC.com. Dozens of XML-RPC implementations are available in Perl, Python, Java, and Ruby. See the XML-RPC home page for a complete list of implementations.
What is SOAP?
SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another.

To get a quick sense of SOAP, here is a sample SOAP request to a weather service (with the HTTP Headers omitted): 

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getWeather 
xmlns:ns1="urn:examples:weatherservice"
SOAP-ENV:encodingStyle=" http://www.w3.org/2001/09/soap-encoding
<zipcode xsi:type="xsd:string">10016</zipcode>
</ns1:getWeather>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode).

Here is a sample SOAP response from the weather service:

<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getWeatherResponse
xmlns:ns1="urn:examples:weatherservice"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding">
<return xsi:type="xsd:int">65</return>
</ns1:getWeatherResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The response indicates a single integer return value (the current temperature). 
The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details.
What is WSDL?
The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack. 
In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following: 

Information on all publicly available functions. 
Data type information for all XML messages. 
Binding information about the specific transport protocol to be used. 
Address information for locating the specified service. 

WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services.

Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points. 
First, the <message> elements specify the individual XML messages that are transferred between computers. In this case, we have a getWeatherRequest and a getWeatherResponse. Second, the element specifies that the service is available via SOAP and is available at a specific URL. 

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="WeatherService"
targetNamespace="http://www.ecerami.com/wsdl/WeatherService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.ecerami.com/wsdl/WeatherService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="getWeatherRequest">
<part name="zipcode" type="xsd:string"/>
</message>
<message name="getWeatherResponse">
<part name="temperature" type="xsd:int"/>
</message>

<portType name="Weather_PortType">
<operation name="getWeather">
<input message="tns:getWeatherRequest"/>
<output message="tns:getWeatherResponse"/>
</operation>
</portType>

<binding name="Weather_Binding" type="tns:Weather_PortType">
<soap:binding style="rpc" 
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="getWeather">
<soap:operation soapAction=""/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:weatherservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:weatherservice"
use="encoded"/>
</output>
</operation>
</binding>

<service name="Weather_Service">
<documentation>WSDL File for Weather Service</documentation>
<port binding="tns:Weather_Binding" name="Weather_Port">
<soap:address 
location="http://localhost:8080/soap/servlet/rpcrouter"/>
</port>
</service>
</definitions>
Using WSDL, a client can locate a Web service, and invoke any of the publicly available functions. With WSDL-aware tools, this process can be entirely automated, enabling applications to easily integrate new services with little or no manual code. For example, check out the GLUE platform from the Mind Electric. 
WSDL has been submitted to the W3C, but it currently has no official status within the W3C. See this W3C page for the latest draft.
What is UDDI?
UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack. 
UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services. 
At its core, UDDI consists of two parts. 
First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data. 
Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services. 
The data captured within UDDI is divided into three main categories: 
White Pages: This includes general information about a specific company. For example, business name, business description, and address. 
Yellow Pages: This includes general classification data for either the company or the service offered. For example, this data may include industry, product, or geographic codes based on standard taxonomies. 
Green Pages: This includes technical information about a Web service. Generally, this includes a pointer to an external specification, and an address for invoking the Web service. 
You can view the Microsoft UDDI site, or the IBM UDDI site. The complete UDDI specification is available at uddi.org. 
Beta versions of UDDI Version 2 are available at: 
Hewlett Packard 
IBM 
Microsoft 
SAP
How do I get started with Web Services? 
The easiest way to get started with Web services is to learn XML-RPC. Check out the XML-RPC specification or read my book, Web Services Essentials. O'Reilly has also recently released a book on Programming Web Services with XML-RPC by Simon St.Laurent, Joe Johnston, and Edd Dumbill. 
Once you have learned the basics of XML-RPC, move onto SOAP, WSDL, and UDDI. These topics are also covered in Web Services Essentials. For a comprehensive treatment of SOAP, check out O'Reilly's Programming Web Services with SOAP, by Doug Tidwell, James Snell, and Pavel Kulchenko.
Does the W3C support any Web service standards? 
The World Wide Web Consortium (W3C) is actively pursuing standardization of Web service protocols. In September 2000, the W3C established an XML Protocol Activity. The goal of the group is to establish a formal standard for SOAP. A draft version of SOAP 1.2 is currently under review, and progressing through the official W3C recommendation process. 
On January 25, 2002, the W3C also announced the formation of a Web Service Activity. This new activity will include the current SOAP work as well as two new groups. The first new group is the Web Services Description Working Group, which will take up work on WSDL. The second new group is the Web Services Architecture Working Group, which will attempt to create a cohesive framework for Web service protocols.







Q. What are the different application integration styles?

A.
 There are a number of different integration styles like

1. Shared database
2. batch file transfer
3. Invoking remote procedures (RPC)
4. Exchanging asynchronous messages over a message oriented middle-ware (MOM).



Q.
 What are the different styles of Web Services used for application integration? 
A.
 SOAP WS and RESTful Web Service


Q.
 What are the differences between both SOAP WS and RESTful WS?  
A. 
 


·                     The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
·                     The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),  Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
·                     The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. 

         GET - read()
         POST - create()
         PUT - update()
         DELETE - delete()
 
·                     SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.
·                     SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
·                     The SOAP has comprehensive support for both ACID based  transaction management  for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it  is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
·                     The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.




Q.
 How would you decide what style of Web Service to use? SOAP WS or REST?
A. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability.

The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.


·                     Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)
·                     Do we need to support multiple data formats?
·                     Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
·                     Is the call synchronous or  asynchronous?
·                     Is the call stateful or stateless? (REST is suited for statless CRUD operations)
·                     What level of security is required? (SOAP WS has better support for security)
·                     What level of transaction support is required? (SOAP WS has better support for transaction management)
·                     Do we have limited band width? (SOAP is more verbose)
·                     What’s best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)


Q.
 What tools do you use to test your Web Services?
A.
 SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.


Q.
 What is the difference between SOA and a Web service? 
A.
 

SOA is
 a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).     

Web service is
 an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based  and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET. 



Q.
 Web services when you can use traditional style middle-ware such as RPC, CORBA, RMI and DCOM?
A.
 

The
 traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use. 

Web Services
 support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.


Q.
 What are the different approaches to developing a SOAP based Web service? A. 2 approaches.


·                     The contract-first approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract.
·                     The contract-last approach where you  define the Java classes first and then generate the contract, which is the  WSDL file from the Java classes.

Note:
 The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses. 

Q.
 What are the pros and cons of each approach, and which approach would you prefer?

A.

Contract-first Web service


PROS:


·                     Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients.
·                     Developers can work simultaneously on client and server side based on the contract both agreed on.
·                     You have full control over how the request and response messages are constructed -- for example, should "status" go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the "status" would be generated as "attribute" instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc
  
CONS:


·                     More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.
 
·                     Developers need to learn XSDs and WSDLs in addition to just knowing Java.

 
 
Contract-last Web service
 
 
PROS:

·                     Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.
  
·                     The learning curve and development time can be smaller compared to the Contract-first Web service.
  
CONS:
 

·                      The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.
·                      In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.



So, which approach will you choose?

The best practice is to use "contract-first", and here is the link that explains this much better with examples --> 
contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the "contract-first".  You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.