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:ch.ralscha.extdirectspring_itest.InfoServiceTest.java

@SuppressWarnings("unchecked")
private static void testUserPost(String method, String errorMsg, MapEntry... entries) throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;
    try {/* ww w  . j  a v a 2 s .  com*/
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("extTID", "1"));
        formparams.add(new BasicNameValuePair("extAction", "infoService"));
        formparams.add(new BasicNameValuePair("extMethod", method));
        formparams.add(new BasicNameValuePair("extType", "rpc"));
        formparams.add(new BasicNameValuePair("extUpload", "false"));
        formparams.add(new BasicNameValuePair("name", "RALPH"));
        formparams.add(new BasicNameValuePair("firstName", "firstName"));
        formparams.add(new BasicNameValuePair("age", "1"));
        formparams.add(new BasicNameValuePair("email", "invalidEmail"));

        UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");

        post.setEntity(postEntity);

        response = client.execute(post);
        HttpEntity entity = response.getEntity();
        assertThat(entity).isNotNull();
        String responseString = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(responseString, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo(method);
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("infoService");
        assertThat(rootAsMap.get("tid")).isEqualTo(1);

        Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");

        int resultSize = entries.length;
        if (errorMsg != null) {
            resultSize += 1;
        }
        assertThat(result).hasSize(resultSize);
        assertThat(result).contains(entries);

        Map<String, Object> errors = (Map<String, Object>) result.get("errors");
        if (errorMsg != null) {
            assertThat(errors).isNotNull();
            assertThat(((List<String>) errors.get("email")).get(0)).isEqualTo(errorMsg);
        } else {
            assertThat(errors).isNull();
        }
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(client);
    }
}

From source file:com.twosigma.beakerx.table.serializer.TableDisplayDeSerializer.java

@SuppressWarnings("unchecked")
public static List<List<?>> getValues(BeakerObjectConverter parent, JsonNode n, ObjectMapper mapper)
        throws IOException {
    List<List<?>> values = null;
    List<String> classes = null;
    if (n.has("types"))
        classes = mapper.readValue(n.get("types").toString(), List.class);
    if (n.has("values")) {
        JsonNode nn = n.get("values");
        values = new ArrayList<List<?>>();
        if (nn.isArray()) {
            for (JsonNode nno : nn) {
                if (nno.isArray()) {
                    ArrayList<Object> val = new ArrayList<Object>();
                    for (int i = 0; i < nno.size(); i++) {
                        JsonNode nnoo = nno.get(i);
                        Object obj = parent.deserialize(nnoo, mapper);
                        val.add(TableDisplayDeSerializer.getValueForDeserializer(obj,
                                classes != null && classes.size() > i ? classes.get(i) : null));
                    }// w w w.j  a  va 2  s  .  c  om
                    values.add(val);
                }
            }
        }
    }
    return values;
}

From source file:com.xeiam.xchange.rest.JSONUtils.java

/**
 * Creates a POJO from a Jackson-annotated class given a jsonString
 * /* w  w w .  j  a  v  a2 s.  c  om*/
 * @param jsonString
 * @param returnType
 * @param objectMapper
 * @return
 */
public static <T> T getJsonObject(String jsonString, Class<T> returnType, ObjectMapper objectMapper) {

    Assert.notNull(jsonString, "jsonString cannot be null");
    if (jsonString.trim().length() == 0) {
        return null;
    }
    Assert.notNull(objectMapper, "objectMapper cannot be null");
    try {
        return objectMapper.readValue(jsonString, returnType);
    } catch (IOException e) {
        // Rethrow as runtime exception
        log.error("Error unmarshalling from json: " + jsonString);
        throw new ExchangeException("Problem getting JSON object", e);
    }
}

From source file:org.zodiark.protocol.Envelope.java

public final static Envelope newEnvelope(String m, ObjectMapper mapper) throws IOException {
    HashMap<String, Object> envelope = (HashMap<String, Object>) mapper.readValue(m, HashMap.class);
    return newEnvelope(envelope, mapper);
}

From source file:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java

public static SysExprJobLogVO executeJobForManualWebClient(SysExprJobVO sysExprJob, String accountId,
        HttpServletRequest request) throws ServiceException, Exception {
    SysExprJobLogVO result = new SysExprJobLogVO();
    // ? executeJob/ ? ManualJobServiceImpl.java @Path("/executeJob/") ?, ,  url ?
    String url = ApplicationSiteUtils.getBasePath(sysExprJob.getSystem(), request);
    if (!url.endsWith("/")) {
        url += "/";
    }//from  ww  w . j a va2s .  c o m
    //url += "services/jaxrs/";
    url += Constants.getCxfWebServiceMainPathName() + Constants.getJAXRSServerFactoryBeanAddress();
    String encUploadOidStr = SystemExpressionJobUtils.getEncUploadOid(accountId, sysExprJob.getOid());
    WebClient client = WebClient.create(url);
    Response response = client.accept("application/json").path("executeJob/{uploadOid}", encUploadOidStr)
            .post(encUploadOidStr);
    int statusCode = response.getStatus();
    if (statusCode != 200 && statusCode != 202) {
        throw new Exception("error, http status code: " + statusCode);
    }
    String responseStr = response.readEntity(String.class);
    ObjectMapper mapper = new ObjectMapper();
    result = mapper.readValue(responseStr, SysExprJobLogVO.class);
    return result;
}

From source file:jeplus.data.RVX.java

/**
 * Read RVX from a json file or a traditional RVI file with extensions
 * @param rvxfile/*from  w  w  w  . ja v a 2 s  . c o  m*/
 * @return RVX object
 * @throws IOException 
 */
public static RVX getRVX(String rvxfile) throws IOException {
    if (rvxfile.toLowerCase().endsWith(EPlusConfig.getJEPlusRvxExt())) { //RVX
        ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
        return mapper.readValue(new File(rvxfile), RVX.class);
    } else {
        RVX rvx = new RVX();
        // Convert RVI into RVX object. User spreadsheet function is no longer supported
        ArrayList<String[]> sqlite = new ArrayList<>();
        ArrayList<String[]> objectives = new ArrayList<>();
        try (BufferedReader fr = new BufferedReader(new FileReader(rvxfile))) {
            ArrayList<String[]> sections = sqlite;

            String line = fr.readLine();
            boolean extra_on = false;
            // Locating the Objectives section
            while (line != null) {
                if (extra_on) {
                    if (line.toLowerCase().startsWith("!-end ")) {
                        extra_on = false;
                    } else {
                        line = line.substring(0, line.contains("!") ? line.indexOf("!") : line.length());
                        if (line.trim().length() > 0) {
                            String[] section = line.split("\\s*;\\s*");
                            sections.add(section);
                        }
                    }
                } else {
                    if (line.trim().toLowerCase().startsWith("!-objectives")) {
                        sections = objectives;
                        extra_on = true;
                    } else if (line.trim().toLowerCase().startsWith("!-sqlite")) {
                        sections = sqlite;
                        extra_on = true;
                    }
                }
                line = fr.readLine();
            }
        } catch (Exception ex) {
            logger.error("Error reading extended rvi file for objective definitions: ", ex);
        }
        // RVI section points to this RVI file
        RVX_RVIitem[] rvis = new RVX_RVIitem[] { new RVX_RVIitem() };
        rvis[0].setFileName(rvxfile);
        rvis[0].setTableName("SimResults");
        rvx.setRVIs(rvis);
        // SQLite section
        if (sqlite.size() > 0) {
            RVX_SQLitem[] sqls = new RVX_SQLitem[sqlite.size()];
            for (int i = 0; i < sqlite.size(); i++) {
                String[] row = sqlite.get(i);
                sqls[i] = new RVX_SQLitem();
                if (row.length >= 3) {
                    sqls[i].setTableName(row[0]);
                    sqls[i].setColumnHeaders(row[1]);
                    sqls[i].setSQLcommand(row[2]);
                }
            }
            rvx.setSQLs(sqls);
        }
        // Objective section
        if (objectives.size() > 0) {
            RVX_Objective[] objs = new RVX_Objective[objectives.size()];
            for (int i = 0; i < objectives.size(); i++) {
                String[] row = objectives.get(i);
                objs[i] = new RVX_Objective();
                if (row.length >= 3) {
                    objs[i].setIdentifier("t" + i);
                    objs[i].setCaption(row[0] + " [" + row[1] + "]");
                    objs[i].setFormula(row[2]);
                    objs[i].setScaling(false);
                }
            }
            rvx.setObjectives(objs);
        }
        // Constraint section is empty
        rvx.setConstraints(new RVX_Constraint[0]);
        // Retrun rvx
        return rvx;
    }
}

From source file:si.mazi.rescu.JSONUtils.java

/**
 * Creates a POJO from a Jackson-annotated class given a jsonString
 *
 * @param jsonString//from w w w .j  a  v  a  2 s  .c  om
 * @param returnType
 * @param objectMapper
 * @return
 */
public static <T> T getJsonObject(String jsonString, Class<T> returnType, ObjectMapper objectMapper) {

    AssertUtil.notNull(jsonString, "jsonString cannot be null");
    if (jsonString.trim().length() == 0) {
        return null;
    }
    AssertUtil.notNull(objectMapper, "objectMapper cannot be null");
    try {
        return objectMapper.readValue(jsonString, returnType);
    } catch (IOException e) {
        // Rethrow as runtime exception
        log.error("Error unmarshalling from json: " + jsonString);
        throw new RuntimeException("Problem getting JSON object", e);
    }
}

From source file:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java

@SuppressWarnings("unchecked")
public static Map<String, Object> getDecUploadOid(String encUploadOidStr) throws ServiceException, Exception {
    if (StringUtils.isBlank(encUploadOidStr)) {
        throw new Exception("error, decrypt uploadOid value is blank!");
    }//from   ww  w .j  a  v a 2s .c  o m
    String uploadOid = EncryptorUtils.decrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(),
            SimpleUtils.deHex(encUploadOidStr));
    String jsonData = new String(UploadSupportUtils.getDataBytes(uploadOid));
    ObjectMapper mapper = new ObjectMapper();
    return (Map<String, Object>) mapper.readValue(jsonData, HashMap.class);
}

From source file:com.tectonica.thirdparty.Jackson2.java

public static <T, P> T fromJson(String jsonStr, Class<T> clz, Class<P> paramClz, ObjectMapper mapper) {
    try {//from   w  w  w  . j  a v  a2  s  .  c  o m
        JavaType jt = mapper.getTypeFactory().constructParametrizedType(clz, clz, paramClz);
        return mapper.readValue(jsonStr, jt);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.tectonica.thirdparty.Jackson2.java

public static <T, P> T fromJson(InputStream is, Class<T> clz, Class<P> paramClz, ObjectMapper mapper) {
    try {/*from  w w w  . j ava2  s. co  m*/
        JavaType jt = mapper.getTypeFactory().constructParametrizedType(clz, clz, paramClz);
        return mapper.readValue(is, jt);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}