下面列出了怎么用com.fasterxml.jackson.databind.InjectableValues的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
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);
}
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));
}
/**
* 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);
}
}
@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;
}
@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);
}
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;
}
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);
}
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;
}
/**
* @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);
}
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);
}
@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": []
}
*/
}
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);
}
}
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);
}
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);
}
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);
}
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()));
}
}
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);
}
@SuppressWarnings("SpringJavaAutowiringInspection")
@Bean
@Primary
@Autowired
public ObjectMapper jacksonObjectMapper(final Jackson2ObjectMapperBuilder builder, final AuthenticationInformationRetriever<?, ?> authenticationInformationRetriever) {
final ObjectMapper mapper = builder.createXmlMapper(false)
.mixIn(Authentication.class, HodAuthenticationMixins.class)
.mixIn(HodQueryRestrictions.class, HodQueryRestrictionsMixin.class)
.build();
mapper.setInjectableValues(new InjectableValues.Std().addValue(AuthenticationInformationRetriever.class, authenticationInformationRetriever));
return mapper;
}
@Test(expected = IllegalArgumentException.class)
public void G_noCustomCaseFields_W_caseStringWithCustomStepsField_T_exception() throws IOException {
// GIVEN
List<CaseField> caseFields = Collections.emptyList();
// WHEN
objectMapper.reader(Case.class).with(new InjectableValues.Std().addValue(Case.class.toString(), caseFields)).readValue(this.getClass().getResourceAsStream("/case_with_step_field_set.json"));
}
@Test
public void G_noCustomCaseFields_W_caseStringWithNoCustomStepsField_T_correctDeserialization() throws IOException {
// GIVEN
List<CaseField> caseFields = Collections.emptyList();
// WHEN
Case actualCase = objectMapper.reader(Case.class).with(new InjectableValues.Std().addValue(Case.class.toString(), caseFields)).readValue(this.getClass().getResourceAsStream("/case_with_no_custom_fields.json"));
// THEN
Case expectedCase = new Case().setId(13).setTitle("Test Case 2").setSectionId(6).setTypeId(6).setPriorityId(4).setCreatedBy(1).setCreatedOn(new Date(1425683583000L)).setUpdatedBy(1).setUpdatedOn(new Date(1425845918000L)).setSuiteId(4);
assertEquals(expectedCase, actualCase);
}
@Test
public void G_customCaseFieldSteps_W_caseStringWithCustomStepsField_T_correctDeserializationAndStepsField() throws IOException {
// GIVEN
CaseField stepField = objectMapper.readValue(this.getClass().getResourceAsStream("/step_field.json"), CaseField.class);
List<CaseField> caseFields = Collections.singletonList(stepField);
// WHEN
Case actualCase = objectMapper.reader(Case.class).with(new InjectableValues.Std().addValue(Case.class.toString(), caseFields)).readValue(this.getClass().getResourceAsStream("/case_with_step_field_set.json"));
// THEN
List<Field.Step> steps = Arrays.asList(new Field.Step().setContent("Step 1").setExpected("Expected 1"), new Field.Step().setContent("Step 2").setExpected("Expected 2"));
Case expectedCase = new Case().setId(13).setTitle("Test Case 2").setSectionId(6).setTypeId(6).setPriorityId(4).setCreatedBy(1).setCreatedOn(new Date(1425683583000L)).setUpdatedBy(1).setUpdatedOn(new Date(1425845918000L)).setSuiteId(4).addCustomField("separated_steps", steps);
assertEquals(expectedCase, actualCase);
}
@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"));
}
@Test
public void G_noCustomResultFields_W_resultStringWithNoCustomResultsField_T_correctDeserialization() throws IOException {
// GIVEN
List<CaseField> resultFields = Collections.emptyList();
// WHEN
Result actualResult = objectMapper.reader(Result.class).with(new InjectableValues.Std().addValue(Result.class.toString(), resultFields)).readValue(this.getClass().getResourceAsStream("/result_with_no_custom_fields.json"));
// THEN
Result expectedResult = new Result().setId(11).setTestId(48).setStatusId(1).setCreatedBy(1).setCreatedOn(new Date(1425687075000L));
assertEquals(expectedResult, actualResult);
}
@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);
}
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;
}
/**
* 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;
}
/**
* 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);
}
}
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);
}
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);
}