com.fasterxml.jackson.databind.ObjectMapper

Here are the examples of the java api class com.fasterxml.jackson.databind.ObjectMapper taken from open source projects.

1. HeroicMappers#config()

Project: heroic
Source File: HeroicMappers.java
View license
/**
     * Setup the ObjectMapper used to deserialize configuration files.
     *
     * @return
     */
public static ObjectMapper config() {
    final ObjectMapper m = new ObjectMapper(new YAMLFactory());
    m.addMixIn(ClusterDiscoveryModule.class, TypeNameMixin.class);
    m.addMixIn(RpcProtocolModule.class, TypeNameMixin.class);
    m.addMixIn(ConsumerModule.Builder.class, TypeNameMixin.class);
    m.addMixIn(MetadataModule.class, TypeNameMixin.class);
    m.addMixIn(SuggestModule.class, TypeNameMixin.class);
    m.addMixIn(MetricModule.class, TypeNameMixin.class);
    m.addMixIn(MetricGeneratorModule.class, TypeNameMixin.class);
    m.addMixIn(MetadataGenerator.class, TypeNameMixin.class);
    m.addMixIn(JettyConnectionFactory.Builder.class, TypeNameMixin.class);
    m.addMixIn(AnalyticsModule.Builder.class, TypeNameMixin.class);
    m.addMixIn(StatisticsModule.class, TypeNameMixin.class);
    m.registerModule(commonSerializers());
    /* support Optional */
    m.registerModule(new Jdk8Module());
    return m;
}

2. WorkflowReportJSON#makeObjectMapperForSave()

View license
protected static ObjectMapper makeObjectMapperForSave() {
    ObjectMapper om = new ObjectMapper();
    om.enable(INDENT_OUTPUT);
    om.disable(FAIL_ON_EMPTY_BEANS);
    om.enable(ORDER_MAP_ENTRIES_BY_KEYS);
    om.disable(WRITE_EMPTY_JSON_ARRAYS);
    om.disable(WRITE_NULL_MAP_VALUES);
    om.disable(WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
    om.disable(WRITE_DATES_AS_TIMESTAMPS);
    om.disable(WRITE_NULL_MAP_VALUES);
    om.addMixInAnnotations(Path.class, PathMixin.class);
    om.setSerializationInclusion(NON_NULL);
    return om;
}

3. JSONUtil#newMapper()

Project: ambrose
Source File: JSONUtil.java
View license
private static ObjectMapper newMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false);
    mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    mapper.disable(SerializationFeature.CLOSE_CLOSEABLE);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    Reflections reflections = new Reflections("com.twitter.ambrose");
    Set<Class<? extends Job>> jobSubTypes = reflections.getSubTypesOf(Job.class);
    mapper.registerSubtypes(jobSubTypes.toArray(new Class<?>[jobSubTypes.size()]));
    return mapper;
}

4. HeroicMappers#json()

Project: heroic
Source File: HeroicMappers.java
View license
public static ObjectMapper json(final QueryParser parser) {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(AggregationInstance.class, TypeNameMixin.class);
    mapper.addMixIn(Aggregation.class, TypeNameMixin.class);
    mapper.registerModule(new Jdk8Module().configureAbsentsAsNulls(true));
    mapper.registerModule(commonSerializers());
    mapper.registerModule(jsonSerializers());
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.registerModule(FilterRegistry.registry().module(parser));
    return mapper;
}

5. JsonHelpers#customizeObjectMapper()

Project: keywhiz
Source File: JsonHelpers.java
View license
/**
   * Customized ObjectMapper for common settings.
   *
   * @return customized object mapper
   */
private static ObjectMapper customizeObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new LogbackModule());
    mapper.registerModule(new GuavaExtrasModule());
    mapper.registerModule(new FuzzyEnumModule());
    mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
    mapper.setSubtypeResolver(new DiscoverableSubtypeResolver());
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper;
}

6. ObjectMapperFactory#createObjectMapper()

Project: qpid-java
Source File: ObjectMapperFactory.java
View license
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;
}

7. JacksonTest#testMapTypeInfo()

Project: ode
Source File: JacksonTest.java
View license
@Test
public void testMapTypeInfo() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper(new SmileFactory());
    mapper.setSerializerFactory(TypeBeanSerializerFactory.instance);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    C c = new C();
    QName qname = new QName("uri", "localtest");
    c.map.put(qname, qname);
    mapper.writeValue(os, c);
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    ObjectMapper m2 = new ObjectMapper(new SmileFactory());
    m2.setSerializerFactory(TypeBeanSerializerFactory.instance);
    m2.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    C de = m2.readValue(is, C.class);
    assertEquals(c.map, de.map);
}

8. JacksonTest#testSmileFormat()

Project: ode
Source File: JacksonTest.java
View license
@Test
public void testSmileFormat() throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper(new SmileFactory());
    D d = new D();
    d.next = d;
    mapper.setSerializerFactory(TypeBeanSerializerFactory.instance);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mapper.writeValue(os, d);
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    ObjectMapper m2 = new ObjectMapper(new SmileFactory());
    m2.setSerializerFactory(TypeBeanSerializerFactory.instance);
    m2.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    D de = m2.readValue(is, D.class);
    assertEquals(D.class, de.next.getClass());
}

9. ConfigSupport#createMapper()

Project: redisson
Source File: ConfigSupport.java
View license
private ObjectMapper createMapper(JsonFactory mapping) {
    ObjectMapper mapper = new ObjectMapper(mapping);
    mapper.addMixIn(MasterSlaveServersConfig.class, MasterSlaveServersConfigMixIn.class);
    mapper.addMixIn(SingleServerConfig.class, SingleSeverConfigMixIn.class);
    mapper.addMixIn(Config.class, ConfigMixIn.class);
    mapper.addMixIn(Codec.class, ClassMixIn.class);
    mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
    FilterProvider filterProvider = new SimpleFilterProvider().addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
    mapper.setFilterProvider(filterProvider);
    mapper.setSerializationInclusion(Include.NON_NULL);
    return mapper;
}

10. EurekaJsonJacksonCodec#createObjectMapper()

Project: eureka
Source File: EurekaJsonJacksonCodec.java
View license
private ObjectMapper createObjectMapper(KeyFormatter keyFormatter, boolean compact, boolean wrapped) {
    ObjectMapper newMapper = new ObjectMapper();
    SimpleModule jsonModule = new SimpleModule();
    jsonModule.setSerializerModifier(EurekaJacksonJsonModifiers.createJsonSerializerModifier(keyFormatter, compact));
    newMapper.registerModule(jsonModule);
    newMapper.setSerializationInclusion(Include.NON_NULL);
    newMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapped);
    newMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
    newMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapped);
    newMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    newMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class);
    if (compact) {
        addMiniConfig(newMapper);
    } else {
        newMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
    }
    return newMapper;
}

11. MessagePackGeneratorTest#testWritePrimitiveObjectViaObjectMapper()

View license
@Test
public void testWritePrimitiveObjectViaObjectMapper() throws Exception {
    File tempFile = createTempFile();
    OutputStream out = new FileOutputStream(tempFile);
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    objectMapper.writeValue(out, 1);
    objectMapper.writeValue(out, "two");
    objectMapper.writeValue(out, 3.14);
    objectMapper.writeValue(out, Arrays.asList(4));
    objectMapper.writeValue(out, 5L);
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new FileInputStream(tempFile));
    assertEquals(1, unpacker.unpackInt());
    assertEquals("two", unpacker.unpackString());
    assertEquals(3.14, unpacker.unpackFloat(), 0.0001);
    assertEquals(1, unpacker.unpackArrayHeader());
    assertEquals(4, unpacker.unpackInt());
    assertEquals(5, unpacker.unpackLong());
}

12. JacksonConverterFactoryTest#setUp()

View license
@Before
public void setUp() {
    SimpleModule module = new SimpleModule();
    module.addSerializer(AnInterface.class, new AnInterfaceSerializer());
    module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(JacksonConverterFactory.create(mapper)).build();
    service = retrofit.create(Service.class);
}

13. ObjectMapperFactory#makeObjectMapper()

Project: petri
Source File: ObjectMapperFactory.java
View license
public static ObjectMapper makeObjectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule(MODULE_NAME, MODULE_VERSION);
    module.addDeserializer(DateTime.class, new TimeZoneAwareDateTimeDeserializer());
    module.addSerializer(DateTime.class, new DateTimeSerializer());
    objectMapper.registerModule(module);
    objectMapper.registerModule(new DefaultScalaModule());
    objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return objectMapper;
}

14. Serializers#lenient()

Project: proctor
Source File: Serializers.java
View license
public static ObjectMapper lenient() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    final SimpleModule module = new SimpleModule();
    final PlainNumericSerializer plainNumericSerializer = new PlainNumericSerializer();
    module.addSerializer(double.class, plainNumericSerializer);
    module.addSerializer(Double.class, plainNumericSerializer);
    mapper.registerModule(module);
    return mapper;
}

15. Serializers#strict()

Project: proctor
Source File: Serializers.java
View license
/**
     * Get an {@link ObjectMapper} configured to do things as we want
     */
@Nonnull
public static ObjectMapper strict() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    final SimpleModule module = new SimpleModule();
    final PlainNumericSerializer plainNumericSerializer = new PlainNumericSerializer();
    module.addSerializer(double.class, plainNumericSerializer);
    module.addSerializer(Double.class, plainNumericSerializer);
    mapper.registerModule(module);
    return mapper;
}

16. ObjectMapperFactory#create()

View license
private static ObjectMapper create(boolean indent) {
    ObjectMapper objectMapper = new ObjectMapper();
    // This will cause the objectmapper to not close the underlying output stream
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    objectMapper.registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL));
    SimpleModule module = new SimpleModule();
    module.addDeserializer(FieldJson.class, new FieldDeserializer());
    module.addSerializer(ExtendedMeter.class, new ExtendedMeterSerializer(TimeUnit.SECONDS));
    module.addDeserializer(ErrorMessage.class, new ErrorMessageDeserializer());
    module.addSerializer(BigDecimal.class, new ToStringSerializer());
    objectMapper.registerModule(module);
    if (indent) {
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    }
    return objectMapper;
}

17. SingularityRunnerBaseModule#providesYamlMapper()

View license
@Provides
@Singleton
@Named(YAML)
public ObjectMapper providesYamlMapper() {
    final YAMLFactory yamlFactory = new YAMLFactory();
    yamlFactory.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
    final ObjectMapper mapper = new ObjectMapper(yamlFactory);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new ProtobufModule());
    return mapper;
}

18. IssueTrackerConfiguration#jacksonObjectMapper()

View license
@Bean
ObjectMapper jacksonObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.registerModule(new ParameterNamesModule(Mode.PROPERTIES));
    mapper.registerModule(new SyntheticLambdaFactoryMethodIgnoringModule());
    return mapper;
}

19. GoogleTemplate#getMessageConverters()

View license
@Override
protected List<HttpMessageConverter<?>> getMessageConverters() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(FAIL_ON_EMPTY_BEANS, false);
    objectMapper.setSerializationInclusion(NON_NULL);
    jsonConverter.setObjectMapper(objectMapper);
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.addPartConverter(jsonConverter);
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(jsonConverter);
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(formHttpMessageConverter);
    messageConverters.add(new ResourceHttpMessageConverter());
    return messageConverters;
}

20. JacksonModule#createJacksonJsonProvider()

Project: wasabi
Source File: JacksonModule.java
View license
private JacksonJsonProvider createJacksonJsonProvider() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setSerializationInclusion(ALWAYS);
    mapper.registerModule(new SimpleModule() {

        {
            addSerializer(Double.class, new NaNSerializerDouble());
            addSerializer(Float.class, new NaNSerializerFloat());
            addDeserializer(Timestamp.class, new SQLTimestampDeserializer());
            addDeserializer(Experiment.State.class, new ExperimentStateDeserializer());
            addSerializer(new UpperCaseToStringSerializer<>(Experiment.State.class));
        }
    });
    SimpleDateFormat iso8601Formatter = new SimpleDateFormat(ISO8601_DATE_FORMAT);
    iso8601Formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    mapper.setDateFormat(iso8601Formatter);
    JacksonJsonProvider provider = new WasabiJacksonJsonProvider();
    provider.setMapper(mapper);
    return provider;
}

21. CliModule#generalMapper()

Project: keywhiz
Source File: CliModule.java
View license
@Provides
public ObjectMapper generalMapper() {
    /**
     * Customizes ObjectMapper for common settings.
     *
     * @param objectMapper to be customized
     * @return customized input factory
     */
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModules(new JavaTimeModule());
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper;
}

22. MessagePackGeneratorTest#testDisableFeatureAutoCloseTarget()

View license
@Test
public void testDisableFeatureAutoCloseTarget() throws Exception {
    File tempFile = createTempFile();
    OutputStream out = new FileOutputStream(tempFile);
    MessagePackFactory messagePackFactory = new MessagePackFactory();
    ObjectMapper objectMapper = new ObjectMapper(messagePackFactory);
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    List<Integer> integers = Arrays.asList(1);
    objectMapper.writeValue(out, integers);
    objectMapper.writeValue(out, integers);
    out.close();
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new FileInputStream(tempFile));
    assertEquals(1, unpacker.unpackArrayHeader());
    assertEquals(1, unpacker.unpackInt());
    assertEquals(1, unpacker.unpackArrayHeader());
    assertEquals(1, unpacker.unpackInt());
}

23. TestUtil#convertObjectToJsonBytes()

Project: expper
Source File: TestUtil.java
View license
/**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);
    return mapper.writeValueAsBytes(object);
}

24. ContentParserTest#testParseJson()

View license
@Test
public void testParseJson() throws Exception {
    ObjectMapper jsonObjectMapper = new ObjectMapper();
    jsonObjectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    jsonObjectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
    // not by default configured, but much easier for unit-testing Java embedded JSON Strings
    jsonObjectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    ContentParser contentParser = new ContentParser(jsonObjectMapper);
    String jsonObjectString = "{ /*comment*/ 'string' : 'foobar', 'int' : 1, 'boolean' : false, 'null' : null }";
    LinkedHashMap<String, Object> jsonObject = new LinkedHashMap<>();
    jsonObject.put("string", "foobar");
    jsonObject.put("int", new Integer(1));
    jsonObject.put("boolean", Boolean.FALSE);
    jsonObject.put("null", null);
    Assert.assertEquals(jsonObject, contentParser.parseJson(jsonObjectString));
    String jsonArrayString = "[" + jsonObjectString + "," + "# yaml comment\n" + jsonObjectString + "]";
    ArrayList<Object> jsonArray = new ArrayList<>(2);
    jsonArray.add(jsonObject);
    jsonArray.add(jsonObject);
    Assert.assertEquals(jsonArray, contentParser.parseJson(jsonArrayString));
}

25. DefaultTypingTest#roundtrip()

Project: immutables
Source File: DefaultTypingTest.java
View license
@Test
public void roundtrip() throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enableDefaultTyping();
    objectMapper.registerModule(new GuavaModule());
    ImmutableOuterObject outer = ImmutableOuterObject.builder().emptyObject(ImmutableEmptyObject.builder().build()).build();
    String serialized = objectMapper.writeValueAsString(outer);
    check(objectMapper.readValue(serialized, ImmutableOuterObject.class)).is(outer);
}

26. JsonMapper#createObjectMapper()

Project: isis
Source File: JsonMapper.java
View license
private static ObjectMapper createObjectMapper(PrettyPrinting prettyPrinting) {
    final ObjectMapper objectMapper = new ObjectMapper();
    final SimpleModule jsonModule = new SimpleModule("json", new Version(1, 0, 0, null, "org.apache", "isis"));
    jsonModule.addDeserializer(JsonRepresentation.class, new JsonRepresentationDeserializer());
    jsonModule.addSerializer(JsonRepresentation.class, new JsonRepresentationSerializer());
    objectMapper.registerModule(jsonModule);
    if (prettyPrinting == PrettyPrinting.ENABLE) {
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    }
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}

27. CatalogClient#getRestTemplate()

Project: microservice
Source File: CatalogClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

28. CustomerClient#getRestTemplate()

Project: microservice
Source File: CustomerClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

29. CatalogClient#getRestTemplate()

Project: microservice
Source File: CatalogClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

30. CustomerClient#getRestTemplate()

Project: microservice
Source File: CustomerClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

31. CatalogClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

32. CustomerClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

33. CatalogClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

34. CustomerClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

35. MessagePackGeneratorTest#testComplexTypeKeyWithV06Format()

View license
@Test
public void testComplexTypeKeyWithV06Format() throws IOException {
    HashMap<TinyPojo, Integer> map = new HashMap<TinyPojo, Integer>();
    TinyPojo pojo = new TinyPojo();
    pojo.t = "foo";
    map.put(pojo, 42);
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    objectMapper.setAnnotationIntrospector(new JsonArrayFormat());
    objectMapper.setSerializerFactory(new MessagePackSerializerFactory());
    byte[] bytes = objectMapper.writeValueAsBytes(map);
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(bytes);
    assertThat(unpacker.unpackMapHeader(), is(1));
    assertThat(unpacker.unpackArrayHeader(), is(1));
    assertThat(unpacker.unpackString(), is("foo"));
    assertThat(unpacker.unpackInt(), is(42));
}

36. ApplicationConfiguration#repositoryPopulator()

View license
/**
	 * Read JSON data from disk and insert those stores.
	 * 
	 * @return
	 */
@Bean
public AbstractRepositoryPopulatorFactoryBean repositoryPopulator() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(GeoJsonPoint.class, GeoJsonPointMixin.class);
    mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    Jackson2RepositoryPopulatorFactoryBean factoryBean = new Jackson2RepositoryPopulatorFactoryBean();
    factoryBean.setResources(new Resource[] { new ClassPathResource("starbucks-in-nyc.json") });
    factoryBean.setMapper(mapper);
    return factoryBean;
}

37. AnalyticsIncorporationComponentEventSerializationTest#testMixinNoCopy()

View license
@Test
public void testMixinNoCopy() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    mapper.addMixInAnnotations(Object.class, PortletRenderExecutionEventFilterMixIn.class);
    final FilterProvider filterProvider = new SimpleFilterProvider().addFilter(PortletRenderExecutionEventFilterMixIn.FILTER_NAME, SimpleBeanPropertyFilter.filterOutAllExcept("fname", "executionTimeNano", "parameters"));
    final ObjectWriter portletEventWriter = mapper.writer(filterProvider);
    final String result = portletEventWriter.writeValueAsString(createEvent());
    assertEquals("{\"@c\":\".PortletRenderExecutionEvent\",\"fname\":\"fname1\",\"executionTimeNano\":123450000,\"parameters\":{}}", result);
}

38. BsonGeneratorTest#generateAndParse()

Project: bson4jackson
Source File: BsonGeneratorTest.java
View license
private BSONObject generateAndParse(Map<String, Object> data, BsonGenerator.Feature... featuresToEnable) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    if (featuresToEnable != null) {
        for (BsonGenerator.Feature fe : featuresToEnable) {
            bsonFactory.enable(fe);
        }
    }
    ObjectMapper om = new ObjectMapper(bsonFactory);
    om.registerModule(new BsonModule());
    om.writeValue(baos, data);
    byte[] r = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(r);
    BSONDecoder decoder = new BasicBSONDecoder();
    return decoder.readObject(bais);
}

39. BsonParserTest#parseBig()

Project: bson4jackson
Source File: BsonParserTest.java
View license
@Test
public void parseBig() throws Exception {
    BSONObject o = new BasicBSONObject();
    o.put("Double", 5.0);
    o.put("Int32", 1234);
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    ObjectMapper mapper = new ObjectMapper(new BsonFactory());
    mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    mapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, true);
    Map<?, ?> data = mapper.readValue(bais, Map.class);
    assertEquals(BigDecimal.class, data.get("Double").getClass());
    assertEquals(BigInteger.class, data.get("Int32").getClass());
}

40. BsonSerializersTest#generateAndParse()

View license
private static Object generateAndParse(Object data) throws Exception {
    Map<String, Object> m = new LinkedHashMap<String, Object>();
    m.put("data", data);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectMapper om = new ObjectMapper(new BsonFactory());
    om.registerModule(new BsonModule());
    om.writeValue(baos, m);
    byte[] r = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(r);
    BSONDecoder decoder = new BasicBSONDecoder();
    BSONObject bo = decoder.readObject(bais);
    return bo.get("data");
}

41. RestSwaggerReaderApiDocsOverrideTest#testReaderRead()

View license
@Test
public void testReaderRead() throws Exception {
    BeanConfig config = new BeanConfig();
    config.setHost("localhost:8080");
    config.setSchemes(new String[] { "http" });
    config.setBasePath("/api");
    RestSwaggerReader reader = new RestSwaggerReader();
    Swagger swagger = reader.read(context.getRestDefinitions(), null, config, context.getName(), new DefaultClassResolver());
    assertNotNull(swagger);
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = mapper.writeValueAsString(swagger);
    log.info(json);
    assertFalse(json.contains("\"/hello/bye\""));
    assertFalse(json.contains("\"summary\" : \"To update the greeting message\""));
    assertTrue(json.contains("\"/hello/bye/{name}\""));
    assertFalse(json.contains("\"/hello/hi/{name}\""));
    context.stop();
}

42. ProcessingResult#serializeJson()

Project: carrot2
Source File: ProcessingResult.java
View license
/**
     * Serializes this processing result as JSON to the provided <code>writer</code>.
     * Documents, clusters and other attributes can be included or skipped in the output
     * as requested.
     * 
     * @param writer the writer to serialize this processing result to. The writer will
     *            <strong>not</strong> be closed.
     * @param callback JavaScript function name in which to wrap the JSON response or
     *            <code>null</code>.
     * @param indent if <code>true</code>, the output JSON will be pretty-printed
     * @param saveDocuments if <code>false</code>, documents will not be serialized.
     * @param saveClusters if <code>false</code>, clusters will not be serialized
     * @param saveOtherAttributes if <code>false</code>, other attributes will not be
     *            serialized
     * @throws IOException in case of any problems with serialization
     */
public void serializeJson(Writer writer, String callback, boolean indent, boolean saveDocuments, boolean saveClusters, boolean saveOtherAttributes) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    if (StringUtils.isNotBlank(callback)) {
        writer.write(callback + "(");
    }
    final Map<String, Object> attrs = prepareAttributesForSerialization(saveDocuments, saveClusters, saveOtherAttributes);
    mapper.writeValue(writer, attrs);
    if (StringUtils.isNotBlank(callback)) {
        writer.write(");");
    }
}

43. JsonReferenceSerializationTest#createMapper()

View license
private ObjectMapper createMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE).withIsGetterVisibility(JsonAutoDetect.Visibility.NONE).withSetterVisibility(JsonAutoDetect.Visibility.NONE).withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    mapper.registerModule(new ActorReferenceModule(factory));
    return mapper;
}

44. PluginDisableIT#test()

Project: pinpoint
Source File: PluginDisableIT.java
View license
@Test
public void test() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", "jackson");
    mapper.writeValueAsString(map);
    mapper.writeValueAsBytes(map);
    ObjectWriter writer = mapper.writer();
    writer.writeValueAsString(map);
    writer.writeValueAsBytes(map);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    verifier.verifyTraceCount(0);
}

45. MetaDataServlet#doGetWithSubjectAndActor()

Project: qpid-java
Source File: MetaDataServlet.java
View license
@Override
protected void doGetWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    Map<String, Map> classToDataMap = new TreeMap<>();
    for (Class<? extends ConfiguredObject> clazz : _instance.getSupportedCategories()) {
        classToDataMap.put(clazz.getSimpleName(), processCategory(clazz));
    }
    final OutputStream stream = getOutputStream(request, response);
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.writeValue(stream, classToDataMap);
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
}

46. AnalyticsIncorporationComponentEventSerializationTest#testMixinWithCopy()

View license
/**
     * Fails as actual output is:
     * {"@c":".PortletRenderExecutionEvent","timestamp":1371671516798,"serverId":"example.com","eventSessionId":"1234567890123_system_AAAAAAAAAAA","userName":"system","fname":"fname1","executionTimeNano":123450000,"parameters":{},"targeted":false,"usedPortalCache":false}
     */
@Ignore
@Test
public void testMixinWithCopy() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    //Clone from "shared" ObjectMapper
    mapper = mapper.copy();
    mapper.addMixInAnnotations(Object.class, PortletRenderExecutionEventFilterMixIn.class);
    final FilterProvider filterProvider = new SimpleFilterProvider().addFilter(PortletRenderExecutionEventFilterMixIn.FILTER_NAME, SimpleBeanPropertyFilter.filterOutAllExcept("fname", "executionTimeNano", "parameters"));
    final ObjectWriter portletEventWriter = mapper.writer(filterProvider);
    final String result = portletEventWriter.writeValueAsString(createEvent());
    assertEquals("{\"@c\":\".PortletRenderExecutionEvent\",\"fname\":\"fname1\",\"executionTimeNano\":123450000,\"parameters\":{}}", result);
}

47. JsonTest#main()

Project: weixin
Source File: JsonTest.java
View license
public static void main(String[] args) throws Exception {
    List<DeviceIdentifier> deviceIdentifierList = new ArrayList<DeviceIdentifier>();
    DeviceIdentifier dd = new DeviceIdentifier();
    dd.setDevice_id(10100);
    dd.setUuid("FDA50693-A4E2-4FB1-AFCF-C6EB07647825");
    dd.setMajor(10001);
    dd.setMinor(10002);
    deviceIdentifierList.add(dd);
    deviceIdentifierList.add(dd);
    System.out.println(JsonUtils.toJson(deviceIdentifierList));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
    String json = "{\"city\":\"??TÈ\\nè\",\"province\":\"?Ñ??l_\"}";
    System.out.println(mapper.readValue(json, Map.class));
    System.out.println(JsonUtils.parse(json, Map.class));
}

48. JacksonIssue429Test#testStackTraceElementWithCustom()

View license
@Test
public void testStackTraceElementWithCustom() throws Exception {
    // first, via bean that contains StackTraceElement
    final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class);
    Assert.assertNotNull(bean);
    Assert.assertNotNull(bean.location);
    Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber());
    // and then directly, iff registered
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Jackson429StackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement elem = mapper.readValue(aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"), StackTraceElement.class);
    Assert.assertNotNull(elem);
    Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber());
}

49. SegmentIdentifierTest#testSerde()

Project: druid
Source File: SegmentIdentifierTest.java
View license
@Test
public void testSerde() throws Exception {
    final ObjectMapper objectMapper = new DefaultObjectMapper();
    objectMapper.registerSubtypes(NumberedShardSpec.class);
    final SegmentIdentifier id2 = objectMapper.readValue(objectMapper.writeValueAsBytes(ID_1), SegmentIdentifier.class);
    Assert.assertEquals(ID_1, id2);
    Assert.assertEquals(DATA_SOURCE, id2.getDataSource());
    Assert.assertEquals(INTERVAL, id2.getInterval());
    Assert.assertEquals(VERSION, id2.getVersion());
    Assert.assertEquals(SHARD_SPEC_1.getPartitionNum(), id2.getShardSpec().getPartitionNum());
    Assert.assertEquals(SHARD_SPEC_1.getPartitions(), ((NumberedShardSpec) id2.getShardSpec()).getPartitions());
}

50. JavaScriptExtractionFnTest#testSerde()

View license
@Test
public void testSerde() throws Exception {
    final ObjectMapper objectMapper = new DefaultObjectMapper();
    objectMapper.setInjectableValues(new InjectableValues.Std().addValue(JavaScriptConfig.class, JavaScriptConfig.getDefault()));
    final String json = "{ \"type\" : \"javascript\", \"function\" : \"function(str) { return str.substring(0,3); }\" }";
    JavaScriptExtractionFn extractionFn = (JavaScriptExtractionFn) objectMapper.readValue(json, ExtractionFn.class);
    Assert.assertEquals("function(str) { return str.substring(0,3); }", extractionFn.getFunction());
    // round trip
    Assert.assertEquals(extractionFn, objectMapper.readValue(objectMapper.writeValueAsBytes(extractionFn), ExtractionFn.class));
}

51. HadoopDruidConverterConfigTest#simpleSerDe()

View license
@Test
public void simpleSerDe() throws IOException {
    final HadoopDruidConverterConfig config = new HadoopDruidConverterConfig("datasource", Interval.parse("2000/2010"), new IndexSpec(), ImmutableList.<DataSegment>of(), true, URI.create("file:/dev/null"), ImmutableMap.<String, String>of(), "HIGH", temporaryFolder.newFolder().getAbsolutePath());
    final ObjectMapper mapper = new DefaultObjectMapper();
    mapper.registerSubtypes(HadoopDruidConverterConfig.class);
    final byte[] value = mapper.writeValueAsBytes(config);
    final HadoopDruidConverterConfig config2 = mapper.readValue(value, HadoopDruidConverterConfig.class);
    Assert.assertEquals(mapper.writeValueAsString(config), mapper.writeValueAsString(config2));
}

52. RedisKeyValueStateProvider#getStateConfig()

View license
StateConfig getStateConfig(Map stormConf) throws Exception {
    StateConfig stateConfig = null;
    String providerConfig = null;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    if (stormConf.containsKey(org.apache.storm.Config.TOPOLOGY_STATE_PROVIDER_CONFIG)) {
        providerConfig = (String) stormConf.get(org.apache.storm.Config.TOPOLOGY_STATE_PROVIDER_CONFIG);
        stateConfig = mapper.readValue(providerConfig, StateConfig.class);
    } else {
        stateConfig = new StateConfig();
    }
    return stateConfig;
}

53. DropwizardModule#provideObjectMapper()

Project: airpal
Source File: DropwizardModule.java
View license
@Singleton
@Provides
protected ObjectMapper provideObjectMapper() {
    ObjectMapper mapper = environment.getObjectMapper();
    mapper.registerSubtypes(new NamedType(CSVPersistentOutput.class, "csv"), new NamedType(HiveTablePersistentOutput.class, "hive"));
    Rosetta.getMapper().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    Rosetta.getMapper().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
    return mapper;
}

54. Metadata#writeFile()

Project: drill
Source File: Metadata.java
View license
/**
   * Serialize parquet metadata to json and write to a file
   *
   * @param parquetTableMetadata
   * @param p
   * @throws IOException
   */
private void writeFile(ParquetTableMetadata_v2 parquetTableMetadata, Path p) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ColumnMetadata_v2.class, new ColumnMetadata_v2.Serializer());
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
    os.flush();
    os.close();
}

55. PipelineOptionsTest#testCloneAs()

View license
@Test
public void testCloneAs() throws IOException {
    DerivedTestOptions options = PipelineOptionsFactory.create().as(DerivedTestOptions.class);
    options.setBaseValue(Lists.<Boolean>newArrayList());
    options.setIgnoredValue(Sets.<String>newHashSet());
    options.getIgnoredValue().add("ignoredString");
    options.setDerivedValue(0);
    BaseTestOptions clonedOptions = options.cloneAs(BaseTestOptions.class);
    assertNotSame(clonedOptions, options);
    assertNotSame(clonedOptions.getBaseValue(), options.getBaseValue());
    clonedOptions.getBaseValue().add(true);
    assertFalse(clonedOptions.getBaseValue().isEmpty());
    assertTrue(options.getBaseValue().isEmpty());
    assertNull(clonedOptions.getIgnoredValue());
    ObjectMapper mapper = new ObjectMapper();
    mapper.readValue(mapper.writeValueAsBytes(clonedOptions), PipelineOptions.class);
}

56. ArchivesJsonTest#test()

View license
@Test
public void test() throws Exception {
    final Archives archives = new Archives();
    archives.addItem().name("hello.jar").path("one/two/hello.jar");
    final ObjectMapper mapper = new ObjectMapper();
    JaxbAnnotationModule module = new JaxbAnnotationModule();
    // configure as necessary
    mapper.registerModule(module);
    mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, archives);
}

57. ElasticsearchSchemaFactory#create()

View license
@Override
public Schema create(SchemaPlus parentSchema, String name, Map<String, Object> operand) {
    final Map map = (Map) operand;
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    try {
        final Map<String, Integer> coordinates = mapper.readValue((String) map.get("coordinates"), new TypeReference<Map<String, Integer>>() {
        });
        final Map<String, String> userConfig = mapper.readValue((String) map.get("userConfig"), new TypeReference<Map<String, String>>() {
        });
        final String index = (String) map.get("index");
        return new ElasticsearchSchema(coordinates, userConfig, index);
    } catch (IOException e) {
        throw new RuntimeException("Cannot parse values from json", e);
    }
}

58. BsonDeserializersTest#generateAndParse()

View license
private static <T> T generateAndParse(Object o, Class<T> cls) throws Exception {
    BSONObject bo = new BasicBSONObject();
    //that's why all properties of classes in TC must be named 'obj'
    bo.put("obj", o);
    BSONEncoder encoder = new BasicBSONEncoder();
    byte[] barr = encoder.encode(bo);
    ByteArrayInputStream bais = new ByteArrayInputStream(barr);
    ObjectMapper om = new ObjectMapper(new BsonFactory());
    om.registerModule(new BsonModule());
    T r = om.readValue(bais, cls);
    return r;
}

59. BsonParserTest#parseRootObjectAsArray()

Project: bson4jackson
Source File: BsonParserTest.java
View license
/**
	 * Tests if a root object is not accidentally parsed as an array
	 * @throws Exception if something went wrong
	 */
@Test(expected = JsonMappingException.class)
public void parseRootObjectAsArray() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    BsonGenerator generator = bsonFactory.createGenerator(out);
    generator.writeStartObject();
    generator.writeStringField("myField", "myValue");
    generator.writeEndObject();
    generator.close();
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    ObjectMapper mapper = new ObjectMapper(bsonFactory);
    bsonFactory.setCodec(mapper);
    mapper.readValue(is, String[].class);
}

60. BsonParserTest#parseBsonObject()

Project: bson4jackson
Source File: BsonParserTest.java
View license
private <T> T parseBsonObject(BSONObject o, Class<T> cls, Module... modules) throws IOException {
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    ObjectMapper mapper = new ObjectMapper(fac);
    if (modules != null) {
        for (Module mod : modules) {
            mapper.registerModule(mod);
        }
    }
    fac.setCodec(mapper);
    return mapper.readValue(bais, cls);
}

61. FormBuilderServiceImpl#convertJsonToDataWrapper()

View license
/**
     * When using Thymeleaf, we need to convert the JSON string back to
     * a DataWrapper object because Thymeleaf escapes JSON strings.
     * Thymeleaf uses it's own object de-serializer
     * see: https://github.com/thymeleaf/thymeleaf/issues/84
     * see: http://forum.thymeleaf.org/Spring-Javascript-and-escaped-JSON-td4024739.html
     * @param json
     * @return DataWrapper
     * @throws IOException
     */
protected DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

62. RuleFieldExtractionUtility#convertJsonToDataWrapper()

View license
/**
     * Takes a JSON string that came from the frontend form submission and deserializes it into its {@link DataWrapper} dto
     * representation so that it can be converted to an MVEL expression
     * @param json
     * @return
     */
public DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    if (json == null || "[]".equals(json)) {
        return null;
    }
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

63. FormBuilderServiceImpl#convertJsonToDataWrapper()

View license
/**
     * When using Thymeleaf, we need to convert the JSON string back to
     * a DataWrapper object because Thymeleaf escapes JSON strings.
     * Thymeleaf uses it's own object de-serializer
     * see: https://github.com/thymeleaf/thymeleaf/issues/84
     * see: http://forum.thymeleaf.org/Spring-Javascript-and-escaped-JSON-td4024739.html
     * @param json
     * @return DataWrapper
     * @throws IOException
     */
protected DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

64. RuleFieldExtractionUtility#convertJsonToDataWrapper()

View license
/**
     * Takes a JSON string that came from the frontend form submission and deserializes it into its {@link DataWrapper} dto
     * representation so that it can be converted to an MVEL expression
     * @param json
     * @return
     */
public DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    if (json == null || "[]".equals(json)) {
        return null;
    }
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

65. VirtualMachinesImpl#capture()

View license
@Override
public String capture(String groupName, String name, String containerName, boolean overwriteVhd) throws CloudException, IOException, InterruptedException {
    VirtualMachineCaptureParametersInner parameters = new VirtualMachineCaptureParametersInner();
    parameters.withDestinationContainerName(containerName);
    parameters.withOverwriteVhds(overwriteVhd);
    ServiceResponse<VirtualMachineCaptureResultInner> captureResult = this.innerCollection.capture(groupName, name, parameters);
    ObjectMapper mapper = new ObjectMapper();
    //Object to JSON string
    return mapper.writeValueAsString(captureResult.getBody().output());
}

66. MessagePackGeneratorTest#testComplexTypeKey()

View license
@Test
public void testComplexTypeKey() throws IOException {
    HashMap<TinyPojo, Integer> map = new HashMap<TinyPojo, Integer>();
    TinyPojo pojo = new TinyPojo();
    pojo.t = "foo";
    map.put(pojo, 42);
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    objectMapper.setSerializerFactory(new MessagePackSerializerFactory());
    byte[] bytes = objectMapper.writeValueAsBytes(map);
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(bytes);
    assertThat(unpacker.unpackMapHeader(), is(1));
    assertThat(unpacker.unpackMapHeader(), is(1));
    assertThat(unpacker.unpackString(), is("t"));
    assertThat(unpacker.unpackString(), is("foo"));
    assertThat(unpacker.unpackInt(), is(42));
}

67. MessagePackGeneratorTest#testDisableStr8Support()

View license
@Test
public void testDisableStr8Support() throws Exception {
    String str8LengthString = new String(new char[32]).replace("\0", "a");
    // Test that produced value having str8 format
    ObjectMapper defaultMapper = new ObjectMapper(new MessagePackFactory());
    byte[] resultWithStr8Format = defaultMapper.writeValueAsBytes(str8LengthString);
    assertEquals(resultWithStr8Format[0], MessagePack.Code.STR8);
    // Test that produced value does not having str8 format
    MessagePack.PackerConfig config = new MessagePack.PackerConfig().withStr8FormatSupport(false);
    ObjectMapper mapperWithConfig = new ObjectMapper(new MessagePackFactory(config));
    byte[] resultWithoutStr8Format = mapperWithConfig.writeValueAsBytes(str8LengthString);
    assertNotEquals(resultWithoutStr8Format[0], MessagePack.Code.STR8);
}

68. MessagePackDataformatForPojoTest#testSerializationWithoutSchema()

View license
@Test
public void testSerializationWithoutSchema() throws IOException {
    // to not affect shared objectMapper state
    ObjectMapper objectMapper = new ObjectMapper(factory);
    objectMapper.setAnnotationIntrospector(new JsonArrayFormat());
    byte[] bytes = objectMapper.writeValueAsBytes(complexPojo);
    String scheme = new String(bytes, Charset.forName("UTF-8"));
    // validating schema doesn't contains keys, that's just array
    assertThat(scheme, not(containsString("name")));
    ComplexPojo value = objectMapper.readValue(bytes, ComplexPojo.class);
    assertEquals("komamitsu", value.name);
    assertEquals(20, value.age);
    assertArrayEquals(complexPojo.values.toArray(), value.values.toArray());
    assertEquals(complexPojo.grades.get("math"), value.grades.get("math"));
}

69. StackTraceElementMixInTest#testFromJsonWithLog4jModule()

View license
@Test
public void testFromJsonWithLog4jModule() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final boolean encodeThreadContextAsList = false;
    final SimpleModule module = new Log4jJsonModule(encodeThreadContextAsList);
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123);
    final String s = this.aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}");
    final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}

70. JacksonIssue429MyNamesTest#testStackTraceElementWithCustom()

View license
@Test
public void testStackTraceElementWithCustom() throws Exception {
    // first, via bean that contains StackTraceElement
    final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}}"), StackTraceBean.class);
    Assert.assertNotNull(bean);
    Assert.assertNotNull(bean.location);
    Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber());
    // and then directly, iff registered
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new MyStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement elem = mapper.readValue(aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}"), StackTraceElement.class);
    Assert.assertNotNull(elem);
    Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber());
}

71. MetadataVersionRefresher#refresh()

Project: kylin
Source File: MetadataVersionRefresher.java
View license
public void refresh() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    List<String> all = Lists.newArrayList();
    collectFiles(this.store, "/", all);
    for (String path : all) {
        if (path.endsWith(MetadataConstants.FILE_SURFIX) && !(path.startsWith(ResourceStore.DICT_RESOURCE_ROOT) || path.startsWith(ResourceStore.SNAPSHOT_RESOURCE_ROOT))) {
            logger.info("Updating metadata version of path {}", path);
            ObjectNode objectNode = (ObjectNode) mapper.readTree(this.store.getResource(path).inputStream);
            objectNode.put("version", version);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mapper.writeValue(baos, objectNode);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            this.store.putResource(path, bais, System.currentTimeMillis());
        }
    }
}

72. MediaIT#shouldRoundTripQuotedPrintableFieldWithNoFieldVisibility()

Project: jsonschema2pojo
Source File: MediaIT.java
View license
@Test
public void shouldRoundTripQuotedPrintableFieldWithNoFieldVisibility() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.NONE));
    roundTripAssertions(new ObjectMapper(), "anyBinaryEncoding", "\"=E3=82=A8=E3=83=B3=E3=82=B3=E3=83=BC=E3=83=89=E3=81=95=E3=82=8C=E3=81=9F=E6=96=87=E5=AD=97=E5=88=97\" is Japanese for \"encoded string\"", "\"???????????\" is Japanese for \"encoded string\"".getBytes("UTF-8"));
}

73. PipelineOptionsTest#testCloneAs()

View license
@Test
public void testCloneAs() throws IOException {
    DerivedTestOptions options = PipelineOptionsFactory.create().as(DerivedTestOptions.class);
    options.setBaseValue(Lists.<Boolean>newArrayList());
    options.setIgnoredValue(Sets.<String>newHashSet());
    options.getIgnoredValue().add("ignoredString");
    options.setDerivedValue(0);
    BaseTestOptions clonedOptions = options.cloneAs(BaseTestOptions.class);
    assertNotSame(clonedOptions, options);
    assertNotSame(clonedOptions.getBaseValue(), options.getBaseValue());
    clonedOptions.getBaseValue().add(true);
    assertFalse(clonedOptions.getBaseValue().isEmpty());
    assertTrue(options.getBaseValue().isEmpty());
    assertNull(clonedOptions.getIgnoredValue());
    ObjectMapper mapper = new ObjectMapper();
    mapper.readValue(mapper.writeValueAsBytes(clonedOptions), PipelineOptions.class);
}

74. PrimaryModule#internalMapper()

Project: heroic
Source File: PrimaryModule.java
View license
@Provides
@Named(HeroicCore.APPLICATION_JSON_INTERNAL)
@PrimaryScope
ObjectMapper internalMapper(QueryParser parser, AggregationRegistry aggregation) {
    final ObjectMapper m = HeroicMappers.json(parser);
    /* configuration determined at runtime, unsuitable for testing */
    m.registerModule(aggregation.module());
    return m;
}

75. JsonTest#testRoundTrip()

Project: GeoIP2-java
Source File: JsonTest.java
View license
protected <T extends AbstractResponse> void testRoundTrip(Class<T> cls, String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, false);
    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    T response = mapper.reader(cls).with(inject).readValue(json);
    JsonNode expectedNode = mapper.readValue(json, JsonNode.class);
    JsonNode actualNode = mapper.readValue(response.toJson(), JsonNode.class);
    assertEquals(expectedNode, actualNode);
}

76. JSONTest#patch()

Project: syncope
Source File: JSONTest.java
View license
@Test
public void patch() throws IOException {
    UserPatch patch = new UserPatch();
    patch.setKey(UUID.randomUUID().toString());
    patch.setUsername(new StringReplacePatchItem.Builder().value("newusername").build());
    assertNotNull(patch.getUsername().getValue());
    patch.setPassword(new PasswordPatch.Builder().onSyncope(false).resource("ext1").resource("ext2").value("newpassword").build());
    assertNotNull(patch.getPassword().getValue());
    patch.getRoles().add(new StringPatchItem.Builder().operation(PatchOperation.DELETE).value("role").build());
    ObjectMapper mapper = new ObjectMapper();
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, patch);
    UserPatch actual = mapper.readValue(writer.toString(), UserPatch.class);
    assertEquals(patch, actual);
}

77. JSONTest#reportletConfImplementations()

Project: syncope
Source File: JSONTest.java
View license
@Test
public void reportletConfImplementations() throws IOException {
    ReportTO report = new ReportTO();
    report.setName("testReportForCreate");
    report.getReportletConfs().add(new UserReportletConf("first"));
    report.getReportletConfs().add(new UserReportletConf("second"));
    ObjectMapper mapper = new ObjectMapper();
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, report);
    ReportTO actual = mapper.readValue(writer.toString(), ReportTO.class);
    assertEquals(report, actual);
}

78. JSONTest#map()

Project: syncope
Source File: JSONTest.java
View license
@Test
public void map() throws IOException {
    WorkflowFormPropertyTO prop = new WorkflowFormPropertyTO();
    prop.getEnumValues().put("key1", "value1");
    prop.getEnumValues().put("key2", "value2");
    ObjectMapper mapper = new ObjectMapper();
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, prop);
    WorkflowFormPropertyTO unserializedProp = mapper.readValue(writer.toString(), WorkflowFormPropertyTO.class);
    assertEquals(prop, unserializedProp);
}

79. TestJackson#test()

Project: suro
Source File: TestJackson.java
View license
@Test
public void test() throws IOException {
    String spec = "{\"a\":\"aaa\", \"b\":\"bbb\"}";
    ObjectMapper mapper = new DefaultObjectMapper();
    final Map<String, Object> injectables = Maps.newHashMap();
    injectables.put("test", "test");
    injectables.put("b", "binjected");
    mapper.setInjectableValues(new InjectableValues() {

        @Override
        public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) {
            return injectables.get(valueId);
        }
    });
    TestClass test = mapper.readValue(spec, new TypeReference<TestClass>() {
    });
    assertEquals(test.getTest(), "test");
    assertEquals(test.getB(), "bbb");
}

80. DateFormatTest#deserializeLongToDate()

Project: streamflow
Source File: DateFormatTest.java
View license
@Test
public void deserializeLongToDate() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule deserializerModule = new SimpleModule("DeserializerModule", new Version(1, 0, 0, null));
    deserializerModule.addDeserializer(Date.class, new DateDeserializer());
    mapper.registerModule(deserializerModule);
    Date testDate = new Date();
    assertEquals("Deserialized time should match Date.getTime()", testDate, mapper.convertValue(testDate.getTime(), Date.class));
}

81. SimilarPlacesDeserializer#deserialize()

View license
@Override
public SimilarPlacesResponse deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new TwitterModule());
    jp.setCodec(mapper);
    JsonNode node = jp.readValueAs(JsonNode.class);
    JsonNode resultNode = node.get("result");
    String token = resultNode.get("token").textValue();
    JsonNode placesNode = resultNode.get("places");
    @SuppressWarnings("unchecked") List<Place> places = (List<Place>) mapper.reader(new TypeReference<List<Place>>() {
    }).readValue(placesNode);
    return new SimilarPlacesResponse(places, token);
}

82. DatasetDao#insertDataset()

Project: WhereHows
Source File: DatasetDao.java
View license
public static void insertDataset(JsonNode dataset) throws Exception {
    ObjectMapper om = new ObjectMapper();
    om.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    DatasetRecord record = om.convertValue(dataset, DatasetRecord.class);
    if (record.getRefDatasetUrn() != null) {
        Map<String, Object> refDataset = getDatasetByUrn(record.getRefDatasetUrn());
        // Find ref dataset id
        if (refDataset != null) {
            record.setRefDatasetId(((Long) refDataset.get("id")).intValue());
        }
    }
    // Find layout id
    if (record.getSamplePartitionFullPath() != null) {
        PartitionPatternMatcher ppm = new PartitionPatternMatcher(PartitionLayoutDao.getPartitionLayouts());
        record.setPartitionLayoutPatternId(ppm.analyze(record.getSamplePartitionFullPath()));
    }
    DatabaseWriter dw = new DatabaseWriter(JdbcUtil.wherehowsJdbcTemplate, "dict_dataset");
    dw.append(record);
    dw.close();
}

83. ANXAdapterTest#testAccountInfoAdapter()

Project: XChange
Source File: ANXAdapterTest.java
View license
@Test
public void testAccountInfoAdapter() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = ANXAdapterTest.class.getResourceAsStream("/v2/account/example-accountinfo-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ANXAccountInfo anxAccountInfo = mapper.readValue(is, ANXAccountInfo.class);
    AccountInfo accountInfo = ANXAdapters.adaptAccountInfo(anxAccountInfo);
    assertThat(accountInfo.getUsername()).isEqualTo("[email protected]");
    assertThat(accountInfo.getWallet().getBalance(Currency.DOGE).getTotal()).isEqualTo(new BigDecimal("9999781.09457936"));
    assertThat(accountInfo.getWallet().getBalance(Currency.DOGE).getAvailable()).isEqualTo(new BigDecimal("9914833.52608521"));
    assertThat(accountInfo.getWallet().getBalance(Currency.DOGE).getFrozen()).isEqualTo(new BigDecimal("84947.56849415"));
}

84. ANXAdapterTest#testOrderAdapterWithDepth()

Project: XChange
Source File: ANXAdapterTest.java
View license
@Test
public void testOrderAdapterWithDepth() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = ANXAdapterTest.class.getResourceAsStream("/v2/marketdata/example-fulldepth-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ANXDepth anxDepth = mapper.readValue(is, ANXDepth.class);
    List<LimitOrder> asks = ANXAdapters.adaptOrders(anxDepth.getAsks(), "BTC", "USD", "ask", "id_567");
    Assert.assertEquals(3, asks.size());
    // Verify all fields filled
    assertThat(asks.get(0).getType()).isEqualTo(OrderType.ASK);
    Assert.assertEquals(new BigDecimal("16.00000000"), asks.get(0).getTradableAmount());
    Assert.assertEquals(new BigDecimal("3260.40000"), asks.get(0).getLimitPrice());
    Assert.assertEquals("BTC", asks.get(0).getCurrencyPair().base.getCurrencyCode());
    Assert.assertEquals("USD", asks.get(0).getCurrencyPair().counter.getCurrencyCode());
}

85. ANXAdapterTest#testWalletAdapter()

Project: XChange
Source File: ANXAdapterTest.java
View license
@Test
public void testWalletAdapter() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = ANXAdapterTest.class.getResourceAsStream("/v2/account/example-accountinfo-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ANXAccountInfo anxAccountInfo = mapper.readValue(is, ANXAccountInfo.class);
    // in Wallet, only wallets from ANXAccountInfo.getBalancesList that contained data are NOT null.
    Collection<Balance> balances = ANXAdapters.adaptWallet(anxAccountInfo.getWallets()).getBalances().values();
    Assert.assertEquals(21, balances.size());
    Assert.assertTrue(balances.contains(new Balance(Currency.CAD, new BigDecimal("100000.00000"), new BigDecimal("100000.00000"))));
    Assert.assertTrue(balances.contains(new Balance(Currency.BTC, new BigDecimal("100000.01988000"), new BigDecimal("100000.01988000"))));
    Assert.assertTrue(balances.contains(new Balance(Currency.DOGE, new BigDecimal("9999781.09457936"), new BigDecimal("9914833.52608521"))));
}

86. ANXAdapterTest#testTickerAdapter()

Project: XChange
Source File: ANXAdapterTest.java
View license
@Test
public void testTickerAdapter() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = ANXAdapterTest.class.getResourceAsStream("/v2/marketdata/example-ticker-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ANXTicker anxTicker = mapper.readValue(is, ANXTicker.class);
    Ticker ticker = ANXAdapters.adaptTicker(anxTicker);
    Assert.assertEquals(new BigDecimal("725.38123"), ticker.getLast());
    Assert.assertEquals(new BigDecimal("725.38123"), ticker.getHigh());
    Assert.assertEquals(new BigDecimal("380.00000"), ticker.getLow());
    Assert.assertEquals(new BigDecimal("7.00000000"), ticker.getVolume());
    Assert.assertEquals(new BigDecimal("725.38123"), ticker.getLast());
    Assert.assertEquals(new BigDecimal("38.85148"), ticker.getBid());
    Assert.assertEquals(new BigDecimal("897.25596"), ticker.getAsk());
    Assert.assertEquals(new Date(1393388594814L), ticker.getTimestamp());
}

87. WalletJSONTest#testCurrencies()

Project: XChange
Source File: WalletJSONTest.java
View license
@Test
public void testCurrencies() throws Exception {
    // Read in the JSON from the example resources
    InputStream is = WalletJSONTest.class.getResourceAsStream("/v2/account/example-accountinfo-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ANXAccountInfo anxAccountInfo = mapper.readValue(is, ANXAccountInfo.class);
    Map<String, ANXWallet> wallets = anxAccountInfo.getWallets();
    Exchange exchange = ExchangeFactory.INSTANCE.createExchange(ANXExchange.class.getName());
    ANXMetaData anxMetaData = ((ANXExchange) exchange).getANXMetaData();
    Set<String> metadataCurrencyStrings = new TreeSet<String>();
    for (Currency currency : anxMetaData.getCurrencies().keySet()) metadataCurrencyStrings.add(currency.toString());
    assertEquals(wallets.keySet(), metadataCurrencyStrings);
}

88. OpenOrdersJSONTest#testUnmarshal()

Project: XChange
Source File: OpenOrdersJSONTest.java
View license
@Test
public void testUnmarshal() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = OpenOrdersJSONTest.class.getResourceAsStream("/v2/trade/example-openorders-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ANXOpenOrder[] anxOpenOrders = mapper.readValue(is, ANXOpenOrder[].class);
    // System.out.println(new Date(anxOpenOrders[0].getTimestamp()));
    // Verify that the example data was unmarshalled correctly
    Assert.assertEquals("7eecf4b2-5785-4500-a5d4-f3f8c924395c", anxOpenOrders[1].getOid());
    Assert.assertEquals("BTC", anxOpenOrders[1].getItem());
    Assert.assertEquals("HKD", anxOpenOrders[1].getCurrency());
    Assert.assertEquals("bid", anxOpenOrders[1].getType());
    Assert.assertEquals("BTC", anxOpenOrders[1].getAmount().getCurrency());
    Assert.assertEquals(new BigDecimal("10.00000000"), anxOpenOrders[1].getAmount().getValue());
    Assert.assertEquals(new BigDecimal("412.34567"), anxOpenOrders[0].getPrice().getValue());
    Assert.assertEquals(new BigDecimal("212.34567"), anxOpenOrders[1].getPrice().getValue());
    Assert.assertEquals("open", anxOpenOrders[1].getStatus());
}

89. AtlasAccountInfoTest#setupClass()

Project: XChange
Source File: AtlasAccountInfoTest.java
View license
@BeforeClass
public static void setupClass() {
    inputStream = AtlasAccountInfoTest.class.getResourceAsStream("/account/accountInfo.json");
    if (inputStream == null) {
        LOGGER.error("Could not Load test data.");
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    try {
        accountInfo = mapper.readValue(inputStream, AtlasAccountInfo.class);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
}

90. AddressJSONTest#testUnmarshal()

Project: XChange
Source File: AddressJSONTest.java
View license
@Test
public void testUnmarshal() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = AddressJSONTest.class.getResourceAsStream("/address.json");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    BitcoinAddress address = mapper.readValue(is, BitcoinAddress.class);
    // Verify that the example data was unmarshalled correctly
    assertThat(address.getNumTransactions()).isEqualTo(59);
    assertThat(address.getFinalBalance()).isEqualTo(78399012);
    assertThat(address.getFinalBalanceDecimal()).isEqualTo(new BigDecimal(".78399012"));
    assertThat(address.getAddress()).isEqualTo("17dQktcAmU4urXz7tGk2sbuiCqykm3WLs6");
}

91. HitbtcSnapshotFullRefreshJsonTest#testUnmarshal()

View license
@Test
public void testUnmarshal() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = HitbtcSnapshotFullRefreshJsonTest.class.getResourceAsStream("/marketdata/example-snapshot-full-refresh-data.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    HitbtcSnapshotFullRefresh snapshotFullRefresh = mapper.readValue(is, HitbtcSnapshotFullRefresh.class);
    assertThat(snapshotFullRefresh.getSnapshotSeqNo()).isEqualTo(8339922L);
    assertThat(snapshotFullRefresh.getSymbol()).isEqualTo("BTCUSD");
    assertThat(snapshotFullRefresh.getExchangeStatus()).isEqualTo("working");
    assertThat(snapshotFullRefresh.getAsk()).hasSize(205);
    assertThat(snapshotFullRefresh.getBid()).hasSize(248);
    HitbtcStreamingOrder ask = snapshotFullRefresh.getAsk().get(0);
    assertThat(ask.getPrice()).isEqualTo("348.34");
    assertThat(ask.getSize()).isEqualTo("40");
    HitbtcStreamingOrder bid = snapshotFullRefresh.getBid().get(247);
    assertThat(bid.getPrice()).isEqualTo("0.02");
    assertThat(bid.getSize()).isEqualTo("36400");
}

92. OERTickersTest#testUnmarshal()

Project: XChange
Source File: OERTickersTest.java
View license
@Test
public void testUnmarshal() throws IOException {
    // Read in the JSON from the example resources
    InputStream is = OERTickersTest.class.getResourceAsStream("/example-latest-rates.json");
    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    OERTickers oERTickers = mapper.readValue(is, OERTickers.class);
    // Verify that the example data was unmarshalled correctly
    System.out.println(oERTickers.getTimestamp().toString());
    assertThat(oERTickers.getTimestamp()).isEqualTo(1354687208L);
    System.out.println(oERTickers.getRates().getAED());
    assertThat(oERTickers.getRates().getAED()).isEqualTo(3.672989);
}

93. PathController#getPathsForProfile()

Project: odo
Source File: PathController.java
View license
@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/path", method = RequestMethod.GET)
@ResponseBody
public String getPathsForProfile(Model model, String profileIdentifier, @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter, @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter);
    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));
    ObjectWriter writer = objectMapper.writer(filters);
    return writer.writeValueAsString(jqReturn);
}

94. PathController#testPath()

Project: odo
Source File: PathController.java
View license
@RequestMapping(value = "/api/path/test", method = RequestMethod.GET)
@ResponseBody
public String testPath(@RequestParam String url, @RequestParam String profileIdentifier, @RequestParam Integer requestType) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> trySelectedRequestPaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, ClientService.getInstance().findClient("-1", profileId), ProfileService.getInstance().findProfile(profileId), url, requestType, true);
    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(trySelectedRequestPaths, "paths");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));
    ObjectWriter writer = objectMapper.writer(filters);
    return writer.writeValueAsString(jqReturn);
}

95. BuckLibGenerator#main()

Project: onos
Source File: BuckLibGenerator.java
View license
/**
     * Main entry point.
     *
     * @param args command-line arguments; JSON input file and BUCK output file
     */
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Not enough args.\n\nUSAGE: <json file> <output>");
        System.exit(5);
    }
    // Parse args
    String jsonFilePath = args[0];
    String outputBuckPath = args[1];
    // Load and parse input JSON file
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    ObjectNode json = (ObjectNode) mapper.reader().readTree(new FileInputStream(jsonFilePath));
    // Traverse dependencies and build a dependency graph (DAG)
    BuckLibGenerator generator = new BuckLibGenerator(json).resolve();
    // Write the output BUCK file
    generator.write(outputBuckPath);
    System.out.printf("\nFinish writing %s\n", outputBuckPath);
}

96. ObjectMapperIT#testConstructor()

Project: pinpoint
Source File: ObjectMapperIT.java
View license
@Test
public void testConstructor() throws Exception {
    ObjectMapper mapper1 = new ObjectMapper();
    ObjectMapper mapper2 = new ObjectMapper(new JsonFactory());
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    Constructor<?> omConstructor = ObjectMapper.class.getConstructor(JsonFactory.class, DefaultSerializerProvider.class, DefaultDeserializationContext.class);
    Constructor<?> omConstructor1 = ObjectMapper.class.getConstructor();
    Constructor<?> omConstructor2 = ObjectMapper.class.getConstructor(JsonFactory.class);
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor1));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor2));
    verifier.verifyTraceCount(0);
}

97. ConfiguredObjectJacksonModuleTest#testManageableAttributeType()

View license
public void testManageableAttributeType() throws IOException {
    ManagedAttributeValue testType = new TestManagedAttributeValue();
    ObjectMapper encoder = ConfiguredObjectJacksonModule.newObjectMapper();
    String encodedValue = encoder.writeValueAsString(testType);
    ObjectMapper decoder = new ObjectMapper();
    Map decodedMap = decoder.readValue(encodedValue, Map.class);
    assertEquals(3, decodedMap.size());
    assertTrue(decodedMap.containsKey("name"));
    assertTrue(decodedMap.containsKey("map"));
    assertTrue(decodedMap.containsKey("type"));
    assertEquals("foo", decodedMap.get("name"));
    assertEquals(Collections.singletonMap("key", "value"), decodedMap.get("map"));
    assertEquals(Collections.singletonMap("nested", true), decodedMap.get("type"));
}

98. MessageTagMapDeserializer#deserialize()

View license
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public Map<Integer, List<MessageTag>> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = jp.readValueAs(JsonNode.class);
        if (dataNode != null) {
            if (// OLD STYLE, SUPPORTED IN GRAPH API 2.3
            dataNode.getNodeType().equals(JsonNodeType.OBJECT)) {
                return (Map<Integer, List<MessageTag>>) mapper.reader(new TypeReference<Map<Integer, List<MessageTag>>>() {
                }).readValue(dataNode);
            } else if (// NEW STYLE 2.4/2.5-ish
            dataNode.getNodeType().equals(JsonNodeType.ARRAY)) {
                List<MessageTag> tagList = (List<MessageTag>) mapper.reader(new TypeReference<List<MessageTag>>() {
                }).readValue(dataNode);
                Map<Integer, List<MessageTag>> messageTagMap = new HashMap<Integer, List<MessageTag>>();
                for (MessageTag messageTag : tagList) {
                    messageTagMap.put(messageTag.getOffset(), Arrays.asList(messageTag));
                }
            }
        }
    }
    return Collections.emptyMap();
}

99. TagListDeserializer#deserialize()

View license
@SuppressWarnings("unchecked")
@Override
public List<Tag> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = (JsonNode) jp.readValueAs(JsonNode.class).get("data");
        return (List<Tag>) mapper.reader(new TypeReference<List<Tag>>() {
        }).readValue(dataNode);
    }
    return null;
}

100. ReferenceListDeserializer#deserialize()

View license
@SuppressWarnings("unchecked")
@Override
public List<Reference> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = (JsonNode) jp.readValueAs(JsonNode.class).get("data");
        if (dataNode != null) {
            return (List<Reference>) mapper.reader(new TypeReference<List<Reference>>() {
            }).readValue(dataNode);
        }
    }
    return Collections.emptyList();
}