I'm developing a Java Web Service. At this moment I can get Http header requests. But I want to add more header requests.
I'm currently doing this in a servlet filter.
@WebFilter(urlPatterns = {"/*"})
public class AddHeader implements Filter {
@Resource
private WebServiceContext context;
public AddHeader() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request.getContentLength() != -1 && context != null) {
MessageContext mc = context.getMessageContext();
((HttpServletResponse) response).addHeader(
"Operation", "something"
);
}
chain.doFilter(request, response);
}
}
The problem with this strategy is that the added header is static.
With SoapHandler class I can obtain a SOAP message - dynamic:
public class SoapClass implements SOAPHandler<SOAPMessageContext> {
@Override
public boolean handleMessage(SOAPMessageContext messageContext) {
log(messageContext);
return true;
}
@Override
public Set<QName> getHeaders() {
Set<QName> qNames = Collections.EMPTY_SET;
return qNames;
}
@Override
public boolean handleFault(SOAPMessageContext messageContext) {
log(messageContext);
return true;
}
@Override
public void close(MessageContext context) {
}
public static String getMsgAsString(SOAPMessage message) {
String msg = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
message.writeTo(baos);
msg = baos.toString();
} catch (SOAPException | IOException soape) {
}
return msg;
}
private String soapToString(SOAPMessage message, boolean indent) {
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(message.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return (indent ? sw.toString() : sw.toString().replaceAll("[\\r\\n]", ""));
}
So, what I really wanted was to join dynamic soap message with filter. How can I achieve this?