Jersey 2 客户端 - 如何获取 JAXBContext

Jersey 2 Client - how to get JAXBContext

我可以在 using custom JAXBContext 上找到 Jersey 2 文档,但我找不到关于重用 其 JAXBContext 的文档。

我希望能够 marshal/unmarshal 实体而无需发出 HTTP 请求(例如解组类路径上的一些 XML 文件,marshal/unmarshal 数据库 I/O 的数据,等)。

如何获取我的 Jersey 2 客户端已经在使用的 JAXBContext 实例?

我仍然没有弄清楚如何 获取 JAXBContext 但我已经弄清楚如何 重用 它:

client.target("file:///path/to/resource")
        .register((ClientRequestFilter) requestContext ->
                requestContext.abortWith(Response.ok()
                        .entity(new FileInputStream(Paths.get(requestContext.getUri())
                                .toFile()))
                        .build()))
        .request()
        .get(Planet.class);

类似的 ClientRequestFilters 可用于从数据库等返回字符串或输入流,或写入 file-system 或数据库。

import org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

public class JaxbContextStore {
    private JaxbProvider jaxbProvider = new JaxbProvider();

    public JAXBContext getStoredJaxbContext(Class type) throws JAXBException {
        return jaxbProvider.getStoredJaxbContext(type);
    }

    private static class JaxbProvider extends AbstractJaxbProvider {
        public JaxbProvider() {
            super(null);
        }

        @Override
        public JAXBContext getStoredJaxbContext(Class type) throws JAXBException {
            return super.getStoredJaxbContext(type);
        }

        @Override
        public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
            throw new UnsupportedOperationException();
        }
    }
}