Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

jersey - How to register my custom MessageBodyReader in my CLIENT?

Maybe somebody can help me find out how to solve this.

I am using jersey-apache-client 1.17

I tried to use Jersey client to build a standalone application (no Servlet container or whatever, just the Java classes) which communicates with a RESTFUL API, and everything worked fine until I tried to handle the mediatype "text/csv; charset=utf-8" which is a CSV stream sent by the server.

The thing is that I can read this stream with the following code:

    InputStreamReader reader = new InputStreamReader(itemExportBuilder
            .get(ClientResponse.class).getEntityInputStream());
    Csv csv = new Csv();
    Input input = csv.createInput(reader);
    try {
        String[] readLine;
        while ((readLine = input.readLine()) != null) {
            LOG.debug("Reading CSV: {}", readLine);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        input.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

But I'd like to encapsulate it and put it into a MessageBodyReader. But after writing this code, I just can't make the client use the following class:

package client.response;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Provider
public class ItemExportMessageBodyReader implements MessageBodyReader<ItemExportResponse> {

private static final Logger LOG = LoggerFactory.getLogger(ItemExportMessageBodyReader.class);

private static final Integer SKU = 0;
private static final Integer BASE_SKU = 1;

public boolean isReadable(Class<?> paramClass, Type type, Annotation[] annotations,
        MediaType mediaType) {
    LOG.info("Cheking if content is readable or not");
    return paramClass == ItemExportResponse.class && !mediaType.isWildcardType()
            && !mediaType.isWildcardSubtype()
            && mediaType.isCompatible(MediaType.valueOf("text/csv; charset=utf-8"));
}

public ItemExportResponse readFrom(Class<ItemExportResponse> paramClass, Type paramType,
        Annotation[] paramArrayOfAnnotation, MediaType paramMediaType,
        MultivaluedMap<String, String> paramMultivaluedMap, InputStream entityStream)
        throws IOException, WebApplicationException {
    InputStreamReader reader = new InputStreamReader(entityStream);
    Csv csv = new Csv();
    Input input = csv.createInput(reader);
    List<Item> items = new ArrayList<Item>();
    try {
        String[] readLine;
        while ((readLine = input.readLine()) != null) {
            LOG.trace("Reading CSV: {}", readLine);
            Item item = new Item();
            item.setBaseSku(readLine[BASE_SKU]);
            items.add(item);
        }
    } catch (IOException e) {
        LOG.warn("Item export HTTP response handling failed", e);
    } finally {
        try {
            input.close();
        } catch (IOException e) {
            LOG.warn("Could not close the HTTP response stream", e);
        }
    }
    ItemExportResponse response = new ItemExportResponse();
    response.setItems(items);
    return response;
}

}

The following documentation says that the preferred way of making this work in a JAX-RS client to register the message body reader with the code below:

Using Entity Providers with JAX-RS Client API

            Client client = ClientBuilder.newBuilder().register(MyBeanMessageBodyReader.class).build();
            Response response = client.target("http://example/comm/resource").request(MediaType.APPLICATION_XML).get();
            System.out.println(response.getStatus());
            MyBean myBean = response.readEntity(MyBean.class);
            System.out.println(myBean);

Now the thing is that I can't use the ClientBuilder. I have to extend from a specific class which constructs the client another way, and I have no access to change the construction.

So when I receive the response from the server, the client fails with the following Exception:

com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class client.response.ItemExportResponse, and Java type class client.response.ItemExportResponse, and MIME media type text/csv; charset=utf-8 was not found

Any other way to register my MessageBodyReader?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK. If anybody would bump into my question I solved this mystery by upgrading from Jersey 1.17 to version 2.9. The documentation I linked above also covers this version not the old one, this is where the confusion stems from.

Jersey introduced backward INCOMPATIBLE changes starting from version 2, so I have no clue how to configure it in version 1.17.

In version 2 the proposed solution worked fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...