Example usage for com.fasterxml.jackson.databind ObjectMapper convertValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper convertValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper convertValue.

Prototype

@SuppressWarnings("unchecked")
    public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException 

Source Link

Usage

From source file:org.springframework.boot.actuate.context.properties.ConfigurationPropertiesReportEndpoint.java

/**
 * Cautiously serialize the bean to a map (returning a map with an error message
 * instead of throwing an exception if there is a problem).
 * @param mapper the object mapper//from  w  w w  .  ja  v a 2s.  c o m
 * @param bean the source bean
 * @param prefix the prefix
 * @return the serialized instance
 */
@SuppressWarnings("unchecked")
private Map<String, Object> safeSerialize(ObjectMapper mapper, Object bean, String prefix) {
    try {
        return new HashMap<>(mapper.convertValue(bean, Map.class));
    } catch (Exception ex) {
        return new HashMap<>(Collections.singletonMap("error", "Cannot serialize '" + prefix + "'"));
    }
}

From source file:com.ikanow.aleph2.v1.document_db.utils.TestJsonNodeBsonUtils.java

@Test
public void test_transform() {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());
    new JsonNodeBsonUtils(); //coverage!

    assertEquals(NullNode.instance,//www.  ja  va2  s .  co m
            JsonNodeBsonUtils.transform(new HashSet<String>(), JsonNodeFactory.instance));
    assertEquals(null, JsonNodeBsonUtils.transform(null, JsonNodeFactory.instance));
    assertEquals(mapper.convertValue(true, JsonNode.class),
            JsonNodeBsonUtils.transform(true, JsonNodeFactory.instance));
    assertEquals(mapper.convertValue("test", JsonNode.class),
            JsonNodeBsonUtils.transform("test", JsonNodeFactory.instance));
    assertEquals(mapper.convertValue(4, JsonNode.class),
            JsonNodeBsonUtils.transform(4, JsonNodeFactory.instance));
    assertEquals(mapper.convertValue(4L, JsonNode.class),
            JsonNodeBsonUtils.transform(4L, JsonNodeFactory.instance));
    assertEquals(mapper.convertValue(new byte[] { (byte) 0xFF, (byte) 0xFE }, JsonNode.class),
            JsonNodeBsonUtils.transform(new byte[] { (byte) 0xFF, (byte) 0xFE }, JsonNodeFactory.instance));
    assertEquals(mapper.convertValue(4.0, JsonNode.class),
            JsonNodeBsonUtils.transform(4.0, JsonNodeFactory.instance));
    assertEquals(mapper.convertValue(0L, JsonNode.class),
            JsonNodeBsonUtils.transform(new Date(0L), JsonNodeFactory.instance));
    assertEquals(mapper.convertValue("4c927585d591d31d7b37097a", JsonNode.class),
            JsonNodeBsonUtils.transform(new ObjectId("4c927585d591d31d7b37097a"), JsonNodeFactory.instance));
    //(had real trouble creating a float node!)
    assertEquals(JsonNodeFactory.instance.numberNode(Float.valueOf((float) 4.0)),
            JsonNodeBsonUtils.transform((float) 4.0, JsonNodeFactory.instance));

    // will test object writable and array writable below      
}

From source file:com.stratio.ingestion.sink.druid.DruidSinkIT.java

private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "user1@santander.com", "user2@santander.com", "user3@santander.com",
            "user4@santander.com" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;/*from  w  w  w.  ja  va  2  s.  c  o  m*/
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp",
            String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random.nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);

    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}

From source file:com.github.gcauchis.scalablepress4j.api.ProductApi.java

/**
 * Specify a product id to receive product information. For each color of the product, this information includes the following
 * WARNING: Item information requests output a large amount of data. As a result, an authorized API key is required to make this request. To authorize your API key, contact api@scalablepress.com.
 *
 * @param productId//ww w.  ja va  2s  .  c o  m
 * @return the detailed product items information
 * @throws ScalablePressBadRequestException for invalid request or error occur during call.
 * @see <a href="https://scalablepress.com/docs/#list-detailed-item-information">https://scalablepress.com/docs/#list-detailed-item-information</a>
 */
public ColorsItem getDetailedProductItemsInformation(String productId) throws ScalablePressBadRequestException {
    Map<String, Object> response = (Map<String, Object>) get("products/" + productId + "/items", Object.class);
    Map<String, ColorSizesItem> colorsItem = new LinkedHashMap<>();
    ObjectMapper mapper = getObjectMapper();
    for (Map.Entry<String, Object> entryResponse : response.entrySet()) {
        String color = entryResponse.getKey();
        Map<String, Object> colorSizes = (Map<String, Object>) entryResponse.getValue();
        Map<String, Size> colorSizesItem = new LinkedHashMap<>();
        for (Map.Entry<String, Object> entrySize : colorSizes.entrySet()) {
            colorSizesItem.put(entrySize.getKey(), mapper.convertValue(entrySize.getValue(), Size.class));
        }
        colorsItem.put(color, new ColorSizesItem(colorSizesItem));
    }
    return new ColorsItem(colorsItem);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Upload the data vector as JSON to the specified Crowdflower job
 * @param job/*from  w  w w. j  a v a 2s .  c  o m*/
 * @param data - Generic vector of data, containing ordinary java classes.
 * They should be annotated so that Jackson understands how to map them to JSON.
 *
 */

void uploadData(CrowdJob job, List<?> data) {
    Log LOG = LogFactory.getLog(getClass());

    //Crowdflower wants a Multi-line JSON, with each line having a new JSON object
    //Thus we have to map each (raw) object in data individually to a JSON string

    ObjectMapper mapper = new ObjectMapper();
    String jsonObjectCollection = "";

    StringBuilder jsonStringBuilder = new StringBuilder();
    int count = 0;
    for (Object obj : data) {
        count++;
        JsonNode jsonData = mapper.convertValue(obj, JsonNode.class);
        jsonStringBuilder.append(jsonData.toString());
        jsonStringBuilder.append("\n");
    }

    jsonObjectCollection = jsonStringBuilder.toString();

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(jsonObjectCollection, headers);

    String result = "";

    if (job == null) {
        LOG.info("Upload new data and create new job: " + String.valueOf(count) + " data items");
        result = restTemplate.postForObject(uploadDataURL, request, String.class, apiKey);
    } else {
        LOG.info("Uploading new data to job: " + job.getId() + ": " + String.valueOf(count) + " data items");
        result = restTemplate.postForObject(uploadDataWithJobURL, request, String.class, job.getId(), apiKey);
    }
    LOG.info("Upload response:" + result);

    //set gold? this is what i would like to do...
    //updateVariable(job, "https://api.crowdflower.com/v1/jobs/{jobid}/gold?key={apiKey}", "set_standard_gold", "TRUE");
}

From source file:com.athena.dolly.cloudant.CloudantEventListener.java

public SFile getSFileByAbsolutePath(String absolutePath) {
    ObjectMapper om = new ObjectMapper();
    ViewQuery query = new ViewQuery().designDocId("_design/index").viewName("absPathView").key(absolutePath)
            .includeDocs(true).limit(1).staleOk(false);
    ViewResult result = conn.queryView(query);
    Iterator<Row> it = result.iterator();
    while (it.hasNext()) {
        Row row = it.next();/*from  w  ww.  j  av  a 2  s . c  om*/
        //         System.out.println(row);
        //         System.out.println(row.getDocAsNode());
        SFile sFile = om.convertValue(row.getDocAsNode(), SFile.class);
        return sFile;
    }

    return null;
}

From source file:com.hortonworks.streamline.streams.catalog.topology.component.TopologyComponentFactory.java

private Map.Entry<String, Provider<StreamlineProcessor>> joinProcessorProvider() {
    Provider<StreamlineProcessor> provider = new Provider<StreamlineProcessor>() {
        @Override/* w w  w  .  j av  a2  s . c  o m*/
        public StreamlineProcessor create(TopologyComponent component) {
            Object joinConfig = component.getConfig().getAny(JoinProcessor.CONFIG_KEY_JOIN);
            ObjectMapper objectMapper = new ObjectMapper();
            JoinAction joinAction = objectMapper.convertValue(joinConfig, JoinAction.class);
            JoinProcessor joinProcessor = new JoinProcessor();
            joinProcessor.addOutputStreams(createOutputStreams((TopologyOutputComponent) component));
            joinProcessor.setJoinAction(joinAction);
            return joinProcessor;
        }
    };
    return new SimpleImmutableEntry<>(JOIN, provider);
}

From source file:com.hortonworks.streamline.streams.catalog.topology.component.TopologyComponentFactory.java

private Map.Entry<String, Provider<StreamlineProcessor>> stageProcessorProvider() {
    Provider<StreamlineProcessor> provider = new Provider<StreamlineProcessor>() {
        @Override//  w ww .j a  v a2  s .c  o m
        public StreamlineProcessor create(TopologyComponent component) {
            Object stageConfig = component.getConfig().getAny(StageProcessor.CONFIG_KEY_STAGE);
            ObjectMapper objectMapper = new ObjectMapper();
            StageAction stageAction = objectMapper.convertValue(stageConfig, StageAction.class);
            StageProcessor stageProcessor = new StageProcessor();
            stageProcessor.setStageAction(stageAction);
            return stageProcessor;
        }
    };
    return new SimpleImmutableEntry<>(STAGE, provider);
}

From source file:com.hortonworks.streamline.streams.catalog.topology.component.TopologyComponentFactory.java

private Map.Entry<String, Provider<StreamlineProcessor>> splitProcessorProvider() {
    Provider<StreamlineProcessor> provider = new Provider<StreamlineProcessor>() {
        @Override/*  ww  w  .j  a  va 2  s  .  com*/
        public StreamlineProcessor create(TopologyComponent component) {
            Object splitConfig = component.getConfig().getAny(SplitProcessor.CONFIG_KEY_SPLIT);
            ObjectMapper objectMapper = new ObjectMapper();
            SplitAction splitAction = objectMapper.convertValue(splitConfig, SplitAction.class);
            SplitProcessor splitProcessor = new SplitProcessor();
            splitProcessor.addOutputStreams(createOutputStreams((TopologyOutputComponent) component));
            splitProcessor.setSplitAction(splitAction);
            return splitProcessor;
        }
    };
    return new SimpleImmutableEntry<>(SPLIT, provider);
}

From source file:eu.europa.ec.fisheries.uvms.reporting.service.util.ReportDeserializer.java

private void addPositionFilter(List<FilterDTO> filterDTOList, Long reportId, JsonNode next) {
    VmsPositionFilterDTO dto = VmsPositionFilterDTO.VmsPositionFilterDTOBuilder().reportId(reportId)
            .id(next.get(FilterDTO.ID) != null ? next.get(FilterDTO.ID).longValue() : null)
            .maximumSpeed(next.get(VmsPositionFilterDTO.MOV_MAX_SPEED) != null
                    ? next.get(VmsPositionFilterDTO.MOV_MAX_SPEED).floatValue()
                    : null)//from   ww w  .  j  a v  a 2s.c  om
            .minimumSpeed(next.get(VmsPositionFilterDTO.MOV_MIN_SPEED) != null
                    ? next.get(VmsPositionFilterDTO.MOV_MIN_SPEED).floatValue()
                    : null)
            .build();

    if (next.get(VmsPositionFilterDTO.MOV_ACTIVITY) != null) {
        dto.setMovementActivity(
                MovementActivityTypeType.valueOf(next.get(VmsPositionFilterDTO.MOV_ACTIVITY).textValue()));
    }
    if (next.get(VmsPositionFilterDTO.MOV_TYPE) != null) {
        dto.setMovementType(MovementTypeType.valueOf(next.get(VmsPositionFilterDTO.MOV_TYPE).textValue()));
    }
    if (next.get(VmsPositionFilterDTO.MOV_SOURCES) != null) {
        ObjectMapper mapper = new ObjectMapper();
        List<String> movSources = mapper.convertValue(next.get(VmsPositionFilterDTO.MOV_SOURCES), List.class);
        dto.setMovementSources(movSources);
    }
    filterDTOList.add(dto);
}