com.fasterxml.jackson.datatype.guava.GuavaModule Java Examples

The following examples show how to use com.fasterxml.jackson.datatype.guava.GuavaModule. 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: TypeTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void isSerializable() throws IOException {
  Type type = new Type("http://example.org/myType");
  type.getOrCreatePredicate("http://example.org/myPredicate", Direction.OUT);
  type.getOrCreatePredicate("http://example.org/myPredicate", Direction.IN);

  ObjectMapper mapper = new ObjectMapper()
    .registerModule(new Jdk8Module())
    .registerModule(new GuavaModule())
    .registerModule(new TimbuctooCustomSerializers())
    .enable(SerializationFeature.INDENT_OUTPUT);
  String result = mapper.writeValueAsString(type);

  Type loadedType = mapper.readValue(result, Type.class);

  assertThat(loadedType, is(type));
}
 
Example #2
Source File: StreamPacketFixturesTest.java    From quilt with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a list of tests based on the json-encoded test vector files.
 */
@Parameters(name = "Test Vector {index}: {0}")
public static Collection<StreamTestFixture> testVectorData() throws Exception {

  final ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new Jdk8Module());
  objectMapper.registerModule(new GuavaModule());
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

  Properties properties = readProperties();
  String fileName = (String) properties.get("stream.packetFixtures.fileName");

  Path path = Paths.get(StreamPacketFixturesTest.class.getClassLoader().getResource(fileName).toURI());

  Stream<String> lines = Files.lines(path);
  String data = lines.collect(Collectors.joining("\n"));
  lines.close();

  List<StreamTestFixture> vectors = objectMapper.readValue(data, new TypeReference<List<StreamTestFixture>>() {});

  return vectors;
}
 
Example #3
Source File: CodegenConfigurator.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
private static DynamicSettings readDynamicSettings(String configFile, Module... modules) {
    ObjectMapper mapper;

    if (FilenameUtils.isExtension(configFile.toLowerCase(Locale.ROOT), new String[]{"yml", "yaml"})) {
        mapper = Yaml.mapper().copy();
    } else {
        mapper = Json.mapper().copy();
    }

    if (modules != null && modules.length > 0) {
        mapper.registerModules(modules);
    }

    mapper.registerModule(new GuavaModule());

    try {
        return mapper.readValue(new File(configFile), DynamicSettings.class);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
        throw new RuntimeException("Unable to deserialize config file: " + configFile);
    }
}
 
Example #4
Source File: ConfigurationManagerTest.java    From dcos-cassandra-service with Apache License 2.0 6 votes vote down vote up
@Before
public void beforeAll() throws Exception {
    server = new TestingServer();
    server.start();
    Capabilities mockCapabilities = Mockito.mock(Capabilities.class);
    when(mockCapabilities.supportsNamedVips()).thenReturn(true);
    taskFactory = new CassandraDaemonTask.Factory(mockCapabilities);
    configurationFactory = new ConfigurationFactory<>(
                    MutableSchedulerConfiguration.class,
                    BaseValidator.newValidator(),
                    Jackson.newObjectMapper()
                            .registerModule(new GuavaModule())
                            .registerModule(new Jdk8Module()),
                    "dw");
    connectString = server.getConnectString();
}
 
Example #5
Source File: Range56Test.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
public void testSnakeCaseNamingStrategy() throws Exception
{
    String json = "{\"lower_endpoint\": 12, \"lower_bound_type\": \"CLOSED\", \"upper_endpoint\": 33, \"upper_bound_type\": \"CLOSED\"}";

    GuavaModule mod = new GuavaModule().defaultBoundType(BoundType.CLOSED);
    ObjectMapper mapper = JsonMapper.builder()
            .addModule(mod)
            .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
            .build();

    @SuppressWarnings("unchecked")
    Range<Integer> r = (Range<Integer>) mapper.readValue(json, Range.class);

    assertEquals(Integer.valueOf(12), r.lowerEndpoint());
    assertEquals(Integer.valueOf(33), r.upperEndpoint());

    assertEquals(BoundType.CLOSED, r.lowerBoundType());
    assertEquals(BoundType.CLOSED, r.upperBoundType());
}
 
Example #6
Source File: BatfishObjectMapper.java    From batfish with Apache License 2.0 6 votes vote down vote up
/** Configures all the default options for a Batfish {@link ObjectMapper}. */
private static ObjectMapper baseMapper() {
  ObjectMapper mapper = new ObjectMapper();

  mapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
  mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
  mapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
  // Next two lines make Instant class serialize as an RFC-3339 timestamp
  mapper.registerModule(new JavaTimeModule());
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  // This line makes Java 8's Optional type serialize
  mapper.registerModule(new Jdk8Module());
  // See https://groups.google.com/forum/#!topic/jackson-user/WfZzlt5C2Ww
  //  This fixes issues in which non-empty maps with keys with empty values would get omitted
  //  entirely. See also https://github.com/batfish/batfish/issues/256
  mapper.setDefaultPropertyInclusion(
      JsonInclude.Value.construct(Include.NON_EMPTY, Include.ALWAYS));
  // This line makes Guava collections work with jackson
  mapper.registerModule(new GuavaModule());

  // Custom (de)serialization for 3rd-party classes
  mapper.registerModule(new BatfishThirdPartySerializationModule());

  return mapper;
}
 
Example #7
Source File: ObjectMappers.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public static ObjectMapper create(Module... extraModules) {
    SimpleModule module = new SimpleModule();

    module.addSerializer(boolean.class, new BooleanSerializer(Boolean.class));
    module.addSerializer(Enum.class, new EnumSerializer(Enum.class));
    module.setDeserializerModifier(new EnumDeserializerModifier());

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    mapper.registerModule(new GuavaModule());
    for (Module extraModule : extraModules) {
        mapper.registerModule(extraModule);
    }
    mapper.setSerializationInclusion(Include.NON_ABSENT);
    return mapper;
}
 
Example #8
Source File: JacksonUtils.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>configureMapper.</p>
 *
 * @param mapper a {@link com.fasterxml.jackson.databind.ObjectMapper} object.
 * @param mode   App mode
 */
public static void configureMapper(ObjectMapper mapper, Application.Mode mode) {
    mapper.registerModule(new GuavaModule());
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .enable(SerializationFeature.WRITE_ENUMS_USING_INDEX)
            .enable(MapperFeature.PROPAGATE_TRANSIENT_MARKER)
            .disable(
                    SerializationFeature.WRITE_NULL_MAP_VALUES,
                    SerializationFeature.FAIL_ON_EMPTY_BEANS
            );
    if (!mode.isDev()) {
        mapper.disable(
                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
        );
    }
}
 
Example #9
Source File: ValidatedConfiguration.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
private static DivolteConfiguration mapped(final Config input) throws IOException {
    final Config resolved = input.resolve();
    final ObjectMapper mapper = new ObjectMapper();

    // snake_casing
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

    // Ignore unknown stuff in the config
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    // Deserialization for Duration
    final SimpleModule module = new SimpleModule("Configuration Deserializers");
    module.addDeserializer(Duration.class, new DurationDeserializer());
    module.addDeserializer(Properties.class, new PropertiesDeserializer());

    mapper.registerModules(
            new Jdk8Module(),                   // JDK8 types (Optional, etc.)
            new GuavaModule(),                  // Guava types (immutable collections)
            new ParameterNamesModule(),         // Support JDK8 parameter name discovery
            module                              // Register custom deserializers module
            );

    return mapper.readValue(new HoconTreeTraversingParser(resolved.root()), DivolteConfiguration.class);
}
 
Example #10
Source File: SingularityClientModule.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
  ObjectMapper objectMapper = JavaUtils.newObjectMapper();
  objectMapper.registerModule(new GuavaModule());
  objectMapper.registerModule(new Jdk8Module());

  HttpClient httpClient = new NingHttpClient(
    httpConfig.orElse(HttpConfig.newBuilder().setObjectMapper(objectMapper).build())
  );
  bind(HttpClient.class)
    .annotatedWith(Names.named(HTTP_CLIENT_NAME))
    .toInstance(httpClient);

  bind(SingularityClient.class)
    .toProvider(SingularityClientProvider.class)
    .in(Scopes.SINGLETON);

  if (hosts != null) {
    bindHosts(binder()).toInstance(hosts);
  }
}
 
Example #11
Source File: SingularityRunnerBaseModule.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@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_ABSENT);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.registerModule(new GuavaModule());
  mapper.registerModule(new ProtobufModule());
  mapper.registerModule(new Jdk8Module());

  return mapper;
}
 
Example #12
Source File: JsonToGuavaMultimap.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void convert() throws JsonParseException, JsonMappingException,
		JsonProcessingException, IOException {

	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.registerModule(new GuavaModule());

	Multimap<String, NavItem> navs = objectMapper.readValue(
			objectMapper.treeAsTokens(objectMapper.readTree(jsonString)),
			objectMapper.getTypeFactory().constructMapLikeType(
					Multimap.class, String.class, NavItem.class));

	logger.info(navs);
	
    assertThat(navs.keys(), hasItems("123455", "999999"));
}
 
Example #13
Source File: JacksonRepoTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  final MongoDatabase database = context.database();
  this.collection = database.getCollection("jackson").withDocumentClass(BsonDocument.class);

  SimpleModule module = new SimpleModule(); // for our local serializers of Date and ObjectId
  module.addDeserializer(Date.class, new DateDeserializer());
  module.addSerializer(new DateSerializer());
  module.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
  module.addSerializer(new ObjectIdSerializer());
  module.addDeserializer(UUID.class, new UUIDDeserializer(UuidRepresentation.JAVA_LEGACY));

  ObjectMapper mapper = new ObjectMapper()
      // to support bson types like: Document, BsonValue etc.
      .registerModule(JacksonCodecs.module(MongoClient.getDefaultCodecRegistry()))
      .registerModule(new GuavaModule())
      .registerModule(module);

  RepositorySetup setup = RepositorySetup.builder()
          .database(database)
          .codecRegistry(JacksonCodecs.registryFromMapper(mapper))
          .executor(MoreExecutors.newDirectExecutorService())
          .build();

  this.repository = new JacksonRepository(setup);
}
 
Example #14
Source File: DefaultTypingTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: Handler.java    From billow with Apache License 2.0 5 votes vote down vote up
public Handler(MetricRegistry registry, AWSDatabaseHolder dbHolder, long maxDBAgeInMs) {
    this.mapper = new ObjectMapper();
    this.mapper.addMixInAnnotations(DBInstance.class, DBInstanceMixin.class);
    this.mapper.addMixInAnnotations(PendingModifiedValues.class, PendingModifiedValuesMixin.class);
    this.mapper.addMixInAnnotations(DBInstanceStatusInfo.class, DBInstanceStatusInfoMixin.class);
    this.mapper.registerModule(new JodaModule());
    this.mapper.registerModule(new GuavaModule());
    this.registry = registry;
    this.dbHolder = dbHolder;
    this.maxDBAgeInMs = maxDBAgeInMs;
}
 
Example #16
Source File: ObjectMappers.java    From roboslack with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper newObjectMapper() {
    return new ObjectMapper().registerModule(new GuavaModule())
            .registerModule(new Jdk8Module().configureAbsentsAsNulls(true))
            .registerModule(new AfterburnerModule())
            .registerModule(new JavaTimeModule())
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
            .disable(DeserializationFeature.WRAP_EXCEPTIONS)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
}
 
Example #17
Source File: JsonRpcServiceTest.java    From simple-json-rpc with MIT License 5 votes vote down vote up
@BeforeAll
public static void init() throws Exception {
    userMapper.registerModule(new GuavaModule());
    userMapper.registerModule(new Jdk8Module());
    testData = new ObjectMapper().readValue(Resources.toString(JsonRpcServiceTest.class.getResource("/test_data.json"), Charsets.UTF_8),
                                            TypeFactory.defaultInstance()
                                                       .constructMapType(Map.class,
                                                                         TypeFactory.defaultInstance().constructType(String.class),
                                                                         TypeFactory.defaultInstance().constructType(RequestResponse.class)));
}
 
Example #18
Source File: JacksonXML.java    From dropwizard-xml with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link com.fasterxml.jackson.dataformat.xml.XmlMapper} using Woodstox
 * with Logback and Joda Time support.
 * Also includes all {@link io.dropwizard.jackson.Discoverable} interface implementations.
 *
 * @return XmlMapper
 */
public static XmlMapper newXMLMapper(JacksonXmlModule jacksonXmlModule) {

    final XmlFactory woodstoxFactory = new XmlFactory(new WstxInputFactory(), new WstxOutputFactory());
    final XmlMapper mapper = new XmlMapper(woodstoxFactory, jacksonXmlModule);

    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new GuavaExtrasModule());
    mapper.registerModule(new JodaModule());
    mapper.registerModule(new FuzzyEnumModule());
    mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
    mapper.setSubtypeResolver(new DiscoverableSubtypeResolver());

    return mapper;
}
 
Example #19
Source File: JavaUtils.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper newObjectMapper() {
  final ObjectMapper mapper = new ObjectMapper();
  mapper.setSerializationInclusion(Include.NON_ABSENT);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.registerModule(new GuavaModule());
  mapper.registerModule(new ProtobufModule());
  mapper.registerModule(new Jdk8Module());
  return mapper;
}
 
Example #20
Source File: JsonTransformer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private JsonTransformer(Collection<Module> modules) {
    objectMapper = new ObjectMapper()
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule())
        .registerModule(new GuavaModule())
        .registerModules(modules);
}
 
Example #21
Source File: MailDTOTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    objectMapper = new ObjectMapper()
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule())
        .registerModule(new GuavaModule());
}
 
Example #22
Source File: JsonExtractor.java    From james-project with Apache License 2.0 5 votes vote down vote up
public JsonExtractor(Class<RequestT> type, List<Module> modules) {
    this.objectMapper = new ObjectMapper()
        .registerModule(new Jdk8Module())
        .registerModule(new GuavaModule())
        .registerModules(modules);
    this.type = type;
}
 
Example #23
Source File: MessageToElasticSearchJson.java    From james-project with Apache License 2.0 5 votes vote down vote up
public MessageToElasticSearchJson(TextExtractor textExtractor, ZoneId zoneId, IndexAttachments indexAttachments) {
    this.textExtractor = textExtractor;
    this.zoneId = zoneId;
    this.indexAttachments = indexAttachments;
    this.mapper = new ObjectMapper();
    this.mapper.registerModule(new GuavaModule());
    this.mapper.registerModule(new Jdk8Module());
}
 
Example #24
Source File: JsonGenericSerializer.java    From james-project with Apache License 2.0 5 votes vote down vote up
private ObjectMapper buildObjectMapper(Set<? extends DTOModule<?, ?>> modules) {
    ObjectMapper objectMapper = new ObjectMapper()
        .registerModule(new Jdk8Module())
        .registerModule(new JavaTimeModule())
        .registerModule(new GuavaModule())
        .setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
    NamedType[] namedTypes = modules.stream()
        .map(module -> new NamedType(module.getDTOClass(), module.getDomainObjectType()))
        .toArray(NamedType[]::new);
    objectMapper.registerSubtypes(namedTypes);
    return objectMapper;
}
 
Example #25
Source File: BiMapPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  // See also https://github.com/google/FreeBuilder/issues/68
  assumeTrue(keys.isSerializableAsMapKey());
  behaviorTester
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("import " + JsonProperty.class.getName() + ";")
          .addLine("@%s", FreeBuilder.class)
          .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class)
          .addLine("public interface DataType {")
          .addLine("  @JsonProperty(\"stuff\") %s<%s, %s> %s;",
              ImmutableBiMap.class, keys.type(), values.type(), convention.get())
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putItems(%s, %s)", keys.example(0), values.example(0))
          .addLine("    .putItems(%s, %s)", keys.example(1), values.example(1))
          .addLine("    .build();")
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", GuavaModule.class)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertThat(clone.%s).isEqualTo(%s);",
              convention.get(), exampleMap(0, 0, 1, 1))
          .build())
      .runTest();
}
 
Example #26
Source File: OptionalPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  // See also https://github.com/google/FreeBuilder/issues/68
  Class<? extends Module> module =
      optional.getName().startsWith("com.google") ? GuavaModule.class : Jdk8Module.class;
  behaviorTester
      .with(new Processor(features))
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("import " + JsonProperty.class.getName() + ";")
          .addLine("@%s", FreeBuilder.class)
          .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class)
          .addLine("public interface DataType {")
          .addLine("  @JsonProperty(\"stuff\") %s<%s> %s;",
              optional, element.type(), convention.get("item"))
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .%s(%s)", convention.set("item"), element.example(0))
          .addLine("    .build();")
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", module)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertEquals(%s.of(%s), clone.%s);",
              optional, element.example(0), convention.get("item"))
          .build())
      .runTest();
}
 
Example #27
Source File: ListMultimapPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  // See also https://github.com/google/FreeBuilder/issues/68
  behaviorTester
      .with(new Processor(features))
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("import " + JsonProperty.class.getName() + ";")
          .addLine("@%s", FreeBuilder.class)
          .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class)
          .addLine("public interface DataType {")
          .addLine("  @JsonProperty(\"stuff\") %s<%s, %s> %s;",
              Multimap.class, key.type(), value.type(), convention.get("items"))
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putItems(%s, %s)", key.example(0), value.example(1))
          .addLine("    .putItems(%s, %s)", key.example(2), value.example(3))
          .addLine("    .build();")
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", GuavaModule.class)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertThat(clone.%s)", convention.get("items"))
          .addLine("    .contains(%s, %s)", key.example(0), value.example(1))
          .addLine("    .and(%s, %s)", key.example(2), value.example(3))
          .addLine("    .andNothingElse()")
          .addLine("    .inOrder();")
          .build())
      .runTest();
}
 
Example #28
Source File: SetMultimapPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  // See also https://github.com/google/FreeBuilder/issues/68
  behaviorTester
      .with(new Processor(features))
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("@%s", FreeBuilder.class)
          .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class)
          .addLine("public interface DataType {")
          .addLine("  @%s(\"stuff\")", JsonProperty.class)
          .addLine("  %s<%s, %s> %s;",
              SetMultimap.class, key.type(), value.type(), convention.get("items"))
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .putItems(%s, %s)", key.example(0), value.example(1))
          .addLine("    .putItems(%s, %s)", key.example(2), value.example(3))
          .addLine("    .build();")
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", GuavaModule.class)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertThat(clone.%s)", convention.get("items"))
          .addLine("    .contains(%s, %s)", key.example(0), value.example(1))
          .addLine("    .and(%s, %s)", key.example(2), value.example(3))
          .addLine("    .andNothingElse()")
          .addLine("    .inOrder();")
          .build())
      .runTest();
}
 
Example #29
Source File: MultisetPropertyTest.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  // See also https://github.com/google/FreeBuilder/issues/68
  behaviorTester
      .with(new Processor(features))
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("import " + JsonProperty.class.getName() + ";")
          .addLine("@%s", FreeBuilder.class)
          .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class)
          .addLine("public interface DataType {")
          .addLine("  @JsonProperty(\"stuff\") %s<%s> %s;",
              Multiset.class, element.type(), convention.get("items"))
          .addLine("")
          .addLine("  class Builder extends DataType_Builder {}")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .addItems(%s)", element.example(0))
          .addLine("    .addItems(%s)", element.example(1))
          .addLine("    .build();")
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", GuavaModule.class)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertThat(clone.%s).iteratesAs(%s);",
              convention.get("items"), element.examples(0, 1))
          .build())
      .runTest();
}
 
Example #30
Source File: ObjectMapperUtils.java    From slack-client with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper create() {
  ObjectMapper mapper = new ObjectMapper();
  mapper.registerModule(new GuavaModule());
  mapper.registerModule(new JodaModule());
  mapper.registerModule(new Jdk8Module());
  mapper.registerModule(new JSR310Module());

  mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, false);
  mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
  mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, true);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  return mapper;
}