com.fasterxml.jackson.databind.MapperFeature Java Examples

The following examples show how to use com.fasterxml.jackson.databind.MapperFeature. 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: CsvUtils.java    From spring-boot-rest-api-helpers with MIT License 11 votes vote down vote up
public static <T> List<T> read(Class<T> clazz, InputStream stream, boolean withHeaders, char separator) throws IOException {
    CsvMapper mapper = new CsvMapper();

    mapper.enable(CsvParser.Feature.TRIM_SPACES);
    mapper.enable(CsvParser.Feature.ALLOW_TRAILING_COMMA);
    mapper.enable(CsvParser.Feature.INSERT_NULLS_FOR_MISSING_COLUMNS);
    mapper.enable(CsvParser.Feature.SKIP_EMPTY_LINES);
    mapper.disable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    CsvSchema schema = mapper.schemaFor(clazz).withColumnReordering(true);
    ObjectReader reader;
    if (separator == '\t') {
        schema = schema.withColumnSeparator('\t');
    }
    else {
        schema = schema.withColumnSeparator(',');
    }
    if (withHeaders) {
        schema = schema.withHeader();
    }
    else {
        schema = schema.withoutHeader();
    }
    reader = mapper.readerFor(clazz).with(schema);
    return reader.<T>readValues(stream).readAll();
}
 
Example #2
Source File: PdxInstanceWrapperUnitTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Test
public void objectMapperConfigurationIsCorrect() {

	PdxInstanceWrapper wrapper = spy(PdxInstanceWrapper.from(mock(PdxInstance.class)));

	ObjectMapper mockObjectMapper = mock(ObjectMapper.class);

	doReturn(mockObjectMapper).when(wrapper).newObjectMapper();
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(DeserializationFeature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(MapperFeature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).findAndRegisterModules();

	ObjectMapper objectMapper = wrapper.getObjectMapper().orElse(null);

	assertThat(objectMapper).isNotNull();

	verify(mockObjectMapper, times(1)).configure(eq(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES), eq(false));
	verify(mockObjectMapper, times(1)).configure(eq(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES), eq(false));
	verify(mockObjectMapper, times(1)).configure(eq(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS), eq(true));
	verify(mockObjectMapper, times(1)).findAndRegisterModules();
	verifyNoMoreInteractions(mockObjectMapper);
}
 
Example #3
Source File: Jackson2ObjectMapperBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION,
					DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
					SerializationFeature.INDENT_OUTPUT)
			.featuresToDisable(MapperFeature.AUTO_DETECT_FIELDS,
					MapperFeature.AUTO_DETECT_GETTERS,
					MapperFeature.AUTO_DETECT_SETTERS,
					SerializationFeature.FAIL_ON_EMPTY_BEANS).build();
	assertNotNull(objectMapper);
	assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}
 
Example #4
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	this.factory.setAutoDetectFields(false);
	this.factory.setAutoDetectGettersSetters(false);
	this.factory.setDefaultViewInclusion(false);
	this.factory.setFailOnEmptyBeans(false);
	this.factory.setIndentOutput(true);
	this.factory.afterPropertiesSet();

	ObjectMapper objectMapper = this.factory.getObject();

	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
	assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
 
Example #5
Source File: FilterableJsonSerializer.java    From caravan with Apache License 2.0 6 votes vote down vote up
public FilterableJsonSerializer(FilterableJsonSerializerConfig config) {
    NullArgumentChecker.DEFAULT.check(config, "config");

    ObjectMapper mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new FilterableBeanSerializerModifier(config));
    mapper.registerModule(module);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

    _mapper = mapper;
}
 
Example #6
Source File: JacksonObjectMapper.java    From frostmourne with MIT License 6 votes vote down vote up
public static ObjectMapper settingCommonObjectMapper(ObjectMapper objectMapper) {
    objectMapper.setDateFormat(new StdDateFormat());
    objectMapper.setTimeZone(TimeZone.getDefault());

    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    objectMapper.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
    objectMapper.configure(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS, false);

    return objectMapper;
}
 
Example #7
Source File: ObjectMapperFactory.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public ObjectMapper createObjectMapper()
{
    SimpleModule module = new SimpleModule();
    module.addDeserializer(PropertyValue.class, new PropertyValueDeserializer());
    module.addSerializer(SimplePropertyValue.class, new SimplePropertyValueSerializer());

    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);

    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.registerModule(module);

    objectMapper.registerModule(module);

    return objectMapper;
}
 
Example #8
Source File: BaseContextImpl.java    From invest-openapi-java-sdk with Apache License 2.0 6 votes vote down vote up
public BaseContextImpl(@NotNull final OkHttpClient client,
                       @NotNull final String url,
                       @NotNull final String authToken,
                       @NotNull final Logger logger) {

    this.authToken = authToken;
    this.finalUrl = Objects.requireNonNull(HttpUrl.parse(url))
            .newBuilder()
            .addPathSegment(this.getPath())
            .build();
    this.client = client;
    this.logger = logger;
    this.mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new JavaTimeModule());
    mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
 
Example #9
Source File: Jackson2ObjectMapperBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationFeature) {
		objectMapper.configure((SerializationFeature) feature, enabled);
	}
	else if (feature instanceof DeserializationFeature) {
		objectMapper.configure((DeserializationFeature) feature, enabled);
	}
	else if (feature instanceof MapperFeature) {
		objectMapper.configure((MapperFeature) feature, enabled);
	}
	else {
		throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
Example #10
Source File: EsPropertyNamingStrategyTest.java    From soundwave with Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeWithStrategy() throws Exception {
  ObjectMapper
      mapper =
      new ObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          .setPropertyNamingStrategy(new EsPropertyNamingStrategy(
              EsDailySnapshotInstance.class, EsInstanceStore.class))
          .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true);

  EsDailySnapshotInstance inst = mapper.readValue(doc, EsDailySnapshotInstance.class);
  Assert.assertEquals("coreapp-webapp-prod-0a018ef5", inst.getName());
  Assert.assertEquals("fixed", inst.getLifecycle());
  Assert.assertTrue(inst.getLaunchTime() != null);

}
 
Example #11
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	this.factory.setAutoDetectFields(false);
	this.factory.setAutoDetectGettersSetters(false);
	this.factory.setDefaultViewInclusion(false);
	this.factory.setFailOnEmptyBeans(false);
	this.factory.setIndentOutput(true);
	this.factory.afterPropertiesSet();

	ObjectMapper objectMapper = this.factory.getObject();

	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
	assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
 
Example #12
Source File: EsInstanceStore.java    From soundwave with Apache License 2.0 6 votes vote down vote up
public EsInstanceStore(String host, int port) {
  super(host, port);
  //This is required to let ES create the mapping of Date instead of long
  insertMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  updateMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .addMixIn(getInstanceClass(), IgnoreCreatedTimeMixin.class);

  //Specific mapper to read EsDailySnapshotInstance from the index
  essnapshotinstanceMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .setPropertyNamingStrategy(new EsPropertyNamingStrategy(
          EsDailySnapshotInstance.class, EsInstanceStore.class))
      .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true);

}
 
Example #13
Source File: MapperBuilder.java    From qconfig with MIT License 6 votes vote down vote up
private static void configure(ObjectMapper om, Object feature, boolean state) {
    if (feature instanceof SerializationFeature)
        om.configure((SerializationFeature) feature, state);
    else if (feature instanceof DeserializationFeature)
        om.configure((DeserializationFeature) feature, state);
    else if (feature instanceof JsonParser.Feature)
        om.configure((JsonParser.Feature) feature, state);
    else if (feature instanceof JsonGenerator.Feature)
        om.configure((JsonGenerator.Feature) feature, state);
    else if (feature instanceof MapperFeature)
        om.configure((MapperFeature) feature, state);
    else if (feature instanceof Include) {
        if (state) {
            om.setSerializationInclusion((Include) feature);
        }
    }
}
 
Example #14
Source File: Jackson2ObjectMapperBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION,
					DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
					SerializationFeature.INDENT_OUTPUT)
			.featuresToDisable(MapperFeature.AUTO_DETECT_FIELDS,
					MapperFeature.AUTO_DETECT_GETTERS,
					MapperFeature.AUTO_DETECT_SETTERS,
					SerializationFeature.FAIL_ON_EMPTY_BEANS).build();
	assertNotNull(objectMapper);
	assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}
 
Example #15
Source File: SerializeTest.java    From raptor with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    HelloRequest request = DemoMessageBuilder.getTestRequest();
    ObjectMapper objectMapper = new RaptorJacksonMessageConverter().getObjectMapper();
    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS,false);
    String json = objectMapper.writeValueAsString(request);

    System.out.println(json);

    Map<String, String> map = RaptorMessageUtils.transferMessageToMap(request);
    RequestTemplate requestTemplate = new RequestTemplate();
    map.forEach(requestTemplate::query);

    System.out.println(URLDecoder.decode(requestTemplate.queryLine(),"UTF-8"));

    Assert.assertFalse(json.contains("tdouble"));

}
 
Example #16
Source File: RedisConfig.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
@Bean
public RedisSerializer<Object> redisSerializer() {
    //创建JSON序列化器
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
            new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    //TODO: 此项必须配置,否则会报java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX
    objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
            ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    return jackson2JsonRedisSerializer;
}
 
Example #17
Source File: SerializerUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static String toJsonString(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    }

    SimpleModule module = createModule();
    try {
        return Json.mapper()
                .copy()
                .registerModule(module)
                .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
                .writerWithDefaultPrettyPrinter()
                .writeValueAsString(openAPI)
                .replace("\r\n", "\n");
    } catch (JsonProcessingException e) {
        LOGGER.warn("Can not create json content", e);
    }
    return null;
}
 
Example #18
Source File: SerializerUtils.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public static String toYamlString(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    }
    SimpleModule module = createModule();
    try {
        ObjectMapper yamlMapper = Yaml.mapper().copy();
        // there is an unfortunate YAML condition where user inputs should be treated as strings (e.g. "1234_1234"), but in yaml this is a valid number and
        // removing quotes forcibly by default means we are potentially doing a data conversion resulting in an unexpected change to the user's YAML outputs.
        // We may allow for property-based enable/disable, retaining the default of enabled for backward compatibility.
        if (minimizeYamlQuotes) {
            ((YAMLFactory) yamlMapper.getFactory()).enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        } else {
            ((YAMLFactory) yamlMapper.getFactory()).disable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        }
        return yamlMapper.registerModule(module)
                .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
                .writeValueAsString(openAPI)
                .replace("\r\n", "\n");
    } catch (JsonProcessingException e) {
        LOGGER.warn("Can not create yaml content", e);
    }
    return null;
}
 
Example #19
Source File: ClientContextTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testContextMarshalling() throws Exception {
    ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    ObjectReader reader = mapper.readerFor(ClientContextImpl.class);

    ClientContext clientContext = reader.readValue(ctx);
    Assertions.assertNotNull(clientContext.getClient());
    Assertions.assertNotNull(clientContext.getCustom());
    Assertions.assertNotNull(clientContext.getEnvironment());

    Assertions.assertEquals("<client_id>", clientContext.getClient().getInstallationId());
    Assertions.assertEquals("<app_title>", clientContext.getClient().getAppTitle());
    Assertions.assertEquals("<app_version_name>", clientContext.getClient().getAppVersionName());
    Assertions.assertEquals("<app_version_code>", clientContext.getClient().getAppVersionCode());
    Assertions.assertEquals("<app_package_name>", clientContext.getClient().getAppPackageName());

    Assertions.assertEquals("world", clientContext.getCustom().get("hello"));
    Assertions.assertEquals("<platform>", clientContext.getEnvironment().get("platform"));

}
 
Example #20
Source File: RestObjectMapper.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public RestObjectMapper() {
  getFactory().disable(Feature.AUTO_CLOSE_SOURCE);
  // Enable features that can tolerance errors and not enable those make more constraints for compatible reasons.
  // Developers can use validation api to do more checks.
  disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  // no view annotations shouldn't be included in JSON
  disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
  disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
  enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

  SimpleModule module = new SimpleModule();
  // custom types
  module.addSerializer(JsonObject.class, new JsonObjectSerializer());
  registerModule(module);
  registerModule(new JavaTimeModule());
}
 
Example #21
Source File: ActionProcessor.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") // as in super
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    mapper = new ObjectMapper()
        .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
        .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    annotationClass = mandatoryFindClass(SYNDESIS_ANNOTATION_CLASS_NAME);
    propertyAnnotationClass = mandatoryFindClass(SYNDESIS_PROPERTY_ANNOTATION_CLASS_NAME);
    propertyEnumAnnotationClass = mandatoryFindClass(SYNDESIS_PROPERTY_ENUM_ANNOTATION_CLASS_NAME);
    dataShapeVariantAnnotationClass = mandatoryFindClass(SYNDESIS_DATA_SHAPE_VARIANT_CLASS_NAME);
    dataShapeMetaAnnotationClass = mandatoryFindClass(SYNDESIS_DATA_SHAPE_META_CLASS_NAME);
    stepClass = findClass(SYNDESIS_STEP_CLASS_NAME);
    beanAnnotationClass = findClass(BEAN_ANNOTATION_CLASS_NAME);
    handlerAnnotationClass = mandatoryFindClass(CAMEL_HANDLER_ANNOTATION_CLASS_NAME);
    routeBuilderClass = mandatoryFindClass(CAMEL_ROUTE_BUILDER_CLASS_NAME_);
}
 
Example #22
Source File: OASGenerator.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String generateOpenApiContent(OpenAPI openApi, OutputFormat outputFormat, Boolean sort) {
  if (sort) {
    ObjectMapper objectMapper = outputFormat.mapper();
    objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    try {
      return objectMapper.writer(new DefaultPrettyPrinter()).writeValueAsString(openApi);
    } catch (JsonProcessingException e) {
      LOGGER.error("Sorting failed!");
      return outputFormat.pretty(openApi);
    }
  } else {
    return outputFormat.pretty(openApi);
  }
}
 
Example #23
Source File: Jackson2ObjectMapperBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationFeature) {
		objectMapper.configure((SerializationFeature) feature, enabled);
	}
	else if (feature instanceof DeserializationFeature) {
		objectMapper.configure((DeserializationFeature) feature, enabled);
	}
	else if (feature instanceof MapperFeature) {
		objectMapper.configure((MapperFeature) feature, enabled);
	}
	else {
		throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
Example #24
Source File: CustomObjectMapper.java    From artemis with Apache License 2.0 5 votes vote down vote up
public CustomObjectMapper() {
    configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
}
 
Example #25
Source File: KnativeEventsBindingRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void init() {
    typeTriggers = new HashMap<>();
    objectMapper = getObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    for (FunctionInvoker invoker : FunctionRecorder.registry.invokers()) {
        Method method = invoker.getMethod();
        CloudEventMapping annotation = method.getAnnotation(CloudEventMapping.class);
        if (annotation != null && !annotation.trigger().isEmpty()) {
            typeTriggers.put(annotation.trigger(), invoker);
        } else {
            typeTriggers.put(invoker.getName(), invoker);
        }

        if (invoker.hasInput()) {
            ObjectReader reader = objectMapper.readerFor(invoker.getInputType());
            invoker.getBindingContext().put(ObjectReader.class.getName(), reader);
        }
        if (invoker.hasOutput()) {
            ObjectWriter writer = objectMapper.writerFor(invoker.getOutputType());
            invoker.getBindingContext().put(ObjectWriter.class.getName(), writer);

            String functionName = invoker.getName();
            if (annotation != null && !annotation.responseType().isEmpty()) {
                invoker.getBindingContext().put(RESPONSE_TYPE, annotation.responseType());
            } else {
                invoker.getBindingContext().put(RESPONSE_TYPE, functionName + ".output");
            }
            if (annotation != null && !annotation.responseSource().isEmpty()) {
                invoker.getBindingContext().put(RESPONSE_SOURCE, annotation.responseSource());
            } else {
                invoker.getBindingContext().put(RESPONSE_SOURCE, functionName);
            }
        }
    }
}
 
Example #26
Source File: FunqyHttpBindingRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void init() {
    objectMapper = getObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    for (FunctionInvoker invoker : FunctionRecorder.registry.invokers()) {
        if (invoker.hasInput()) {
            ObjectReader reader = objectMapper.readerFor(invoker.getInputType());
            invoker.getBindingContext().put(ObjectReader.class.getName(), reader);
        }
        if (invoker.hasOutput()) {
            ObjectWriter writer = objectMapper.writerFor(invoker.getOutputType());
            invoker.getBindingContext().put(ObjectWriter.class.getName(), writer);
        }
    }
}
 
Example #27
Source File: PrimaryMetaStoreTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Test
public void toJson() throws Exception {
  String expected = "{\"accessControlType\":\"READ_ONLY\",\"connectionType\":\"DIRECT\",\"databasePrefix\":\"\",\"federationType\":\"PRIMARY\",\"latency\":0,\"mappedDatabases\":null,\"metastoreTunnel\":null,\"name\":\"name\",\"remoteMetaStoreUris\":\"uri\",\"status\":\"UNKNOWN\",\"writableDatabaseWhiteList\":[]}";
  ObjectMapper mapper = new ObjectMapper();
  // Sorting to get deterministic test behaviour
  mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
  String json = mapper.writerFor(PrimaryMetaStore.class).writeValueAsString(metaStore);
  assertThat(json, is(expected));
}
 
Example #28
Source File: JacksonObjectToJsonConverterUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Test
public void newObjectMapperIsConfiguredCorrectly() {

	Object target = Customer.newCustomer(1L, "Jon Doe");

	ObjectMapper mockObjectMapper = mock(ObjectMapper.class);

	JacksonObjectToJsonConverter converter = spy(new JacksonObjectToJsonConverter());

	doReturn(mockObjectMapper).when(converter).newObjectMapper();
	doReturn(mockObjectMapper).when(mockObjectMapper).addMixIn(any(), any());
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(JsonGenerator.Feature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(MapperFeature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(SerializationFeature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).findAndRegisterModules();

	ObjectMapper objectMapper = converter.newObjectMapper(target);

	assertThat(objectMapper).isNotNull();

	verify(converter, times(1)).newObjectMapper();

	verify(mockObjectMapper, times(1))
		.addMixIn(eq(target.getClass()), eq(JacksonObjectToJsonConverter.ObjectTypeMetadataMixin.class));
	verify(mockObjectMapper, times(1))
		.configure(eq(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN), eq(true));
	verify(mockObjectMapper, times(1))
		.configure(eq(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY), eq(true));
	verify(mockObjectMapper, times(1))
		.configure(eq(SerializationFeature.INDENT_OUTPUT), eq(true));
	verify(mockObjectMapper, times(1)).findAndRegisterModules();
	verifyNoMoreInteractions(mockObjectMapper);
}
 
Example #29
Source File: WebConfig.java    From grpc-swagger with MIT License 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper;
}
 
Example #30
Source File: OfframpConfiguration.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper jsonMapper() {
  return new ObjectMapper()
      .registerModule(new SchemaSerializationModule())
      .registerModule(Event.module())
      .registerModule(new JavaTimeModule())
      .disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
      .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
      .disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}