com.fasterxml.jackson.datatype.jdk8.Jdk8Module Java Examples

The following examples show how to use com.fasterxml.jackson.datatype.jdk8.Jdk8Module. 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: ObjectMappers.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper createAppScalePolicyMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.addMixIn(AlarmConfiguration.class, AlarmConfigurationMixIn.class);
    objectMapper.addMixIn(StepAdjustment.class, StepAdjustmentMixIn.class);
    objectMapper.addMixIn(StepScalingPolicyConfiguration.class, StepScalingPolicyConfigurationMixIn.class);
    objectMapper.addMixIn(PolicyConfiguration.class, PolicyConfigurationMixIn.class);
    objectMapper.addMixIn(AutoScalingPolicy.class, AutoScalingPolicyMixIn.class);
    objectMapper.addMixIn(TargetTrackingPolicy.class, TargetTrackingPolicyMixin.class);
    objectMapper.addMixIn(PredefinedMetricSpecification.class, PredefinedMetricSpecificationMixin.class);
    objectMapper.addMixIn(CustomizedMetricSpecification.class, CustomizedMetricSpecificationMixin.class);
    objectMapper.addMixIn(MetricDimension.class, MetricDimensionMixin.class);

    return objectMapper;
}
 
Example #2
Source File: RestHelper.java    From taskana with Apache License 2.0 6 votes vote down vote up
/**
 * Return a REST template which is capable of dealing with responses in HAL format.
 *
 * @return RestTemplate
 */
private static RestTemplate getRestTemplate() {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  mapper.registerModule(new Jackson2HalModule());
  mapper
      .registerModule(new ParameterNamesModule())
      .registerModule(new Jdk8Module())
      .registerModule(new JavaTimeModule());

  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
  converter.setObjectMapper(mapper);

  RestTemplate template = new RestTemplate();
  // important to add first to ensure priority
  template.getMessageConverters().add(0, converter);
  return template;
}
 
Example #3
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 #4
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 #5
Source File: Issue141Test.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Test
public void itShouldSerializeJavaOptionalYearMonthAsString() throws IOException {
    // Given an instance with java.util.Optional
    MyJavaOptionalClass obj = new MyJavaOptionalClass();
    obj.operatingMonth = Optional.of(YearMonth.of(2019, 12));

    // When serializing the instance using object mapper
    // with Java Time Module and JDK8 Module
    ObjectMapper objectMapper = mapper();
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.registerModule(new Jdk8Module());
    String json = objectMapper.writeValueAsString(obj);

    // Then serialization is successful
    Assertions.assertEquals("{\"operatingMonth\":\"12-2019\"}", json);

    // And deserialization is successful
    MyJavaOptionalClass obj2 = objectMapper.readValue(json, MyJavaOptionalClass.class);
    Assertions.assertEquals(Optional.of(YearMonth.of(2019, 12)), obj2.operatingMonth);
}
 
Example #6
Source File: SerializationUtils.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new {@link ObjectMapper} with default modules against the provided factory.
 *
 * @param mapper the instance to register default modules with
 */
public static ObjectMapper registerDefaultModules(ObjectMapper mapper) {
  // enable support for ...
  return mapper.registerModules(
      // Optional<>s
      new Jdk8Module(),
      // Protobuf objects
      new ProtobufModule());
}
 
Example #7
Source File: ObjectMapperProvider.java    From jersey-jwt with MIT License 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {

        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(new Jdk8Module());
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new ParameterNamesModule());

        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        return mapper;
    }
 
Example #8
Source File: ObjectMapperProvider.java    From jersey-jwt-springsecurity with MIT License 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {

        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(new Jdk8Module());
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new ParameterNamesModule());

        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

        return mapper;
    }
 
Example #9
Source File: HeroicMappers.java    From heroic with Apache License 2.0 6 votes vote down vote up
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.registerModule(new KotlinModule());

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    mapper.registerModule(FilterRegistry.registry().module(parser));

    return mapper;
}
 
Example #10
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 #11
Source File: PrimitiveOptionalPropertyTest.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
@Test
public void testJacksonInteroperability() {
  behaviorTester
      .with(new Processor(features))
      .with(datatype)
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder().%s(%s).build();",
              convention.set("item"), optional.example(0))
          .addLine("%1$s mapper = new %1$s()", ObjectMapper.class)
          .addLine("    .registerModule(new %s());", Jdk8Module.class)
          .addLine("String json = mapper.writeValueAsString(value);")
          .addLine("assertEquals(\"{\\\"item\\\":%s}\", json);", optional.example(0))
          .addLine("DataType clone = mapper.readValue(json, DataType.class);")
          .addLine("assertEquals(%s.of(%s), clone.%s);",
              optional.type, optional.example(0), convention.get("item"))
          .build())
      .runTest();
}
 
Example #12
Source File: JacksonAdapter.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Initializes an instance of JacksonMapperAdapter with default configurations
 * applied to the object mapper.
 *
 * @param mapper the object mapper to use.
 */
private static ObjectMapper initializeObjectMapper(ObjectMapper mapper) {
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true)
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
            .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule())
            .registerModule(new ParameterNamesModule())
            .registerModule(ByteArraySerializer.getModule())
            .registerModule(Base64UrlSerializer.getModule())
            .registerModule(HeadersSerializer.getModule());
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
    return mapper;
}
 
Example #13
Source File: ConfigValidatorTest.java    From dcos-cassandra-service with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEach() throws Exception {
  factory = new ConfigurationFactory<>(
    MutableSchedulerConfiguration.class,
    BaseValidator.newValidator(),
    Jackson.newObjectMapper().registerModule(new GuavaModule())
      .registerModule(new Jdk8Module()),
    "dw");

  configuration = factory.build(
    new SubstitutingSourceProvider(
      new FileConfigurationSourceProvider(),
      new EnvironmentVariableSubstitutor(false, true)),
    Resources.getResource("scheduler.yml").getFile());
}
 
Example #14
Source File: HttpClient.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static Client createClient() {
    final ObjectMapper mapper = new ObjectMapper().registerModules(new Jdk8Module());
    final ResteasyJackson2Provider resteasyJacksonProvider = new ResteasyJackson2Provider();

    resteasyJacksonProvider.setMapper(mapper);

    final ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
    providerFactory.register(resteasyJacksonProvider);

    return ClientBuilder.newBuilder()
        .withConfig(providerFactory)
        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
        .build();
}
 
Example #15
Source File: BaragonAgentServiceModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Binder binder) {
  binder.requireExplicitBindings();
  binder.requireExactBindingAnnotations();
  binder.requireAtInjectOnConstructors();

  binder.install(new BaragonDataModule());
  binder.install(new BargonAgentResourcesModule());

  // Healthchecks
  binder.bind(LoadBalancerHealthcheck.class).in(Scopes.SINGLETON);
  binder.bind(ZooKeeperHealthcheck.class).in(Scopes.SINGLETON);
  binder.bind(ConfigChecker.class).in(Scopes.SINGLETON);

  // Managed
  binder.bind(BaragonAgentGraphiteReporterManaged.class).asEagerSingleton();
  binder.bind(BootstrapManaged.class).asEagerSingleton();
  binder.bind(LifecycleHelper.class).asEagerSingleton();

  // Manager
  binder.bind(AgentRequestManager.class).in(Scopes.SINGLETON);

  binder.bind(ResyncListener.class).in(Scopes.SINGLETON);
  binder.bind(LocalLbAdapter.class).in(Scopes.SINGLETON);
  binder.bind(LbConfigGenerator.class).in(Scopes.SINGLETON);
  binder.bind(ServerProvider.class).in(Scopes.SINGLETON);
  binder.bind(FilesystemConfigHelper.class).in(Scopes.SINGLETON);
  binder.bind(AgentHeartbeatWorker.class).in(Scopes.SINGLETON);
  binder.bind(InternalStateChecker.class).in(Scopes.SINGLETON);
  binder.bind(DirectoryChangesListener.class).in(Scopes.SINGLETON);

  final ObjectMapper objectMapper = new ObjectMapper();

  objectMapper.registerModule(new GuavaModule());
  objectMapper.registerModule(new Jdk8Module());

  binder.bind(ObjectMapper.class).toInstance(objectMapper);
}
 
Example #16
Source File: KeywhizService.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
/**
 * Customizes ObjectMapper for common settings.
 *
 * @param objectMapper to be customized
 * @return customized input factory
 */
public static ObjectMapper customizeObjectMapper(ObjectMapper objectMapper) {
  objectMapper.registerModules(new Jdk8Module());
  objectMapper.registerModules(new JavaTimeModule());
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  return objectMapper;
}
 
Example #17
Source File: TaskStatusesTracker.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
public Response getJson(@QueryParam("plan") String filterPlan,
                        @QueryParam("phase") String filterPhase,
                        @QueryParam("step") String filterStep,
                        @QueryParam("sync") boolean requireSync)
{
  ObjectMapper jsonMapper = new ObjectMapper();
  jsonMapper.registerModule(new Jdk8Module());
  jsonMapper.registerModule(new JsonOrgModule());

  List<PlanResponse> serviceResponse = getTaskStatuses(filterPlan, filterPhase, filterStep);

  JSONArray response = jsonMapper.convertValue(serviceResponse, JSONArray.class);

  return ResponseUtils.jsonOkResponse(response);
}
 
Example #18
Source File: ShopRestController.java    From state-machine with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public ObjectMapper objectMapper() {
    return new ObjectMapper() //
            .setVisibility(PropertyAccessor.FIELD, Visibility.PUBLIC_ONLY)
            .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) //
            .registerModule(new Jdk8Module()) //
            .registerModule(new ParameterNamesModule());
}
 
Example #19
Source File: StandaloneConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    //Enable ObjectMapper to manage Optional type.
    Json.mapper.registerModule(new Jdk8Module());//Manage Optional java type
    //Json.mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);//Reject duplicated keys
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper;
}
 
Example #20
Source File: YAMLConfigurationFactory.java    From dcos-cassandra-service with Apache License 2.0 5 votes vote down vote up
@Override
public Configuration parse(byte[] bytes) throws ConfigStoreException {
    try {
        final ObjectMapper mapper = Jackson.newObjectMapper()
                .registerModule(new GuavaModule())
                .registerModule(new JavaTimeModule())
                .registerModule(new Jdk8Module());
        return (Configuration) mapper.readValue(bytes, typeParameterClass);
    } catch (Exception e) {
        throw new ConfigStoreException(e);
    }
}
 
Example #21
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 #22
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 #23
Source File: ExternalVerifierService.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    if (this.client == null) {
        final ObjectMapper mapper = new ObjectMapper().registerModules(new Jdk8Module());
        final ResteasyJackson2Provider resteasyJacksonProvider = new ResteasyJackson2Provider();

        resteasyJacksonProvider.setMapper(mapper);

        final ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance();
        providerFactory.register(resteasyJacksonProvider);

        this.client = ClientBuilder.newClient(providerFactory);
    }

}
 
Example #24
Source File: CamundaJacksonFormatConfiguratorJdk8.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(JacksonJsonDataFormat dataFormat) {
  ObjectMapper mapper = dataFormat.getObjectMapper();
  final Jdk8Module jdk8Module = new Jdk8Module();

  mapper.registerModule(jdk8Module);
}
 
Example #25
Source File: DeployOptionsTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void it_serializes_version() throws IOException {
    DeployOptions options = new DeployOptions(false, Optional.of(new Version("6.98.227")), false, false);
    final ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(new Jdk8Module());

    String string = objectMapper.writeValueAsString(options);
    assertEquals("{\"deployDirectly\":false,\"vespaVersion\":\"6.98.227\",\"ignoreValidationErrors\":false,\"deployCurrentVersion\":false}", string);
}
 
Example #26
Source File: JacksonContextResolver.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public JacksonContextResolver() {
    this.objectMapper = new ObjectMapper()
        .registerModule(new Jdk8Module())
        .setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
        .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true)
        .configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
}
 
Example #27
Source File: NewRelicClient.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
private JacksonJsonProvider createMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    mapper.setSerializationInclusion(NON_NULL);
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new JavaTimeModule());
    return new JacksonJaxbJsonProvider(mapper, DEFAULT_ANNOTATIONS);
}
 
Example #28
Source File: Mappers.java    From ffwd with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper setupApplicationJson() {
    final ObjectMapper m = new ObjectMapper();
    m.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
    m.enable(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES);
    m.registerModule(new Jdk8Module());
    return m;
}
 
Example #29
Source File: BaragonClientModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper buildObjectMapper() {
  final ObjectMapper objectMapper = new ObjectMapper();

  objectMapper.registerModule(new GuavaModule());
  objectMapper.registerModule(new Jdk8Module());

  return objectMapper;
}
 
Example #30
Source File: FeignClientFactory.java    From web-budget with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method to configure the Jackson JSON mappers
 * 
 * @return jakcson {@link ObjectMapper} for JSON objects
 */
private ObjectMapper configureMapper() {
    return new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());
}