The writer interceptors manage the writer interceptor context. This context lets you manage the following things:
- Headers
- Output stream
- Entities
The entity and the output streams represent the result of a REST call. The entity is the serialized object declared in the service methods. Here's a sample of writer interceptor that adds an encrypted MD5 string in the output stream:
@Provider
public class ContentMD5Writer implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
MessageDigest digest = null;
try {
digest = getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DigestOutputStream digestStream = new DigestOutputStream(buffer, digest);
OutputStream old = context.getOutputStream();
context.setOutputStream(digestStream);
try {
context.proceed();
byte[] hash = digest.digest();
String encodedHash = getEncoder().encodeToString(hash);
context.getHeaders().putSingle(CONTENT_MD5_STRING, encodedHash);
byte[] content = buffer.toByteArray();
old.write(content);
} finally {
context.setOutputStream(old);
}
}
}
The result can be seen in the client:
Client client = newClient();
client.register(ContentMD5Writer.class);
String md5 = response.getHeaderString(CONTENT_MD5_STRING);
The variable MD5 will return the hcEzFGyuhOARcfBb4bM1sw== encrypted value.