Skip to content

Instantly share code, notes, and snippets.

@jerhon
Last active May 13, 2019 18:59
Show Gist options
  • Save jerhon/d1be64a778666329922cae95f781815a to your computer and use it in GitHub Desktop.
Save jerhon/d1be64a778666329922cae95f781815a to your computer and use it in GitHub Desktop.
Java / Spring Framework / WebServiceGatewaySupport : Web service client with tracing, configurable read timeout
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.WebServiceIOException;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.transport.http.ClientHttpRequestMessageSender;
public class WebServiceClientImpl extends WebServiceGatewaySupport {
public WebServiceClientImpl(String baseUri, Jaxb2Marshaller marshall, int readTimeout) {
super();
setDefaultUri(baseUri);
setMarshaller(marshall);
setUnmarshaller(marshall);
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(readTimeout);
setMessageSender(new ClientHttpRequestMessageSender(requestFactory));
setInterceptors(new ClientInterceptor[] { new ClientInterceptor() {
@Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
messageContext.getRequest().writeTo(os);
} catch (IOException e) {
throw new WebServiceIOException(e.getMessage(), e);
}
String request = new String(os.toByteArray());
request = request.replaceAll("<password>.*</password>", "<password>******</password>");
logger.trace("Request Envelope (" + baseUri + "): " + request);
return true;
}
@Override
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
messageContext.getResponse().writeTo(os);
} catch (IOException e) {
throw new WebServiceIOException(e.getMessage(), e);
}
String response = new String(os.toByteArray());
logger.trace("Response Envelope (" + baseUri + "): " + response);
return true;
}
@Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
return false;
}
@Override
public void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException {
}
}});
}
public Object callWebService(Object request){
return getWebServiceTemplate().marshalSendAndReceive(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment