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.mule.modules.cookbook.CookbookConnector.java

/**
 * Description for create//from www. j  a v  a  2  s  .co  m
 *
 * {@sample.xml ../../../doc/cook-book-connector.xml.sample cook-book:create}
 *
 * @param entity
 *            Ingredient to be created
 * @return return Ingredient with Id from the system.
 *
 * @throws InvalidTokenException
 * @throws SessionExpiredException
 * @throws InvalidEntityException
 */
@SuppressWarnings("unchecked")
@OAuthProtected
@Processor
@OnException(handler = CookbookHandler.class)
@ReconnectOn(exceptions = { SessionExpiredException.class })
public Map<String, Object> create(@MetaDataKeyParam(affects = MetaDataKeyParamAffectsType.BOTH) String type,
        @Default("#[payload]") @RefOnly Map<String, Object> entity)
        throws InvalidEntityException, SessionExpiredException {
    ObjectMapper m = new ObjectMapper();
    CookBookEntity input = null;
    if (type.contains("com.cookbook.tutorial.service.Recipe")) {
        input = m.convertValue(entity, Recipe.class);
    } else if (type.contains("com.cookbook.tutorial.service.Ingredient")) {
        input = m.convertValue(entity, Ingredient.class);
    } else {
        throw new InvalidEntityException("Don't know how to handle type:" + type);
    }
    return m.convertValue(this.getConfig().getClient().create(input), Map.class);
}

From source file:org.mule.modules.cookbook.CookbookConnector.java

/**
 * Description for update//w  ww.  j  a  v  a  2s  .c  om
 *
 * {@sample.xml ../../../doc/cook-book-connector.xml.sample cook-book:update}
 *
 * @param entity
 *            Ingredient to be updated
 * @return return Ingredient with Id from the system.
 *
 * @throws SessionExpiredException
 * @throws InvalidEntityException
 * @throws NoSuchEntityException
 */
@SuppressWarnings("unchecked")
@OAuthProtected
@Processor
@OnException(handler = CookbookHandler.class)
@ReconnectOn(exceptions = { SessionExpiredException.class })
public Map<String, Object> update(@MetaDataKeyParam(affects = MetaDataKeyParamAffectsType.BOTH) String type,
        @Default("#[payload]") @RefOnly Map<String, Object> entity)
        throws InvalidEntityException, SessionExpiredException, NoSuchEntityException {
    ObjectMapper m = new ObjectMapper();
    CookBookEntity input = null;
    if (type.contains("com.cookbook.tutorial.service.Recipe")) {
        input = m.convertValue(entity, Recipe.class);
    } else if (type.contains("com.cookbook.tutorial.service.Ingredient")) {
        input = m.convertValue(entity, Ingredient.class);
    } else {
        throw new InvalidEntityException("Don't know how to handle type:" + type);
    }
    return m.convertValue(this.getConfig().getClient().update(input), Map.class);
}

From source file:com.almende.eve.rpc.jsonrpc.JSONRequest.java

/**
 * Put param./* ww w  . j  av  a2s . co m*/
 *
 * @param name the name
 * @param value the value
 */
public void putParam(final String name, final Object value) {
    final ObjectMapper mapper = JOM.getInstance();
    req.with(PARAMS).put(name, mapper.convertValue(value, JsonNode.class));
}

From source file:com.yahoo.druid.hadoop.DruidHelper.java

protected List<DataSegment> getSegmentsToLoad(String dataSource, Interval interval, String overlordUrl) {
    String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action";
    logger.info("Sending request to overlord at " + urlStr);

    String requestJson = getSegmentListUsedActionJson(dataSource, interval.toString());
    logger.info("request json is " + requestJson);

    int numTries = 3; //TODO: should be configurable?
    for (int trial = 0; trial < numTries; trial++) {
        try {/*from   ww w  . ja v a 2s . com*/
            logger.info("attempt number {} to get list of segments from overlord", trial);
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/json");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000); //TODO: 60 secs, shud be configurable?
            OutputStream out = conn.getOutputStream();
            out.write(requestJson.getBytes());
            out.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                ObjectMapper mapper = DruidInitialization.getInstance().getObjectMapper();
                Map<String, Object> obj = mapper.readValue(conn.getInputStream(),
                        new TypeReference<Map<String, Object>>() {
                        });
                return mapper.convertValue(obj.get("result"), new TypeReference<List<DataSegment>>() {
                });
            } else {
                logger.warn(
                        "Attempt Failed to get list of segments from overlord. response code {} , response {}",
                        responseCode, IOUtils.toString(conn.getInputStream()));
            }
        } catch (Exception ex) {
            logger.warn("Exception in getting list of segments from overlord", ex);
        }

        try {
            Thread.sleep(5000); //wait before next trial
        } catch (InterruptedException ex) {
            Throwables.propagate(ex);
        }
    }

    throw new RuntimeException(
            String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]",
                    dataSource, interval, overlordUrl));
}

From source file:com.nebhale.jsonpath.JsonPath.java

/**
 * Reads content from a JSON payload based on the expression compiled into this instance
 *
 * @param json The JSON payload to retrieve data from
 * @param expectedReturnType The type that the return value is expected to be
 *
 * @return The content read from the JSON payload
 *//*from w w  w  .j  av a 2 s  . com*/
public <T> T read(JsonNode json, Class<T> expectedReturnType) {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode result = this.pathComponent.get(json);
    return objectMapper.convertValue(result, expectedReturnType);
}

From source file:com.nebhale.jsonpath.JsonPath.java

/**
 * Reads content from a JSON payload based on the expression compiled into this instance
 *
 * @param json The JSON payload to retrieve data from
 * @param expectedReturnType The type that the return value is expected to be
 *
 * @return The content read from the JSON payload
 *//*from w  w w  .  j a  va 2  s .co m*/
public <T> T read(JsonNode json, TypeReference<?> expectedReturnType) {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode result = this.pathComponent.get(json);
    return objectMapper.convertValue(result, expectedReturnType);
}

From source file:com.nebhale.jsonpath.JsonPath.java

/**
 * Reads content from a JSON payload based on the expression compiled into this instance
 *
 * @param json The JSON payload to retrieve data from
 * @param expectedReturnType The type that the return value is expected to be
 *
 * @return The content read from the JSON payload
 *///from w  ww  . j a va 2 s .  co  m
public <T> T read(JsonNode json, JavaType expectedReturnType) {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode result = this.pathComponent.get(json);
    return objectMapper.convertValue(result, expectedReturnType);
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Returns a JsonNode with the field's mapping
 * @param tokenize_dual/*from   w  w  w. j  a  va  2 s . c om*/
 * @param defaults
 * @return
 */
protected static JsonNode getMapping(final Tuple2<Boolean, Boolean> tokenize_dual,
        final SearchIndexSchemaDefaultBean defaults, final ObjectMapper mapper, boolean is_dynamic_template) {
    return Optional
            .of(Patterns.match(tokenize_dual).<JsonNode>andReturn()
                    .when(td -> td.equals(Tuples._2T(true, true)),
                            __ -> mapper.convertValue(defaults.dual_tokenized_string_field(), JsonNode.class))
                    .when(td -> td.equals(Tuples._2T(true, false)),
                            __ -> mapper.convertValue(defaults.tokenized_string_field(), JsonNode.class))
                    .when(td -> td.equals(Tuples._2T(false, true)),
                            __ -> mapper.convertValue(defaults.dual_untokenized_string_field(), JsonNode.class))
                    .when(td -> td.equals(Tuples._2T(false, false)),
                            __ -> mapper.convertValue(defaults.untokenized_string_field(), JsonNode.class))
                    .otherwiseAssert())
            .map(j -> is_dynamic_template ? mapper.createObjectNode().set("mapping", j) : j).get();

}

From source file:inti.ws.spring.resource.index.IndexConfig.java

@Override
public void configureWebResources(ObjectMapper mapper, JsonNode node,
        Map<String, FilteredWebResource> resources, Map<String, Map<String, FilteredWebResource>> resourceStack)
        throws Exception {
    IndexBean indexBean = mapper.convertValue(node, IndexBean.class);
    Entry<String, FilteredWebResource> entry = resources.entrySet().iterator().next();
    FilteredWebResource index = entry.getValue();
    Matcher matcher;/*from www . j a v  a  2 s  .  c  o m*/
    String domain;
    String resource;
    Object value;

    if (indexBean.getDependencies() != null) {

        for (String dependency : indexBean.getDependencies()) {
            matcher = DEPENDENCY_SCANNER.matcher(dependency);

            LOGGER.debug("configureWebResources - dependency={}", dependency);
            if (matcher.matches()) {
                domain = matcher.group(1);
                resource = matcher.group(2);

                LOGGER.debug("configureWebResources - domain={}, resource={}, resourceStack={}",
                        new Object[] { domain, resource, resourceStack });
                if (resourceStack.containsKey(domain)) {
                    if (resourceStack.get(domain).containsKey(resource)) {
                        index.getDependencies().add(resourceStack.get(domain).get(resource));
                    }
                }
            }
        }

    }

    if (indexBean.getParameters() != null) {

        for (Map.Entry<String, String> parameter : indexBean.getParameters().entrySet()) {
            matcher = DEPENDENCY_SCANNER.matcher(parameter.getValue());
            value = "";

            if (matcher.matches()) {
                domain = matcher.group(1);
                resource = matcher.group(2);

                if (resourceStack.containsKey(domain)) {
                    if (resourceStack.get(domain).containsKey(resource)) {
                        value = resourceStack.get(domain).get(resource);
                    }
                }
            } else {
                value = parameter.getValue();
            }
            index.getParameters().put(parameter.getKey(), value);
        }

    }

    LOGGER.debug("configureWebResources - index.getParameters()={}, index.getDependencies()={}",
            index.getParameters(), index.getDependencies());
}

From source file:com.almende.eve.rpc.jsonrpc.JSONRPCException.java

/**
 * Sets the data.//  w ww.j  a  va 2s .  c o  m
 * 
 * @param data
 *            the new data
 */
public final void setData(final Object data) {
    final ObjectMapper mapper = JOM.getInstance();
    error.put(DATA_S, data != null ? mapper.convertValue(data, JsonNode.class) : null);
}