Registering client filters for JAX-RS ClientBuilder

I write this here so I don't forget some of the goodies in below packages :)
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.Invocation.*;
Helpful Links

ClientRequestFilter

public class RequestFilter implements ClientRequestFilter {

    private static final Logger LOG = Logger.getLogger(RequestFilter.class.getName());

    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        LOG.log(Level.INFO, ">> " + requestContext.getMethod() + " " + requestContext.getUri());
        LOG.log(Level.INFO, ">> (body) " + requestContext.getEntity().toString());
        LOG.log(Level.INFO, ">> (headers) " + requestContext.getHeaders().toString());
    }
}

ClientResponseFilter

public class ResponseFilter implements ClientResponseFilter {

    private static final Logger LOG = Logger.getLogger(ResponseFilter.class.getName());

    @Override
    public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
        LOG.log(Level.INFO, "<< " + requestContext.getMethod() + " " + requestContext.getUri());
        LOG.log(Level.INFO, "<< (status) " + responseContext.getStatus());
        LOG.log(Level.INFO, "<< (headers) " + responseContext.getHeaders().toString());

        InputStream entityStream = responseContext.getEntityStream();
        if (entityStream != null) {
            LOG.log(Level.FINER, "<< (body)" + entityStream.toString());
        }
    }
}

Usage

JSONObject body = new JSONObject();
body.put("key", "value");

Client client = ClientBuilder.newClient();
client.register(ResponseFilter.class); // Response logging
client.register(new RequestFilter()); // Request logging

Response response = client.target("https://api.example.com")
    .path("clients")
    .request()
    .buildPost(Entity.json(body))
    .invoke();

if (response.getStatus() == 200) { ... } else { ... }

0 comments :

This work is licensed under BSD Zero Clause License | nacho4d ®