Example usage for com.fasterxml.jackson.core JsonParser readValueAs

List of usage examples for com.fasterxml.jackson.core JsonParser readValueAs

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser readValueAs.

Prototype

@SuppressWarnings("unchecked")
public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content into a Java type, reference to which is passed as argument.

Usage

From source file:org.apache.olingo.client.core.edm.xml.v4.annotation.DynExprConstructDeserializer.java

@Override
protected DynExprConstructImpl doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    DynExprConstructImpl construct = null;

    if (DynExprSingleParamOp.Type.fromString(jp.getCurrentName()) != null) {
        final DynExprSingleParamOp dynExprSingleParamOp = new DynExprSingleParamOp();
        dynExprSingleParamOp.setType(DynExprSingleParamOp.Type.fromString(jp.getCurrentName()));

        jp.nextToken();/*from w  ww.jav a  2s  .c o m*/
        jp.nextToken();
        dynExprSingleParamOp.setExpression(jp.readValueAs(DynExprConstructImpl.class));

        construct = dynExprSingleParamOp;
    } else if (DynExprDoubleParamOp.Type.fromString(jp.getCurrentName()) != null) {
        final DynExprDoubleParamOp dynExprDoubleParamOp = new DynExprDoubleParamOp();
        dynExprDoubleParamOp.setType(DynExprDoubleParamOp.Type.fromString(jp.getCurrentName()));

        jp.nextToken();
        jp.nextToken();
        dynExprDoubleParamOp.setLeft(jp.readValueAs(DynExprConstructImpl.class));
        dynExprDoubleParamOp.setRight(jp.readValueAs(DynExprConstructImpl.class));

        construct = dynExprDoubleParamOp;
    } else if (ArrayUtils.contains(EL_OR_ATTR, jp.getCurrentName())) {
        final AbstractElOrAttrConstruct elOrAttr = getElOrAttrInstance(jp.getCurrentName());
        elOrAttr.setValue(jp.nextTextValue());

        construct = elOrAttr;
    } else if (APPLY.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(Apply.class);
    } else if (CAST.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(Cast.class);
    } else if (COLLECTION.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(Collection.class);
    } else if (IF.equals(jp.getCurrentName())) {
        jp.nextToken();
        jp.nextToken();

        final If _if = new If();
        _if.setGuard(parseConstOrEnumExprConstruct(jp));
        _if.setThen(parseConstOrEnumExprConstruct(jp));
        _if.setElse(parseConstOrEnumExprConstruct(jp));

        construct = _if;
    } else if (IS_OF.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(IsOf.class);
    } else if (LABELED_ELEMENT.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(LabeledElement.class);
    } else if (NULL.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(Null.class);
    } else if (RECORD.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(Record.class);
    } else if (URL_REF.equals(jp.getCurrentName())) {
        jp.nextToken();
        construct = jp.readValueAs(UrlRef.class);
    }

    return construct;
}

From source file:org.forgerock.openam.doc.jwt.bearer.Main.java

private static String parseTokenId(String publishResponse) throws Exception {
    java.util.Map responseContent;
    try {/*from   ww w  .java2  s .  c  o  m*/
        com.fasterxml.jackson.core.JsonParser parser = new com.fasterxml.jackson.databind.ObjectMapper()
                .getFactory().createParser(publishResponse);
        responseContent = parser.readValueAs(java.util.Map.class);
    } catch (IOException e) {
        throw new Exception(
                "Could not map the response from the PublishService to a json object. The response: "
                        + publishResponse + "; The exception: " + e);
    }
    return responseContent.get("tokenId").toString();

}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.java

public Map<String, List<Map>> getUserPluginInfo() throws IOException {
    String url = new StringBuilder(artifactoryUrl).append("/api/plugins").toString();
    HttpGet getPlugins = new HttpGet(url);
    HttpResponse getResponse = httpClient.getHttpClient().execute(getPlugins);
    StatusLine statusLine = getResponse.getStatusLine();
    HttpEntity responseEntity = getResponse.getEntity();
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Failed to obtain user plugin information. Status code: "
                + statusLine.getStatusCode() + getMessageFromEntity(responseEntity));
    } else {//from w w w.j a  v a  2  s.c om
        if (responseEntity != null) {
            InputStream content = responseEntity.getContent();
            JsonParser parser;
            try {
                parser = httpClient.createJsonParser(content);
                return parser.readValueAs(Map.class);
            } finally {
                if (content != null) {
                    content.close();
                }
            }
        }
    }
    return Maps.newHashMap();
}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryBuildInfoClient.java

public Map getStagingStrategy(String strategyName, String buildName, Map<String, String> requestParams)
        throws IOException {
    StringBuilder urlBuilder = new StringBuilder(artifactoryUrl).append("/api/plugins/build/staging/")
            .append(encodeUrl(strategyName)).append("?buildName=").append(encodeUrl(buildName)).append("&");
    appendParamsToUrl(requestParams, urlBuilder);
    HttpGet getRequest = new HttpGet(urlBuilder.toString());
    HttpResponse response = httpClient.getHttpClient().execute(getRequest);
    StatusLine statusLine = response.getStatusLine();
    HttpEntity responseEntity = response.getEntity();
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Failed to obtain staging strategy. Status code: " + statusLine.getStatusCode()
                + getMessageFromEntity(responseEntity));
    } else {/*w  ww  .j a  v a2s. c  o  m*/
        if (responseEntity != null) {
            InputStream content = responseEntity.getContent();
            JsonParser parser;
            try {
                parser = httpClient.createJsonParser(content);
                return parser.readValueAs(Map.class);
            } finally {
                if (content != null) {
                    content.close();
                }
            }
        }
    }
    return Maps.newHashMap();
}

From source file:org.jfrog.build.extractor.clientConfiguration.client.ArtifactoryDependenciesClient.java

/**
 * Reads HTTP response and converts it to object of the type specified.
 *
 * @param response     response to read/*from w ww  . j av a  2s . c o m*/
 * @param valueType    response object type
 * @param errorMessage error message to throw in case of error
 * @param <T>          response object type
 * @return response object converted from HTTP Json reponse to the type specified.
 * @throws java.io.IOException if reading or converting response fails.
 */
private <T> T readResponse(HttpResponse response, TypeReference<T> valueType, String errorMessage,
        boolean ignorMissingFields) throws IOException {

    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return null;
        }

        InputStream content = null;

        try {
            content = entity.getContent();
            JsonParser parser = httpClient.createJsonParser(content);
            if (ignorMissingFields) {
                ((ObjectMapper) parser.getCodec()).configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
            }
            // http://wiki.fasterxml.com/JacksonDataBinding
            return parser.readValueAs(valueType);
        } finally {
            if (content != null) {
                IOUtils.closeQuietly(content);
            }
        }
    } else {
        HttpEntity httpEntity = response.getEntity();
        if (httpEntity != null) {
            IOUtils.closeQuietly(httpEntity.getContent());
        }
        throw new IOException(errorMessage + ": " + response.getStatusLine());
    }
}

From source file:org.springframework.social.weibo.api.impl.json.TrendsDeserializer.java

@Override
public SortedSet<Trends> deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    TreeSet<Trends> result = new TreeSet<Trends>(comparator);
    TreeNode treeNode = jp.readValueAsTree();

    Iterator<String> fieldNames = treeNode.fieldNames();

    while (fieldNames.hasNext()) {
        Trends trends = new Trends();
        try {// ww w. j  a  va 2s  .  c om
            String filedName = fieldNames.next();
            dateFormat.applyPattern(retrieveDateFormatPattern(filedName));
            trends.setDate(dateFormat.parse(filedName));
            TreeNode trendsNode = treeNode.get(filedName);
            if (trendsNode.isArray()) {
                for (int i = 0; i < trendsNode.size(); i++) {
                    JsonParser nodeParser = trendsNode.get(i).traverse();
                    nodeParser.setCodec(jp.getCodec());
                    Trend readValueAs = nodeParser.readValueAs(Trend.class);
                    trends.getTrends().add(readValueAs);
                }
            }
            result.add(trends);
        } catch (ParseException e) {
            logger.warn("Unable to parse date", e);
        }
    }

    return result;
}

From source file:org.talend.dataprep.api.dataset.LightweightExportableDataSetUtils.java

/**
 * Reads token of the specified JsonParser and returns a list of column metadata.
 *
 * @param jsonParser the jsonParser whose next tokens are supposed to represent a list of column metadata
 * @return The column metadata parsed from JSON parser.
 * @throws IOException In case of JSON exception related error.
 */// w  w  w  . j  av  a2s  .  co  m
private static List<ColumnMetadata> parseAnArrayOfColumnMetadata(JsonParser jsonParser) throws IOException {
    try {
        List<ColumnMetadata> columns = new ArrayList<>();
        // skip the array beginning [
        jsonParser.nextToken();
        while (jsonParser.nextToken() != JsonToken.END_ARRAY && !jsonParser.isClosed()) {
            ColumnMetadata columnMetadata = jsonParser.readValueAs(ColumnMetadata.class);
            columns.add(columnMetadata);
        }
        if (columns.isEmpty()) {
            throw new IllegalArgumentException(
                    "No column metadata has been retrieved when trying to parse the retrieved data set.");
        }
        return columns;
    } catch (IOException e) {
        throw new IOExceptionWithCause("Unable to parse and retrieve the list of column metadata", e);
    }
}

From source file:org.talend.dataprep.api.dataset.LightweightExportableDataSetUtils.java

private static LightweightExportableDataSet parseRecords(JsonParser jsonParser, RowMetadata rowMetadata,
        String joinOnColumn) throws IOException {
    try {//from w  w w .  j  a  v a 2 s  .com
        LightweightExportableDataSet lookupDataset = new LightweightExportableDataSet();
        lookupDataset.setMetadata(rowMetadata);
        jsonParser.nextToken();
        while (jsonParser.nextToken() != JsonToken.END_ARRAY && !jsonParser.isClosed()) {
            Map<String, String> values = jsonParser.readValueAs(Map.class);
            lookupDataset.addRecord(values.get(joinOnColumn), values);
        }
        if (lookupDataset.isEmpty()) {
            throw new IllegalArgumentException(
                    "No lookup record has been retrieved when trying to parse the retrieved data set.");
        }
        return lookupDataset;
    } catch (IOException e) {
        throw new IOExceptionWithCause("Unable to parse and retrieve the records of the data set", e);
    }
}

From source file:org.xlcloud.openstack.model.climate.json.OpenStackDateDeserializer.java

@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String input = jp.readValueAs(String.class);
    if (input == null) {
        return null;
    }/* ww w  .ja  v  a2s. c o m*/

    try {
        return parseDate(input, DATE_PATTERNS); // We cannot use DateUtils.parseDate(), because it uses local timezone, instead of UTC.
    } catch (ParseException e) {
        throw new JsonMappingException("Could not parse date: " + input, e);
    }
}

From source file:portal.api.PortalClientIT.java

@Test
public void testPortalClientInstallServiceNotFoundAndFail() throws Exception {

    logger.info("Executing TEST = testPortalRSInstallServiceNotFound");
    List<Object> providers = new ArrayList<Object>();
    providers.add(new com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider());
    String uuid = UUID.fromString("55cab8b8-668b-4c75-99a9-39b24ed3d8be").toString();
    InstalledVxF is = prepareInstalledService(uuid);

    WebClient client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/", providers);
    Response r = client.accept("application/json").type("application/json").post(is);
    assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());

    String portalAPIVersionListHeaders = (String) r.getHeaders().getFirst("X-Portal-API-Version");
    assertEquals("1.0.0", portalAPIVersionListHeaders);

    MappingJsonFactory factory = new MappingJsonFactory();
    JsonParser parser = factory.createJsonParser((InputStream) r.getEntity());
    InstalledVxF output = parser.readValueAs(InstalledVxF.class);
    logger.info("InstalledServiceoutput = " + output.getUuid() + ", status=" + output.getStatus());
    assertEquals(InstalledVxFStatus.INIT, output.getStatus());

    // wait for 2 seconds
    Thread.sleep(2000);/*from   w ww.  j  a  v  a2  s .  c om*/
    // ask again about this task
    client = WebClient.create(endpointUrl + "/services/api/client/ivxfs/" + uuid);
    r = client.accept("application/json").type("application/json").get();

    factory = new MappingJsonFactory();
    parser = factory.createJsonParser((InputStream) r.getEntity());
    output = parser.readValueAs(InstalledVxF.class);

    assertEquals(uuid, output.getUuid());
    assertEquals(InstalledVxFStatus.FAILED, output.getStatus());
    assertEquals("(pending)", output.getName());
}