All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.openesb.rest.api.provider.ObjectMapperProvider Maven / Gradle / Ivy

package net.openesb.rest.api.provider;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import java.io.IOException;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.namespace.QName;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;

/**
 *
 * @author David BRASSELY (brasseld at gmail.com)
 * @author OpenESB Community
 */
@Provider
public class ObjectMapperProvider implements ContextResolver {

    private final ObjectMapper defaultObjectMapper;

    public ObjectMapperProvider() {
        defaultObjectMapper = createDefaultMapper();
    }

    @Override
    public ObjectMapper getContext(Class type) {
        return defaultObjectMapper;
    }

    private static ObjectMapper createDefaultMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

        AnnotationIntrospector ai = AnnotationIntrospector.pair(
                new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()), 
                new JacksonAnnotationIntrospector());

        mapper.setAnnotationIntrospector(ai);
        
        SimpleModule customModule = new SimpleModule("OpenesbModule", new Version(1, 0, 0, null));
        customModule.addSerializer(new QNameSerializer());
        mapper.registerModule(customModule);
        
        return mapper;
    }
    
    private static class QNameSerializer extends StdSerializer {
        private QNameSerializer() {
            super(QName.class);
        }
        
        @Override
        public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException, JsonProcessingException
        {
            jgen.writeStartObject();
            
            jgen.writeStringField("namespaceURI", value.getNamespaceURI());
            jgen.writeStringField("localPart", value.getLocalPart());
            
            jgen.writeEndObject();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy