com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule Java Examples

The following examples show how to use com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestJsonEntitySerializer.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeProcessor() throws IOException {
    final ObjectMapper jsonCodec = new ObjectMapper();
    jsonCodec.registerModule(new JaxbAnnotationModule());
    jsonCodec.setSerializationInclusion(Include.NON_NULL);

    // Test that we can properly serialize a ProcessorEntity because it has many nested levels, including a Map
    final JsonEntitySerializer serializer = new JsonEntitySerializer(jsonCodec);
    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final ProcessorConfigDTO configDto = new ProcessorConfigDTO();
        configDto.setProperties(Collections.singletonMap("key", "value"));
        final ProcessorDTO processorDto = new ProcessorDTO();
        processorDto.setConfig(configDto);

        final ProcessorEntity processor = new ProcessorEntity();
        processor.setId("123");
        processor.setComponent(processorDto);

        serializer.serialize(processor, baos);

        final String serialized = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        assertEquals("{\"id\":\"123\",\"component\":{\"config\":{\"properties\":{\"key\":\"value\"}}}}", serialized);
    }
}
 
Example #2
Source File: SwaggerBootstrapServlet.java    From render with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void init(final ServletConfig config) throws ServletException {
    super.init(config);

    final BeanConfig beanConfig = loadConfig(new File("resources/swagger.properties"));
    beanConfig.setVersion("v1");
    beanConfig.setSchemes(new String[]{"http"});
    beanConfig.setBasePath("/render-ws");
    beanConfig.setResourcePackage("org.janelia.render.service");
    beanConfig.setScan(true);
    beanConfig.setPrettyPrint(true);

    // Needed to register these modules to get Swagger to use JAXB annotations
    // (see https://github.com/swagger-api/swagger-core/issues/960 for explanation)
    Json.mapper().registerModule(new JaxbAnnotationModule());
    Yaml.mapper().registerModule(new JaxbAnnotationModule());
}
 
Example #3
Source File: NsObjectTransducer.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * Creates instance of transducer using given NetSuite client.
 *
 * @param clientService client to be used
 */
protected NsObjectTransducer(NetSuiteClientService<?> clientService) {
    this.clientService = clientService;

    try {
        datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new ComponentException(e);
    }

    objectMapper = new ObjectMapper();

    // Customize typing of JSON objects.
    objectMapper.setDefaultTyping(new NsTypeResolverBuilder(clientService.getBasicMetaData()));

    // Register JAXB annotation module to perform mapping of data model objects to/from JSON.
    JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
    objectMapper.registerModule(jaxbAnnotationModule);

    setMetaDataSource(clientService.getMetaDataSource());
}
 
Example #4
Source File: TestJaxbNullProperties.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
public void testNillability() throws Exception
{
    ObjectMapper mapper = getJaxbMapper();
    // by default, something not marked as nillable will still be written if null
    assertEquals("{\"z\":null}", mapper.writeValueAsString(new NonNillableZ()));
    assertEquals("{\"z\":3}", mapper.writeValueAsString(new NonNillableZ(3)));

    // but we can change that...
    mapper = getJaxbMapperBuilder()
            .annotationIntrospector(new JaxbAnnotationIntrospector()
                    .setNonNillableInclusion(JsonInclude.Include.NON_NULL)
                )
            .addModule(new JaxbAnnotationModule().setNonNillableInclusion(JsonInclude.Include.NON_NULL))
            .build();
    assertEquals("{}", mapper.writeValueAsString(new NonNillableZ()));
    assertEquals("{\"z\":3}", mapper.writeValueAsString(new NonNillableZ(3)));
}
 
Example #5
Source File: DefaultMapperDecorator.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectMapper decorate(ObjectMapper mapper) {
    
    if (null == mapper) {
        throw new IllegalArgumentException("mapper cannot be null");
    }
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new JaxbAnnotationModule());
    
    registerAbstractTypes(mapper);
    
    return mapper;
}
 
Example #6
Source File: TestJsonEntitySerializer.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testBulletinEntity() throws Exception {
    final ObjectMapper jsonCodec = new ObjectMapper();
    jsonCodec.registerModule(new JaxbAnnotationModule());
    jsonCodec.setSerializationInclusion(Include.NON_NULL);

    final Date timestamp = new Date();
    final TimeAdapter adapter = new TimeAdapter();
    final String formattedTimestamp = adapter.marshal(timestamp);

    // Test that we can properly serialize a Bulletin because it contains a timestmap,
    // which uses a JAXB annotation to specify how to marshal it.
    final JsonEntitySerializer serializer = new JsonEntitySerializer(jsonCodec);

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final BulletinDTO bulletinDto = new BulletinDTO();
        bulletinDto.setCategory("test");
        bulletinDto.setLevel("INFO");
        bulletinDto.setTimestamp(timestamp);

        final BulletinEntity bulletin = new BulletinEntity();
        bulletin.setBulletin(bulletinDto);
        serializer.serialize(bulletin, baos);

        final String serialized = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        assertEquals("{\"bulletin\":{\"category\":\"test\",\"level\":\"INFO\",\"timestamp\":\"" + formattedTimestamp + "\"}}", serialized);
    }
}
 
Example #7
Source File: ModelTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Test
void testTreeEntry() throws JAXBException, IOException
{
    TreeEntry parent = new TreeEntry( );
    TreeEntry entry = new TreeEntry( );
    entry.setParent( parent );
    Artifact artifact1 = new Artifact( );
    artifact1.setGroupId( "test.group" );
    artifact1.setArtifactId( "artifact1" );
    artifact1.setVersion( "1.0" );
    entry.setArtifact( artifact1 );

    TreeEntry child1 = new TreeEntry( );
    TreeEntry child2 = new TreeEntry( );
    child1.setParent( entry );
    child2.setParent( entry );
    Artifact artifact2 = new Artifact( );
    artifact2.setGroupId( "test.group" );
    artifact2.setArtifactId( "artifact1" );
    artifact2.setVersion( "1.1" );
    child1.setArtifact( artifact2 );
    child2.setArtifact( artifact2 );
    entry.setChilds( Arrays.asList( child1, child2) );

    ObjectMapper objectMapper = new ObjectMapper( );
    objectMapper.registerModule( new JaxbAnnotationModule( ) );
    StringWriter sw = new StringWriter( );
    objectMapper.writeValue( sw, entry );

    JSONObject js = new JSONObject( sw.toString() );
    assertFalse( js.has( "parent" ) );
    assertTrue( js.has( "childs" ) );
    assertEquals(2, js.getJSONArray( "childs" ).length());
    assertTrue( js.has( "artifact" ) );

}
 
Example #8
Source File: CqlTranslator.java    From clinical_quality_language with Apache License 2.0 5 votes vote down vote up
public String convertToJxson(Library library) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    JaxbAnnotationModule annotationModule = new JaxbAnnotationModule();
    mapper.registerModule(annotationModule);
    LibraryWrapper wrapper = new LibraryWrapper();
    wrapper.setLibrary(library);
    return mapper.writeValueAsString(wrapper);
}
 
Example #9
Source File: CoreJacksonConfigurator.java    From micro-server with Apache License 2.0 5 votes vote down vote up
public void accept(ObjectMapper mapper) {
	
	
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	// configure as necessary
	inc.map(include->mapper.setSerializationInclusion(include));
	mapper.registerModule(module);
	PluginLoader.INSTANCE.plugins.get().stream()
		.filter(m -> m.jacksonModules()!=null)
		.flatMap(m -> m.jacksonModules().stream())
		.forEach(m -> mapper.registerModule(m));
		
	mapper.registerModule(new Jdk8Module());
	mapper.registerModule(new CyclopsModule());
}
 
Example #10
Source File: Client.java    From metacat with Apache License 2.0 5 votes vote down vote up
private Client(
    final String host,
    final feign.Client client,
    final feign.Logger.Level logLevel,
    final RequestInterceptor requestInterceptor,
    final Retryer retryer,
    final Request.Options options
) {
    final MetacatJsonLocator metacatJsonLocator = new MetacatJsonLocator();
    final ObjectMapper mapper = metacatJsonLocator
        .getPrettyObjectMapper()
        .copy()
        .registerModule(new GuavaModule())
        .registerModule(new JaxbAnnotationModule());

    log.info("Connecting to {}", host);
    this.host = host;

    feignBuilder = Feign.builder()
        .client(client)
        .logger(new Slf4jLogger())
        .logLevel(logLevel)
        .contract(new JAXRSContract())
        .encoder(new JacksonEncoder(mapper))
        .decoder(new JacksonDecoder(mapper))
        .errorDecoder(new MetacatErrorDecoder(metacatJsonLocator))
        .requestInterceptor(requestInterceptor)
        .retryer(retryer)
        .options(options);

    api = getApiClient(MetacatV1.class);
    partitionApi = getApiClient(PartitionV1.class);
    metadataApi = getApiClient(MetadataV1.class);
    resolverApi = getApiClient(ResolverV1.class);
    tagApi = getApiClient(TagV1.class);
}
 
Example #11
Source File: MCRJobQueueResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private <T> String toJSON(T entity) throws IOException {
    StringWriter sw = new StringWriter();

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JaxbAnnotationModule());
    mapper.writeValue(sw, entity);

    return sw.toString();
}
 
Example #12
Source File: RotationRequestTest.java    From fernet-java8 with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    mapper = new ObjectMapper().registerModule(new JaxbAnnotationModule());
}
 
Example #13
Source File: JacksonBundle.java    From base-framework with Apache License 2.0 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson藕合.
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的.
 */
public void enableJaxbAnnotation() {
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	mapper.registerModule(module);
}
 
Example #14
Source File: AbstractDocumentSource.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
public void loadModelModifier() throws GenerateException, IOException {
    ObjectMapper objectMapper = Json.mapper();
    if (apiSource.isUseJAXBAnnotationProcessor()) {
        JaxbAnnotationModule jaxbAnnotationModule = new JaxbAnnotationModule();
        if (apiSource.isUseJAXBAnnotationProcessorAsPrimary()) {
            jaxbAnnotationModule.setPriority(Priority.PRIMARY);
        } else {
            jaxbAnnotationModule.setPriority(Priority.SECONDARY);
        }
        objectMapper.registerModule(jaxbAnnotationModule);

        // to support @ApiModel on class level.
        // must be registered only if we use JaxbAnnotationModule before. Why?
        objectMapper.registerModule(new EnhancedSwaggerModule());
    }
    ModelModifier modelModifier = new ModelModifier(objectMapper);

    List<String> apiModelPropertyAccessExclusions = apiSource.getApiModelPropertyAccessExclusions();
    if (apiModelPropertyAccessExclusions != null && !apiModelPropertyAccessExclusions.isEmpty()) {
        modelModifier.setApiModelPropertyAccessExclusions(apiModelPropertyAccessExclusions);
    }

    if (modelSubstitute != null) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(this.modelSubstitute)));
            String line = reader.readLine();
            while (line != null) {
                String[] classes = line.split(":");
                if (classes.length != 2) {
                    throw new GenerateException("Bad format of override model file, it should be ${actualClassName}:${expectClassName}");
                }
                modelModifier.addModelSubstitute(classes[0].trim(), classes[1].trim());
                line = reader.readLine();
            }
        } catch (IOException e) {
            throw new GenerateException(e);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    ModelConverters.getInstance().addConverter(modelModifier);
}
 
Example #15
Source File: JsonMapper.java    From dubai with MIT License 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public void enableJaxbAnnotation() {
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	mapper.registerModule(module);
}
 
Example #16
Source File: JsonMapper.java    From frpMgr with MIT License 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public JsonMapper enableJaxbAnnotation() {
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	this.registerModule(module);
	return this;
}
 
Example #17
Source File: JsonMapper.java    From lightconf with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public JsonMapper enableJaxbAnnotation() {
    JaxbAnnotationModule module = new JaxbAnnotationModule();
    this.registerModule(module);
    return this;
}
 
Example #18
Source File: JacksonPrinterTest.java    From eclair with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
    xmlMapper = new XmlMapper();
    xmlMapper.registerModule(new JaxbAnnotationModule());
}
 
Example #19
Source File: UnwrappedAttributeTest.java    From dropwizard-xml with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    xmlMapper.enable(SerializationFeature.INDENT_OUTPUT).registerModule(new JaxbAnnotationModule());
}
 
Example #20
Source File: AbstractFernetKeyRotator.java    From fernet-java8 with Apache License 2.0 4 votes vote down vote up
protected AbstractFernetKeyRotator(final SecretsManager secretsManager, final AWSKMS kms,
        final SecureRandom random) {
    this(new ObjectMapper().registerModule(new JaxbAnnotationModule()), secretsManager, kms, random);
}
 
Example #21
Source File: JsonMapper.java    From wish-pay with Apache License 2.0 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public void enableJaxbAnnotation() {
    JaxbAnnotationModule module = new JaxbAnnotationModule();
    mapper.registerModule(module);
}
 
Example #22
Source File: BaseTest.java    From vavr-jackson with Apache License 2.0 4 votes vote down vote up
public XmlMapper xmlMapperJaxb() {
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.registerModule(new JaxbAnnotationModule());
    xmlMapper.registerModule(new VavrModule());
    return xmlMapper;
}
 
Example #23
Source File: JacksonExtensionManifestParser.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
public JacksonExtensionManifestParser() {
    this.mapper = new XmlMapper();
    this.mapper.registerModule(new JaxbAnnotationModule());
    this.mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
}
 
Example #24
Source File: JsonMapper.java    From spring-boot-quickstart with Apache License 2.0 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public void enableJaxbAnnotation() {
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	mapper.registerModule(module);
}
 
Example #25
Source File: JsonMapper.java    From LDMS with Apache License 2.0 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public JsonMapper enableJaxbAnnotation() {
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	this.registerModule(module);
	return this;
}
 
Example #26
Source File: PolicyRest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private ObjectMapper getMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JaxbAnnotationModule());
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper;
}
 
Example #27
Source File: JsonMapper.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
 * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。
 */
public JsonMapper enableJaxbAnnotation() {
	JaxbAnnotationModule module = new JaxbAnnotationModule();
	this.registerModule(module);
	return this;
}