Saturday 24 December 2016

OOPS concepts in Java

OOPS concepts in Java



OOPS concepts in Java:


Object oriented programming  is a methodology in which programs are created by using classes and Objects.

Principles/Features

·       Abstraction
         Encapsulation
         Inheritance
         Polymorphism

 
Abstraction:
Mechanism of hiding the implementation complexity. Key is to simplify a complex design into smaller parts.

Abstraction in java can be achieved using Abstract classes. Read Abstract class in java

Encapsulation:

Mechanism of binding both data members and member methods in the same class.

Encapsulation in java can b achieved using Abstract classes and Interfaces. Read Interface in java

Uses:

Provides Security:

In tightly encapsulated classes data members make private. Hence, it can be accessed by other methods in the same class guaranty security.

Improved maintainability:

As all the methods while use the data members of class are included in the same class it is easy to find required method.

Example:

            package com.javasourceworld.oops;

            public class Encapsulation {
      
                   private int k=10; //binding the member variables as privaate
      
                   void show(){
                    //do something
                   }


              }


Inheritance:

Mechanism of acquiring some or all the features of one class into another class.

Java doesn’t support multiple inheritance to avoid complexity and ambiguity.(Diamond problem)

Example:

       package com.javasourceworld.oops;

             class Parent{
                   int x;
                   void show(){
                       //do something
                   }
             }

//Parent ->  Parent class/Base class/Derived class
//Child -> child class/sub class/Deriving class

        class Child extends Parent{
                int x;
                void doSomething(){
                 int y;
                }

             }

Benefits
·         Re usability
·         Improved maintainability
·         Minimized code redundancy
·         High productivity
·         Cost effective
·         Quality can be guaranteed
·         Errors can be avoided


Polymorphism:

Polymorphism is a Oops feature according to which a single entity can take different forms.

Example: ‘Shape’ that is square, circle. ‘Man’-son, father.

Types of Polymorphism

1.       Static Polymorphism.
                  Example: Overloading.

2.       Dynamic Polymorphism.
                  Example: Overriding.

When Polymorphism takes place at compile time it is called static Polymorphism.

When Polymorphism takes place at run time it is called Dynamic or runtime Polymorphism.


Overloading:

Signature : Signature of a method considers,

·         Number of parameters.
·         Datatype of parameters.
·         Order of parameters.

If the combination of these three values is unique then signature is unique.

Overloading:

Mechanism by which we can define more than one method with same name but different signature either in parent class or child class also.

Conditions for overloading

1.       Method name should be same.

2.       Methods return type is not considered.

3.       Signature must be unique.

4.       Access specifiers are also not considered.

5.       Overloaded method could static or non- static.

6.       ‘Final’ method could be overloaded.

7.       A single method could be overloaded by multiple overloading methods.

8.       The overloaded method to be executed it decided by compiler at the time of compilation itself.           (based on unique signature).

Overloading provides flexibility and simplifier the use of methods.

Constructors also can be overloaded.

* main method also can be overloaded but JVM calls only standard main method.

         package com.javasourceworld.oops;

         public class Bank {
             //Constructor overloading
           Bank(){
              //default constructor
           }
           Bank(int x){
              //Parameterized constructor
           }
          Bank(int x, double y){
              //Parameterized constructor
           }
      
          //Method overloading
          int calculateTax(int x){
              //do something
              return x;
          }
        
         double calculateTax(double x){
              //do something
              return x;
         }

      }

Overriding:

Mechanism by which we can define a method in child class whose name, signature and return type are same as the parent class, but implementation could be different.
Uses of overriding

·         In inherited method, implementation doesn’t suit the child’s requirement, the child can hide it by providing overriding method with suitable implementation.
Thus allows the child class to reuse useful features of parent class and hide unsuitable features.

·         It supports dynamic method dispatch, which can be used to reduce burden on the primary memory.

          package com.javasourceworld.oops;

          public class Account {
 
              void calculateTax(double x){
                     System.out.println("Calculating tax");
              }
            }

         class SavingAccount extends Account{
              void calcualteTax(double x){
                     System.out.println("Calculating Saving account tax");
              }
            }

         class FixedAccount extends Account{
             void calculateTax(double x){
                System.out.println("Calculating Fixed Account tax");
             }

         }


Conditions for overriding:

1. Method name and signature should be same as the parent class method.

2. Method return type should be either same or it could be co-variant return type.

3. The access specifier overriding method should be either same or wider than overridden method.

4. Overriding method cannot throw more checked exception.

5. Overriding method can throw unchecked exception, even though overridden method doesn’t throw.

6. Overridden method can have only one overriding method in a child class.

7. Only inherited method can be overridden.

8. are not inherited hence they cannot be overridden.

9. Private methods are not     so they can’t be overridden.

10. ‘Final’ methods cannot be overridden.

11. If the class itself is made ‘final’ we cannot create child class, cannot overridden.

12.  Static methods cannot overridden by non-static methods and vice-versa is also true.

13. Static method can be overridden by another static method. But we will not get benefit of dynamic Polymorphism.

Continue reading:
Association, Aggregation, Composition
Read More »

Friday 2 December 2016

java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String

java.lang.NoSuchMethodError



java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String



java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String

If you trying to use JAX-WS 2.2 on top of JDK 6, you run into classloading problems. 

The reason could be using JAX-WS 2.1 on JDK 6. 

JDK 6 (U4 and later) has JAX-WS implementation with JAX-WS 2.1 API. 

If you try to use JAX-WS 2.2, the runtime always picks up the JAX-WS API from boot clasloader and will not see JAX-WS 2.2 API in your classpath.

 Well, the solution is the same, i.e, using the endorsed overriding mechanism.

That I will explain in this post how to do that set up, and resolving the error 


"java.lang.NoSuchMethodError:javax.xml.ws.WebFault.messageName()Ljava/lang/String"


When we run the tomcat we come across the fallowing error as shown below.







How to endorse, required jar files into endorsed folder:

Required jar files:

jaxb-api.jar
jaxws-api.jar


Steps:

1. Go to tomcat home directory

     For example: D:\Applns\apache-tomcat-7.0.23\

2. Create a floder named endorsed in the tomcat home directory.

    After creating the floder endorsed your tomcat endorsed directory structure should as     
    below:

    D:\Applns\apache-tomcat-7.0.23\endorsed\

3. Copy the jaxb-api.jar, jaxws-api.jar to the folder D:\Applns\apache-tomcat-
    7.0.23\endorsed\ 

4. Restart the tomcat server. Error will be resolved and you can able to acces the service.



After copying the jars to the endorsed folder that directory structure will be as shown below:



Read More »

How to handle JAX-WS Exceptions and Faults

How to handle JAX-WS Exceptions and Faults



How to handle JAX-WS Exceptions and Faults



This post will  discusses the JAX-WS mapping of WSDL faults to Java exceptions,  Java exceptions to WSDL faults.

To unserstand the concept of handling faults and exceptions in webservices, you should have a basic knowledge on how to create JAX-WS web services and clients. You may find the following posts helpful.

Creating SOAP Web Services using JAX-WS
Testing the SOAP web services using SOAP UI

Tools required:

1. Eclipse
2. Tomcat 6 or above version
3. Java 1.6 or above verson.

What is  JAX-WS Fault Handing and Exception Handling:

The JAX-WS Specification demands that mapped exception must be annotated with a javax.xml.ws.WebFault (@WebFault) annotation. A wsdl:fault element is mapped to this Java exception . A wsdl:fault element refers to a wsdl:message that contains a single part and is mapped to a Java bean, called a fault bean , which is just a POJO class which has only setter and getter methods. The exception class should have two constructors and a getter method (to obtain fault details) as follows

InvalidRequestFault(String message, ServiceFault faultInfo)
InvalidRequestFault(String message, ServiceFault  faultInfo, Throwable cause)
ServiceFault getFaultInfo()

Where, WrapperException is the name of the Exception class and FaultBean is the fault bean POJO.

JAX-WS Exception Handling and JAX-WS SOAP Fault Handling Example

Now, let us create a web service and custom exception class to handle JAX-WS exception and SOAP faults.

Web Service SEI and Implementation Classes are as fallows:

SEI: AirportService.java

package com.javasourceworld.webservice;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface AirportService {
      @WebMethod
      String findAirportNames(String countryCode);
}

Implementation:


package com.javasourceworld.webservice;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService(endpointInterface = "com.javasourceworld.webservice.AirportService")
public class AirportServiceImpl implements AirportService{

      AirportUtility utility;
     
      public AirportServiceImpl(){
            utility = new AirportUtility();
            utility.loadAirports();
      }

      @Override
      @WebMethod
      public  String findAirportNames(String countryCode) throws 
                                         InvalidRequestFault {
            
          Airport airport = utility.findAirports(countryCode);
              StringBuilder bd = new StringBuilder();
            if(airport != null){
                  bd.append("Airport Name: ").append(" ").
                  append(airport.getAirportCode()).append(";  ").
                  append("City Name: ").append(airport.getCityName());
                return bd.toString();
            }else{
                  ServiceFault fault = new ServiceFault();
                  fault.setErrorcode("1234");
                  fault.setErrorDescription("My Service Error");
                  throw new InvalidRequestFault("1234","My Service Error: The 
                           given country is not found");
            }
          
      }  
}

In the above  implementation class, the findAirportNames() web service method throws InvalidRequestFault(customized exception) if the incoming countrycode is invalid. 

Otherwise the service method returns airport name info to the consumer.

ServiceFault.java

This is the fault bean POJO class required by the JAXB runtime to process exceptions.

package com.javasourceworld.webservice;

public class ServiceFault {
      private String errorcode;
      private String errorDescription;
      /**
       * @return the errorcode
       */
      public String getErrorcode() {
            return errorcode;
      }
      /**
       * @param errorcode the errorcode to set
       */
      public void setErrorcode(String errorcode) {
            this.errorcode = errorcode;
      }
      /**
       * @return the errorDescription
       */
      public String getErrorDescription() {
            return errorDescription;
      }
      /**
       * @param errorDescription the errorDescription to set
       */
      public void setErrorDescription(String errorDescription) {
            this.errorDescription = errorDescription;
      }

}

Custom Exception class InvalidRequestFault.java

This class is required to be annotated with @WebFault annotation.


package com.javasourceworld.webservice;

import javax.xml.ws.WebFault;

@WebFault(name="ServiceFault", targetNamespace="http://webservice.javasourceworld.com/")
public class InvalidRequestFault extends Exception {
      /**
       *
       */
      private static final long serialVersionUID = -6647544772732631037L;
     
      private ServiceFault fault;
      /**
       *
       */
      public InvalidRequestFault() {
      }
      /**
       *
       * @param fault
       */
      protected InvalidRequestFault(ServiceFault fault) {
        super(fault.getErrorDescription());
        this.fault = fault;
     }
      /**
       *
       * @param message
       * @param faultInfo
       */
      public InvalidRequestFault(String message, ServiceFault faultInfo){
            super(message);
        this.fault = faultInfo;
      }
      /**
       *
       * @param message
       * @param faultInfo
       * @param cause
       */
      public InvalidRequestFault(String message, ServiceFault faultInfo,         
                 Throwable cause){
            super(message,cause);
        this.fault = faultInfo;
      }
      /**
       *
       * @return
       */
      public ServiceFault getFaultInfo(){
            return fault;
      }
     
      /**
       * @param message
       */
      public InvalidRequestFault(String message) {
            super(message);
      }
      /**
       * @param message
       */
      public InvalidRequestFault(String code, String message) {
            super(message);
            this.fault = new ServiceFault();
          this.fault.setErrorDescription(message);
          this.fault.setErrorcode(code);
      }

      /**
       * @param cause
       */
      public InvalidRequestFault(Throwable cause) {
            super(cause);
            // TODO Auto-generated constructor stub
      }

      /**
       * @param message
       * @param cause
       */
      public InvalidRequestFault(String message, Throwable cause) {
            super(message, cause);
            // TODO Auto-generated constructor stub
      }
}

You can create the WSDL of the above service, by using the “wsgen” tool or the web container will create one for you, if you package and deploy the service to a web container such as tomcat.  Read the below article to know more about how to do that.


In this post, we are creating our wsdl using the web container such as tomcat, we will get the wsdl from the host location and copy it to the .wsdl file, and we test that using SOAP UI.

Now deploying the service in tomcat.

Hosted wsdl will be as shown below with the fault elements:

Click on the image to see it clearly.





Note:

While running/ hosting the JAX-WS service faults if JAX-WS 2.2 on top of JDK 6 with tomcat , we may come across the fallowing error on deployment
java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String
To solve that fallow the below link:

java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String


Now we will copy this wsdl to a file with the extension of wsdl.

To test it in SOAP UI, load the wsdl to the created project and run the request by giving the end point url.

For detail overview on testing the web service in SOAP UI, read the fallowing post that will be helpful in understanding the current concept.

Testing the SOAP web services using SOAP UI

After loading the wsdl and ran it in the soap UI, the view of the request and response will be as shown in the below image. For a clear view double click on the image.




 Now we will trigger a request with valid and invalid data and will see the difference.

Testing with the valid request:

Passing the countryCode as 'IN', which is valid and show the response with the airport  details

Request:




Response:



Testing with aninvalid request:

Passing the countryCode as 'AA', which is invalid and show the response with the fault details

Request:













Response:











As shown in the above image, in the <ns2:ServiceFault> elemente, <errorDescription> and <errorcode> are showing the fault info with the meaning ful message instead with no response.

This is the way we handle the faults and exceptions in the web services when using JAX-WS API.

Read:
Creating SOAP Web Services using JAX-WS
Difference between SOAP and REST web services
java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String


Read More »