Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey converting from ClientResponse to Response

Tags:

java

jersey

I'm currently using Jersey as a proxy REST api to call another RESTful web service. Some of the calls will be passed to and from with minimal processing in my server.

Is there a way to do this cleanly? I was thinking of using the Jersey Client to make the REST call, then converting the ClientResponse into a Response. Is this possible or is there a better way to do this?

Some example code:

@GET
@Path("/groups/{ownerID}")
@Produces("application/xml")
public String getDomainGroups(@PathParam("ownerID") String ownerID) {
    WebResource r = client.resource(URL_BASE + "/" + URL_GET_GROUPS + "/" + ownerID);
    String resp = r.get(String.class);
    return resp;
}

This works if the response is always a success, but if there's a 404 on the other server, I'd have to check the response code. In other words, is there clean way to just return the response I got?

like image 532
user1442804 Avatar asked Dec 26 '22 23:12

user1442804


1 Answers

There is no convenience method as far as I am aware. You can do this:

public Response getDomainGroups(@PathParam("ownerID") String ownerID) {
    WebResource r = client.resource(URL_BASE + "/" + URL_GET_GROUPS + "/" + ownerID);
    ClientResponse resp = r.get(ClientResponse.class);
    return clientResponseToResponse(resp);
}

public static Response clientResponseToResponse(ClientResponse r) {
    // copy the status code
    ResponseBuilder rb = Response.status(r.getStatus());
    // copy all the headers
    for (Entry<String, List<String>> entry : r.getHeaders().entrySet()) {
        for (String value : entry.getValue()) {
            rb.header(entry.getKey(), value);
        }
    }
    // copy the entity
    rb.entity(r.getEntityInputStream());
    // return the response
    return rb.build();
}
like image 66
Martin Matula Avatar answered Jan 07 '23 21:01

Martin Matula