com.fasterxml.jackson.databind.InjectableValues Java Examples

The following examples show how to use com.fasterxml.jackson.databind.InjectableValues. 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: DatabaseReader.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @param ipAddress IPv4 or IPv6 address to lookup.
 * @return An object of type T with the data for the IP address or null if no information could be found for the given IP address
 * @throws IOException if there is an error opening or reading from the file.
 */
private <T> T get(InetAddress ipAddress, Class<T> cls, boolean hasTraits, String type) throws IOException {
    String databaseType = this.getMetadata().getDatabaseType();
    if (!databaseType.contains(type)) {
        String caller = Thread.currentThread().getStackTrace()[2].getMethodName();
        throw new UnsupportedOperationException("Invalid attempt to open a " + databaseType + " database using the " + caller + " method");
    }

    ObjectNode node = (ObjectNode) this.reader.get(ipAddress);

    if (node == null) {
        return null;
    }

    InjectableValues inject = new JsonInjector(ipAddress.getHostAddress());
    return this.om.reader(inject).treeToValue(node, cls);
}
 
Example #2
Source File: GuiceBundle.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(Bootstrap<?> bootstrap)
{
    final InjectableValues injectableValues = new InjectableValues()
    {
        @Override
        public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance)
        {
            return null;
        }
    };
    final ConfigurationFactoryFactory<? extends Configuration> configurationFactoryFactory = bootstrap.getConfigurationFactoryFactory();
    ConfigurationFactoryFactory factoryFactory = new ConfigurationFactoryFactory()
    {
        @Override
        public ConfigurationFactory create(Class klass, Validator validator, ObjectMapper objectMapper, String propertyPrefix)
        {
            objectMapper.setInjectableValues(injectableValues);
            //noinspection unchecked
            return configurationFactoryFactory.create(klass, validator, objectMapper, propertyPrefix);
        }
    };
    //noinspection unchecked
    bootstrap.setConfigurationFactoryFactory(factoryFactory);
}
 
Example #3
Source File: ObjectMapperResolver.java    From clouditor with Apache License 2.0 6 votes vote down vote up
public static void configureObjectMapper(ObjectMapper mapper) {
  mapper.registerModule(new JavaTimeModule());
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.setSerializationInclusion(Include.NON_NULL);
  mapper.setConfig(mapper.getSerializationConfig().withView(ApiOnly.class));

  // add all sub types of CloudAccount
  for (var type : REFLECTIONS_SUBTYPE_SCANNER.getSubTypesOf(CloudAccount.class)) {
    mapper.registerSubtypes(type);
  }

  // set injectable value to null
  var values = new InjectableValues.Std();
  values.addValue("hash", null);

  mapper.setInjectableValues(values);
}
 
Example #4
Source File: ClientODataDeserializerImpl.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected XmlMapper getXmlMapper() {
  final XmlMapper xmlMapper = new XmlMapper(
      new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule());

  xmlMapper.setInjectableValues(new InjectableValues.Std().addValue(Boolean.class, Boolean.FALSE));

  xmlMapper.addHandler(new DeserializationProblemHandler() {
    @Override
    public boolean handleUnknownProperty(final DeserializationContext ctxt, final JsonParser jp,
        final com.fasterxml.jackson.databind.JsonDeserializer<?> deserializer,
        final Object beanOrClass, final String propertyName)
        throws IOException, JsonProcessingException {

      // skip any unknown property
      ctxt.getParser().skipChildren();
      return true;
    }
  });
  return xmlMapper;
}
 
Example #5
Source File: IdolConfiguration.java    From find with MIT License 6 votes vote down vote up
@SuppressWarnings("SpringJavaAutowiringInspection")
@Bean
@Autowired
@Primary
public ObjectMapper jacksonObjectMapper(
        final Jackson2ObjectMapperBuilder builder,
        final AuthenticationInformationRetriever<?, ?> authenticationInformationRetriever
) {
    final ObjectMapper mapper = builder
            .createXmlMapper(false)
            .mixIn(Authentication.class, IdolAuthenticationMixins.class)
            .mixIn(Widget.class, WidgetMixins.class)
            .mixIn(WidgetDatasource.class, WidgetDatasourceMixins.class)
            .mixIn(QueryRestrictions.class, IdolQueryRestrictionsMixin.class)
            .mixIn(IdolQueryRestrictions.class, IdolQueryRestrictionsMixin.class)
            .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
            .build();

    mapper.setInjectableValues(new InjectableValues.Std().addValue(AuthenticationInformationRetriever.class, authenticationInformationRetriever));

    return mapper;
}
 
Example #6
Source File: DatabaseReader.java    From nifi with Apache License 2.0 6 votes vote down vote up
private DatabaseReader(Builder builder) throws IOException {
    if (builder.stream != null) {
        this.reader = new Reader(builder.stream);
    } else if (builder.database != null) {
        this.reader = new Reader(builder.database, builder.mode);
    } else {
        // This should never happen. If it does, review the Builder class
        // constructors for errors.
        throw new IllegalArgumentException("Unsupported Builder configuration: expected either File or URL");
    }

    this.om = new ObjectMapper();
    this.om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.om.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    InjectableValues inject = new InjectableValues.Std().addValue("locales", builder.locales);
    this.om.setInjectableValues(inject);
}
 
Example #7
Source File: DatabaseReader.java    From nifi with Apache License 2.0 6 votes vote down vote up
private DatabaseReader(final Builder builder) throws IOException {
    if (builder.stream != null) {
        this.reader = new Reader(builder.stream);
    } else if (builder.database != null) {
        this.reader = new Reader(builder.database, builder.mode);
    } else {
        // This should never happen. If it does, review the Builder class
        // constructors for errors.
        throw new IllegalArgumentException("Unsupported Builder configuration: expected either File or URL");
    }

    this.om = new ObjectMapper();
    this.om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    this.om.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    InjectableValues inject = new InjectableValues.Std().addValue("locales", builder.locales);
    this.om.setInjectableValues(inject);

    this.locales = builder.locales;
}
 
Example #8
Source File: BucketConfigParser.java    From java-dcp-client with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a raw configuration into a {@link BucketConfig}.
 *
 * @param input the raw string input.
 * @param origin the origin of the configuration (only the hostname is used).
 * @return the parsed bucket configuration.
 */
public static BucketConfig parse(String input, HostAndPort origin) {
  input = input.replace("$HOST", origin.formatHost());

  try {
    InjectableValues inject = new InjectableValues.Std()
        .addValue("origin", origin.host());
    return DefaultObjectMapper.reader()
        .forType(BucketConfig.class)
        .with(inject)
        .with(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
        .readValue(input);
  } catch (IOException e) {
    throw new CouchbaseException("Could not parse configuration", e);
  }
}
 
Example #9
Source File: FailedItemMarshaller.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
ObjectMapper createConfiguredObjectMapper() {
    return new ExtendedObjectMapper(new JsonFactory())
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .configure(SerializationFeature.CLOSE_CLOSEABLE, false)
            .addMixIn(FailedItemInfo.class, FailedItemInfoMixIn.class)
            .addMixIn(ItemSource.class, ItemSourceMixIn.class)
            .addMixIn(FailedItemSource.class, FailedItemSourceDelegateMixIn.class)
            .addMixIn(ByteBufItemSource.class, ByteBufItemSourceMixIn.class)
            .addMixIn(StringItemSource.class, StringItemSourceMixIn.class)
            .addMixIn(ByteBuf.class, CompositeByteBufMixIn.class)
            .addMixIn(KeySequenceConfigKeys.class, KeySequenceConfigKeysMixIn.class)
            .addMixIn(KeySequenceConfig.class, KeySequenceConfigMixIn.class)
            .setInjectableValues(new InjectableValues.Std()
                    .addValue("releaseCallback", (ReleaseCallback<ByteBuf>) source -> source.getSource().release()))
            .setVisibility(VisibilityChecker.Std.defaultInstance()
                    .withFieldVisibility(JsonAutoDetect.Visibility.ANY));
}
 
Example #10
Source File: WebServiceClient.java    From GeoIP2-java with Apache License 2.0 6 votes vote down vote up
private <T> T handleResponse(CloseableHttpResponse response, URL url, Class<T> cls)
        throws GeoIp2Exception, IOException {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 400 && status < 500) {
        this.handle4xxStatus(response, url);
    } else if (status >= 500 && status < 600) {
        throw new HttpException("Received a server error (" + status
                + ") for " + url, status, url);
    } else if (status != 200) {
        throw new HttpException("Received an unexpected HTTP status ("
                + status + ") for " + url, status, url);
    }

    InjectableValues inject = new JsonInjector(locales, null, null);

    HttpEntity entity = response.getEntity();
    try {
        return mapper.readerFor(cls).with(inject).readValue(entity.getContent());
    } catch (IOException e) {
        throw new GeoIp2Exception(
                "Received a 200 response but could not decode it as JSON", e);
    } finally {
        EntityUtils.consume(entity);
    }
}
 
Example #11
Source File: TestISPEnrichIP.java    From nifi with Apache License 2.0 6 votes vote down vote up
private IspResponse getIspResponse(final String ipAddress) throws Exception {
    final String maxMindIspResponse = "{\n" +
        "         \"isp\" : \"Apache NiFi - Test ISP\",\n" +
        "         \"organization\" : \"Apache NiFi - Test Organization\",\n" +
        "         \"autonomous_system_number\" : 1337,\n" +
        "         \"autonomous_system_organization\" : \"Apache NiFi - Test Chocolate\", \n" +
        "         \"ip_address\" : \"" + ipAddress + "\"\n" +
        "      }\n";

    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


    return new ObjectMapper().readerFor(IspResponse.class).with(inject).readValue(maxMindIspResponse);

}
 
Example #12
Source File: DatabaseReader.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private DatabaseReader(Builder builder) throws IOException {
    if (builder.stream != null) {
        this.reader = new Reader(builder.stream);
    } else if (builder.database != null) {
        this.reader = new Reader(builder.database, builder.mode);
    } else {
        // This should never happen. If it does, review the Builder class
        // constructors for errors.
        throw new IllegalArgumentException(
                "Unsupported Builder configuration: expected either File or URL");
    }
    this.om = new ObjectMapper();
    this.om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            false);
    this.om.configure(
            DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    InjectableValues inject = new InjectableValues.Std().addValue(
            "locales", builder.locales);
    this.om.setInjectableValues(inject);
}
 
Example #13
Source File: JacksonInjectUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenDeserializingUsingJacksonInject_thenCorrect() throws IOException {

    UUID id = UUID.fromString("9616dc8c-bad3-11e6-a4a6-cec0c932ce01");

    // arrange
    String authorJson = "{\"firstName\": \"Alex\", \"lastName\": \"Theedom\"}";

    // act
    InjectableValues inject = new InjectableValues.Std().addValue(UUID.class, id);
    Author author = new ObjectMapper().reader(inject).forType(Author.class).readValue(authorJson);

    // assert
    assertThat(author.getId()).isEqualTo(id);


    /*
        {
          "firstName": "Alex",
          "lastName": "Theedom",
          "publications": []
        }
    */

}
 
Example #14
Source File: GeoEnrichTestUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static CityResponse getFullCityResponse() throws Exception {
    // Taken from MaxMind unit tests.
    final String maxMindCityResponse = "{\"city\":{\"confidence\":76,"
            + "\"geoname_id\":9876,\"names\":{\"en\":\"Minneapolis\""
            + "}},\"continent\":{\"code\":\"NA\","
            + "\"geoname_id\":42,\"names\":{" + "\"en\":\"North America\""
            + "}},\"country\":{\"confidence\":99,"
            + "\"iso_code\":\"US\",\"geoname_id\":1,\"names\":{"
            + "\"en\":\"United States of America\"" + "}" + "},"
            + "\"location\":{" + "\"accuracy_radius\":1500,"
            + "\"latitude\":44.98," + "\"longitude\":93.2636,"
            + "\"metro_code\":765," + "\"time_zone\":\"America/Chicago\""
            + "}," + "\"postal\":{\"confidence\": 33, \"code\":\"55401\"},"
            + "\"registered_country\":{" + "\"geoname_id\":2,"
            + "\"iso_code\":\"CA\"," + "\"names\":{" + "\"en\":\"Canada\""
            + "}" + "}," + "\"represented_country\":{" + "\"geoname_id\":3,"
            + "\"iso_code\":\"GB\"," + "\"names\":{"
            + "\"en\":\"United Kingdom\"" + "}," + "\"type\":\"C<military>\""
            + "}," + "\"subdivisions\":[{" + "\"confidence\":88,"
            + "\"geoname_id\":574635," + "\"iso_code\":\"MN\"," + "\"names\":{"
            + "\"en\":\"Minnesota\"" + "}" + "}," + "{\"iso_code\":\"TT\"}],"
            + "\"traits\":{" + "\"autonomous_system_number\":1234,"
            + "\"autonomous_system_organization\":\"AS Organization\","
            + "\"domain\":\"example.com\"," + "\"ip_address\":\"1.2.3.4\","
            + "\"is_anonymous_proxy\":true,"
            + "\"is_satellite_provider\":true," + "\"isp\":\"Comcast\","
            + "\"organization\":\"Blorg\"," + "\"user_type\":\"college\""
            + "}," + "\"maxmind\":{\"queries_remaining\":11}" + "}";

    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return new ObjectMapper().reader(CityResponse.class).with(inject).readValue(maxMindCityResponse);
}
 
Example #15
Source File: GeoEnrichTestUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static CityResponse getNullLatAndLongCityResponse() throws Exception {
    // Taken from MaxMind unit tests and modified.
    final String maxMindCityResponse = "{" + "\"city\":{" + "\"confidence\":76,"
            + "\"geoname_id\":9876," + "\"names\":{" + "\"en\":\"Minneapolis\""
            + "}" + "}," + "\"continent\":{" + "\"code\":\"NA\","
            + "\"geoname_id\":42," + "\"names\":{" + "\"en\":\"North America\""
            + "}" + "}," + "\"country\":{" + "\"confidence\":99,"
            + "\"iso_code\":\"US\"," + "\"geoname_id\":1," + "\"names\":{"
            + "\"en\":\"United States of America\"" + "}" + "},"
            + "\"location\":{" + "\"accuracy_radius\":1500,"
            + "\"metro_code\":765," + "\"time_zone\":\"America/Chicago\""
            + "}," + "\"postal\":{\"confidence\": 33, \"code\":\"55401\"},"
            + "\"registered_country\":{" + "\"geoname_id\":2,"
            + "\"iso_code\":\"CA\"," + "\"names\":{" + "\"en\":\"Canada\""
            + "}" + "}," + "\"represented_country\":{" + "\"geoname_id\":3,"
            + "\"iso_code\":\"GB\"," + "\"names\":{"
            + "\"en\":\"United Kingdom\"" + "}," + "\"type\":\"C<military>\""
            + "}," + "\"subdivisions\":[{" + "\"confidence\":88,"
            + "\"geoname_id\":574635," + "\"iso_code\":\"MN\"," + "\"names\":{"
            + "\"en\":\"Minnesota\"" + "}" + "}," + "{\"iso_code\":\"TT\"}],"
            + "\"traits\":{" + "\"autonomous_system_number\":1234,"
            + "\"autonomous_system_organization\":\"AS Organization\","
            + "\"domain\":\"example.com\"," + "\"ip_address\":\"1.2.3.4\","
            + "\"is_anonymous_proxy\":true,"
            + "\"is_satellite_provider\":true," + "\"isp\":\"Comcast\","
            + "\"organization\":\"Blorg\"," + "\"user_type\":\"college\""
            + "}," + "\"maxmind\":{\"queries_remaining\":11}" + "}";

    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return new ObjectMapper().reader(CityResponse.class).with(inject).readValue(maxMindCityResponse);
}
 
Example #16
Source File: ResultModuleTest.java    From testrail-api-java-client with MIT License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void G_noCustomResultFields_W_resultStringWithCustomStepResultsField_T_exception() throws IOException {
    // GIVEN
    List<CaseField> resultFields = Collections.emptyList();

    // WHEN
    objectMapper.reader(Result.class).with(new InjectableValues.Std().addValue(Result.class.toString(), resultFields)).readValue(this.getClass().getResourceAsStream("/result_with_step_result_field_set.json"));
}
 
Example #17
Source File: BucketConfigParser.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a raw configuration into a {@link BucketConfig}.
 *
 * @param input the raw string input.
 * @param env the environment to use.
 * @param origin the origin of the configuration. If null / none provided then localhost is assumed.
 * @return the parsed bucket configuration.
 */
public static BucketConfig parse(final String input, final ConfigParserEnvironment env, final String origin) {
    try {
        InjectableValues inject = new InjectableValues.Std()
                .addValue("env", env)
                .addValue("origin", origin == null ? "127.0.0.1" : origin);
        return DefaultObjectMapper.reader()
                .forType(BucketConfig.class)
                .with(inject)
                .with(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
                .readValue(input);
    } catch (IOException e) {
        throw new CouchbaseException("Could not parse configuration", e);
    }
}
 
Example #18
Source File: TestISPEnrichIP.java    From nifi with Apache License 2.0 5 votes vote down vote up
private IspResponse getIspResponseWithoutASNDetail(final String ipAddress) throws Exception {
    final String maxMindIspResponse = "{\n" +
        "         \"isp\" : \"Apache NiFi - Test ISP\",\n" +
        "         \"organization\" : \"Apache NiFi - Test Organization\",\n" +
        "         \"autonomous_system_number\" : null,\n" +
        "         \"ip_address\" : \"" + ipAddress + "\"\n" +
        "      }\n";

    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


    return new ObjectMapper().readerFor(IspResponse.class).with(inject).readValue(maxMindIspResponse);
}
 
Example #19
Source File: IndexV1Updater.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the standard {@link ObjectMapper} instance used for parsing {@code index-v1.json}.
 * This ignores unknown properties so that old releases won't crash when new things are
 * added to {@code index-v1.json}.  This is required for both forward compatibility,
 * but also because ignoring such properties when coming from a malicious server seems
 * reasonable anyway.
 */
public static ObjectMapper getObjectMapperInstance(long repoId) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.setInjectableValues(new InjectableValues.Std().addValue("repoId", repoId));
    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY);
    return mapper;
}
 
Example #20
Source File: TestDefaultIndexInfoBuilder.java    From suro with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreation() throws IOException {
    String desc = "{\n" +
            "    \"type\": \"default\",\n" +
            "    \"indexTypeMap\":{\"routingkey1\":\"index1:type1\", \"routingkey2\":\"index2:type2\"},\n" +
            "    \"idFields\":{\"routingkey\": [\"f1\", \"f2\", \"ts_minute\"]},\n" +
            "    \"timestamp\": {\"field\":\"ts\"},\n" +
            "    \"indexSuffixFormatter\":{\"type\": \"date\", \"properties\":{\"dateFormat\":\"YYYYMMdd\"}}\n" +
            "}";
    jsonMapper.setInjectableValues(new InjectableValues() {
                @Override
                public Object findInjectableValue(
                        Object valueId,
                        DeserializationContext ctxt,
                        BeanProperty forProperty,
                        Object beanInstance
                ) {
                    if (valueId.equals(ObjectMapper.class.getCanonicalName())) {
                        return jsonMapper;
                    } else {
                        return null;
                    }
                }
            });
    DateTime dt = new DateTime("2014-10-12T12:12:12.000Z");

    Map<String, Object> msg = new ImmutableMap.Builder<String, Object>()
            .put("f1", "v1")
            .put("f2", "v2")
            .put("f3", "v3")
            .put("ts", dt.getMillis())
            .build();
    IndexInfoBuilder builder = jsonMapper.readValue(desc, new TypeReference<IndexInfoBuilder>(){});
    IndexInfo info = builder.create(new Message("routingkey", jsonMapper.writeValueAsBytes(msg)));
    assertEquals(info.getId(), ("v1v2" + dt.getMillis() / 60000));
}
 
Example #21
Source File: JacksonAnnotationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException {
    final String json = "{\"name\":\"My bean\"}";
    final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1);

    final BeanWithInject bean = new ObjectMapper().reader(inject)
        .forType(BeanWithInject.class)
        .readValue(json);
    assertEquals("My bean", bean.name);
    assertEquals(1, bean.id);
}
 
Example #22
Source File: DigdagClient.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper objectMapper()
{
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new JacksonTimeModule());
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    // InjectableValues makes @JacksonInject work which is used at io.digdag.client.config.Config.<init>
    InjectableValues.Std injects = new InjectableValues.Std();
    injects.addValue(ObjectMapper.class, mapper);
    mapper.setInjectableValues(injects);

    return mapper;
}
 
Example #23
Source File: TestKafkaSink.java    From suro with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startup() {
    jsonMapper.registerSubtypes(new NamedType(KafkaSink.class, "kafka"));
    jsonMapper.setInjectableValues(new InjectableValues() {
        @Override
        public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) {
            if (valueId.equals(KafkaRetentionPartitioner.class.getName())) {
                return new KafkaRetentionPartitioner();
            } else {
                return null;
            }
        }
    });
}
 
Example #24
Source File: PhysicalPlanReader.java    From Bats with Apache License 2.0 5 votes vote down vote up
public PhysicalPlanReader(DrillConfig config, ScanResult scanResult, LogicalPlanPersistence lpPersistance,
                          final DrillbitEndpoint endpoint, final StoragePluginRegistry pluginRegistry) {

  ObjectMapper lpMapper = lpPersistance.getMapper();

  // Endpoint serializer/deserializer.
  SimpleModule serDeModule = new SimpleModule("PhysicalOperatorModule")
      .addSerializer(DrillbitEndpoint.class, new DrillbitEndpointSerDe.Se())
      .addDeserializer(DrillbitEndpoint.class, new DrillbitEndpointSerDe.De())
      .addSerializer(MajorType.class, new MajorTypeSerDe.Se())
      .addDeserializer(MajorType.class, new MajorTypeSerDe.De())
      .addDeserializer(DynamicPojoRecordReader.class,
          new StdDelegatingDeserializer<>(new DynamicPojoRecordReader.Converter(lpMapper)))
      .addSerializer(Path.class, new PathSerDe.Se());

  lpMapper.registerModule(serDeModule);
  Set<Class<? extends PhysicalOperator>> subTypes = PhysicalOperatorUtil.getSubTypes(scanResult);
  subTypes.forEach(lpMapper::registerSubtypes);
  lpMapper.registerSubtypes(DynamicPojoRecordReader.class);
  InjectableValues injectables = new InjectableValues.Std()
      .addValue(StoragePluginRegistry.class, pluginRegistry)
      .addValue(DrillbitEndpoint.class, endpoint);

  this.mapper = lpMapper;
  this.physicalPlanReader = mapper.readerFor(PhysicalPlan.class).with(injectables);
  this.operatorReader = mapper.readerFor(PhysicalOperator.class).with(injectables);
  this.logicalPlanReader = mapper.readerFor(LogicalPlan.class).with(injectables);
}
 
Example #25
Source File: JsonTest.java    From GeoIP2-java with Apache License 2.0 5 votes vote down vote up
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.readerFor(cls).with(inject).readValue(json);

    JsonNode expectedNode = mapper.readValue(json, JsonNode.class);
    JsonNode actualNode = mapper.readValue(response.toJson(), JsonNode.class);

    assertEquals(expectedNode, actualNode);
}
 
Example #26
Source File: TestGeoEnrichIP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private CityResponse getFullCityResponse() throws Exception {
    // Taken from MaxMind unit tests.
    final String maxMindCityResponse = "{" + "\"city\":{" + "\"confidence\":76,"
        + "\"geoname_id\":9876," + "\"names\":{" + "\"en\":\"Minneapolis\""
        + "}" + "}," + "\"continent\":{" + "\"code\":\"NA\","
        + "\"geoname_id\":42," + "\"names\":{" + "\"en\":\"North America\""
        + "}" + "}," + "\"country\":{" + "\"confidence\":99,"
        + "\"iso_code\":\"US\"," + "\"geoname_id\":1," + "\"names\":{"
        + "\"en\":\"United States of America\"" + "}" + "},"
        + "\"location\":{" + "\"accuracy_radius\":1500,"
        + "\"latitude\":44.98," + "\"longitude\":93.2636,"
        + "\"metro_code\":765," + "\"time_zone\":\"America/Chicago\""
        + "}," + "\"postal\":{\"confidence\": 33, \"code\":\"55401\"},"
        + "\"registered_country\":{" + "\"geoname_id\":2,"
        + "\"iso_code\":\"CA\"," + "\"names\":{" + "\"en\":\"Canada\""
        + "}" + "}," + "\"represented_country\":{" + "\"geoname_id\":3,"
        + "\"iso_code\":\"GB\"," + "\"names\":{"
        + "\"en\":\"United Kingdom\"" + "}," + "\"type\":\"C<military>\""
        + "}," + "\"subdivisions\":[{" + "\"confidence\":88,"
        + "\"geoname_id\":574635," + "\"iso_code\":\"MN\"," + "\"names\":{"
        + "\"en\":\"Minnesota\"" + "}" + "}," + "{\"iso_code\":\"TT\"}],"
        + "\"traits\":{" + "\"autonomous_system_number\":1234,"
        + "\"autonomous_system_organization\":\"AS Organization\","
        + "\"domain\":\"example.com\"," + "\"ip_address\":\"1.2.3.4\","
        + "\"is_anonymous_proxy\":true,"
        + "\"is_satellite_provider\":true," + "\"isp\":\"Comcast\","
        + "\"organization\":\"Blorg\"," + "\"user_type\":\"college\""
        + "}," + "\"maxmind\":{\"queries_remaining\":11}" + "}";

    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return new ObjectMapper().reader(CityResponse.class).with(inject).readValue(maxMindCityResponse);
}
 
Example #27
Source File: TestGeoEnrichIP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private CityResponse getNullLatAndLongCityResponse() throws Exception {
    // Taken from MaxMind unit tests and modified.
    final String maxMindCityResponse = "{" + "\"city\":{" + "\"confidence\":76,"
        + "\"geoname_id\":9876," + "\"names\":{" + "\"en\":\"Minneapolis\""
        + "}" + "}," + "\"continent\":{" + "\"code\":\"NA\","
        + "\"geoname_id\":42," + "\"names\":{" + "\"en\":\"North America\""
        + "}" + "}," + "\"country\":{" + "\"confidence\":99,"
        + "\"iso_code\":\"US\"," + "\"geoname_id\":1," + "\"names\":{"
        + "\"en\":\"United States of America\"" + "}" + "},"
        + "\"location\":{" + "\"accuracy_radius\":1500,"
        + "\"metro_code\":765," + "\"time_zone\":\"America/Chicago\""
        + "}," + "\"postal\":{\"confidence\": 33, \"code\":\"55401\"},"
        + "\"registered_country\":{" + "\"geoname_id\":2,"
        + "\"iso_code\":\"CA\"," + "\"names\":{" + "\"en\":\"Canada\""
        + "}" + "}," + "\"represented_country\":{" + "\"geoname_id\":3,"
        + "\"iso_code\":\"GB\"," + "\"names\":{"
        + "\"en\":\"United Kingdom\"" + "}," + "\"type\":\"C<military>\""
        + "}," + "\"subdivisions\":[{" + "\"confidence\":88,"
        + "\"geoname_id\":574635," + "\"iso_code\":\"MN\"," + "\"names\":{"
        + "\"en\":\"Minnesota\"" + "}" + "}," + "{\"iso_code\":\"TT\"}],"
        + "\"traits\":{" + "\"autonomous_system_number\":1234,"
        + "\"autonomous_system_organization\":\"AS Organization\","
        + "\"domain\":\"example.com\"," + "\"ip_address\":\"1.2.3.4\","
        + "\"is_anonymous_proxy\":true,"
        + "\"is_satellite_provider\":true," + "\"isp\":\"Comcast\","
        + "\"organization\":\"Blorg\"," + "\"user_type\":\"college\""
        + "}," + "\"maxmind\":{\"queries_remaining\":11}" + "}";

    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return new ObjectMapper().reader(CityResponse.class).with(inject).readValue(maxMindCityResponse);
}
 
Example #28
Source File: PhysicalPlanReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public FragmentRoot readFragmentOperator(com.google.protobuf.ByteString json, FragmentCodec codec) throws JsonProcessingException, IOException {
  final InjectableValues.Std injectableValues = new InjectableValues.Std(new HashMap<>(injectables));
  PhysicalOperator op = readValue(mapper.readerFor(PhysicalOperator.class).with(injectableValues), json, codec);
  if(op instanceof FragmentRoot){
    return (FragmentRoot) op;
  }else{
    throw new UnsupportedOperationException(String.format("The provided json fragment doesn't have a FragmentRoot as its root operator.  The operator was %s.", op.getClass().getCanonicalName()));
  }
}
 
Example #29
Source File: ExceptionConverter.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
private static LineMessagingException applyInternal(final String requestId, final Response<?> response)
        throws IOException {
    final int code = response.code();
    final ResponseBody responseBody = response.errorBody();

    final ErrorResponse errorResponse = OBJECT_READER
            .with(new InjectableValues.Std(singletonMap("requestId", requestId)))
            .readValue(responseBody.byteStream());

    switch (code) {
        case 400:
            return new BadRequestException(
                    errorResponse.getMessage(), errorResponse);
        case 401:
            return new UnauthorizedException(
                    errorResponse.getMessage(), errorResponse);
        case 403:
            return new ForbiddenException(
                    errorResponse.getMessage(), errorResponse);
        case 404:
            return new NotFoundException(
                    errorResponse.getMessage(), errorResponse);
        case 429:
            return new TooManyRequestsException(
                    errorResponse.getMessage(), errorResponse);
        case 500:
            return new LineServerException(
                    errorResponse.getMessage(), errorResponse);
    }

    return new GeneralLineMessagingException(errorResponse.getMessage(), errorResponse, null);
}
 
Example #30
Source File: ResultModuleTest.java    From testrail-api-java-client with MIT License 5 votes vote down vote up
@Test
public void G_customResultFieldStepResults_W_resultStringWithCustomStepResultsField_T_correctDeserializationAndStepResultsField() throws IOException {
    // GIVEN
    ResultField stepResultField = objectMapper.readValue(this.getClass().getResourceAsStream("/step_result_field.json"), ResultField.class);
    List<ResultField> resultFields = Collections.singletonList(stepResultField);

    // WHEN
    Result actualResult = objectMapper.reader(Result.class).with(new InjectableValues.Std().addValue(Result.class.toString(), resultFields)).readValue(this.getClass().getResourceAsStream("/result_with_step_result_field_set.json"));

    // THEN
    List<Field.StepResult> stepResults = Arrays.asList(new Field.StepResult().setContent("Step 1").setExpected("Expected 1").setActual("Expected 2").setStatusId(4), new Field.StepResult().setContent("Step 2").setExpected("Expected 2").setActual("Unexpected").setStatusId(3));
    Result expectedResult = new Result().setId(11).setTestId(48).setStatusId(1).setCreatedBy(1).setCreatedOn(new Date(1425687075000L)).addCustomField("step_results", stepResults);
    assertEquals(expectedResult, actualResult);
}