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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:de.rallye.config.RallyeConfig.java

/**
 * Read Config from Config File if present
 * @return Found Config File or Default Config
 *///w w w  .j a  v a  2 s.c  o  m
public static RallyeConfig fromFile(File configFile, GitRepositoryState git) {
    RallyeConfig config;

    if (configFile == null) {
        logger.error("No config file found.");
        return null;
    }
    logger.info("Loading config file from {}", configFile);
    ObjectMapper mapper = new ObjectMapper();
    try {
        config = mapper.readValue(configFile, RallyeConfig.class);
        File parent = configFile.getParentFile();
        if (parent != null)
            config.configFileDir = parent + File.separator;
        else
            config.configFileDir = "";

        config.lastModified = configFile.lastModified();

        if (git != null) {
            config.setGit(git);
            logger.info("Current Build:\n\t{}", git);
        }

        return config;
    } catch (IOException e) {
        logger.error("Config invalid.", e);
        return null;
    }
}

From source file:org.ulyssis.ipp.config.Config.java

/**
 * Create a configuration from the given JSON configuration string.
 *///from w  w  w.  j av a2  s  .  co  m
public static Optional<Config> fromConfigurationString(String configuration) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    try {
        Config result = mapper.readValue(configuration, Config.class);
        return Optional.of(result);
    } catch (IOException e) {
        LOG.error("Error reading configuration", e);
        return Optional.empty();
    }
}

From source file:cn.dataprocess.cfzk.JsonUtil.java

public static <K> K toJavaBean(String content, Class<K> valueType) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    K ret = mapper.readValue(content, valueType);
    mapper = null;// w  ww . java 2 s. c o m
    return ret;
}

From source file:de.alpharogroup.xml.json.JsonTransformer.java

/**
 * Transforms the given json string into a java object list.
 *
 * @param <T>//from w ww  .j av  a  2s  .  c o m
 *            the generic type of the return type
 * @param jsonString
 *            the json string
 * @param clazz
 *            the clazz of the generic type
 * @return the list with the java objects.
 * @throws JsonParseException
 *             If an error occurs when parsing the string into Object
 * @throws JsonMappingException
 *             the If an error occurs when mapping the string into Object
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static <T> List<T> toObjectList(final String jsonString, final Class<T> clazz)
        throws JsonParseException, JsonMappingException, IOException {
    final ObjectMapper mapper = getObjectMapper(true);
    final List<T> objectList = mapper.readValue(jsonString,
            mapper.getTypeFactory().constructCollectionType(List.class, clazz));
    return objectList;
}

From source file:net.floodlightcontroller.queuepusher.QueuePusherSwitchMapper.java

/**
 * Given the switch DPID it returns its ip and port by querying floodlight
 * /*from w ww  . j  a v  a 2  s . c o m*/
 * @param dpid Switch dpid
 * @return 0: ip 1: port
 */

private static Object[] getCURLMatch(String dpid) {

    Object[] rsp = eval("curl -s http://127.0.0.1:8080/wm/core/controller/switches/json");
    ObjectMapper mapper = new ObjectMapper();

    List<Map<String, Object>> args = null;
    try {
        logger.info("JSON received from CURL: " + rsp[1]);
        args = mapper.readValue((String) rsp[1],
                TypeFactory.defaultInstance().constructCollectionType(List.class, Map.class));
    } catch (IOException e) {
        logger.warn("Error parsing JSON arguments", e);
    }

    String ip = null;
    int port = 0;
    for (Map<String, Object> entry : args) {
        if (((String) entry.get("dpid")).equals(dpid)) {
            String temp = ((String) entry.get("inetAddress")).substring(1);
            ip = temp.substring(0, temp.indexOf(":"));
            port = Integer.parseInt(temp.substring(temp.indexOf(":") + 1));
            break;
        }
    }

    return new Object[] { ip, port };

}

From source file:de.rallye.config.RallyeConfig.java

public static RallyeConfig fromStream(InputStream stream) {
    if (stream == null) {
        logger.warn("No config stream. Using Default Config");
        return new RallyeConfig();
    }//from ww  w  .  j  a va 2  s  .c  o m
    logger.info("Loading config file from stream");
    ObjectMapper mapper = new ObjectMapper();
    try {
        RallyeConfig config = mapper.readValue(stream, RallyeConfig.class);

        if (config.isDataRelativeToConfig()) {
            logger.warn(
                    "Data relative to config is not supported for Stream Config. Falling back to default config");
            return new RallyeConfig();
        }

        logger.debug(config.toString());
        return config;
    } catch (IOException e) {
        logger.error("Falling back to default config", e);
        return new RallyeConfig();
    }
}

From source file:com.springapp.domain.http.account.Account.java

public static Account fromXML(String xml) {
    ObjectMapper xmlMapper = new XmlMapper();
    try {//from  w w  w .  j  a  va2  s  . co  m
        Account value = xmlMapper.readValue(xml, Account.class);
        return value;
    } catch (IOException e) {

        log.error("Error in creating Account object from xml :{} , error : {}", xml, e);
    }
    return null;
}

From source file:oracle.custom.ui.utils.ServerUtils.java

public static PublicKey getServerPublicKey(String domainName) throws Exception {
    HttpClient client = getClient(domainName);
    PublicKey key = null;//ww w.  ja  va2 s  . co  m
    String url = getIDCSBaseURL(domainName) + "/admin/v1/SigningCert/jwk";
    URI uri = new URI(url);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Authorization", "Bearer " + AccessTokenUtils.getAccessToken(domainName));
    HttpResponse response = client.execute(host, httpGet);
    try {
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("result is " + res);
        SigningKeys signingKey = mapper.readValue(res, SigningKeys.class);

        String base64Cert = signingKey.getKeys().get(0).getX5c().get(0);
        byte encodedCert[] = Base64.getDecoder().decode(base64Cert);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(encodedCert);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
        key = cert.getPublicKey();
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
    return key;
}

From source file:com.dell.asm.asmcore.asmmanager.util.razor.RazorUtil.java

/**
 * Parse the return value of the razor node GET api, e.g.
 * http://RAZOR_HOST/api/collections/nodes/node2
 *
 * @param mapper ObjectMapper to parse JSON
 * @param nodeJson Json node data/*from  w w w . ja v  a  2  s .co  m*/
 * @return Device object
 */
public static RazorDevice parseNodeJson(ObjectMapper mapper, String nodeJson) throws IOException {
    Map node = mapper.readValue(nodeJson, Map.class);
    Map hwInfo = (Map) node.get(NODE_HW_INFO_KEY);
    String uuid = (String) hwInfo.get(NODE_HW_INFO_UUID_KEY);
    RazorDevice ret = new RazorDevice();
    ret.setId((String) node.get("name"));
    ret.setUuid(uuid);

    Map policy = (Map) node.get(NODE_POLICY);
    if (policy == null || policy.isEmpty()) {
        ret.setStatus(RazorDeviceStatus.UNPROVISIONED);
    } else {
        //System.out.println("Policy...");
        for (Object key : policy.keySet()) {
            String policyName = (String) key;
            Object policyValueObject = policy.get(policyName);
            String policyValueString = policyValueObject.toString();
            ret.getPolicy().put(policyName, policyValueString);

            //System.out.println(policyName + ":" + policyValueString);
        }
        //System.out.println("");
        ret.setStatus(RazorDeviceStatus.PROVISIONED);
    }

    List tagslist = (List) node.get("tags");
    if (tagslist != null && tagslist.size() > 0) {
        for (Object aTagslist : tagslist) {
            Map tags = (Map) aTagslist;
            if (tags != null && tags.size() > 0) {
                //System.out.println("Tag...");
                for (Object key : tags.keySet()) {
                    String tagName = (String) key;
                    Object tagValueObject = tags.get(tagName);
                    String tagValueString = tagValueObject.toString();
                    ret.getTags().put(tagName, tagValueString);

                    //System.out.println(tagName + ":" + tagValueString);
                }
                //System.out.println("");
            }
        }
    }

    Map facts = (Map) node.get(NODE_FACTS_KEY);
    if (facts == null) {
        LOGGER.warn("No facts found for node uuid " + ret.getId());
    } else {
        for (Object key : facts.keySet()) {
            String factName = (String) key;
            Object factValueObject = facts.get(factName);
            // Fact values are generally strings, but can be other raw types like integers,
            // e.g. for physicalprocessorcount
            String factValue = factValueObject.toString();
            ret.getFacts().put(factName, factValue);
            switch (factName) {
            case FACT_IPADDRESS_KEY:
                ret.setIpAddress(factValue);
                break;
            case FACT_MACADDRESS_KEY:
                ret.setMacAddress(factValue);
                break;
            case FACT_MANUFACTURER_KEY:
                ret.setManufacturer(factValue);
                break;
            }
        }
    }

    return ret;
}

From source file:com.aerofs.baseline.config.Configuration.java

@SuppressWarnings("unchecked")
public static <C extends Configuration> C loadYAMLConfigurationFromStream(Class<?> derived,
        InputStream configStream) throws IOException {
    ObjectMapper configurationMapper = new ObjectMapper(new YAMLFactory());
    Class<?> configurationTypeClass = Generics.getTypeParameter(derived, Configuration.class);
    return (C) configurationMapper.readValue(configStream, configurationTypeClass);
}