Showing posts with label Interview Questions - Web Services. Show all posts
Showing posts with label Interview Questions - Web Services. Show all posts

Friday, 2 December 2016

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 »

Monday, 14 September 2015

Java Source World: Describes the high-level differences to JAX-RPC



Describes the high-level differences to JAX-RPC


Introduction

Web services have been around a while now. First there was SOAP. But SOAP only described what the messages looked like. Then there was WSDL. But WSDL didn't tell you how to write web services in Java™. Then along came JAX-RPC 1.0. 

After a few months of use, the Java Community Process (JCP) folks who wrote that specification realized that it needed a few tweaks, so out came JAX-RPC 1.1. After a year or so of using that specification, the JCP folks wanted to build a better version: JAX-RPC 2.0.


 A primary goal was to align with industry direction, but the industry was not merely doing RPC web services, they were also doing message-oriented web services. So "RPC" was removed from the name and replaced with "WS" (which stands for web Services, of course). 


Thus the successor to JAX-RPC 1.1 is JAX-WS 2.0 - the Java API for XML-based web services.



What remains the same?
Before we itemize the differences between JAX-RPC 1.1 and JAX-WS 2.0, we should first discuss what is the same.
  • JAX-WS still supports SOAP 1.1 over HTTP 1.1, so interoperability will not be affected. The same messages can still flow across the wire.
  • JAX-WS still supports WSDL 1.1, so what you've learned about that specification is still useful. A WSDL 2.0 specification is nearing completion, but it was still in the works at the time that JAX-WS 2.0 was finalized.





What is different?
  • SOAP 1.2
JAX-RPC and JAX-WS support SOAP 1.1. JAX-WS also supports SOAP 1.2.
  • XML/HTTP
The WSDL 1.1 specification defined an HTTP binding, which is a means by which you can send XML messages over HTTP without SOAP. JAX-RPC ignored the HTTP binding. JAX-WS adds support for it.
  • WS-I's Basic Profiles
JAX-RPC supports WS-I's Basic Profile (BP) version 1.0. JAX-WS supports BP 1.1. (WS-I is the web services interoperability organization.)
  • New Java features
    • JAX-RPC maps to Java 1.4. JAX-WS maps to Java 5.0. JAX-WS relies on many of the features new in Java 5.0.
    • Java EE 5, the successor to J2EE 1.4, adds support for JAX-WS, but it also retains support for JAX-RPC, which could be confusing to today's web services novices.
  • The data mapping model
    • JAX-RPC has its own data mapping model, which covers about 90 percent of all schema types. Those that it does not cover are mapped to javax.xml.soap.SOAPElement.
    • JAX-WS's data mapping model is JAXB. JAXB promises mappings for all XML schemas.
  • The interface mapping model
JAX-WS's basic interface mapping model is not extensively different from JAX-RPC's; however:
    • JAX-WS's model makes use of new Java 5.0 features.
    • JAX-WS's model introduces asynchronous functionality.
  • The dynamic programming model
    • JAX-WS's dynamic client model is quite different from JAX-RPC's. Many of the changes acknowledge industry needs:
      • It introduces message-oriented functionality.
      • It introduces dynamic asynchronous functionality.
    • JAX-WS also adds a dynamic server model, which JAX-RPC does not have.
  • MTOM (Message Transmission Optimization Mechanism)
JAX-WS, via JAXB, adds support for MTOM, the new attachment specification. Microsoft never bought into the SOAP with Attachments specification; but it appears that everyone supports MTOM, so attachment interoperability should become a reality.
  • The handler model
    • The handler model has changed quite a bit from JAX-RPC to JAX-WS.
    • JAX-RPC handlers rely on SAAJ 1.2. JAX-WS handlers rely on the new SAAJ 1.3 specification.
In the remainder of this tip, we will discuss SOAP 1.2, XML/HTTP, the WS-I Basic Profiles, and Java 5. Each of the remaining five bullets above will be a separate tip in this series.


SOAP encoding
SOAP encoding has fallen out of favor in the web services community. It is not supported by the WS-I basic profile. So JAX-WS, as the latest incarnation of Java web services, has disallowed SOAP encoding. JAX-RPC supports SOAP encoding, so if you really must use SOAP encoded messages, stick with JAX-RPC.


SOAP 1.2
There is really not a lot of difference, from a programming model point of view, between SOAP 1.1 and SOAP 1.2. As a Java programmer, the only place you will encounter these differences is when using the handlers, which we will cover in a future tip. SAAJ 1.3 has been updated to support SOAP 1.2.


XML/HTTP
Like the changes for SOAP 1.2, there is really not a lot of difference, from a programming model point of view, between SOAP/HTTP and XML/HTTP messages. As a Java programmer, the only place you will encounter these differences is when using the handlers, which we will cover in a future tip. The HTTP binding has its own handler chain and its own set of message context properties.


WS-I's basic profiles

JAX-RPC 1.1 supports WS-I's Basic Profile (BP) 1.0. Since that time, the WS-I folks have developed BP 1.1 (and the associated AP 1.0 and SSBP 1.0). These new profiles clarify some minor points, and more clearly define attachments. JAX-WS 2.0 supports these newer profiles.

For the most part, the differences between them do not affect the Java programming model. The exception is attachments. WS-I not only cleared up some questions about attachments, but they also defined their own XML attachment type: wsi:swaRef.


Many people are confused by all these profiles. You will need a little history to clear up the confusion.

WS-I's first basic profile (BP 1.0) did a good job of clarifying the various specs. But it wasn't perfect. And support for SOAP with Attachments (Sw/A) in particular was still rather fuzzy. In their second iteration, the WS-I folks pulled attachments out of the basic profile - BP 1.1 - and fixed some of the things they missed the first time around. At that point they also added two mutually exclusive supplements to the basic profile: AP 1.0 and SSBP 1.0. AP 1.0 is the Attachment Profile which describes how to use Sw/A. SSBP 1.0 is the Simple SOAP Binding Profile, which describes a web services engine that does not support Sw/A (such as Microsoft's .NET).

 The remaining profiles that WS-I has and is working on build on top of those basic profiles.

Java 5
There are a number of changes to the Java language. JAX-WS relies on: annotations, generics, and executors. We will detail exactly how JAX-WS relies on this new functionality in follow-on tips.


Summary
JAX-WS 2.0 is the successor to JAX-RPC 1.1. There are some things that haven't changed, but most of the programming model is different to a greater or lesser degree. The topics introduced in this tip will be expanded upon in a series of tips which we will publish over the coming months that will compare, in detail, JAX-WS and JAX-RPC. At a high level though, here are a few reasons why you would or would not want to move to JAX-WS from JAX-RPC.
Reasons you may want to stay with JAX-RPC 1.1:

  • If you want to stay with something that's been around a while, JAX-RPC will continue to be supported for some time to come.
  • If you don't want to step up to Java 5.
  • If you want to send SOAP encoded messages or create RPC/encoded style WSDL.
Reasons to step up to JAX-WS 2.0:

  • If you want to use the new message-oriented APIs.
  • If you want to use MTOM to send attachment data.
  • If you want better support for XML schema through JAXB.
  • If you want to use an asynchronous programming model in your web service clients.
  • If you need to have clients or services that can handle SOAP 1.2 messages.
  • If you want to eliminate the need for SOAP in your web services and just use the XML/HTTP binding.
  • If you like playing with leading edge technology.

    Read:
  • Differences between JAX-RPC, JAX-WS
  • Creating SOAP Web Services using JAX-WS
                  
Read More »