Tuesday 5 May 2009

JAX-WS: A @SchemaValidation custom handler to alter framework SOAP faults

A few days ago I blogged about suppressing the SOAP fault detail Java stack trace on WebLogic Server when using the JAX-WS @SchemaValidation annotation for your web services.

One of the problems with the @SchemaValidation annotation is dependent on the error in your incoming SOAP payload, you may get all sorts of potential errors returned in a SOAP fault. In some cases it might be useful or a requirement that a generic SOAP fault message be sent back in this case. How to do this?

As usual I'm documenting my research and solution here for my own purposes, but hopefully helpful to others. Your mileage may vary.

Consider the following JAX-WS endpoint:


@WebService
@SchemaValidation
public class WebServiceClass {

@WebMethod
public MyResponse lodgeReport(@WebParam MyRequest request)
throws GenericSoapFault {
// do some stuff
}
}


(I've clipped a lot of the detail from above to focus on the specifics)

Notice the @SchemaValidation annotation. By default this will enforce that the incoming SOAP payload conforms to the XML schema for the operation. For instance an invalid payload may throw the following error:






S:Receiver


org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: '?' is not a valid value for 'dateTime'.






Note the reason/text part of the SOAP fault may be virtually any SAXParseException error message depending on the error discovered in the incoming SOAP payload.

We can however override the @SchemaValidation annotation to specify the actual error handler. We change the endpoint code as such:


@WebService
@SchemaValidation(handler = SchemaValidationErrorHandler.class)
public class WebServiceClass {

@WebMethod
public MyResponse lodgeReport(@WebParam MyRequest request)
throws GenericSoapFault {
// do some stuff
}
}


Note the handler attribute specifying the SchemaValidationErrorHandler class for the @SchemaValidation annotation. In turn the SchemaValidationErrorHandler is implemented as follows:


import com.sun.xml.ws.developer.ValidationErrorHandler;
import org.xml.sax.SAXParseException;

public class SchemaValidationErrorHandler extends ValidationErrorHandler {

public void warning(SAXParseException exception) { }

public void error(SAXParseException exception) { }

public void fatalError(SAXParseException exception) { }
}


Any warning, error or fatal error for the @SchemaValidation will now be passed through to the methods above. Remembering our goal to supplement a custom error message for any of the errors above (well, maybe not warning, we'll ignore warnings), we'd like to return our own SOAP fault. Unfortunately we can't do that from the handler, we need to pass the error back to the endpoint method. This is done by using the com.sun.xml.ws.api.message.Packet that is available from the ValidationErrorHandler super class. In essence we can change our handler class as follows:


public class SchemaValidationErrorHandler extends ValidationErrorHandler {

public static final String WARNING = "SchemaValidationWarning";
public static final String ERROR = "SchemaValidationError";
public static final String FATAL_ERROR = "SchemaValidationFatalError";

public void warning(SAXParseException exception) {
packet.invocationProperties.put(WARNING, exception);
}

public void error(SAXParseException exception) {
packet.invocationProperties.put(ERROR, exception);
}

public void fatalError(SAXParseException exception) {
packet.invocationProperties.put(FATAL_ERROR, exception);
}
}


I can't for the life of me find the JavaDoc for the Packet class, but what I believe it does is wrap the overall web service message context, and we can drop properties into the packet to be retrieved elsewhere by our JAX-WS solution , specifically our end point.

Returning to the JAX-WS endpoint we need to inject the web service message context, and then we can retrieve each of the individual errors from the SchemaValidationErrorHandler above:


@WebService
@SchemaValidation(handler = SchemaValidationErrorHandler.class)
public class WebServiceClass {

@Resource
WebServiceContext wsContext;

@WebMethod
public MyResponse lodgeReport(@WebParam MyRequest request)
throws GenericSoapFault {

MessageContext messageContext = wsContext.getMessageContext();
// We'll ignore warnings
// SAXParseException warningException = (SAXParseException)messageContext.get(SchemaValidationErrorHandler.WARNING);
SAXParseException errorException = (SAXParseException)messageContext.get(SchemaValidationErrorHandler.ERROR);
SAXParseException fatalErrorException = (SAXParseException)messageContext.get(SchemaValidationErrorHandler.FATAL_ERROR);

String errorMessage = null;

if (errorException != null)
errorMessage = errorException.getMessage();
else if (fatalErrorException != null)
errorMessage = fatalErrorException.getMessage();


if (errorMessage != null)
throw new GenericSoapFault(errorMessage);

// Otherwise process the request
}
}


Note the @Resource annotation in the class injecting the web service context, then within our endpoint method fetching the MessageContext from the wsContext, which gives us the ability to retrieve the properties we inserted in the SchemaValidationErrorHandler class.

As per the solution above, instead of just checking if the errorMessage is null and passing that to the GenericSoapFault, you could instead replace the SAXParseException with a more generic error message.

5 comments:

Gerard Davison said...

Not javadoc, but you can see the source code from this and others from:

http://fisheye5.cenqua.com/browse/jax-ws-sources/jaxws-ri/rt/src/com/sun/xml/ws/api/message/Packet.java?r=1.21

You can always download the full RI implementation from the following URL, just edit the version to match that in your weblogic modules directory:

https://jax-ws.dev.java.net/2.1.5/

Gerard

ptha said...

Hi I'm using Glassfish 2.1.1 and implemented your SchemaValidationErrorHandler so I could return more user friendly messages.

I'm logging the SAXParseException messages in the handler so I can see it is being called. But another exception is thrown before I ever get to the start of my WebMethod where I throw my GenericSoapFault,

This is the exception:
Caused by: java.lang.IllegalAccessError: tried to access class com.sun.xml.bind.v2.runtime.reflect.opt.Const from class service.crawling.CrawlInputType$JaxbAccessorF_maxBytesDownload

I'm using a JAXB binding to bind a schema I've defined to the Web Method input object. So it is trying to parse the invalid inputted value into the generated input object and failing. This obviously happens before I throw the fault in the Web Method itself.

My question is, how can I throw the fault before this parsing takes place?

Thanks,
Peter

Chris Muir said...

Hi Peter

Please excuse me if the following answer is a bit trivial, it's over a year since I worked on that section of code (and the resulting blog entry).

From memory one of the things I discovered, a shortcoming of JAX-WS, and one that you've discovered, is the handler is actually called after some JAX-WS processing has already occurred. We discovered if we send a badly formed XML document to JAX-WS (ie. missing end tags, or doubling up on opening tags, or some other silly error), JAX-WS threw a SOAP fault before our handler was called.

However it's possible this may have been fixed in later versions of JAX-WS.

I suggest you post to the relevant Sun (now Oracle) JAX-WS/web service forums, I remember them being very proactive in answering my questions.

My apologies I can't be more help at this stage.

Regards,

CM.

ptha said...

Hi Chris thanks for getting back to me, in my case the handler is getting called before the exception is thrown, but retrieving the SAXParseException from the packet (added by the handler) I cannot do it in the Web Method (operation of the web service) as a JAXB binding exception is thrown before I get there.

After some trial and error, I found I was able to throw a ProtocolException in SchemaValidationErrorHandler with the SAXParseException message, and this results in the message being returned to the user.

Thanks again for your help.

Chris Muir said...

Thanks for the feedback Peter, I'm sure this will help other readers. Good luck with your JAX-WS project.

CM.