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.up.ling.irtg.util.FirstOrderModel.java

/**
 * Reads the options from a Json string representation. The options for the
 * SetAlgebra consist in a specification of the universe and the
 * interpretations of the atomic concepts. For instance, the following
 * string says that "sleep" is a binary relation with the single element
 * (e,r1), whereas "rabbit" is a unary relation containing the elements r1
 * and r2.<p>//from   w w  w  .j a va 2 s.c  o m
 *
 * {"sleep": [["e", "r1"]], "rabbit": [["r1"], ["r2"]], "white": [["r1"],
 * ["b"]], "in": [["r1","h"], ["f","h2"]], "hat": [["h"], ["h2"]] }
 *
 *
 * @param optionReader
 * @throws Exception
 */
public static FirstOrderModel read(Reader optionReader) throws Exception {
    FirstOrderModel model = new FirstOrderModel();

    String optionString = StringTools.slurp(optionReader);
    Map<String, Set<List<String>>> atomicInterpretations = new HashMap<String, Set<List<String>>>();

    if (!optionString.trim().equals("")) {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readValue(optionString, JsonNode.class);

        if (!root.isObject()) {
            throw new Exception("Invalid universe description: should be a map");
        } else {
            Iterator<String> preds = root.fieldNames();

            while (preds.hasNext()) {
                String pred = preds.next();
                Set<List<String>> tuples = new HashSet<List<String>>();
                JsonNode child = root.get(pred);

                if (!child.isArray()) {
                    throw new Exception("Invalid universe description: Entry '" + pred + "' should be a list.");
                } else {
                    int childIndex = 0;
                    for (JsonNode tuple : child) {
                        List<String> tupleElements = new ArrayList<String>();
                        childIndex++;

                        if (!tuple.isArray()) {
                            throw new Exception("Invalid universe description: tuple " + childIndex + " under '"
                                    + pred + "' should be a list.");
                        } else {
                            for (JsonNode tupleEl : tuple) {
                                tupleElements.add(tupleEl.textValue());
                            }
                        }

                        tuples.add(tupleElements);
                    }
                }

                atomicInterpretations.put(pred, tuples);
            }
        }
    }

    model.setAtomicInterpretations(atomicInterpretations);
    return model;
}

From source file:alluxio.cli.LogLevel.java

private static void setLogLevel(final TargetInfo targetInfo, String logName, String level) throws IOException {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http");
    uriBuilder.setHost(targetInfo.getHost());
    uriBuilder.setPort(targetInfo.getPort());
    uriBuilder.setPath(Constants.REST_API_PREFIX + "/" + targetInfo.getRole() + "/" + LOG_LEVEL);
    uriBuilder.addParameter(LOG_NAME_OPTION_NAME, logName);
    if (level != null) {
        uriBuilder.addParameter(LEVEL_OPTION_NAME, level);
    }/*ww  w .j  ava 2s  . c o m*/
    HttpUtils.post(uriBuilder.toString(), 5000, new HttpUtils.IProcessInputStream() {
        @Override
        public void process(InputStream inputStream) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            LogInfo logInfo = mapper.readValue(inputStream, LogInfo.class);
            System.out.println(targetInfo.toString() + logInfo.toString());
        }
    });
}

From source file:com.google.openrtb.json.OpenRtbJsonRequestHelper.java

/**
 * Json generator method.//from  w ww  .  jav a2 s.c om
 *
 * @param isFull true, if nearly all fields should be filled; just some selected fields otherwise
 * @param isRootNative true, if the "native" field should be included as root element
 * @param isNativeObject true, if the native part should be generated as Json object;
 *     String otherwise
 * @return not pretty printed String representation of Json
 */
private static String generateJson(boolean isFull, boolean isRootNative, boolean isNativeObject)
        throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Object json = mapper.readValue(generateRequest(isFull, isRootNative, isNativeObject), Object.class);
    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
}

From source file:io.ingenieux.lambada.runtime.LambadaUtils.java

public static <T> PassthroughRequest<T> getRequest(ObjectMapper mapper, Class<T> clazz, InputStream inputStream)
        throws IOException {
    final JavaType typeReference = getReferenceFor(mapper, clazz);

    return mapper.readValue(inputStream, typeReference);
}

From source file:com.krj.karbon.GetPlayerSummaries.java

/**
 *
 * @param ids//  www.  ja  v a2s  .  com
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
private static List<Map> getPlayerMaps(String ids) throws MalformedURLException, IOException {

    //build the url
    String urlString = host + path + key + ids;
    URL url = new URL(urlString);

    //fetch the JSON from the API and turn it into a map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> JSONMap = mapper.readValue(url, Map.class);

    //descend into the response to get to the real data
    Map response = (Map) JSONMap.get("response");

    //get a list of maps containing the real data!
    if (response != null) {
        List<Map> playerMaps = (List<Map>) response.get("players");

        return playerMaps;
    }
    return null;
}

From source file:org.apache.hadoop.gateway.util.JsonUtils.java

public static Map<String, String> getMapFromJsonString(String json) {
    Map<String, String> map = null;
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
    };/*  ww w.j  a v  a2s  .  co  m*/
    try {
        map = mapper.readValue(json, typeRef);
    } catch (JsonParseException e) {
        LOG.failedToGetMapFromJsonString(json, e);
    } catch (JsonMappingException e) {
        LOG.failedToGetMapFromJsonString(json, e);
    } catch (IOException e) {
        LOG.failedToGetMapFromJsonString(json, e);
    }
    return map;
}

From source file:de.anycook.social.facebook.FacebookHandler.java

public static FacebookRequest decode(String input) throws IOException {
    String[] split = input.split("\\.");
    String sig = decodeBase64(split[0]);
    String data = decodeBase64(split[1]);
    if (verifySigSHA256(sig, split[1])) {
        LOGGER.debug(data);//  www.ja va 2 s .c  o  m
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(data, FacebookRequest.class);
    }
    throw new IOException("failed to parse fb request");

}

From source file:com.microsoft.alm.client.utils.JsonHelper.java

/**
 * Map to QueryParameters//  w w  w. j ava2s.c o m
 *
 * @param model
 * @return Map<String, String>
 */
public static Map<String, String> toQueryParametersMap(final Object model) {
    final ObjectMapper objectMapper = getObjectMapper();

    try {
        return objectMapper.readValue(objectMapper.writeValueAsString(model),
                new TypeReference<Map<String, String>>() {
                });
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
        throw new VssServiceException(e.getMessage(), e);
    }
}

From source file:de.unirostock.sems.cbarchive.web.dataholder.WorkspaceHistory.java

@JsonIgnore
public static WorkspaceHistory fromCookieJson(String json)
        throws JsonParseException, JsonMappingException, IOException {

    if (json == null)
        return null;

    json = new String(Base64.decodeBase64(json));

    ObjectMapper mapper = new ObjectMapper();
    List<Workspace> recent = mapper.readValue(json, new TypeReference<List<Workspace>>() {
    });//from   ww w  .j a  v a2s.co m
    List<Workspace> result = new ArrayList<Workspace>();

    WorkspaceManager workspaceManager = WorkspaceManager.getInstance();

    // looking up the names
    for (Workspace elem : recent) {
        Workspace workspace = workspaceManager.getWorkspace(elem.getWorkspaceId());
        if (workspace != null)
            result.add(workspace);
    }

    return new WorkspaceHistory(result);
}

From source file:fll.web.WebTestUtils.java

/**
 * Submit a query to developer/QueryHandler, parse the JSON and return it.
 *//*from   w  w  w . ja  v  a  2s.co m*/
public static QueryHandler.ResultData executeServerQuery(final String query) throws IOException, SAXException {
    final WebClient conversation = getConversation();

    final URL url = new URL(TestUtils.URL_ROOT + "developer/QueryHandler");
    final WebRequest request = new WebRequest(url);
    request.setRequestParameters(
            Collections.singletonList(new NameValuePair(QueryHandler.QUERY_PARAMETER, query)));

    final Page response = loadPage(conversation, request);
    final String contentType = response.getWebResponse().getContentType();
    if (!"application/json".equals(contentType)) {
        final String text = getPageSource(response);
        final File output = File.createTempFile("json-error", ".html", new File("screenshots"));
        final FileWriter writer = new FileWriter(output);
        writer.write(text);
        writer.close();
        Assert.fail("Error JSON from QueryHandler: " + response.getUrl()
                + " Contents of error page written to: " + output.getAbsolutePath());
    }

    final String responseData = getPageSource(response);

    final ObjectMapper jsonMapper = new ObjectMapper();
    QueryHandler.ResultData result = jsonMapper.readValue(responseData, QueryHandler.ResultData.class);
    Assert.assertNull("SQL Error: " + result.getError(), result.getError());

    return result;
}