Skip to content

Instantly share code, notes, and snippets.

@m-wrona
Last active June 15, 2016 09:50
Show Gist options
  • Save m-wrona/06cdfb372dbc3752605c74431ccf488e to your computer and use it in GitHub Desktop.
Save m-wrona/06cdfb372dbc3752605c74431ccf488e to your computer and use it in GitHub Desktop.
Spring Web service - attaching header to SOAP req
import org.springframework.ws.client.core.WebServiceMessageCallback;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import static com.mwronski.log.Tracer.tracer;
public final class SoapUtils {
/**
* Create JAXB context
*
* @param objects objects that should be defined in scope of ctx
* @return new instance
* @throws JAXBException when ctx couldn't be created
*/
private static JAXBContext jaxbCtx(Object... objects) throws JAXBException {
Class[] classes = new Class[objects.length];
for (int i = 0; i < objects.length; i++) {
classes[i] = objects[i].getClass();
}
return JAXBContext.newInstance(classes);
}
/**
* Attach headers to out-going SOAP request
*
* @param headers headers to be attached
* @return new instance of callback that will attach headers
*/
public static WebServiceMessageCallback withHeaders(Object... headers) {
return (wsMsg) -> {
SoapHeader soapHeader = ((SoapMessage) wsMsg).getSoapHeader();
try {
JAXBContext context = jaxbCtx(headers);
Marshaller marshaller = context.createMarshaller();
for (Object header : headers) {
marshaller.marshal(header, soapHeader.getResult());
}
} catch (JAXBException e) {
tracer(SoapUtils.class).error("Couldn't attach headers", e);
}
};
}
private SoapUtils() {
//no instances
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment