"WebServices "

This Section focuses on Web Services both Soap , REST likc Axis, CXF, JAX-RS.

1 )   What is a Web Service ? and Show its Architecture


  • What is a Web Service ? and Show its Architecture
    Sample Img 1
A  Web service is a method of communication between two electronic devices over the Web (Internet).
"Web service" is "a software system designed to support interoperable machine-to-machine interaction
over a network".

2 )   Web service Stack ?


  • Web service Stack ?
    Sample Img 2

3 )   Web Service VS RMI VS EJB ?

EJBs are built on top of RMI. So RMI and EJB both imply Java clients and beans. If your clients
need to be written in something else (e.g., .NET, PHP, etc.) go with Web services or something
else that speaks a platform-agnostic wire protocol, like HTTP or XML over HTTP or SOAP.
If you choose RMI, you don't need a Java EE EJB app server. You have to keep client and server
JVMs in synch; you can't upgrade the client without upgrading the server.You have to write
all the services that the EJB Container provides for you (e.g., naming and directory services,
pooling, request queuing,transactions, etc.).
Web services have some gotchas that you need to watch out for,  Marshalling from XML to
objects and back consumes CPU cycles that aren't providing any business value besides
allowing your clients to speak a platform-agnostic protocol.
SOAP is a standard that is becoming more bloated and complex every day, but it has lots of
tool support. Vendors like it because it helps drive sales of ESBs. REST is simple but not
as well understood. It's not supported by tools.

4 )   What is Soap ?

SOAP (Simple Object Access Protocol) is an XML-based messaging protocol. It defines a set
of rules for structuring messages that can be used for simple one-way messaging but is
particularly useful for performing

5 )   What is RPC, XML-RPC ?

Remote Procedure Call (RPC) is a protocol that one program can use to request a service from
a program located in another computer in a network without having to understand network details.
(A procedure call is also sometimes known as a function call or a subroutine call.) 
RPC uses
the client/server model. The requesting program is a client and the service-providing program
is the server. RPC is Syncronous Call.
XML-RPC is nothing but remote procedure calling using HTTP as the transport and XML as the encoding.
XML-RPC is designed to be as simple as possible, while allowing complex data structures to be
transmitted, processed and returned.

6 )   What is WSDL ?, Sample WSDL ?

WSDL is a specification defining how to describe web services in a common XML grammar.
WSDL describes four critical pieces of data:
i) Interface information describing all publicly available functions
ii) Data type information for all message requests and message responses
iii)Binding information about the transport protocol to be used
iv)Address information for locating the specified service
In a nutshell, WSDL represents a contract between the service requestor and the service provider,
in much the same way that a Java interface represents a contract between client code and the actual
Java object. The crucial difference is that WSDL is platform- and language-independent
and is used primarily (although not exclusively) to describe SOAP services.
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="HelloService"
    <message name="SayHelloRequest">
      <part name="firstName" type="xsd:string"/>
   <message name="SayHelloResponse">
      <part name="greeting" type="xsd:string"/>
    <portType name="Hello_PortType">
      <operation name="sayHello">
         <input message="tns:SayHelloRequest"/>
         <output message="tns:SayHelloResponse"/>
   <binding name="Hello_Binding" type="tns:Hello_PortType">
      <soap:binding style="rpc"
      <operation name="sayHello">
         <soap:operation soapAction="sayHello"/>
  <service name="Hello_Service_New">
      <documentation>WSDL File for HelloService</documentation>
      <port binding="tns:Hello_Binding" name="Hello_Port">

7 )   What are the different Parts of a WSDL ?

Please take a look at the Sample WSDL provided above, Every Soap Request has the following parts.
<definitions>: The Hello Service
<portType>:sayHello Operation that consist of a Request/Response service
<binding> :Direction to use the Soap Http Protocal
<Service> :
Serive available at "http://localhost:8080/soap/servlet/HelloService"

8 )   What is Data Binding ?

Databinding is a general concept that is regularly applied even outside the context of
Web services, but  in the context of Web services, databinding is always XML databinding.

XML databinding is nothing but a process which maps the content of an XML document to a set
of objects generated specifically to provide access to data contained in those documents.
This could be done by using several APIs , some of them are below.
  • JaxB
  • Castor
  • Xstream
  • Jbix
  • XMLBeans

9 )   List of generated Classes for a Web Service and show the communication between them ?


  • Webservice Generated Classes.
    Sample Img 9
Assume  that you have a class called as follows and the list of generated classes and the communications between
these classes is as dipected in above daigram.

10 )   Jaxb VS XMLBeans ?

The JAXB binding compiler translates a W3C XML Schema into one or more Java classes,
a jaxb.properties file, and possibly other files, depending on the specific implementation
of JAXB. Alternatively, JAXB2 offers a way to generate a schema from annotated Java classes.
Below is the call to generate the JAXB classes from an XML schema:
 xjc -d out Example.xsd 

XMLBeans is an XML binding tool that has full XML Schema support, and offers full XML Infoset
fidelity. It takes a different approach to that of most other O/X mapping frameworks,
in that all classes that are generated from an XML Schema are all derived from XmlObject,
and contain XML binding information in them.
Below is the call to generate the JAXB classes from an XML schema:
 scomp -d out -srconly  Example.xsd
Both XMLBeans and JAXB produce Java models that make it easy for developers to interact with XML.
 The JAXB model however is annotated POJOs which has the following advantages:
i) JPA annotations could easily be applied to the JAXB model enabling the model to be persisted
in a relational database.
ii) Once generated the JAXB model could be modified to handle changes in the XML schema,
the XMLBeans model would need to be regenerated.
iii) Starting with Java SE 6 no additional compile/runtime dependencies are required
for the JAXB model.
iv)There are multiple JAXB implementations available:  EclipseLink MOXy, Metro,
Apache JaxMe, etc.
v)JAXB is the standard binding layer for JAX-WS (SOAP) and JAX-RS (RESTful) Web Services.
vi) In XMLbeans you can traverse any element by using Xpath/XQuery, but in Jaxb.

11 )   Dynamic Web Service Client ?

There are several ways to create Dynamic Soap Client, the following
is one of them.
     URL url = new URL("http://api.google.com/GoogleSearch.wsdl");
     QName serviceName = new QName("urn:GoogleSearch", "GoogleSearchService");
     QName portName = new QName("urn:GoogleSearch", "GoogleSearchPort");
     Service service = Service.create(url, serviceName);
     Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
     SOAPMessage request = MessageFactory.newInstance().createMessage(null,
         new FileInputStream("yourGoogleKey.xml"));
     SOAPMessage response = dispatch.invoke(request);

12 )   Xstream toXML() and fromXML () ?

Xstream is another Bindking API like Jaxb, this could be used as follows. Please note
if you do not have Schemas, you need to use alias()
Xstream toXML()  :
XStream xstream = new XStream();//You require xstream-[version].jar and kxml2-min-[version].jar
XStream xstream = new XStream(new DomDriver());
XStream(new StaxDriver());
String xml = xstream.toXML(YourJavaObject);
Xstream fromXML() :
YourJavaObject yourJavaObject= (YourJavaObject)xstream.fromXML(xml);

13 )   Axis 1.x VS Axis 2.0 VS CFX ?

This brings us to a good point to compare Axis2 and CXF on their own merits. They are of
course in many ways comparable; of necessity web services frameworks must fill in all the
same blanks, but since both projects are very young, each has certain areas that are more
well-developed than others. The chief differences are as follows:
i) CXF has support for WS-Addressing, WS-Policy, WS-RM, WS-Security, and WS-I BasicProfile.
Axis2 supports each of these except for WS-Policy, which will be supported in an
upcoming version.
ii) CXF was written with Spring in mind; Axis2 is not.
iii) Axis2 supports a wider range of data bindings, including XMLBeans, JiBX, JaxMe and JaxBRI
as well as its own native data binding, ADB. Note that support for JaxME and JaxBRI are
still considered experimental in Axis2 1.2.
iv) CXF currently supports only JAXB and Aegis; support for XMLBeans, JiBX and Castor
will come in CXF 2.1.Axis2 supports multiple languages--there is a C/C++ version available
 in addition to the Java version.

14 )   What is UDDI ?

Universal Description, Discovery and Integration (UDDI) is a directory service where businesses
can register and search for Web services.
UDDI is a platform-independent framework for describing services, discovering businesses, and
integrating business services by using the Internet.
UDDI stands for Universal Description, Discovery and Integration
UDDI is a directory for storing information about web services
UDDI is a directory of web service interfaces described by WSDL
UDDI communicates via SOAP
If you want to create a Client for a UDDI registered Service ,
you have to something similar below.
            // Create the SOAP envelope
            org.apache.soap.Envelope envelope = new org.apache.soap.Envelope(  );
            envelope.declareNamespace("idoox", "http://idoox.com/uddiface");
            envelope.declareNamespace("ua", "http://idoox.com/uddiface/account");
            envelope.declareNamespace("attr", "http://idoox.com/uddiface/attr");
            envelope.declareNamespace("fxml", "http://idoox.com/uddiface/formxml");
            envelope.declareNamespace("inner", "http://idoox.com/uddiface/inner");
            envelope.declareNamespace("", "http://idoox.com/uddiface/inner");
            envelope.declareNamespace("uddi", "urn:uddi-org:api_v2");

15 )    Marshalling and Unmarshalling ?

"Marshalling" refers to the process of converting the data or the objects into a byte-stream,
and "Unmarshalling" is the reverse process of converting the byte-stream back to their original
data or objec
t. The conversion is achieved through "serialization".

The purpose of the "marshalling/unmarshalling" process is to transfer data between the Systems
integrated with RMI or EJB Or Web Services.

16 )   What is Web Sevice Authentication ?

Basic Authentication : (Jax -RPC)
Web.xml changes :


Client Code :
      Call call = (Call) service.createCall();
       Stub stub = (Stub)(new
          javax.xml.rpc.Stub.USERNAME_PROPERTY, username);
          javax.xml.rpc.Stub.PASSWORD_PROPERTY, password);
          (javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);

With WSS4J :
A number of pieces are needed to make this happen.
the SOAP client in ClientJAXRPC.java, which we've already seen
a client deployment descriptor, which tells WSS4J how to handle security for the request
on the client: client_deploy_sec.wsdd
a client-side handler that sets the password: PWCallbackClient.java
a server deployment descriptor, which tells WSS4J how to handle security for the request
on the server: deploy.wsdd
a server-side handler that checks whether the security requirements declared in the
deployment descriptor have been met: PWCallbackServer.java
Let's go through these one by one and examine the details. We'll omit the client, as
it hasn't changed. The important part of the client deployment descriptor is this:
        <handler type="java:org.apache.ws.axis.security.WSDoAllSender">
                <parameter name="action" value="UsernameToken"/>
                <parameter name="user" value="wsuser"/>
                <parameter name="passwordCallbackClass"
                <parameter name="passwordType" value="PasswordText"/>
                <parameter name="passwordType" value="PasswordDigest"/>
Spring : (Jax-Ws)

Witk CFX :
With IBM Metro :
And finally with Metro

17 )   Marshall and UnMarshall with JAXB ?

Jaxb Marshalling :
This converts your Java Object to XML and write that to "StringWriter()".
                //Result messageString = null;
                JAXBContext jc;
                StringWriter sw = null;
                try {
                        jc = JAXBContext.newInstance( "com.test.generated" );
                        Marshaller marshaller = jc.createMarshaller();
                        sw = new StringWriter();
                        marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
                        marshaller.marshal( yourObject, sw );
             } catch (JAXBException e) {
                        // TODO Auto-generated catch block
Jaxb UnMarshalling :
This converts the "message" string to YourJavaObject.
                       StringReader reader = new StringReader(message);
                        jc = JAXBContext.newInstance("com.test.generated");
                        Marshaller marshaller = jc.createMarshaller();
                        javax.xml.bind.Unmarshaller unmarshaller = jc.createUnmarshaller();
                        InputStream is = new ByteArrayInputStream(message.getBytes());
                        jAXBElement = (YourJavaObject) unmarshaller.unmarshal(reader);

18 )   ASYNC Web Service example with JAX-WS

@WebService(name="StockQuote", serviceName="StockQuoteService")
public class StockQuoteImpl {
       public double getQuote(String ticker) {
                double result = 0.0;
                if (ticker.equals("MHP")) {
                        result = 50.0;
                } else if (ticker.equals("IBM")) {
                        result = 83.0;
                return result;
Server Ant Target :
<?xml version="1.0" encoding="UTF-8"?>
<target depends="setup" name="build-server-java">
  <apt debug="${debug}" destdir="${build.classes.home}" fork="true"
    sourcedestdir="${build.classes.home}" sourcepath="${basedir}/src" verbose="${verbose}">
      <path refid="jaxws.classpath"/>
      <pathelement location="${basedir}/src"/>
    <option key="r" value="${build.home}"/>
    <source dir="${basedir}/src">
      <include name="**/server/*.java"/>
Client Async Target :
<?xml version="1.0" encoding="UTF-8"?>
<target depends="setup" name="generate-client-async">
  <wsimport debug="${debug}" destdir="${build.classes.home}"
    extension="${extension}" keep="${keep}" verbose="${verbose}" wsdl="${client.wsdl}">
    <binding dir="${basedir}/etc" includes="${schema.binding}"/>
    <binding dir="${basedir}/etc" includes="${client.binding.async}"/>
----- Client with Call back Class
private class GetQuoteCallbackHandler implements AsyncHandler<GetQuoteResponse>{
 private GetQuoteResponse output;
 public void handleResponse (Response<GetQuoteResponse>response)
 { output = response.get ();
 } catch (ExecutionException e)
 { e.printStackTrace (); }
 catch (InterruptedException e)
 { e.printStackTrace (); }

 GetQuoteResponse getResponse (){
 return output;
Client :
StockQuote port = new StockQuoteService().getStockQuotePort();

 GetQuoteCallbackHandler callbackHandler = new GetQuoteCallbackHandler ();

 responseCallback = port.getQuoteAsync ("MHP", callbackHandler);
 while( ! responseCallback.isDone()){
 //some client side processes
 result = callbackHandler.getResponse().getReturn();

19 )   What is a RESTful web service ?

Representational State Transfer (REST) a simpler alternative to SOAP- and Web Services
Description Language (WSDL)-based Web services, i
t defines a set of architectural principles
by which you can design Web services that focus on a system's resources, including how
resource states are addressed and transferred over HTTP by a wide range of clients written
in different languages.
A REST Web service implementation follows four basic design principles:
i) Use HTTP methods explicitly.
ii) Be stateless.
iii) Expose directory structure-like URIs.
iv) Transfer XML, JavaScript Object Notation (JSON), or both.

20 )   SOAP VS REST web services ?

Here are some of the differences.
Protocol for invoking operationsSoapHttp
Transport ProtocalHttp,TCP,OthersHttp
Language for describing
Conveying security tokensWS-SecurityHTTP, SSL
Supporting distributed ACIDTransactions WS-AtomicTransaction,WS-CoordinationNo standard

21 )   Jax-Ws RestFul Service Example


Client :
public class RESTclient {
    private Service service;
        private JAXBContext jc;
    private static final String url = "";
    private static final QName qname = new QName("", "");
    private static final String poXML = "<tns:PurchaseOrderDocument
        xmlns:tns=\"urn:PurchaseOrderDocument\">\n" ;

        public RESTclient() {
        try {
            jc = JAXBContext.newInstance("com.sun.examples.rest");
        } catch(JAXBException je) {
            System.out.println("Cannot create JAXBContext " + je);
         private void acceptPO() {
                service = Service.create(qname);
                service.addPort(qname, HTTPBinding.HTTP_BINDING, url + "acceptPO");
        Dispatch<Source> dispatcher = service.createDispatch(qname, Source.class, Service.Mode.MESSAGE);
        Map<String, Object> requestContext = dispatcher.getRequestContext();

        requestContext.put(MessageContext.HTTP_REQUEST_METHOD, "POST");
        Source result = dispatcher.invoke(new StreamSource(new StringReader(poXML)));
         public static void main(String argsp[]) throws Exception{
        RESTclient client= new RESTclient();
Server Side :

public class PurchaseOrderService  implements Provider<Source>{

        private JAXBContext jc;

    protected WebServiceContext wsContext;

    public PurchaseOrderService() {
        try {
            jc = JAXBContext.newInstance("com.sun.examples.rest");
        } catch(JAXBException je) {
            System.out.println("Exception " + je);
            throw new WebServiceException("Cannot create JAXBContext", je);
 public Source invoke(Source source) {
            MessageContext mc = wsContext.getMessageContext();
            String path = (String)mc.get(MessageContext.PATH_INFO);
            String method = (String)mc.get(MessageContext.HTTP_REQUEST_METHOD);
            System.out.println("Got HTTP "+method+" request for "+path);
                    if (method.equals("GET"))
                       return get(mc);
                        if (method.equals("POST"))
                                    return post(source, mc);
                if (method.equals("PUT"))
                                        return put(source, mc);
                if (method.equals("DELETE"))
                                        return delete(source, mc);
                        throw new WebServiceException("Unsupported method:" +method);
        } catch(JAXBException je) {
            throw new WebServiceException(je);
     * Handles HTTP GET.
 private Source get(MessageContext mc) throws JAXBException {
        String path = (String)mc.get(MessageContext.PATH_INFO);
            if((path.indexOf("/errortest")!=-1)  || path.equals("") || path.equals("/")){
                         mc.put(MessageContext.HTTP_RESPONSE_CODE, 400);
             POProcessingProblem fault= new POProcessingProblem();
             fault.setMessage("Unable to retrieve the order associated with the orderid you specified");
             return new JAXBSource(jc, new ObjectFactory().createPOProcessingFault(fault));
                // demonstrates verb in path strategy
        if (path != null && path.lastIndexOf("/acceptPO")!=-1) {
          String xml= java.net.URLDecoder.decode(path.substring(10,path.length()),"UTF-8");
                  String replacedstr=xml.replace("http:/","http://");
                        Unmarshaller u = jc.createUnmarshaller();
                        JAXBElement o = (JAXBElement)u.unmarshal(new StringReader(xml.trim()));
                        PurchaseOrder request = (PurchaseOrder)o.getValue();
                        PurchaseOrderStatus response= acceptPO(request);
                     return new JAXBSource(jc, new ObjectFactory().createStatus(response));
                        }catch(java.io.UnsupportedEncodingException e){}
                {               path.replace("/","");
                                        PurchaseOrder order= retreivePO(path);
                                        return new JAXBSource(jc, new ObjectFactory().createPurchaseOrderDocument(order));
                throw new WebServiceException("Webservice does not understand the operation you invoked="+path);
Web XML :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <display-name>PurchaseOrder Service</display-name>
sun-jaxws.xml :
<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
    <endpoint name="RESTfulWebService"

22 )   Browser as client for a Restful

Below is the Browser Client Example for above RestFul Service Example,
as we all know we have to use AJAX for this.

<script type="text/javascript" language="javascript">
   var http_request = false;
   function makePOSTRequest(method,url, parameters) {
      http_request = false;
      if(window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
               // Set type accordingly to anticipated content type.
            // http_request.overrideMimeType('text/html');
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
      if (!http_request) {
         alert('Cannot create XMLHttpRequest object);
         return false;
      http_request.onreadystatechange = alertContents;
     // http_request.open(method, url, true);
                 http_request.open(method, url+parameters, true);
                 http_request.setRequestHeader("Content-type", "text/xml");
                 http_request.setRequestHeader("Content-length", parameters.length);
                 http_request.setRequestHeader("Connection", "close");
     if(method=='POST')  {
                 http_request.open(method, url, true);
                 http_request.setRequestHeader("Content-type", "text/xml");
                 http_request.setRequestHeader("Content-length", parameters.length);
                 http_request.setRequestHeader("Connection", "close");
     if(method=='PUT')  {
                 http_request.open(method, url, true);
                 http_request.setRequestHeader("Content-type", "text/xml");
                 http_request.setRequestHeader("Content-length", parameters.length);
                 http_request.setRequestHeader("Connection", "close");
     if(method=='DELETE')  {
                 http_request.open(method, url+parameters, true);
                 http_request.setRequestHeader("Content-type", "text/xml");
                 http_request.setRequestHeader("Content-length", parameters.length);
                 http_request.setRequestHeader("Connection", "close");
function alertContents() {
   if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        alert('Response received from server:\n'+http_request.responseText);
        result = http_request.responseText;
   // Turn < and > into &lt; and &gt; for displaying on the page.
        result = result.replace(/\<([^!])/g, '&lt;$1');
        result = result.replace(/([^-])\>/g, '$1&gt;');
       document.getElementById('serverresponse').innerHTML = result;
    } else {
      alert('There was a problem with the request.'
                    +http_request.responseText +' '+http_request.status);
      document.getElementById('serverresponse').innerHTML = http_request.responseText;

   function postTheForm() {
      var poststr = document.myform.xmldata.value ;
      alert('Sending XML to server:\n'+poststr);
      makePOSTRequest('POST',document.myform.endpointURL.value , poststr);

   function getTheForm() {
      var getStr = encodeURI(document.myform.xmldata.value) ;
      alert('Sending XML to server:\n'+getStr);
      makePOSTRequest('GET',document.myform.endpointURL.value , getStr);

   function putTheForm() {
      var poststr = document.myform.xmldata.value ;
      alert('Sending XML to server:\n'+poststr);
      makePOSTRequest('PUT',document.myform.endpointURL.value , poststr);

   function deleteTheForm() {
      var getStr = encodeURI(document.myform.xmldata.value) ;
      alert('Sending XML to server:\n'+getStr);
      makePOSTRequest('DELETE',document.myform.endpointURL.value , getStr);

23 )   How to use HTTP Client ?

There are Several ways of doing this. Following most popular ways. We can also consider
this as REST Web services client.
i) By using HTTPConnectionURL :
public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.yourwebsite.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)

ii) By using Apache HttpClient :
          HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://yourhost/QueueTester/messageSender.do");
                try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
                        nameValuePairs.add(new BasicNameValuePair("jmsMessage","http post"));
                        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = client.execute(post);
                        BufferedReader rd = new BufferedReader(
      new InputStreamReader(response.getEntity().getContent()));
                        String line = "";
                        while ((line = rd.readLine()) != null) {
        } catch (IOException e) {

24 )   What are the different Parts of a soap request ?

Please take a look at the following sampe Soap Request :
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
     <!-- Header information here -->
    <!-- Body or "Payload" here, a Fault if error happened -->
The SOAP <Header>
SOAP uses special attributes in the standard "soap-envelope" namespace to handle
the extensibility elements that can be defined in the header.
The SOAP <Body>
The SOAP body contains the "payload" of the message, which is defined by the WSDL's
<Message> part. The SOAP <Fault>
The SOAP <Fault>
The <Fault> is the standard element for error handling in your soap response. When present,
it would be the only child element of the SOAP <Body>. The structure of a fault looks like:
<env:Fault xmlns:m="http://test/timeouts">
     <env:Text xml:lang="en">Sender Timeout</env:Text>

25 )   How many way Spring Support Remote functionality ?

Spring support Remoting several ways, but the following are important ones among them.
Remote Method Invocation (RMI). Through the use of the RmiProxyFactoryBean and the
RmiServiceExporter Spring supports both traditional RMI (with java.rmi.Remote interfaces
and java.rmi.RemoteException) and transparent remoting via RMI invokers.
Spring's HTTP invoker. Spring provides a special remoting strategy which allows for Java
serialization via HTTP, supporting any Java interface (just like the RMI invoker). The
corresponding support classes are HttpInvokerProxyFactoryBean and HttpInvokerServiceExporter.
JAX RPC. Spring provides remoting support for Web Services via JAX-RPC.
<bean id="accountService" class="example.AccountServiceImpl">
    <!-- any additional properties, maybe a DAO? -->
Next we'll have to expose our service using the RmiServiceExporter:
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
        <!-- does not necessarily have to be the same name as the bean to be exported -->
        <property name="serviceName" value="AccountService"/>
        <property name="service" ref="accountService"/>
        <property name="serviceInterface" value="example.AccountService"/>
        <!-- defaults to 1099 -->
        <property name="registryPort" value="1199"/>

HTTPInvoker :
Server side :
<bean id="httpInvokerProxy" class="org.sprfr.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
  <property name="serviceUrl" value="http://remotehost:8080/AccountService"/>
  <property name="serviceInterface" value="example.AccountService"/>
<property name="httpInvokerRequestExecutor"> <bean class="org.springframework.remoting.
httpinvoker.CommonsHttpInvokerRequestExecutor"/> </property>
Web Services:
Exposing services using JAX-RPC :
Spring has a convenience base class for JAX-RPC servlet endpoint implementations -
ServletEndpointSupport. To expose our AccountService we extend Spring's ServletEndpointSupport
class and implement our business logic here, usually delegating the call to the business layer
public class AccountServiceEndpoint extends ServletEndpointSupport
implements RemoteAccountService {
    private AccountService biz;
Accessing Web Services
<bean id="yourWebService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
        <property name="serviceInterface">
        <property name="wsdlDocumentUrl">
        <property name="namespaceUri">
        <property name="serviceName">
        <property name="portName">

26 )   How to use JMS with Spring (JmsTemplate) ?

public class JmsQueueSender {
  private JmsTemplate jmsTemplate;
  private Queue queue;
  public void setConnectionFactory(ConnectionFactory cf) {
    jt = new JmsTemplate102(cf, false);
  public void setQueue(Queue q) {
    queue = q;
  public void simpleSend() {
    this.jmsTemplate.send(this.queue, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage("hello queue world");

27 )   How to Generate Java classes from WSDL ?

You need to use WSDL2Java
Please download the CXF package and use WSDL2JAVA which is bin folder.
CXF ANT Target :
<property name="cxf.home" location ="C://tools//cfx"/>
   <path id="cxf.classpath">
      <fileset dir="${cxf.home}/lib">
         <include name="*.jar"/>
   <target name="cxfWSDLToJava">
      <java classname="org.apache.cxf.tools.wsdlto.WSDLToJava" fork="true">
         <arg value="-client"/>
         <arg value="-d"/>
        <arg value="src"/>
        <arg value="${wsdl.uri.yourService}"/>
            <path refid="cxf.classpath"/>
Axis2 Ant Target:
 <target name="yourservice">
   <java classname="org.apache.axis2.wsdl.WSDL2Java" fork="true" classpathref="axis2.classpath">
     <arg line="-uri ${wsdl.uri.yourservices}"/>
        <arg line="-s"/>
        <arg line="-ss"/>
        <arg line="-sd"/>
        <arg line="-ssi"/>
        <arg line="-ap"/>
         <arg line="-l java"/>
         <arg line="-d xmlbeans"/>
        <arg line="-o ${build.dir}/service"/>                                      

28 )   Web Service Testing with SOAP UI ?


  • Web Service Testing  with SOAP UI ?
    Sample Img 28
We could use SOAP UI to test the Web Services before Completing the Client implementation
to test if the Service is functional as expected .
Please take a look at above Image for getting an idea how the SOAPUI looks like.

29 )   How to get Soap Request Response from Axis call ?

You could get the Soap Request and Response from a Axis Web service Call as shown below.
Getting Soap Request :

Getting Soap Response :

"AJaxTechs "

This Section focuses on AJAX based Techs such as DOJO,DWR,GWT etc.,
1 )   What is Ajax ?

Ajax stands for Asynchronous JavaScript and XML,enables us to create asynchronous web applications. By using Ajax,
the web clients (Browsers) can send data to, and retrieve data from, a server asynchronously without impacting the
the existing page. Data is usually retrieved using the XMLHttpRequest object.

2 )   How you make AJAX call from a Browser ? Or What is XMLHttpRequest () ?

We could make a AJAX call from browser using "XMLHttpRequest". The XMLHttpRequest
object provide a method for exchanging data asynchronously between browser and
server to avoid full page reloads.
Here is the quick example:
             function makeAjaxCall(){
                                alert("XMLHttpRequest supported by browser ee");
                                xhttp = new XMLHttpRequest();
                                xhttp.open("GET", url, false);
                                alert("reching your Request ?");

                                alert("ActiveXObject supported by browser");

3 )    How you come to know if an AJax call is Success or failed ?

onreadystatechange is a event listener in AJAX,  this will be automatically invoked
for all the actions such as submiting data, finishing call etc., of any Ajax call,
and these would change the readyState property of the XMLHttpRequest object,
that will inform you if the given Ajax request is successed or failed.
So by using readyState value we can see check if a given Ajax call is successful or not,
if readyState Value is 4, we could consider that is successful. You could also check
xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status==200){


4 )   Ajax call is going to cause Cross Scripting ?

Opps stands for Object Oriented

5 )    How to Parse the XML by using Java Script ?

You can parse the given XML string by using jQuery as follows.
function xmlParser(elementName, questionName) {
            str = "<QuestionsList><Question>What is your name?</Question>
                       /QuestionsList><QuestionsList><Question>Where you born ?
                var questionArray =new Array();
                var xml = $.parseXML(str);
                 if(elementName=="QuestionsList") {        
                var result = $(xml).find("QuestionsList").each(
    var img_path = $(this).find('Question').text();
                                        var name_text = $(this).find('Answer').text();
                                        questionArray[i] = img_path;


6 )   How to generate JSON by using Java ?

You have to use "JSONObject" API. Please take a look at the following Example.
import net.sf.json.JSONObject;
public class YourJSONJavaExample
  public static void main(String args[]){
  JSONObject object=new JSONObject();
 object.put("age",new Integer(21));

7 )   What is JSON , how to create JSON objects in java ?

JSON is short form of JavaScript Object Notation, is a lightweight text-based open standard
designed for human-readable data interchange, th
is could be considered as an alternative for
XML. It is derived from the JavaScript scripting language for representing simple data
structures and associative arrays, called objects.
Example JSON Schema:
Example JSON object for above schema :
        "id": 1,
        "name": "Smith",
        "price": 88,

8 )   What are different popular Ajax Techs ?

Some of there below
2) DWR
3) GWT ?
4) Ext JS

9 )   How to use GWT ?

Opps stands for Object Abstraction

10 )   What is GWTC ?


GWTC - GWT Compiler, 
GWTC compiles GWT classes and generate JavaScript.
After you create GWT classes , we need to compile them by using GWTC, here is the GWTC ANT Target.
<target name="gwtc" depends="compile,server-jar" description="GWT compile to JavaScript">
  <java failonerror="true" fork="true" classname="com.google.gwt.dev.Compiler">
    <pathelement location="../gwt/src/main/java"/>
    <pathelement path="src/main/java" />
    <path refid="project.class.path" />
   <jvmarg value="-Xmx256M" />
   <arg value="com.test.gwt" />

11 )   What kind of issue you may face with Ajax ?

Opps stands for Object Abstraction

12 )   Race Condition Issues with AJAX calls ?

Racing issues, these are very serious issues if you will not design the Ajax calls properly,
this may force you to change your UI architecture some times. You have to careful while
you use Ajax for making interdependent calls.
Here are the situation you may come across, when your browser makes Two Ajax calls which
are interdependent and are expected to be run sequencially, but as these are Asyncronuos
calls you may not know which one will be completed first gets
the Response,  if you get the response of the Second Ajax call before getting the
Response of First Ajax which may be wrong and impact the functionality . 
To avoid this , you may stop the browser process as shown below.
function firstCall() {
  //do some things
  setTimeout(secondCall, 1000)
  function secondCall() {
  //finish doing things after the pause
Please note this is not a optimal solution, because there are some chances that this also
may not work If the FirstCall is not completed in "1000" Milli Secs.

13 )   Spring DWR example

Step 1 : Create a Service "YourPageManager" with different methods
  Step 2: Add the following Spring Config.
<dwr:remote javascript="YourPageManagerJS">
   <dwr:include method="getAccountSalesList"/>
   <dwr:include method="getEmailAddressByWebUserObjid"/>
   <dwr:include method="getStates"/>
   <dwr:include method="getTransportType"/>
   <dwr:include method="getContacts"/>
   <dwr:include method="findContacts"/>
   <dwr:filter class="com.your.ajax.DwrSecurityFilter"/>

     <dwr:convert type="bean" class="com.yourApp.ContactDetails"
     javascript="Contact" />
 <bean id="Contact" class="com.yourApp.ContactDetails">
Step 3 :
Add the following to JSP
Jsp changes :
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/util.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/YourPageManagerJS.js"></script>

YourPageManagerJS.addContactsToDTO(contactInfo, function(data){
    window.saveClicked = false;
    window.contactSaved = true;

15 )   DOJO Example


As mentioned in one of the above questions, DOJO is one of the popular Ajax Technologies
which enables you to
make HTTP calls Asyncronously.
Step 1:
Include DOJO libraries (.js files)
 <script type="text/javascript" src="<c:url value="/includes/dojo_nav/js/
 <script type="text/javascript" src="<c:url value="/includes/dojo_nav/js/

Step 2:
Write Java Script method to make a Serverside call.
function fillContactFields() {

 dojo.xhrGet( {
        url: "<c:url value="/populateContact.do"/>",
        handleAs: "json",
  form: dojo.byId("populateContactForm"),
        load: function(response) {
          return response;
        // The ERROR function will be called in an error case.
        error:  function(type, data, evt){alert("Error");}

Step 2:
Display the result in whichever way to want.
//function populateContactFields(type, data, evt) {
function populateSiteFields(data) {
    var contactId, address1, address2, city, state, zip, contactName, siteTenantType;
    contactId = document.forms[0].contactId;
    contactId.value = "0";

    if (data.contactId) {
       contactId.value = data.contactId;      
    address1 = document.getElementById("address1");
    address1.value = "";
    if (data.address1) {
        address1.value = data.address1;
    address2 = document.getElementById("address2");
    address2.value = "";
    if (data.address2) {
        address2.value = data.address2;
    city = document.getElementById("city");
    city.value = "";
    if (data.city) {
        city.value = data.city;
    state = document.getElementById("state");
    state.vaue = "";
    if (data.state) {
        state.value = data.state;
    zip = document.getElementById("zip");
    zip.value = "";
    if (data.zip) {
        zip.value = data.zip;
    siteName = document.getElementById("siteName");
    siteName.value = "";
    if (data.siteName) {
        siteName.value = data.siteName;

"BuildProcess "

This section focuces Build and deployment Process.
1 )   What is continuous Integration ?

Continuous Integration is a software development practice where members of a team integrate
their work (Code) frequently, usually each person integrates at least daily - leading to multiple
integrations per day. By having scheduled automated builds we can determine if are there any
integration issues , also by running the Unit Testcases as part of these builds and verify
if is the existing functionality is broken. Automated tools such as CruiseControl, Jenkins,
Hudson, Bamboo, BuildMaster, AnthillPro or Teamcity offer this scheduling automatically.
Here are the principles of "Continuous Integration"
Maintain a code repository :
Code should be maintained in a Version Control such as CVS,SVN,VSS,ClearCase etc., which could allow
multiple developers to work collaboratively in parallel by Versioning the Files (code).
Automate the build :
Should Have scheduled automated builds by using the tools like "Hudson,TeamCity, CruiseControl" etc.,
which could automatically checkout(Get) the code from Code Repository and build.
Make the build self-testing :
During the build process, after compiling the code we can make the Code Self-Testing by
executing the Unit Test cases such as JUNIT or Cactus or EasyMock etc. and confirms that
nothings is broken.
Automate deployment :
Once build and self-testing process is done, we should have automated Deployments.
Tools such as  "Hudson,TeamCity, CruiseControl" do complete "Continuous Integation" for you,
but you have to have some build script such as ANT or MAVEN scripts to perform some of these Tasks.
Here is the sequence of tasks that could be done by above tools.
i) Having Scheduled Builds. (Daily or Hours)
i) Checkout the code.
ii) Compile the Code.
iii) Running Unit Test-Casess.
iv) FTP code to different hosts
v) Deploy the artifacts.

2 )   What is Version Control ?

A "Version control" system (also known as a Revision Control System) is a repository of files,
often the files for the source code of computer programs, with monitored access. Every change
made to the source is tracked, along with who made the change, why they made it, and references
to problems fixed, or enhancements introduced, by the change.
Version control systems are essential for any form of distributed, collaborative development,
as different teams want to design, develop and deploy software in parallel and merge them easily.
Key Terms :
Check in :
 Saving your charges into Version Control .
Check Out :
 Getting the latest version from Version Control.
Conflict :
In general the "Version Control" merges your changes with existing Code automatically, and
merges them automatically , but sometimes the "Versions Control" detect Conflicts, and
the "Version Control" would not be able resolve, it would require a  manual
intervention to resolve the Conflict. 
Merge :
Combining multiple changes made to different working copies of the same files in the
source repository. Merging is a strategy for managing conflicts by letting multiple developers
work at the same time (with no locks on files), and then incorporating their work into one
combined version.
"Trunk" refers to the unnamed branch (version) of a file tree under revision control. The
trunk is usually meant to be the base of a project on which development progresses.
Branching :
Branching, in revision control and software configuration management, is the duplication
of an object under revision control (such as a source code file, or a directory tree) so that
modifications can happen in parallel along both branches.

3 )   SVN ?


  • SVN ?
    Sample Img 3
As we discssed SVN is a Sourcecode Version Control, you could manage
the files and folders in SVN by using the Command Line commands as
shown below or You could also use the some SVN clients like SmartSVN
or Tortoisesvn
svn diff
Shows line-level details of a particular change
svn log
Shows you broad information: log messages with date and author information attached to
 revisions and which paths changed in each revision
svn cat
Retrieves a file as it existed in a particular revision number and displays it on your screen
svn list
Displays the files in a directory for any given revision
Please take a look at above Sceenshot for getting an idea on how SmartSVN looks like. 

4 )   CVS VS SVN ?


Revision NumbersIn CVS, revision numbers are per file. This is because CVS stores its data in RCS files; each file has a corresponding RCS file in
the repository, and the repository is roughly laid out according to the structure of your project tree.
In Subversion, the repository looks like a single filesystem. Each commit results in an entirely new filesystem tree; in essence, the
repository is an array of trees. Each of these trees is labeled with a single revision number.
A tag or branchA tag or branch is an annotation on the file or on the version information for that individual file.In Subversion, a tag or branch is  a copy of an entire tree (by convention, into the /branches or /tags directories that appear at the toplevel of the repository, beside /trunk). In the repository as a whole, many versions of each file may be visible: the latest version  on each branch, every tagged version, and of course the latest version on the trunk itself.
Directory Versions The Subversion tracks tree structures, not just file contents. It's one of the biggest reasons Subversion was written to replace CVS.
The svn add and svn delete commands work on directories now, just as they work on files.
Binary Files and Translation Subversion handles binary files more gracefully than CVS does. Because CVS uses RCS, it can only  store successive full copies of a changing binary file. Subversion, however, expresses differences between files using a binary differencingalgorithm, regardless of whether they contain textual or binary data. That means all files are stored differentially
(compressed) in the repository.

5 )   JIRA , DOORs ?

JIRA is the project tracker for teams building great software.
JIRA sits at the center of your development team, connecting the people and the
work being done. Track bugs and tasks, link issues to related source code, plan
agile development, monitor activity, report on project status, and more.
DOORS, a leading solution for requirements management, provide capabilities including:
o A collaborative requirements management environment that allows all stakeholders to actively
     participate in the requirements process
o The ability to manage changing requirements
o Powerful life cycle traceability to help teams align their efforts with the business needs
    and measure the impact that changes will have on everything from business goals to development
o Support for requirements-driven testing with built-in test tracking tool and integrations with
     Rational Quality Manager and HP Quality Center
o Integrates with enterprise architecture, product portfolio management, model-driven development,
 quality management, and change and release management solutions from IBM and third party companies.

6 )   What is Hudson ? How to use this ?


  • Hudson ?
    Sample Img 6
Hudson is a continuous integration (CI) tool written in Java, which runs in a servlet
container, such as Apache Tomcat or the Weblogic application server. It supports SCM
tools including CVS, Subversion, Git, Perforce and Clearcase and can execute Apache Ant
and Apache Maven based projects, as well as arbitrary shell scripts and Windows batch commands.
Please take a look at above screenshot to get an undestanding how the Hudson looks like.

more info...       
7 )   Hudson Part2 Image


  • Hudson Part2
    Sample Img 7
Please take a look at Hudson Part2

more info...       
8 )   How to Compile classes using ANT ?

  <target name="compile-tests" depends="init">
  <fileset dir="${test.src.dir}"/>
    <javac srcdir="${test.src.dir}" destdir="${test.build.dir}" verbose="false" debug="on">
      <classpath refid="classpath.test"/>


9 )   How to start Tomcat by using ANT ?

 <target name="start-tomcat" if="start.tomcat.jdpa">
   <echo>Starting Tomcat with JDPA on port ${jpda.port}</echo>
    <java jar="${container.home}/bin/bootstrap.jar" fork="true">
        <jvmarg value="-Xms512m"/>
        <jvmarg value="-Xmx1280m"/>
        <jvmarg value="-Dcatalina.home=${container.home}"/>
        <jvmarg value="-Dcatalina.base=${container.home}"/>
        <jvmarg value="-Djava.endorsed.dirs=${container.home}\common\endorsed"/>
        <jvmarg value="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"/>
     <jvmarg value="-Xdebug"/>
     <jvmarg value="-Xrunjdwp:transport=dt_socket,address=5454,server=y,suspend=n"/>

10 )    How to stop the Tomcat using ANT Target ?

  <target name="stop-tomcat">
    <java jar="${container.home}/bin/bootstrap.jar" fork="true">
        <jvmarg value="-Dcatalina.home=${container.home}"/>
        <arg line="stop"/>


11 )   How to run JUNIT and generate a Report by using ANT ?

 <target name="test-Junit" depends="init">
      <junit fork="no" haltonfailure="no" failureproperty="tests.failed">
        <classpath refid="classpath.clientside" />
        <formatter type="xml" />
        <test name="test.TestSuite" haltonfailure="no" todir="${reports.junit.dir}" />


12 )   How to run more than one Task in Parell by using ANT

<target name="run-tests"
        description="Runs alltests in-container.">
            <antcall target="start-tomcat" />
                 <antcall target="test-Junit" />
                    <antcall target="stop-tomcat" />
                     ----- Some Other Ant Taget


13 )   How to do GWTC with ANT ?


<target name="gwtc" depends="compile,server-jar" description="GWT compile to JavaScript">
  <java failonerror="true" fork="true" classname="com.google.gwt.dev.Compiler">
    <pathelement location="../gwt/src/main/java"/>
    <pathelement path="src/main/java" />
    <path refid="project.class.path" />
   <jvmarg value="-Xmx256M" />
   <arg value="com.test.gwt" />
  <copy todir="../../../web/gwt/">
   <fileset dir="war/"/>
  <zip destfile="../../../web/WEB-INF/lib/gwt.jar">
   <fileset dir="war/WEB-INF/classes"  includes="**/*.class,**/*.xml" />

14 )   What is Team City ?


15 )   How to pre-compile the JSPs ?

<taskdef classname="org.apache.jasper.JspC" name="jasper" >
         <pathelement location="${java.home}/../lib/tools.jar"/>
         <fileset dir="${ENV.CATALINA_HOME}/lib">
             <include name="*.jar"/>
         <path refid="myjars"/>
 <jasper verbose="0"
          outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />

"UnitTesting "

UnitTesting is very important in development life cycle, this section focuses on Unit Testing methodologies.
1 )   What is Unit Testing ?

In computer programming, Unit testing is a method by which individual units of source
, sets of one or more computer program modules together with associated control data,
usage procedures, and operating procedures, are tested to determine if they are fit
for use.one can view a unit as the smallest testable part of an application. In
object-oriented programming a unit is often an entire interface, such as a class,
but could be an individual method.
In Java World there are so many APIs which could be used for performing Unit Testing,

2 )   JUnit Unit Testcase Example ?

JUNIT is a very popular Unit Tesing API, this has been widely used
for performning Unit Testing.
Below are steps to follow for creating a JUNIT Test Case.
public class TestYourService extends TestCase {

 protected void setUp()  {
  try {
  } catch (Exception e) {
   // TODO Auto-generated catch block

 protected void tearDown() throws Exception {
 public void testYourMethod() throws ComergentException {
         TestService testService = new TestServiceImpl(); 
         String result = testService.perform();
         assertEquals("Success", result);

3 )   Cactus Unit Testcase Sample ?

Cactus is used for Unit Testing of the source code which requires a Servlet Containers
meaning which requies HTTPServletRequest, HTTPServletResponse.
Step 1:
import org.apache.cactus.ServletTestCase;
import org.junit.Test;
public class YourCactusTest extends ServletTestCase {
 protected void setUp() throws Exception {

 public void testFillPriceLines ()  {
  assertEquals(2, hboCount);
  assertEquals(3, premierCount);

 public void testFillPriceLinesOnlyHBO ()  {
  assertEquals(2, hboCount);

Step 2:
Deploy your test in a Servlet Container and use the following URL to
run the Test.
Step 3 :
Add the Following to web.xml

4 )   Unit Testing of Struts Action Class.

"Servletunit" should be used to perform the Unit Testing of the Struts actions also as we need ServletRequest/Response etc.,  for this.
 "MockStrutsTestCase" should be used for this purpose. Please see below for full example.
Step 1 :
Please download "servletunit" jar
Step 2:
Your Test Case should extend "MockStrutsTestCase".
Step 3:
Create your TestCase as follows .
public class EditActionTest extends MockStrutsTestCase {
public EditActionTest(String name) {
 public void tearDown() throws Exception {
   public void test_update() throws Exception{
  addRequestParameter("method", "update");
  addRequestParameter("contactId", "273016914");
  addRequestParameter("reloadContact", "false");
  addRequestParameter("zipCode", "08053");
  addRequestParameter("address1" , new String[]{"225 Test road", "Apt 6","Test City","Test State"});

  assertEquals(request.getAttribute("isAddressVarified"), true);
 public void test_getContactData() throws Exception {
  ContactForm form = new ContactForm();
  HttpServletRequest request = createMock(HttpServletRequest.class);
 BigDecimal oppObjid = new BigDecimal("273028572");
  Contact opportunity = (Contact) ContactServices

5 )   JMockito Unit Testcase Example ?


Junit has some limitaions , for instance we could not test the Private and Static methods
with JUNIT, this issue is addressed by some other Unit Testing APIs such EasyMock, Mockito
and all.
Here is the sample Mocktio Unit Test case.
Step 1 :
Util class which has a Static Method.
class TestUtil {

 public static printName (Srting name ) {

  System.out.println("Your Name is " + name);
Step 2 :
 Your service that to be tested.
class YourService {
 public YourService() {

 public void printName (Srting Name) {
Step 3:
Your Test Case
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.whenNew;

import org.apache.tools.ant.taskdefs.Length.When;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@PrepareForTest({ TestUtil.class})

public class TestBroadBandService {

 public void createData() {
  when (TestUtil.printName("") .thenReturn("newName");
 public void testInvokeWebService() {
  YourService YourService = new YourService();

6 )   Spring Unit Testing

Full Spring Unit Testing Example.
If you want to perform unit testing for your Spring Classes, you have to use "SpringJUnit4ClassRunner",
Please follow the below steps to create Unit Test cases for Spring Classes.
Step 1:
Use "@RunWith" annotation as follows.
Step 2:
Provide the path of Spring Config file as shown below.
Step 3:
Use "@Autowired" for the Java class that you want to be loaded by Spring as shown below.
    ContactServices ContactServices;

Example :

import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import javax.servlet.ServletException;
import org.hibernate.classic.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.salesorder.enumtypes.EnumConditions;
import com.salesorder.Contact.services.ContactServices;
import com.salesorder.hibernate.Address;
import com.salesorder.hibernate.HibernateConfig;
import com.salesorder.hibernate.Contact;
import com.salesorder.user.services.ProfileServices;
public class ContactServiceTest {

    ContactServices ContactServices;
 public ContactServiceTest (){
        try {
   new HibernateConfig().init();
  } catch (ServletException e) {
   // TODO Auto-generated catch block
 public void testCreateContact() throws BLException {   

        Address address = new Address();
        String ContactName = "Test" + System.currentTimeMillis();
        Contact Contact = new Contact();
        Contact = ContactServices.createContact(Contact, address);
        assertTrue("Contact Not Created", !(Contact == null)); 
 public void testFindContactsWithInfo() throws BLException {
        List Contacts =ContactServices.findContacts(EnumConditions.BEGINS_WITH, null,
          EnumConditions.BEGINS_WITH, "TEST", EnumConditions.BEGINS_WITH, "TEST",
          EnumConditions.BEGINS_WITH, null, EnumConditions.BEGINS_WITH, "PA",
          EnumConditions.BEGINS_WITH, "19087");

        assertTrue("incorrect search result", Contacts.size() > 0);
        System.out.println("No. of Contacts found " + Contacts.size());   

 public void testFindContactByContactId() throws BLException {
   Contact contact = ContactServices.findContactByContactID(new BigDecimal(12345));

7 )   Selenium Unit Testcase ?

Stay Tuned

8 )   How to write an Unit Test Case for a Hibernate Class?


Step 1:
Hibernate Classes also should be tested as normal classes, with exception of passing the
hibernate Properties files as follows.
System.setProperty("hibernate.properties.file.name", "hibernate_junit.properties");
Step 2:
In Hiberante Properties file or XML file you need to use dbcp Connection APIas follows.
hibernate.dialect org.hibernate.dialect.OracleDialect
hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
hibernate.connection.url jdbc:oracle:thin:@HostName:1522:DBName
hibernate.connection.username sa
hibernate.connection.password yourPassword
hibernate.connection.pool_size 5
hibernate.dbcp.poolPreparedStatements true
hibernate.connection.provider_class com.salesorder.DBCPConnectionProvider
Step 3 :
Create Your own DBCPConnectionProvider as follows
public class DBCPConnectionProvider implements ConnectionProvider {
    private static final Log log = LogFactory.getLog(DBCPConnectionProvider.class);
    private static final String PREFIX = "hibernate.dbcp.";
    private BasicDataSource ds;
Step 4:
Write a TestCase as follows
public class SalesOrderTestCase extends TestCase {
    static {
        try {
            System.setProperty("hibernate.properties.file.name", "hibernateDEV_junit.properties");
            new HibernateConfig().init(null);
        catch (Exception ex) {
            System.err.println("Could not initialize Hibernate Config");
            throw new RuntimeException("Could not initialize Hibernate Config");
    public SalesOrderTestCase() {
    public SalesOrderTestCase(String name) {
     * override this in a subclass if you want to setup a separate principle than
     * nkuppili.
    public void setUp() throws Exception {
    public void tearDown() throws Exception {

9 )   Web Service Testing with SOAP UI ?


  • Web Service Testing  with SOAP UI ?
    Sample Img 9
We could use SOAP UI to test the Web Services before Completing the Client implementation
to test if the Service is functional as expected .
Please take a look at above Image for getting an idea how the SOAPUI looks like.