protected XmlMapper getXmlMapper() { final XmlMapper xmlMapper = new XmlMapper( new XmlFactory(new InputFactoryImpl(), new OutputFactoryImpl()), new JacksonXmlModule()); xmlMapper.setInjectableValues(new InjectableValues.Std().addValue(ODataClient.class, client)); xmlMapper.addHandler(new DeserializationProblemHandler() { @Override public boolean handleUnknownProperty(final DeserializationContext ctxt, final JsonParser jp, final JsonDeserializer<?> deserializer, final Object beanOrClass, final String propertyName) throws IOException, JsonProcessingException { // skip any unknown property LOG.warn("Skipping unknown property {}", propertyName); ctxt.getParser().skipChildren(); return true; } }); return xmlMapper; }
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; }
public PhysicalPlanReader(DrillConfig config, ObjectMapper mapper, final DrillbitEndpoint endpoint, final StoragePluginRegistry pluginRegistry) { // Endpoint serializer/deserializer. SimpleModule deserModule = 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()); mapper.registerModule(deserModule); mapper.registerSubtypes(PhysicalOperatorUtil.getSubTypes(config)); InjectableValues injectables = new InjectableValues.Std() // .addValue(StoragePluginRegistry.class, pluginRegistry) // .addValue(DrillbitEndpoint.class, endpoint); // this.mapper = mapper; this.physicalPlanReader = mapper.reader(PhysicalPlan.class).with(injectables); this.operatorReader = mapper.reader(PhysicalOperator.class).with(injectables); this.logicalPlanReader = mapper.reader(LogicalPlan.class).with(injectables); }
@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); }
@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; }
@Test public void shouldLoadConfigWithIPv6() throws Exception { assumeFalse(NetworkAddress.FORCE_IPV4); String raw = Resources.read("memcached_with_ipv6.json", getClass()); InjectableValues inject = new InjectableValues.Std() .addValue("env", environment); MemcachedBucketConfig config = JSON_MAPPER.readerFor(MemcachedBucketConfig.class).with(inject).readValue(raw); assertEquals(2, config.nodes().size()); for (Map.Entry<Long, NodeInfo> node : config.ketamaNodes().entrySet()) { String hostname = node.getValue().hostname().address(); assertTrue(hostname.equals("fd63:6f75:6368:2068:1471:75ff:fe25:a8be") || hostname.equals("fd63:6f75:6368:2068:c490:b5ff:fe86:9cf7")); assertTrue(node.getValue().services().containsKey(ServiceType.BINARY)); } }
public static void main(String[] args) throws Exception { final Nexus nexus = new Nexus(); ObjectMapper mapper = new XmlMapper(); mapper.setInjectableValues(new InjectableValues() { @Override public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) { if (Nexus.class.getName().equals(valueId)) { return nexus; } return null; } }); File src = new File(args[0]).getCanonicalFile(); System.out.format("Using test configuration %s\n", src); PerformanceTest test = mapper.readValue(src, PerformanceTest.class); test.run(); System.out.println("Exit"); System.exit(0); }
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); 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); } }
/** * 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; }
public PhysicalPlanReader(SabotConfig config, ScanResult scanResult, LogicalPlanPersistence lpPersistance, final NodeEndpoint endpoint, final StoragePluginRegistry pluginRegistry, SabotContext context) { this.lpPersistance = lpPersistance; // Endpoint serializer/deserializer. final SimpleModule deserModule = new SimpleModule("PhysicalOperatorModule") .addSerializer(NodeEndpoint.class, new NodeEndpointSerDe.Se()) .addDeserializer(NodeEndpoint.class, new NodeEndpointSerDe.De()) .addSerializer(MajorType.class, new MajorTypeSerDe.Se()) .addSerializer(ByteString.class, new ByteStringSer()) .addDeserializer(ByteString.class, new ByteStringDeser()) .addDeserializer(MajorType.class, new MajorTypeSerDe.De()); final ObjectMapper lpMapper = lpPersistance.getMapper(); lpMapper.registerModule(deserModule); Set<Class<? extends PhysicalOperator>> subTypes = PhysicalOperatorUtil.getSubTypes(scanResult); for (Class<? extends PhysicalOperator> subType : subTypes) { lpMapper.registerSubtypes(subType); } final InjectableValues injectables = new InjectableValues.Std() .addValue(StoragePluginRegistry.class, pluginRegistry) .addValue(SabotContext.class, context) .addValue(NodeEndpoint.class, endpoint); this.mapper = lpMapper; this.physicalPlanReader = mapper.readerFor(PhysicalPlan.class).with(injectables); this.optionListReader = mapper.readerFor(OptionList.class).with(injectables); this.operatorReader = mapper.readerFor(PhysicalOperator.class).with(injectables); }
private <X> X check(final InputStream stream, final Class<X> type) throws IOException, JsonParseException, JsonMappingException, JsonProcessingException { final InjectableValues.Std injectableValues = new InjectableValues.Std(); for (final String key : this.injectionValues.keySet()) { injectableValues.addValue(key, this.injectionValues.get(key)); } return this.mapper.readerFor(type).with(injectableValues).readValue(stream); }
private <X> X read(final InputStream stream, final Class<X> type) throws IOException, JsonParseException, JsonMappingException, JsonProcessingException { final InjectableValues.Std injectableValues = new InjectableValues.Std(); for (final String key : this.injectionValues.keySet()) { injectableValues.addValue(key, this.injectionValues.get(key)); } return this.mapper.readerFor(type).with(injectableValues).readValue(stream); }
/** * Reads config from a location * * @param location location of config * @return this * @throws IOException */ public ConfigBuilder from(URI location) throws IOException { InjectableValues inject = new InjectableValues.Std() .addValue("location", location); addConfig(new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true) .setInjectableValues(inject).readValue(location.toURL(), Config.class)); return this; }
/** * Reads config from a reader * * @param reader reader containing JSON config * @return this * @throws IOException */ public ConfigBuilder from(Reader reader) throws IOException { InjectableValues inject = new InjectableValues.Std() .addValue("location", null); addConfig(new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true) .setInjectableValues(inject).readValue(reader, Config.class)); return this; }
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); }
public PhysicalPlanReader(DrillConfig config, ScanResult scanResult, LogicalPlanPersistence lpPersistance, final DrillbitEndpoint endpoint, final StoragePluginRegistry pluginRegistry) { ObjectMapper lpMapper = lpPersistance.getMapper(); // Endpoint serializer/deserializer. SimpleModule deserModule = 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))); lpMapper.registerModule(deserModule); Set<Class<? extends PhysicalOperator>> subTypes = PhysicalOperatorUtil.getSubTypes(scanResult); for (Class<? extends PhysicalOperator> subType : subTypes) { lpMapper.registerSubtypes(subType); } lpMapper.registerSubtypes(DynamicPojoRecordReader.class); InjectableValues injectables = new InjectableValues.Std() // .addValue(StoragePluginRegistry.class, pluginRegistry) // .addValue(DrillbitEndpoint.class, endpoint); // this.mapper = lpMapper; this.physicalPlanReader = mapper.reader(PhysicalPlan.class).with(injectables); this.operatorReader = mapper.reader(PhysicalOperator.class).with(injectables); this.logicalPlanReader = mapper.reader(LogicalPlan.class).with(injectables); }
private <T> T handleResponse(CloseableHttpResponse response, URL url, Class<T> cls) throws MinFraudException, 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); } HttpEntity entity = response.getEntity(); if (entity.getContentLength() <= 0L) { throw new HttpException("Received a 200 response for " + url + " but there was no message body.", 200, url); } InjectableValues inject = new Std().addValue( "locales", locales); try { return mapper.readerFor(cls).with(inject).readValue(entity.getContent()); } catch (IOException e) { throw new MinFraudException( "Received a 200 response but could not decode it as JSON", e); } finally { EntityUtils.consume(entity); } }
@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); }
@Before public void before() throws IOException { document = new BeanWrapper<ReactiveEntity>(entity); when(serializedEntity.content()).thenReturn("{json}"); when(mapper.reader(reference)).thenReturn(reader); when(reader.with(any(InjectableValues.Std.class))).thenReturn(reader); when(reader.readValue(anyString())).thenReturn(document); deserializer = new JacksonDeserializer<ReactiveEntity>(mapper, reference); }
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; }
@Override public <T> T unmarshall(BsonDocument document, Class<T> clazz, InjectableValues cache) { try { return mapping.getReader(clazz).with(cache).readValue(document.toByteArray(), 0, document.getSize()); } catch (IOException e) { String message = String.format("Unable to unmarshall result to %s from content %s", clazz, document.toString()); throw new MarshallingException(message, e); } }
@Override public <T> T unmarshall(BsonDocument document, T toUpdate, InjectableValues cache) { try{ return mapping.getReader(toUpdate.getClass()).with(cache).withValueToUpdate(toUpdate).readValue(document.toByteArray(), 0, document.getSize()); } catch (IOException e) { String message = String.format("Unable to unmarshall result to %s from content %s", toUpdate.getClass(), document.toString()); throw new MarshallingException(message, e); } }
@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; }
/** * This exists only for use by {@link JacksonSerializationM} */ /* package-private */ Builder withInjectionBindings(AnnotationIntrospector annotationIntrospector, InjectableValues injectableValues) { final Builder ret = copy(); ret.annotationIntrospector = checkNotNull(annotationIntrospector); ret.injectableValues = checkNotNull(injectableValues); return ret; }
protected ObjectMapper getObjectMapper() { final ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setInjectableValues(new InjectableValues.Std().addValue(ODataClient.class, client)); mapper.setSerializerProvider(new InjectableSerializerProvider(mapper.getSerializerProvider(), mapper.getSerializationConfig().withAttribute(ODataClient.class, client), mapper.getSerializerFactory())); return mapper; }
/** * Parse a raw configuration into a {@link BucketConfig}. * * @param input the raw string input. * @return the parsed bucket configuration. */ public static BucketConfig parse(final String input, final ConfigParserEnvironment env) { try { InjectableValues inject = new InjectableValues.Std() .addValue("env", env); return jackson().readerFor(BucketConfig.class).with(inject).readValue(input); } catch (IOException e) { throw new CouchbaseException("Could not parse configuration", e); } }
/** * The config loaded has 4 nodes, but only two are data nodes. This tests checks that the ketama * nodes are only populated for those two nodes which include the binary service type. */ @Test public void shouldOnlyUseDataNodesForKetama() throws Exception { String raw = Resources.read("memcached_mixed_sherlock.json", getClass()); InjectableValues inject = new InjectableValues.Std() .addValue("env", environment); MemcachedBucketConfig config = JSON_MAPPER.readerFor(MemcachedBucketConfig.class).with(inject).readValue(raw); assertEquals(4, config.nodes().size()); for (Map.Entry<Long, NodeInfo> node : config.ketamaNodes().entrySet()) { String hostname = node.getValue().hostname().address(); assertTrue(hostname.equals("192.168.56.101") || hostname.equals("192.168.56.102")); assertTrue(node.getValue().services().containsKey(ServiceType.BINARY)); } }
public static void main(String[] args) throws Exception { final Nexus nexus = new Nexus(); ObjectMapper mapper = new XmlMapper(); mapper.setInjectableValues(new InjectableValues() { @Override public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) { if (Nexus.class.getName().equals(valueId)) { return nexus; } return null; } }); File src = new File(args[0]).getCanonicalFile(); String name = src.getName().substring(0, src.getName().lastIndexOf(".")); Collection<ClientSwarm> swarms = mapper.readValue(src, PerformanceTest.class).getSwarms(); List<Metric> metrics = new ArrayList<>(); for (ClientSwarm swarm : swarms) { metrics.add(swarm.getMetric()); } System.out.println("Test " + name + " metrics:" + metrics); assertTest(name, metrics); System.out.println("Exit"); System.exit(0); }
private FeatureCollection load(InputStream countryInfo, InputStream shapes) throws IOException { Map<String, Country> countries = Country.load(new InputStreamReader(countryInfo, UTF_8)); InjectableValues injectables = new InjectableValues.Std().addValue(Map.class, countries); return new ObjectMapper() .readerFor(FeatureCollection.class) .with(injectables) .readValue(shapes); }
@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)); }
@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; } } }); }
protected <T extends AbstractResponse> void testRoundTrip (Class<T> cls, String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, false); InjectableValues inject = new InjectableValues.Std().addValue( "locales", Collections.singletonList("en")); T response = mapper.reader(cls).with(inject).readValue(json); JsonNode expectedNode = mapper.readValue(json, JsonNode.class); JsonNode actualNode = mapper.readValue(response.toJson(), JsonNode.class); assertEquals(expectedNode, actualNode); }
public CurentNameInjectable(InjectableValues delegate) { super(); this.delegate = delegate; }
@Override public CloseableRecordBatch getBatch(FragmentContext context, DynamoSubScan subScan, List<RecordBatch> children) throws ExecutionSetupException { Preconditions.checkArgument(children.isEmpty()); List<RecordReader> readers = Lists.newArrayList(); List<SchemaPath> columns = subScan.getColumns(); ClientProperties clientProps = subScan.getClient(); ClientConfiguration client = clientProps.getConfiguration(); AWSCredentialsProvider credentials = subScan.getCredentials(); DynamoEndpoint endpoint = subScan.getEndpoint(); DynamoTableDefinition table = subScan.getTable(); DynamoKeyMapper key = null; if (table.getKeyMapper() != null) { DynamoKeyMapperSpec spec = table.getKeyMapper(); Map<String, Object> args = spec.getArgs(); ObjectMapper mapper = new ObjectMapper(); try { String argString = mapper.writeValueAsString(args); InjectableValues inject = new InjectableValues.Std() .addValue(DynamoKeyMapperSpec.class, spec); key = mapper.setInjectableValues(inject).readValue(argString, DynamoKeyMapper.class); } catch (IOException e) { throw new ExecutionSetupException(e); } } for (DynamoSubReadSpec scanSpec : subScan.getSpecs()) { try { DynamoRecordReader reader; if (scanSpec instanceof DynamoSubGetSpec) { reader = new DynamoGetRecordReader(credentials, client, endpoint, (DynamoSubGetSpec) scanSpec, columns, clientProps.getConsistentRead(), table); } else if (scanSpec instanceof DynamoSubQuerySpec) { reader = new DynamoQueryRecordReader(credentials, client, endpoint, (DynamoSubQuerySpec) scanSpec, columns, clientProps.getConsistentRead(), subScan.getScanProps(), table); } else { reader = new DynamoScanRecordReader(credentials, client, endpoint, (DynamoSubScanSpec) scanSpec, columns, clientProps.getConsistentRead(), subScan.getScanProps(), table); } if (key != null) { reader.setKeyMapper(key); } readers.add(reader); } catch (Exception e1) { throw new ExecutionSetupException(e1); } } return new ScanBatch(subScan, context, readers.iterator()); }