Thursday, December 6, 2012

Understanding JAX-WS


                            The Java API for XML Web Services (JAX-WS) is a Java programming language API for creating web services. It is used to develop Web services and is a part of the Sun Java development kit (JDK). JAX-WS technology is used with other technologies, either from the core group or more enhanced Web services.
  • JAX-WS was designed to replace the existing JAX-RPC (remote procedure call). The name was changed to JAX-WS from JAX-RPC to reflect the shift from RPC-style to document-style Web services. 
  • JAX-WS consists of a standardized set of extensions for Java, which enable the development of Java-based Web services through WSDL. Just like JAX-RPC, JAX-WS also uses SOAP to represent a RPC. SOAP includes specifications, encoding rules, important structures, corresponding responses and necessary conventions to do RPCs over the network.
  • JAX-WS makes use of annotations to keep the development and deployment of Web service clients and endpoints simple. It is also known as JAX-WS RI, which means JAX-WS for reference implementation, and is now a part of metro distribution. The reference implementation of JAX-WS is designed as an open-source project, which is a part of GlassFish -- an open-source Java application server. This definition was written in the context of JAX-WS. 

Developing a Service using JAX-WS

You can develop a service using one of two approaches:
  • Start with a WSDL contract and generate Java objects to implement the service.
  • Start with a Java object and service enable it using annotations.
    For new development the preferred path is to design your services in WSDL and then generate the code to implement them. This approach enforces the concept that a service is an abstract entity that is implementation neutral. It also means you can spend more time working out the exact interface your service requires before you start coding.
However, there are many cases where you may need to service enable an existing application. While JAX-WS eases the process, it does require that you make some changes to source code of your application. You will need to add annotations to the source. It also requires that you migrate your code to Java 5.0.

WSDL First Development

Using the WSDL first model of service development, you start with a WSDL document that defines the service you wish to implement. This WSDL document could be obtained from another developer, a system architect, a UDDI registry, or you could write it yourself. The document must contain at least a fully specified logical interface before you can begin generating code from it.
Once you have a WSDL document, the process for developing a JAX-WS service is three steps:
  1. Generate starting point code.
  2. Implement the service's operations.
  3. Publish the implemented service.

Generating the Starting Point Code

JAX-WS specifies a detailed mapping from a service defined in WSDL to the Java classes that will implement that service. The logical interface, defined by the wsdl:portType element, is mapped to a service endpoint interface (SEI). Any complex types defined in the WSDL are mapped into Java classes following the mapping defined by the Java Architecture for XML Binding (JAXB) specification. The endpoint defined by the wsdl:service element is also generated into a Java class that is used by consumers to access endpoints implementing the service.
The wsdl2java command automates the generation of this code. It also provides options for generating starting point code for your implementation and an ant based makefile to build the application. wsdl2java provides a number of arguments for controlling the generated code.


Running wsdl2java can be done in two ways :-

1. Using Command Prompt.

You can generate the code needed to develop your service using the following command:
wsdl2java -ant -impl -server -d outputDir myService.wsdl
The command does the following:
  • The -ant argument generates a Ant makefile, called build.xml, for your application.
  • The -impl argument generates a shell implementation class for each portType element in the WSDL document.
  • The -server argument generates a simple main() to launch your service as a stand alone application.
  • The -d outputDir argument tells wsdl2java to write the generated code to a directory called outputDir.
  • myService.wsdl is the WSDL document from which code is generated.
 2. Using the below ANT Script :-

Create a project and install ANT Build tool in it.

http://ant.apache.org/manual/install.html

Use the below script to generate WSDLtoJava.

 <?xml version="1.0"?>
<project name="cxf wsdl2java" basedir=".">  
   <property name="cxf.home" location ="C:/Data/Technical/apache-cxf-2.6.1"/>

   <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">
//Use this for generating Client code
         <arg value="-client"/>
//Use this for generating Server code
         <arg value="-server"/>
         <arg value="-d"/>
         <arg value="client"/>
         <arg value="http://localhost:9080/CXFBasic/ChangeStudent?wsdl"/>
         <classpath>
            <path refid="cxf.classpath"/>
         </classpath>
      </java>
   </target>
</project>


Wednesday, December 5, 2012

Web Services Interview Questions

WEB SERVICES 

What is a webservice ?

web service is a network accessible interface to application functionality, built using standard Internet technologies. 



                                  

A web service allows access to application code using standard Internet technologies


In other words, if an application can be accessed over a network using a combination of protocols like HTTP, XML, SMTP, or Jabber, then it is a web service. Despite all the media hype around web services, it really is that simple.
Web services are nothing new. Rather, they represent the evolution of principles that have guided the Internet for years. 
          Web Services support loosely coupled  connections. The interface of the Web Service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. 
            
          Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a web service using any language andeploy it on to any platform, from small device to the largest supercomputer. Web Service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API which do work across internet, less expensive and easier to use.

1.What are the different styles of Web Services used for application integration ?
  •       SOAP WS (Web Service)and RESTful Web Service.
 SOAP - Simple Object Access Protocol.
  REST -  Representational State Transfer
    2.What are the differences between both SOAP WS and RESTful WS ?
    1. The SOAP WS supports both remote procedure call (i.e RPC) and message oriented middle- ware(MOM) integration styles. 
    2. The RESTful Web Service supports only RPC integration style.
    3. The SOAP WS is a transport protocol neutral. Supports multiple protocols like HTTP(s), Messaging, TCP, UDP SMTP, etc.
    4.  The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
    5.   The SOAP WS permits only XML data format. you define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service.
    6. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT,POST,and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service.
    7. REST has AJAX Support. It can use the XMLHTTpRequest object. Good for Stateless CRUD(Create,Read,Update and Delete ) operations.
    8. SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.
    9. SOAP WS supports both SSL-Security and WS-Security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and just not point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL Security. The SSL encrypts the whole message, whether all of it is sensitive or not.
    10. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. 
    11. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
    3. How would you decide what style of Web Service to use ?
    • In general, a REST based Web Service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. 
    • SOAP is favored where services requires comprehensive support for security and transactional reliability.
    4. Does the Service expose data or business logic ?
    •  REST is a better choice for exposing data, SOAP WS might  be a better choice for logic.
    5. What level of security is required ?
    • SOAP WS has better support for security than REST.
    6. What's best for the developers who will build clients for the service ?
    • REST is easier to implement, test, and maintain.
    7. What tools do you use to test your Web Service ?
    • SOAP UI for SOAP WS and the Firefox "poster" plugin for RESTful services.
    8. What is the difference between SOA and Web Service ?
    • SOA is a software design principle and and architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS,JMS,SMTP,RMI,IIOP (i.e., EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).
    • Web Service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web Services- for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web Services offer is the standards based and platform-independent service via HTTP, XML,SOAP,WSDL and UDDI, thus allowing interoperability between heterogeneous technologies sucha as JEEE and .NET.

    Monday, October 22, 2012

    Java Collections Important Questions & Concepts

    1) What is a Collection Framework ?

    A) Collection framework is a class library to handle group of objects. Collection framework is implemented in java.util package.

    2) Does a Collection object store copies of other objects or their references ?

    A) collection object stores references of other objects.

    3) Can you store primitive data type into a collection ?

    A) No, Collections store only objects.

    4) What is the difference between Iterator and ListIterator ?

    A) Both are useful to retrieve elements from a collection. Iterator can retrieve the elements only in forward direction. But ListIterator can retrieve the elements in forward and backward direction also. So ListIterator is preferred to Iterator.

    5) What is the difference between Iterator and Enumeration ?

    A) Both are useful to retrieve elements from a collection. Iterator has methods whose names are easy to follow and Enumeration methods are difficult to remember. Also Iterator has an option to remove elements from the collection which is not available in Enumeration. So, Iterator is preferred to Enumeration.

    6) What is auto boxing ?

    A) Converting a primitive data type into an object form automatically is called 'auto boxing'. Auto boxing is done in generic types.

    7) What is difference between an ArrayList and a Vector?

    A)       There are two important differences between an ArrayList and Vector
               a) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
                b) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

    8) How can Arraylist be synchronized without using Vector?

    A)  Arraylist can be synchronized using :-
                    
                     Collection.synchronizedList(List list)

          Map can be synchronized using :-
     
                     Collection.synchronizedMap(Map map)

          Other collections can be synchronized using :-

                     Collection.synchronizedCollection(Collection c)

    9) What is difference between HashMap and HashTable?

    A)  Both Collections implements Map. Both Collections store values as key-value pairs. The key differences between the two are :-
                    a. Hashmap is not Synchronized in nature where as HashTable is Synchronized.

                    b. Another difference is that iterator in the HashMap is fail-safe, while the enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

                   c. HashMap permits null values and only one null key, while Hashtable doesn't allow any of its key or value as null.

    •  If you want to learn more about FailFast and FailSafe please refer to the below link
    http://javarevisited.blogspot.in/2012/02/fail-safe-vs-fail-fast-iterator-in-java.html


    10) What all classes implement List Interface ?

    A) There are three classes that implement the List Interface they are :-
     
                ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased   dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

                Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

                LinkedList: The LinkedList also implements Queue interface and provides FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.


    11) Which all classes implement Set interface ?

    A) A Set is a collection that contains no duplicate elements. More formally, Sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.

                SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.

                 TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

                 HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.


     12) What is difference between List and a Set?

    A) List can contain duplicate values but Set doesnt allow. Set allows only unique elements. List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(except HashSet)

    13) What is difference between Arrays and ArrayList ?

    A) Arrays are of fixed size whereas ArrayList is is not of fixed size.

    Some of the advantages ArrayList has over arrays are :-

    • ArrayList can grow dynamically.
    • It provides more powerful insertion and search mechanisms than arrays.
    It means that once array is declared as :

    Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
    Once the array is created elements cannot be added or deleted from it.

     But with ArrayList the elements can be added and deleted at runtime.

           List list = new ArrayList();
           list.add(1);
           list.add(3);
           list.remove(0) // will remove the element from the 1st location.

              ArrayList is one dimensional but Array can be multidimensional.

    To create an array the size should be known or initalized to some value. If not it should be initialized carefully such that there could me no memory wastage. But arrayList is all about dynamic memory creation and there is no wastage of memory.







    Sunday, October 21, 2012

    The Java Virtual Machine

    Components in JVM architecture





    Core Java Interview Questions

    Dynamic Method Dispatch or RunTime Polymorphism

    Dynamic Method Dispatch is a process in which a call to an overriden method is resolved at runtime rather than compile time. An overriden method is called through the reference variable of a super class.

    When reference variable of a parent class refers to the object of a child class, it is known as upcasting.

    class India{}
    class Mumbai extends class India{}
    India ind = new Mumbai() // This is called upcasting

    Example :-

    class Vehicle {
    void drive(){
    System.out.println("Driving Vehicle");
         }
    }

    class Bentley extends Vehicle {
    void drive() {
    System.out.println("Driving Bentley");
    }

    public static void main(String ar[]){
    Vehicle v = new Bentley();
    v.drive();
       }
    }

    OUTPUT: Driving Bentley

    • Runtime polymorphism cannot be achieved by data members.
    • Runtime polymorphism can be achieved through multilevel inheritance.


    1. What is the difference between an executable file and a .class file ?
       A) ".exe" file contains machine language instructions for the microprocessor and is system dependent. ".class" file contains byte code instructions for the JVM and is system independent.

    2. Why Java is suitable for Internet ?
        A) Java is suitable for Internet because of two main reasons.
             1) It is system independent and hence its programs can run on any type of computer system available on internet.
              2) It eliminates a lot of security problems for data on internet.

    3. Why Pointers are eliminated in Java ?
         A)  1) Pointers lead to confusion for a programmer.
               2) Pointers may crash a program easily, for example, when we add two pointers, the program crashes immediately. The same thing could also happen when we forget to free the memory allotted to a variable and reallocate it to some other variable.
               3) Pointers break security. Using pointers, harmful programs like Virus and other hacking programs can be developed.
    Because of the above reasons pointers have been eliminated from Java.

    4. What is the difference between a function and a method ?

    A)  A method is a function that is written in a class. We do not have functions in Java; instead we have methods. This means whenever a function is written in Java, it should be written inside the class only. But if we take C++, we can write the functions inside as well as outside the class. So in C++, they are called member functions and not methods.

    5. Is Java a purely object oriented language or not ?

    A) The following reasons are put forward by many people to say Java is not a purely object oriented programming language.

          1. 'Purely object oriented' means it should contain only classes and objects. It should not contain primitive datatypes like int, float, char etc, since they are neither classes nor objects.

          2. In pure object oriented languages, we should access every thing by messages passing (through objects). But, Java contains static variables and methods which can be accessed directly without using objects.

          3.Java does not contain multiple inheritance. It means an important feature of object oriented design is lacking. So how can we say it is purely object oriented ?

    No doubt Java is purely object oriented programming language. The preceding points represent lack of in depth understanding of Java.

          1. Even if Java has primitive datatypes, these types are used inside a class and never outside of it. So, they are part of a class. See the API specification on the class. 'Class'.Java specification says that all the arrays and the primitive Java types(boolean,byte,char,short,int,long,float, and double), and the keyword void are also represented as objects of the class 'Class'.

           2. Even static variables and static methods are written inside a class. When accessing them from outside, we should use classname. It means they are part and parcel of class definition and should not be considered as individual elements. For reducing memory utilization, only one copy of them will be created in memory and shared by all objects.

           3. Any purely object oriented language should follow all the 5 features of Object oriented Programming System(OOPS). They are :-
    • Classes and objects.
    • Encapsulation 
    • Abstraction
    • Inheritance 
    • Polymorphism
    Remember Java contains all these features and hence it is purely object oriented language. Just because Java does not contain multiple inheritance, we should not say it is not purely object oriented language. Multiple inheritance is not the main feature of OOPS, it is only a sub feature under inheritance.

    6. Which part of JVM will allocate the memory for a Java program ?
    A) Class loader subsystem of JVM will allocate the necessary memory needed by the Java program.

    7. Which algorithm is used by garbage collector to remove the unused variables or objects from memory ?
    A) Garbage collector uses many algorithms but the most commonly used algorithms is mark and sweep.

    8. How can you call the garbage collector ?
    A) Garbage Collector is automatically invoked when the program is being run. It can be also called by calling gc() method of Runtime class or System class in Java.