List of usage examples for com.fasterxml.jackson.databind ObjectMapper convertValue
@SuppressWarnings("unchecked") public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException
From source file:com.yahoo.elide.graphql.GraphQLEndpoint.java
private Response buildErrorResponse(HttpStatusException error, boolean isVerbose) { ObjectMapper mapper = elide.getMapper().getObjectMapper(); JsonNode errorNode;/* ww w .j a v a 2 s. com*/ if (!(error instanceof CustomErrorException) && elideSettings.isReturnErrorObjects()) { ErrorObjects errors = ErrorObjects.builder().addError() .with("message", isVerbose ? error.getVerboseMessage() : error.toString()).build(); errorNode = mapper.convertValue(errors, JsonNode.class); } else { errorNode = isVerbose ? error.getVerboseErrorResponse().getRight() : error.getErrorResponse().getRight(); } String errorBody; try { errorBody = mapper.writeValueAsString(errorNode); } catch (JsonProcessingException e) { errorBody = errorNode.toString(); } return Response.status(error.getStatus()).entity(errorBody).build(); }
From source file:com.hortonworks.streamline.streams.catalog.topology.component.TopologyComponentFactory.java
private Map.Entry<String, Provider<StreamlineProcessor>> normalizationProcessorProvider() { Provider<StreamlineProcessor> provider = new Provider<StreamlineProcessor>() { @Override// w w w . j a v a 2s. co m public StreamlineProcessor create(TopologyComponent component) { Config config = component.getConfig(); Object typeObj = config.getAny(NormalizationProcessor.CONFIG_KEY_TYPE); Object normConfObj = config.getAny(NormalizationProcessor.CONFIG_KEY_NORMALIZATION); ObjectMapper objectMapper = new ObjectMapper(); NormalizationProcessor.Type type = objectMapper.convertValue(typeObj, NormalizationProcessor.Type.class); Map<String, NormalizationConfig> normConfig = objectMapper.convertValue(normConfObj, new TypeReference<Map<String, NormalizationConfig>>() { }); updateWithSchemas(component.getTopologyId(), component.getVersionId(), normConfig); Set<Stream> outputStreams = createOutputStreams((TopologyOutputComponent) component); if (outputStreams.size() != 1) { throw new IllegalArgumentException( "Normalization component [" + component + "] must have only one output stream"); } return new NormalizationProcessor(normConfig, outputStreams.iterator().next(), type); } }; return new SimpleImmutableEntry<>(NORMALIZATION, provider); }
From source file:org.apache.druid.segment.realtime.plumber.RealtimePlumberSchoolTest.java
@Before public void setUp() throws Exception { tmpDir = Files.createTempDir(); ObjectMapper jsonMapper = new DefaultObjectMapper(); schema = new DataSchema("test", jsonMapper .convertValue(/*from w w w .jav a2 s.c o m*/ new StringInputRowParser( new JSONParseSpec(new TimestampSpec("timestamp", "auto", null), new DimensionsSpec(null, null, null), null, null), null), Map.class), new AggregatorFactory[] { new CountAggregatorFactory("rows") }, new UniformGranularitySpec(Granularities.HOUR, Granularities.NONE, null), null, jsonMapper); schema2 = new DataSchema("test", jsonMapper .convertValue( new StringInputRowParser( new JSONParseSpec(new TimestampSpec("timestamp", "auto", null), new DimensionsSpec(null, null, null), null, null), null), Map.class), new AggregatorFactory[] { new CountAggregatorFactory("rows") }, new UniformGranularitySpec(Granularities.YEAR, Granularities.NONE, null), null, jsonMapper); announcer = EasyMock.createMock(DataSegmentAnnouncer.class); announcer.announceSegment(EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); segmentPublisher = EasyMock.createNiceMock(SegmentPublisher.class); dataSegmentPusher = EasyMock.createNiceMock(DataSegmentPusher.class); handoffNotifierFactory = EasyMock.createNiceMock(SegmentHandoffNotifierFactory.class); handoffNotifier = EasyMock.createNiceMock(SegmentHandoffNotifier.class); EasyMock.expect(handoffNotifierFactory.createSegmentHandoffNotifier(EasyMock.anyString())) .andReturn(handoffNotifier).anyTimes(); EasyMock.expect(handoffNotifier.registerSegmentHandoffCallback(EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.anyObject())).andReturn(true).anyTimes(); emitter = EasyMock.createMock(ServiceEmitter.class); EasyMock.replay(announcer, segmentPublisher, dataSegmentPusher, handoffNotifierFactory, handoffNotifier, emitter); tuningConfig = new RealtimeTuningConfig(1, null, null, null, null, new IntervalStartVersioningPolicy(), rejectionPolicy, null, null, null, true, 0, 0, false, null, null, null, null); realtimePlumberSchool = new RealtimePlumberSchool(emitter, new DefaultQueryRunnerFactoryConglomerate(Maps.newHashMap()), dataSegmentPusher, announcer, segmentPublisher, handoffNotifierFactory, MoreExecutors.sameThreadExecutor(), TestHelper.getTestIndexMergerV9(segmentWriteOutMediumFactory), TestHelper.getTestIndexIO(), MapCache.create(0), FireDepartmentTest.NO_CACHE_CONFIG, new CachePopulatorStats(), TestHelper.makeJsonMapper()); metrics = new FireDepartmentMetrics(); plumber = (RealtimePlumber) realtimePlumberSchool.findPlumber(schema, tuningConfig, metrics); }
From source file:uk.ac.cam.cl.dtg.segue.comm.EmailManager.java
/** * Method to take a random (potentially nested map) and flatten it into something where values can be easily extracted * for email templates./*www.java 2 s . c om*/ * * Nested fields are addressed as per json objects and separated with the dot operator. * * @param inputMap - A map of string to random object * @param outputMap - the flattened map which is also the returned object * @param keyPrefix - the key prefix - used for recursively creating the map key. * @return a flattened map for containing strings that can be used in email template replacement. */ public Map<String, String> flattenTokenMap(final Map<String, Object> inputMap, final Map<String, String> outputMap, String keyPrefix) { if (null == keyPrefix) { keyPrefix = ""; } for (Map.Entry<String, Object> mapEntry : inputMap.entrySet()) { String valueToStore = ""; if (mapEntry.getValue() == null) { valueToStore = ""; } else if (mapEntry.getValue() instanceof Map) { // if we have a general map we should recurse until we get objects we can do something with. this.flattenTokenMap((Map) mapEntry.getValue(), outputMap, keyPrefix + mapEntry.getKey() + "."); } else if (mapEntry.getValue() instanceof ContentDTO) { Map objectWithJavaTypes = new org.apache.commons.beanutils.BeanMap(mapEntry.getValue()); // go through and convert any known java types into our preferred string representation Map<String, String> temp = this.flattenTokenMap(objectWithJavaTypes, Maps.newHashMap(), keyPrefix + mapEntry.getKey() + "."); outputMap.putAll(temp); // now convert any java types we haven't defined specific conversions for into the basic Jackson serialisations. ObjectMapper om = new ObjectMapper(); this.flattenTokenMap(om.convertValue(mapEntry.getValue(), HashMap.class), outputMap, keyPrefix + mapEntry.getKey() + "."); } else { valueToStore = this.emailTokenValueMapper(mapEntry.getValue()); } if (valueToStore != null) { String existingValue = outputMap.get(keyPrefix + mapEntry.getKey()); if (existingValue != null && "".equals(existingValue) && !"".equals(valueToStore)) { // we can safely replace it with a better value outputMap.put(keyPrefix + mapEntry.getKey(), valueToStore); } // assume that the first entry into the output map is the correct one and only replace if something isn't already there outputMap.putIfAbsent(keyPrefix + mapEntry.getKey(), valueToStore); } } return outputMap; }
From source file:org.openecomp.sdnc.sli.aai.r1607.R1607AutoGeneratedTest.java
public void test04VceDataPost() { LOG.info("----------------------- Test: " + new Object() { }.getClass().getEnclosingMethod().getName() + " -----------------------"); try {//from www. j a v a 2s . c o m URL resource = this.getClass().getResource("/json/tails4.json"); LOG.info("Resource is " + resource.getFile()); File requestFile = new File(resource.getFile()); if (!requestFile.exists()) { fail("Test file does not exist"); } SvcLogicContext ctx = new SvcLogicContext(); ObjectMapper mapper = AAIService.getObjectMapper(); InventoryResponseItems request = mapper.readValue(requestFile, InventoryResponseItems.class); Map<String, Object> subnetsList = mapper.convertValue(request, Map.class); AAIDeclarations.class.cast(client).writeMap(subnetsList, "aaiTmp", ctx); assertNotNull(request); } catch (Exception e) { LOG.error("Caught exception", e); fail("Caught exception"); } }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.TestJsonNodeWritableUtils.java
@Test public void test_transform() { final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty()); new JsonNodeWritableUtils(); //coverage! assertEquals(NullNode.instance, JsonNodeWritableUtils.transform("banana", JsonNodeFactory.instance)); assertEquals(null, JsonNodeWritableUtils.transform(null, JsonNodeFactory.instance)); assertEquals(NullNode.instance,/* www . ja v a2 s .co m*/ JsonNodeWritableUtils.transform(NullWritable.get(), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(true, JsonNode.class), JsonNodeWritableUtils.transform(new BooleanWritable(true), JsonNodeFactory.instance)); assertEquals(mapper.convertValue("test", JsonNode.class), JsonNodeWritableUtils.transform(new Text("test"), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(new byte[] { (byte) 0xFF }, JsonNode.class), JsonNodeWritableUtils.transform(new ByteWritable((byte) 0xFF), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(4, JsonNode.class), JsonNodeWritableUtils.transform(new IntWritable(4), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(4, JsonNode.class), JsonNodeWritableUtils.transform(new VIntWritable(4), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(4L, JsonNode.class), JsonNodeWritableUtils.transform(new LongWritable(4), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(4L, JsonNode.class), JsonNodeWritableUtils.transform(new VLongWritable(4), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(new byte[] { (byte) 0xFF, (byte) 0xFE }, JsonNode.class), JsonNodeWritableUtils.transform(new BytesWritable(new byte[] { (byte) 0xFF, (byte) 0xFE }), JsonNodeFactory.instance)); assertEquals(mapper.convertValue(4.0, JsonNode.class), JsonNodeWritableUtils.transform(new DoubleWritable(4), JsonNodeFactory.instance)); //(had real trouble creating a float node!) assertEquals(JsonNodeFactory.instance.numberNode(Float.valueOf((float) 4.0)), JsonNodeWritableUtils.transform(new FloatWritable(4), JsonNodeFactory.instance)); // will test object writable and array writable below }
From source file:com.thinkbiganalytics.scheduler.QuartzScheduler.java
public Map<String, Object> getMetaData() throws JobSchedulerException { Map<String, Object> map = new HashMap<String, Object>(); try {//from w ww . j a v a2 s . c o m SchedulerMetaData metaData = getScheduler().getMetaData(); if (metaData != null) { ObjectMapper objectMapper = new ObjectMapper(); map = objectMapper.convertValue(metaData, Map.class); } } catch (IllegalArgumentException | SchedulerException e) { throw new JobSchedulerException(e); } return map; }
From source file:com.yahoo.elide.parsers.state.RecordTerminalState.java
private JsonNode getResponseBody(PersistentResource rec, RequestScope requestScope, ObjectMapper mapper) { Optional<MultivaluedMap<String, String>> queryParams = requestScope.getQueryParams(); JsonApiDocument jsonApiDocument = new JsonApiDocument(); //TODO Make this a document processor Data<Resource> data = rec == null ? null : new Data<>(rec.toResource()); jsonApiDocument.setData(data);//w ww . jav a 2 s . com //TODO Iterate over set of document processors DocumentProcessor includedProcessor = new IncludedProcessor(); includedProcessor.execute(jsonApiDocument, rec, queryParams); return mapper.convertValue(jsonApiDocument, JsonNode.class); }
From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java
/** Check if a new mapping based on a schema is equivalent to a mapping previously stored (from a schema) * @param stored_mapping/* w w w . j a va 2 s . c o m*/ * @param new_mapping * @param mapper * @return * @throws JsonProcessingException * @throws IOException */ protected static boolean mappingsAreEquivalent(final IndexTemplateMetaData stored_mapping, final JsonNode new_mapping, final ObjectMapper mapper) throws JsonProcessingException, IOException { final ObjectNode stored_json_mappings = StreamSupport.stream(stored_mapping.mappings().spliterator(), false) .reduce(mapper.createObjectNode(), Lambdas.wrap_u( (acc, kv) -> (ObjectNode) acc.setAll((ObjectNode) mapper.readTree(kv.value.string()))), (acc1, acc2) -> acc1); // (can't occur) final JsonNode new_json_mappings = Optional.ofNullable(new_mapping.get("mappings")) .orElse(mapper.createObjectNode()); final JsonNode stored_json_settings = mapper.convertValue(Optional.ofNullable(stored_mapping.settings()) .orElse(ImmutableSettings.settingsBuilder().build()).getAsMap(), JsonNode.class); final JsonNode new_json_settings = Optional.ofNullable(new_mapping.get("settings")) .orElse(mapper.createObjectNode()); final ObjectNode stored_json_aliases = StreamSupport .stream(Optional.ofNullable( stored_mapping.aliases()).orElse( ImmutableOpenMap.of()) .spliterator(), false) .reduce(mapper.createObjectNode(), Lambdas.wrap_u((acc, kv) -> (ObjectNode) acc.set(kv.key, kv.value.filteringRequired() ? mapper.createObjectNode().set("filter", mapper.readTree(kv.value.filter().string())) : mapper.createObjectNode())), (acc1, acc2) -> acc1); // (can't occur) final JsonNode new_json_aliases = Optional.ofNullable(new_mapping.get("aliases")) .orElse(mapper.createObjectNode()); return stored_json_mappings.equals(new_json_mappings) && stored_json_settings.equals(new_json_settings) && stored_json_aliases.equals(new_json_aliases); }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java
/** Creates a mapping for the bucket - search service elements .. up to but not including the mapping + type * NOTE: creates an embedded object that is {{, ie must be closed twice subsequently in order to be a well formed JSON object * @param bucket//w w w. j a v a 2s .c om * @return * @throws IOException */ public static XContentBuilder getSearchServiceMapping(final DataBucketBean bucket, final Optional<String> secondary_buffer, final boolean is_primary, final ElasticsearchIndexServiceConfigBean schema_config, final Optional<XContentBuilder> to_embed, final ObjectMapper mapper) { try { final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject()); // (Nullable) final ElasticsearchIndexServiceConfigBean.SearchIndexSchemaDefaultBean search_schema = schema_config .search_technology_override(); //(very briefly Nullable) final JsonNode settings = Optional.ofNullable(search_schema).map(s -> s.settings()) .map(o -> mapper.convertValue(o, JsonNode.class)).orElse(null); //(very briefly Nullable) final ObjectNode aliases = (ObjectNode) Optional.ofNullable(search_schema).map(s -> s.aliases()) .map(o -> mapper.convertValue(o, JsonNode.class)).orElse(mapper.createObjectNode()); if (is_primary) { // add the "read only" prefix alias aliases.set( ElasticsearchContext.READ_PREFIX + ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty()), mapper.createObjectNode()); } // Settings final String type_key = getTypeKey(bucket, mapper); return Lambdas.wrap_u(__ -> { if (null == settings) { // nothing to do return start; } else { return start.rawField("settings", settings.toString().getBytes()); } }) // Aliases .andThen(Lambdas.wrap_u(json -> { if (!aliases.elements().hasNext()) { // nothing to do return json; } else { return start.rawField("aliases", aliases.toString().getBytes()); } })) // Mappings and overrides .andThen(Lambdas.wrap_u(json -> json.startObject("mappings").startObject(type_key))) // Add the secondary buffer name to the metadata: .andThen(Lambdas.wrap_u(json -> { return json.rawField(CUSTOM_META, createMergedMeta(Either.right(mapper), bucket, is_primary, secondary_buffer) .toString().getBytes()); })) // More mapping overrides .andThen(Lambdas.wrap_u(json -> { return Optional.ofNullable(search_schema).map(ss -> ss.mapping_overrides()) .map(m -> m.getOrDefault(type_key, m.get("*"))).orElse(Collections.emptyMap()) .entrySet().stream().reduce(json, Lambdas.wrap_u((acc, kv) -> { if (CUSTOM_META.equals(kv.getKey())) { // meta is a special case, merge my results in regardless return acc.rawField(kv.getKey(), createMergedMeta( Either.left( mapper.convertValue(kv.getValue(), JsonNode.class)), bucket, is_primary, secondary_buffer).toString() .getBytes()); } else { return acc.rawField(kv.getKey(), mapper .convertValue(kv.getValue(), JsonNode.class).toString().getBytes()); } }), (acc1, acc2) -> acc1 // (can't actually ever happen) ); })).apply(null); } catch (IOException e) { //Handle fake "IOException" return null; } }