How to properly handle Exceptions in client thrown by a SOAP web service - spring-boot

I am setting up a Client using Spring-boot in Java to access a soap endpoint (for testing purpose).What's the best approach to handle Exceptions? I want to handle SOAPFaultClientExceptions...
I have already tried this:
How to Parse SoapFaultClientException in spring-ws
but it didn't work properly, as I couldn't call the getValue() method on detail
try {
JAXBElement res = (JAXBElement) getWebServiceTemplate().marshalSendAndReceive(url, request);
return (GetBankResponseType) res.getValue();
}catch (SoapFaultClientException ex) {
SoapFaultDetail soapFaultDetail = ex.getSoapFault().getFaultDetail(); // <soapFaultDetail> node
// if there is no fault soapFaultDetail ...
if (soapFaultDetail == null) {
throw ex;
}
SoapFaultDetailElement detailElementChild = soapFaultDetail.getDetailEntries().next();
Source detailSource = detailElementChild.getSource();
Object detail = getWebServiceTemplate().getUnmarshaller().unmarshal(detailSource);
JAXBElement source = (JAXBElement) detail;
System.out.println("Text::"+source.getValue());
}//catch other Exceptions...Which ones?
return null;
}
Expected result is a handled Exception, (SOAPFaultClientException) or others... which get Thrown by the webservice when wrong parameters are passed. I don't find any suitable solutions.

Configure ClientInterceptor or FaultMessageResolver to your WebServiceTemplate and do your error handling there.

Related

How to consume spring web client response

I am using web client in a spring application
I am facing memory leak issues while doing the same
I am using below code to get the response body for non 2XX response from service:
return client.get()
.uri(uriString)
.headers(ServiceCommonUtil.getHttpHeaderConsumer(headersMap))
.exchange()
.flatMap(clientResponse -> {
try {
clientResponse.body((clientHttpResponse, context) ->
clientHttpResponse.getBody());
logResponseStatus(clientResponse.statusCode(), serviceName);
return clientResponse.bodyToMono(String.class);
} catch (Exception e) {
return null;
}
})
and later on subscriber uses subscribe/ error block to process this response.
responseMono.subscribe(response -> {
//process response string
},error->{
//process error response
});
My question is, if i use dispose method on responseMono, it takes way long time for processing while without it i face memory leak issues.
Am i doing anything wrong here?
Yes, actually you are not consumming response in case of Exception is thrown.
If you want to use exchange() your responsibillity is to consume response.
See: docs
Take a look on toBodilessEntity()/ releaseBody() in 'ClientResponse` api.
Seems you've gotten a little complicated. Why a try/catch block in the clientResponse lambda? If your logResponseStatus throws a checked exception then handle it there. I suggest starting simpler.
Ex 1:
Mono<String> stringMono = webClient.get().uri("test").header("head", "value").exchange().flatMap(clientResponse->clientResponse.bodyToMono(String.class));
stringMono.subscribe(System.out::println);
Ex 2:
Mono<String> stringMono = webClient.get().uri("test").header("head", "value").exchange().flatMap(clientResponse->clientResponse.body(BodyExtractors.toMono(String.class)));
stringMono.subscribe(System.out::println);
Ex 3:
Mono<String> stringMono = webClient.get().uri("test").header("head", "value").retrieve().bodyToMono(String.class);
stringMono.subscribe(System.out::println);
For logging it is better to use ExchangeFilterFunctions. See How to intercept a request when using SpringBoot WebClient
.

Apache Camel Spring webservices SpringWebserviceConsumer does not read answer from in if not out

I use Camel spring-ws component to expose SOAP web service by specifying it in the 'from' part of the route.
It happens to be, that at the end of the route logic, the 'out' message of Exchange is not populated, however the 'in' message contains desired response data.
Default convention for producer component is to use 'in' message of exchange if 'out' is not present when generating final response.
SpringWebserviceConsumer however only supports scenario when final exchange has the 'out' message.
Here is the snippet of code from https://github.com/apache/camel/blob/master/components/camel-spring-ws/src/main/java/org/apache/camel/component/spring/ws/SpringWebserviceConsumer.java:
public void invoke(MessageContext messageContext) throws Exception {
Exchange exchange = getEndpoint().createExchange(ExchangePattern.InOptionalOut);
populateExchangeFromMessageContext(messageContext, exchange);
// start message processing
getProcessor().process(exchange);
if (exchange.getException() != null) {
throw exchange.getException();
} else if (exchange.getPattern().isOutCapable()) {
Message responseMessage = exchange.getOut(Message.class);
if (responseMessage != null) {
Source responseBody = responseMessage.getBody(Source.class);
WebServiceMessage response = messageContext.getResponse();
configuration.getMessageFilter().filterConsumer(exchange, response);
XmlConverter xmlConverter = configuration.getXmlConverter();
xmlConverter.toResult(responseBody, response.getPayloadResult());
}
}
}
This results in no response generated to the SOAP request.
Question:
Is this a bug/limitation of camel-spring-ws or I'm not using the spring-ws consumer correctly?
Otherwise, it sounds like I have to explicitly set the exchange patter to InOut?
Until CAMEL-10888 is released, as a work-around, in the route, you can set the exchange pattern to InOut to get not-null 'out' message of Exchange:
.setExchangePattern(ExchangePattern.InOut)

Spring WS client handling HTML instead of SOAP Fault

I have a SOAP client that is calling many different web services. In some cases some send back HTML error pages with HTTP error status codes instead of SOAP faults. I know that they should be sending SOAP faults, but I want to be able to handle this scenario. I'd like to be able to get access to the HTML error page. Right now when I get back an HTML error page with a 200 status code, a SoapMessageCreationException is thrown, which I catch. HTML error pages with HTTP error status codes throw WebServiceTransportException. How can I access the HTML data in the response at that point? I am using org.springframework.ws.transport.http.CommonsHttpMessageSender (Jakarta Commons HttpClient) as the message sender, with Spring 2.0.
I would like the code to be able to work with the default message sender if possible, otherwise, I would just check whether the instance of the message sender is CommonsHttpMessageSender or not. I prefer not to have to upgrade to Spring-WS 3/Apache HttpComponents right now, but am open to it if necessary. If I call this.webserviceTemplate.getMessageSenders(), is it ok to always take the first one ([0])?
try {
this.webserviceTemplate.sendSourceAndReceiveToResult(source,
new WebServiceMessageCallback() {
#Override
public void doWithMessage(WebServiceMessage message)
throws IOException, TransformerException {
if (LOG.isDebugEnabled()) {
// log the SOAP request
ByteArrayOutputStream out = new ByteArrayOutputStream();
message.writeTo(out);
LOG.debug("SOAP Request Payload: " + new String(out.toByteArray()));
}
if (soapActionHttpHeader != null) {
((SoapMessage)message).setSoapAction(soapActionHttpHeader);
LOG.debug("Setting SOAP Action HTTP header to: " + soapActionHttpHeader);
}
else
LOG.debug("SOAP Action HTTP not set in the configuration.");
}
}, result);
}
catch (SoapMessageCreationException e)
{//org.springframework.ws.transport.http.CommonsHttpMessageSender
String errorMsg= "Error processing SOAP message";
LOG.info(errorMsg);
LOG.debug("Stack trace: ",e);
throw new ServiceInvocationException(errorMsg);
}
catch (WebServiceTransportException e) {
String errorMsg= "Error invoking SOAP service";
LOG.info(errorMsg);
LOG.debug("Stack trace: ",e);
throw e;
}
catch (WebServiceIOException e) {
throw new ServiceInvocationException(e);
}

JUnit needs special permissions?

My builds have been failing due to some of the integration tests I've been running. I'm stuck on why it won't work. Here is an example of the output:
I'm using Maven to first build, then it calls the JUnit tests. I'm seeing this 401 Unauthorized message in every single test, and I believe that's what is causing the builds to fail. In my mind, this means there are some permissions / authentication parameters that need to be set. Where would I go about doing this in JUnit?
Edit
#Test
public void testXmlHorsesNonRunners() throws Exception {
String servletUrl = SERVER + "sd/date/2013-01-13/horses/nonrunners";
Document results = issueRequest(servletUrl, APPLICATION_XML, false);
assertNotNull(results);
// debugDocument(results, "NonRunners");
String count = getXPathStringValue(
"string(count(hrdg:data/hrdg:meeting/hrdg:event/hrdg:nonrunner/hrdg:selection))",
results);
assertEquals("non runners", "45", count);
}
If you can, try to ignore the detail. Effectively, this is making a request. This is a sample of a test that uses the issueRequest method. This method is what makes HTTP requests. (This is a big method, which is why I didn't post it originally. I'll try to make it as readable as possible.
logger.info("Sending request: " + servletUrl);
HttpGet httpGet = null;
// InputStream is = null;
DefaultHttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
doFormLogin(httpclient, servletUrl, acceptMime, isIrishUser);
httpGet = new HttpGet(servletUrl);
httpGet.addHeader("accept", acceptMime);
// but more importantly now add the user agent header
setUserAgent(httpGet, acceptMime);
logger.info("executing request" + httpGet.getRequestLine());
// Execute the request
HttpResponse response = httpclient.execute(httpGet);
// Examine the response status
StatusLine statusLine = response.getStatusLine();
logger.info(statusLine);
switch (statusLine.getStatusCode()) {
case 401:
throw new HttpResponseException(statusLine.getStatusCode(),
"Unauthorized");
case 403:
throw new HttpResponseException(statusLine.getStatusCode(),
"Forbidden");
case 404:
throw new HttpResponseException(statusLine.getStatusCode(),
"Not Found");
default:
if (300 < statusLine.getStatusCode()) {
throw new HttpResponseException(statusLine.getStatusCode(),
"Unexpected Error");
}
}
// Get hold of the response entity
HttpEntity entity = response.getEntity();
Document doc = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
// debugContent(instream);
doc = documentBuilder.parse(instream);
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpGet.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
instream.close();
}
}
return doc;
} finally {
// Release the connection.
closeConnection(httpclient);
}
I notice that your test output shows HTTP/1.1 500 Internal Server Error a couple of lines before the 401 error. I wonder if the root cause could be hiding in there. If I were you I'd try looking for more details about what error happened on the server at that point in the test, to see if it could be responsible for the authentication problem (maybe the failure is in a login controller of some sort, or is causing a session to be cancelled?)
Alternately: it looks like you're using the Apache HttpClient library to do the request, inside the issueRequest method. If you need to include authentication credentials in the request, that would be the code you'd need to change. Here's an example of doing HTTP Basic authentication in HttpClient, if that helps. (And more examples, if that one doesn't.)
(I'd second the observation that this problem probably isn't specific to JUnit. If you need to do more research, I'd suggest learning more about HttpClient, and about what this app expects the browser to send. One possibility: use something like Chrome Dev Tools to peek at your communications with the server when you do this manually, and see if there's anything important that the test isn't doing, or is doing differently.
Once you've figured out how to login, it might make sense to do it in a #Before method in your JUnit test.)
HTTP permission denied has nothing to do with JUnit. You probably need to set your credentials while making the request in the code itself. Show us some code.
Also, unit testing is not really meant to access the internet. Its purpose is for testing small, concise parts of your code which shouldn't rely on any external factors. Integration tests should cover that.
If you can, try to mock your network requests using EasyMock or PowerMock and make them return a resource you would load from your local resources folder (e.g. test/resources).

Elmah doesn't log exceptions using WebAPI with HttpResponseException

In my WebApi code, I raise a HttpResponseException which short-circuits the request pipeline and generates a valid Http response. However, I'm trying to integrate webApi with elmah logging, yet the HttpResponseExeptions aren't showing up.
I have the web.config set-up for elmah and have the following code:
In Global.asx.cs:
static void ConfigureWebApi(HttpConfiguration config)
{
config.Filters.Add(new ServiceLayerExceptionFilter());
config.Filters.Add(new ElmahHandledErrorLoggerFilter());
config.DependencyResolver = new WebApiDependencyResolver(ObjectFactory.Container);
}
Filter:
public class ElmahHandledErrorLoggerFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext);
ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
}
}
Code where exception is raised:
public Task<FileUpModel> UploadFile()
{
if (Request.Content.IsMimeMultipartContent())
{
var provider = new TolMobileFormDataStreamProvider("C:\images\");
var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(
t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = provider.FileData.FirstOrDefault();
if (fileInfo == null)
// the exception here isn't logged by Elmah?!
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var uploadModel = new FileUpModel { success = true };
return uploadModel;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
Can anyone who has implemented this before let me know what I'm doing wrong?
As mentioned above, the Elmah filter does not catch and log anything when you raise a HttpResponseException. More specifically, if the following syntax is used:
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "It was a bad request");
or
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "HttpResponseException - This request is not properly formatted"));
I wanted to trap and log an error in both cases. The way to do it is to use an "ActionFilterAttribute", override "OnActionExecuted", and check actionExecutedContext.Response.IsSuccessStatusCode.
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// when actionExecutedContext.Response is null, the error will be caught and logged by the Elmah filter
if ((actionExecutedContext.Response != null) && !actionExecutedContext.Response.IsSuccessStatusCode)
{
try
{
var messages = (System.Web.Http.HttpError)((System.Net.Http.ObjectContent<System.Web.Http.HttpError>)actionExecutedContext.Response.Content).Value;
StringBuilder stringBuilder = new StringBuilder();
foreach (var keyValuePair in messages) {
stringBuilder.AppendLine("Message: Key - " + keyValuePair.Key + ", Value - " + keyValuePair.Value);
}
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Web API Failed Status Code returned - " + stringBuilder.ToString()));
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Error in OnActionExecuted - " + ex.ToString()));
}
}
}
On a side note, I also overwrote "OnActionExecuting" to validate the model state. This allowed me to remove all of the checks within my actions.
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ModelState != null && !actionContext.ModelState.IsValid)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var obj in actionContext.ModelState.Values)
{
foreach (var error in obj.Errors)
{
if(!string.IsNullOrEmpty(error.ErrorMessage)) {
stringBuilder.AppendLine("Error: " + error.ErrorMessage);
}
}
}
Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Invalid Model State -- " + stringBuilder.ToString()));
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
Of course, you will need to add the filter using "config.Filters.Add".
Web API special cases HttpResponseException thrown in action and converts into HttpResponseMessage and hence you are not seeing your exception filter getting invoked.
This is not true in the case of throwing HttpResponseException from filters. However, ideally one need not throw HttpResponseException from filters as you could short-circuit a request by setting the Response property on the supplied input context.
You need to turn on Elmah for HttpFilters in order to get this to work as you expect for WebApi.
Use Elmah.Contrib.WebApi available as a NuGet Package, it will wire include a class that you can then wire up following the instructions on the Elmah.Contrib.WebApi project site.
If you want to do this yourself, Capturing Unhandled Exceptions in ASP.NET Web API's with ELMAH walks you through what the Elmah.Contrib.WebApi is doing for you.
Additionally, I had to change the way that the error response is thrown for it to be picked by Elmah to:
throw new HttpException((int)HttpStatusCode.NotAcceptable, "This request is not properly formatted");
I would also recommend the use of the Elmah.MVC NuGet Package.

Resources