Loading
WebServices Interview Questions

Java Quick Notes

Refresh Your Java

We are Agile, believe in less Documentation - Only Quick notes of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

"Click on other Tabs for more Questions"  

"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


Ans)


  • 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".



Back to top

2 )   Web service Stack ?


Ans)


  • Web service Stack ?
    Sample Img 2



Back to top

3 )   Web Service VS RMI VS EJB ?


Ans)

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.



Back to top

4 )   What is Soap ?


Ans)

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
 



Back to top

5 )   What is RPC, XML-RPC ?


Ans)

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.



Back to top

6 )   What is WSDL ?, Sample WSDL ?


Ans)

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"
   targetNamespace="http://www.ecerami.com/wsdl/HelloService.wsdl"
   xmlns="http://schemas.xmlsoap.org/wsdl/"
   xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
   xmlns:tns="http://www.ecerami.com/wsdl/HelloService.wsdl"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <message name="SayHelloRequest">
      <part name="firstName" type="xsd:string"/>
   </message>
   <message name="SayHelloResponse">
      <part name="greeting" type="xsd:string"/>
   </message>
    <portType name="Hello_PortType">
      <operation name="sayHello">
         <input message="tns:SayHelloRequest"/>
         <output message="tns:SayHelloResponse"/>
      </operation>
   </portType>
   <binding name="Hello_Binding" type="tns:Hello_PortType">
      <soap:binding style="rpc"
         transport="http://schemas.xmlsoap.org/soap/http"/>
      <operation name="sayHello">
         <soap:operation soapAction="sayHello"/>
         <input>
            <soap:body
               encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
               namespace="urn:examples:helloservice"
               use="encoded"/>
         </input>
         <output>
            <soap:body
               encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
               namespace="urn:examples:helloservice"
               use="encoded"/>
         </output>
      </operation>
   </binding>
  <service name="Hello_Service_New">
      <documentation>WSDL File for HelloService</documentation>
      <port binding="tns:Hello_Binding" name="Hello_Port">
         <soap:address
            location="http://localhost:8080/soap/servlet/HelloService"/>
      </port>
   </service>
</definitions>



Back to top

7 )   What are the different Parts of a WSDL ?


Ans)

Please take a look at the Sample WSDL provided above, Every Soap Request has the following parts.
 

<definitions>: The Hello Service
<message>:
i)sayHelloRequest:Firstname
ii)sayHelloResponse:
<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"



Back to top

8 )   What is Data Binding ?


Ans)

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



Back to top

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


Ans)


  • 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.



Back to top

10 )   Jaxb VS XMLBeans ?


Ans)

JAXB:
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:
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.



Back to top

11 )   Dynamic Web Service Client ?


Ans)

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.class,Service.Mode.MESSAGE);

     SOAPMessage request = MessageFactory.newInstance().createMessage(null,
         new FileInputStream("yourGoogleKey.xml"));

     SOAPMessage response = dispatch.invoke(request);
     response.writeTo(System.out);



Back to top

12 )   Xstream toXML() and fromXML () ?


Ans)

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
or
XStream xstream = new XStream(new DomDriver());
or
XStream(new StaxDriver());
String xml = xstream.toXML(YourJavaObject);
 

Xstream fromXML() :
YourJavaObject yourJavaObject= (YourJavaObject)xstream.fromXML(xml);



Back to top

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


Ans)

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.



Back to top

14 )   What is UDDI ?


Ans)

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("config",
              "http://idoox.com/uddiface/config");
            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");



Back to top

15 )    Marshalling and Unmarshalling ?


Ans)

"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.



Back to top

16 )   What is Web Sevice Authentication ?


Ans)

Basic Authentication : (Jax -RPC)

Web.xml changes :


  <security-constraint>
    <web-resource-collection>
         <web-resource-name>Axis-Servlet</web-resource-name>
       <description>...text...</description>
       <url-pattern>/services/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
       <role-name>yourWebServiceUser</role-name>
    </auth-constraint>
    <user-data-constraint>
       <description>...text...</description>
       <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>  
  </security-constraint>

  <login-config>
     <auth-method>BASIC</auth-method>
     <realm-name>myrealm</realm-name>
  </login-config>

  <security-role>
     <description>...text...</description>
     <role-name>yourWebServiceUser</role-name>
  </security-role>


Client Code :

      Call call = (Call) service.createCall();
      call.setUsername("yourWebServiceUser");
      call.setPassword("yourWebServiceUser");
         
                Or
               
       Stub stub = (Stub)(new
          MyHelloService_Impl().getHelloIFPort());
       
          stub._setProperty(
          javax.xml.rpc.Stub.USERNAME_PROPERTY, username);
        stub._setProperty(
          javax.xml.rpc.Stub.PASSWORD_PROPERTY, password);
        stub._setProperty
          (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"
                              value="fibonacci.handler.PWCallbackClient"/>
                <parameter name="passwordType" value="PasswordText"/>
                <!--
                <parameter name="passwordType" value="PasswordDigest"/>
                -->
        </handler>

       
Spring : (Jax-Ws)

Using WS-Security with Spring Web Services


Witk CFX :

Using Apache CXF with WS-Security
 

With IBM Metro :

And finally with Metro



Back to top

17 )   Marshall and UnMarshall with JAXB ?


Ans)

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
                        e.printStackTrace();
                }  
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);



Back to top

18 )   ASYNC Web Service example with JAX-WS


Ans)

@WebService(name="StockQuote", serviceName="StockQuoteService")
public class StockQuoteImpl {
        @WebMethod(operationName="getQuote")
       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}">
    <classpath>
      <path refid="jaxws.classpath"/>
      <pathelement location="${basedir}/src"/>
    </classpath>
    <option key="r" value="${build.home}"/>
    <source dir="${basedir}/src">
      <include name="**/server/*.java"/>
    </source>
  </apt>
</target>

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}"/>
  </wsimport>
</target>

----- Client with Call back Class
private class GetQuoteCallbackHandler implements AsyncHandler<GetQuoteResponse>{
 private GetQuoteResponse output;
 public void handleResponse (Response<GetQuoteResponse>response)
 {
 try
 { 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();

 



Back to top

19 )   What is a RESTful web service ?


Ans)

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.



Back to top

20 )   SOAP VS REST web services ?


Ans)

Here are some of the differences.

                  Soap-Ws Rest
Protocol for invoking operations Soap Http
Transport Protocal Http,TCP,Others Http
Language for describing
interfaces
WSDL No
Conveying security tokens WS-Security HTTP, SSL
Supporting distributed ACIDTransactions  WS-AtomicTransaction,WS-Coordination No standard

 



Back to top

21 )   Jax-Ws RestFul Service Example


Ans)

 

Client :

public class RESTclient {
    private Service service;
        private JAXBContext jc;
    private static final String url = "http://127.0.0.1:9090/restfulwebservice-war/poservice/";
    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)));
        printSource(result);
    }
       
         public static void main(String argsp[]) throws Exception{
        RESTclient client= new RESTclient();
        client.acceptPO();
        client.acceptPOJAXB();
    }

}

Server Side :

@javax.xml.ws.WebServiceProvider
@javax.xml.ws.ServiceMode(value=javax.xml.ws.Service.Mode.MESSAGE)

public class PurchaseOrderService  implements Provider<Source>{


 

        private JAXBContext jc;
   
    @javax.annotation.Resource(type=Object.class)
    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) {
        try{
            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) {
            try{
          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){}
                }
                else
                {               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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>PurchaseOrder Service</display-name>
  <listener>
    <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
  </listener>
  <servlet>
    <display-name>POServiceImpl</display-name>
    <servlet-name>POServiceImpl</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>POServiceImpl</servlet-name>
    <url-pattern>/poservice/*</url-pattern>
  </servlet-mapping>
</web-app>

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"
        implementation="com.sun.examples.rest.PurchaseOrderService" 
        binding="http://www.w3.org/2004/08/wsdl/http"
          url-pattern='/poservice/*'/>
</endpoints>



Back to top

22 )   Browser as client for a Restful


Ans)

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/xml');
            // 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);

     if(method=='GET'){
                 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");
                 http_request.send(null);
         }
     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");
                 http_request.send(parameters);
         }
     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");
                 http_request.send(parameters);
         }
     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");
                 http_request.send(null);
         }
}
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);
   }
</script>



Back to top

23 )   How to use HTTP Client ?


Ans)

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)
            System.out.println(inputLine);
        in.close();
    }
}


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) {
                                System.out.println(line);
                   }
        } catch (IOException e) {
                        e.printStackTrace();
                }



Back to top

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


Ans)

Please take a look at the following sampe Soap Request :

<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
 <env:Header>
     <!-- Header information here -->
 </env:Header>
 <env:Body>
    <!-- Body or "Payload" here, a Fault if error happened -->
 </env:Body>
</env:Envelope>

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:Code>
     <env:Value>env:Sender</env:Value>
     <env:Subcode>
      <env:Value>m:MessageTimeout</env:Value>
     </env:Subcode>
   </env:Code>
   <env:Reason>
     <env:Text xml:lang="en">Sender Timeout</env:Text>
   </env:Reason>
   <env:Detail>
     <m:MaxTimeout>P5M</m:MaxTimeout>
   </env:Detail>   
</env:Fault>



Back to top

25 )   How many way Spring Support Remote functionality ?


Ans)

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.

RMI:
<bean id="accountService" class="example.AccountServiceImpl">
    <!-- any additional properties, maybe a DAO? -->
</bean>
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"/>
</bean>


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"/>
</bean>

Client:
<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">
            <value>example.RemoteYourService</value>
        </property>
        <property name="wsdlDocumentUrl">
            <value>http://localhost:8080/your/services/yourService?WSDL</value>
        </property>
        <property name="namespaceUri">
            <value>http://localhost:8080/your/services/yourService</value>
        </property>
        <property name="serviceName">
            <value>yourService</value>
        </property>
        <property name="portName">
            <value>yourPort</value>
        </property>
    </bean>



Back to top

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


Ans)

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");
      }
    });
  }
}



Back to top

27 )   How to Generate Java classes from WSDL ?


Ans)

You need to use WSDL2Java

CXF CMD :

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"/>
      </fileset>
   </path>
     
   <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}"/>
         <classpath>
            <path refid="cxf.classpath"/>
         </classpath>
      </java>
   </target>

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"/>                                          
        </java>
  </target>

 

 



Back to top

28 )   Web Service Testing with SOAP UI ?


Ans)


  • 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.



Back to top

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


Ans)

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

Getting Soap Request :
 
bindingStub._getCall().getMessageContext().getRequestMessage().getSOAPPartAsString();

Getting Soap Response :

bindingStub._getCall().getMessageContext().getResponseMessage().getSOAPPartAsString();

 



Back to top

31 )   WS Security Axis 1.x


Ans)

WS-Security :

WS-Security is a standard for adding security to SOAP Web service
message exchanges (see Resources). It uses a SOAP message-header
element to attach the security information to messages, in the
form of tokens conveying different types of claims (which can
include names, identities, keys, groups, privileges,
capabilities, and so on) along with encryption
and digital-signature information.

Security Header Block :

<S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope"
 xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/xx/secext">
 <S:Header>
 <wsse:Security>
 <wsse:UsernameToken
   xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/xx/secext"
   xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/xx/utility">
    <wsse:Username> NNK </wsse:Username>
    <wsse:Password Type="wsse:PasswordDigest">
     D2A12DFE8D9F0C6BB82C89B091DF5C8A872F94DC
    </wsse:Password>
    <wsse:Nonce> EFD89F06CCB28C89 </wsse:Nonce>
   <wsu:Created> 2001-10-13T09:00:00Z </wsu:Created>
 </wsse:UsernameToken>
 </wsse:Security>
 ...
 </S:Header>
 ...
</S:Envelope>

 Server Side Changes :

<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<service name="stock-wss-01" provider="java:RPC" style="document" use="literal">
 <requestFlow>
 <handler type="java:org.apache.ws.axis.security.WSDoAllReceiver">
 <parameter name="passwordCallbackClass" value="PWCallback"/>
 <parameter name="action" value="UsernameToken"/>
 </handler>
 </requestFlow>
 <parameter name="className" value="samples.stock.StockQuoteService"/>
 <parameter name="allowedMethods" value="getQuote"/>
 <parameter name="scope" value="application"/
</service>
</deployment>

Create a Callback :

import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.ws.security.WSPasswordCallback

public class PWCallback implements CallbackHandler {

  public void handle(Callback[] callbacks) throws IOException,
      UnsupportedCallbackException {
  for (int i = 0; i < callbacks.length; i++) {
  if (callbacks[i] instanceof WSPasswordCallback) {
  WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
  // set the password given a username
  if ("wss4j".equals(pc.getIdentifier())) {
    pc.setPassword("security");
    }
      }
    }
  }
}

Client Side Changes :

Remote remote = locator.getPort(StockQuoteService.class);
Stub axisPort = (Stub)remote;
axisPort._setProperty(UsernaeToken.PASSWORD_TYPE, WSConstants.PASSWORD_DIGEST);
axisPort._setProperty(WSHandlerConstants.USER, "wss4j");
axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_REF, pwCallback);



Back to top

Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,

This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.




Face Book

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free

Go To Site Map