Skip to content

Instantly share code, notes, and snippets.

@azare
Created July 24, 2015 15:38
Show Gist options
  • Save azare/633284d14f6c5008868b to your computer and use it in GitHub Desktop.
Save azare/633284d14f6c5008868b to your computer and use it in GitHub Desktop.
Outbound interceptor that adds a new header with the services original response status code
public class ResponseHeaderInterceptor extends AbstractPhaseInterceptor<Message> {
private static final String ORIGINAL_HTTP_STATUS_CODE = "X-Original-Http-Status-Code";
public ResponseHeaderInterceptor() {
super(Phase.MARSHAL);
}
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message message) throws Fault {
if (ServiceContext.get().isHttpStatusCodeValueOverridden()) {
MetadataMap<String, Object> headers = (MetadataMap<String, Object>) message.get(Message.PROTOCOL_HEADERS);
headers.add(ORIGINAL_HTTP_STATUS_CODE, getMessageResponseStatus(message));
message.put(Message.PROTOCOL_HEADERS, headers);
}
}
public int getMessageResponseStatus(Message message) {
int statusCode = 500;
if (null == message) return statusCode;
org.apache.cxf.message.MessageContentsList objs = org.apache.cxf.message.MessageContentsList.getContentsList(message);
if (objs == null || objs.size() == 0) {
// Assume error message or no response payload
return statusCode;
}
Object responseObj = objs.get(0);
if (responseObj instanceof javax.ws.rs.core.Response) {
statusCode = ((javax.ws.rs.core.Response) responseObj).getStatus();
}
else {
statusCode = getStatus(message, responseObj != null ? 200 : 204);
}
return statusCode;
}
public int getStatus(Message message, int defaultValue) {
if (null == message) return defaultValue;
Object customStatus = message.getExchange().get(Message.RESPONSE_CODE);
return customStatus == null ? defaultValue : (Integer) customStatus;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment