Search code examples
jaxbjersey-2.0jersey-client

Jersey 2 Client - how to get JAXBContext


I can find Jersey 2 documentation on using custom JAXBContext but what I can't find is documentation on reusing its JAXBContext.

I want to be able to marshal/unmarshal entities without making an HTTP request (e.g. unmarshal some XML files on the classpath, marshal/unmarshal data for database I/O, etc.).

How can I get the JAXBContext instance that my Jersey 2 Client is already using?


Solution

  • 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();
            }
        }
    }