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

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

Introduction

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

Prototype

public abstract boolean hasCurrentToken();

Source Link

Document

Method for checking whether parser currently points to a token (and data for that token is available).

Usage

From source file:org.dbrain.data.jackson.serializers.JacksonSerializationUtils.java

/**
 * Helper method to ensure to get the current token.
 *///from   w ww .  j a va 2  s  .c o m
public static JsonToken getToken(JsonParser parser) throws IOException {
    return parser.hasCurrentToken() ? parser.getCurrentToken() : parser.nextToken();
}

From source file:org.agorava.linkedin.jackson.DeserializationUtils.java

public static <T> T deserializeFromDataNode(JsonParser jp, DeserializationContext ctxt, String propertyName,
        TypeReference<T> typeReference) throws IOException, JsonProcessingException {
    if (jp.hasCurrentToken() && jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        JsonNode dataNode = jp.readValueAs(JsonNode.class);
        if (dataNode.has(propertyName)) {
            return OBJECT_MAPPER.reader(typeReference).<T>readValue(dataNode.get(propertyName));
        }/*from w  w w  .  j a  v  a  2 s  . c  om*/
        return null;
    }
    throw ctxt.mappingException("Expected JSON object");
}

From source file:com.microsoft.azure.storage.blob.BlobEncryptionData.java

public static BlobEncryptionData deserialize(String inputData) throws JsonProcessingException, IOException {
    JsonParser parser = Utility.getJsonParser(inputData);
    BlobEncryptionData data = new BlobEncryptionData();
    try {// w  ww . j a va  2s.  co  m
        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();

        while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
            String name = parser.getCurrentName();
            parser.nextToken();

            if (name.equals(Constants.EncryptionConstants.ENCRYPTION_MODE)) {
                data.setEncryptionMode(parser.getValueAsString());
            } else if (name.equals(Constants.EncryptionConstants.WRAPPED_CONTENT_KEY)) {
                data.setWrappedContentKey(WrappedContentKey.deserialize(parser));
            } else if (name.equals(Constants.EncryptionConstants.ENCRYPTION_AGENT)) {
                data.setEncryptionAgent(EncryptionAgent.deserialize(parser));
            } else if (name.equals(Constants.EncryptionConstants.CONTENT_ENCRYPTION_IV)) {
                data.setContentEncryptionIV(parser.getBinaryValue());
            } else if (name.equals(Constants.EncryptionConstants.KEY_WRAPPING_METADATA)) {
                data.setKeyWrappingMetadata(deserializeKeyWrappingMetadata(parser));
            } else {
                consumeJsonObject(parser);
            }
            parser.nextToken();
        }

        JsonUtilities.assertIsEndObjectJsonToken(parser);
    } finally {
        parser.close();
    }

    return data;
}

From source file:com.microsoft.azure.storage.queue.CloudQueueEncryptedMessage.java

public static CloudQueueEncryptedMessage deserialize(String inputMessage)
        throws JsonProcessingException, IOException {
    JsonParser parser = Utility.getJsonParser(inputMessage);
    CloudQueueEncryptedMessage message = new CloudQueueEncryptedMessage();
    try {//  w  w  w.  java  2  s  .  com
        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();

        while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
            String name = parser.getCurrentName();
            parser.nextToken();

            if (name.equals("EncryptedMessageContents")) {
                message.setEncryptedMessageContents(parser.getValueAsString());
            } else if (name.equals("EncryptionData")) {
                message.setEncryptionData(EncryptionData.deserialize(parser));
            }
            parser.nextToken();
        }

        JsonUtilities.assertIsEndObjectJsonToken(parser);
    } finally {
        parser.close();
    }

    return message;
}

From source file:com.microsoft.azure.storage.core.EncryptionData.java

public static EncryptionData deserialize(String inputData) throws JsonProcessingException, IOException {
    JsonParser parser = Utility.getJsonParser(inputData);
    try {/*  ww w  .  j  a va2 s.  c o m*/
        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        return EncryptionData.deserialize(parser);
    } finally {
        parser.close();
    }
}

From source file:com.microsoft.azure.storage.table.TableStorageErrorDeserializer.java

/**
 * Gets the Extended Error information./*from w  w  w  . jav  a2 s .  c  o m*/
 * 
 * @return the Extended Error information.
 * 
 * @param reader
 *            the input stream to read error details from.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing
 * @throws IOException
 *             if an error occurs while accessing the stream with Json.
 * @throws JsonParseException
 *             if an error occurs while parsing the stream.
 */
public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader,
        final TablePayloadFormat format) throws JsonParseException, IOException {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser parser = jsonFactory.createParser(reader);
    try {
        final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation();

        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);
        JsonUtilities.assertIsExpectedFieldName(parser, "odata.error");

        // start getting extended error information
        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        // get code
        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE);
        errorInfo.setErrorCode(parser.getValueAsString());

        // get message
        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);
        JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE);

        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, "lang");

        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, "value");
        errorInfo.setErrorMessage(parser.getValueAsString());

        parser.nextToken();
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        parser.nextToken();

        // get innererror if it exists
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR);
            errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser));
            parser.nextToken();
        }

        // end code object
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        // end odata.error object
        parser.nextToken();
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        return errorInfo;
    } finally {
        parser.close();
    }
}

From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java

/**
 * Private routine to deserialize JSON containing monomer categorization data.
 * This is done manually to give more freedom regarding data returned by the
 * webservice./*from  ww  w.  j  a v a 2 s.  c o m*/
 *
 * @param parser the JSONParser containing JSONData.
 * @return List containing the monomer categorization
 *
 * @throws JsonParseException
 * @throws IOException
 */
private static List<CategorizedMonomer> deserializeEditorCategorizationConfig(JsonParser parser)
        throws JsonParseException, IOException {
    List<CategorizedMonomer> config = new LinkedList<CategorizedMonomer>();
    CategorizedMonomer currentMonomer = null;

    parser.nextToken();
    while (parser.hasCurrentToken()) {
        String fieldName = parser.getCurrentName();
        JsonToken token = parser.getCurrentToken();

        if (JsonToken.START_OBJECT.equals(token)) {
            currentMonomer = new CategorizedMonomer();
        } else if (JsonToken.END_OBJECT.equals(token)) {
            config.add(currentMonomer);
        }

        if (fieldName != null) {
            switch (fieldName) {
            // id is first field
            case "monomerID":
                parser.nextToken();
                currentMonomer.setMonomerID(parser.getText());
                break;
            case "monomerName":
                parser.nextToken();
                currentMonomer.setMonomerName(parser.getText());
                break;
            case "naturalAnalogon":
                parser.nextToken();
                currentMonomer.setNaturalAnalogon(parser.getText());
                break;
            case "monomerType":
                parser.nextToken();
                currentMonomer.setMonomerType(parser.getText());
                break;
            case "polymerType":
                parser.nextToken();
                currentMonomer.setPolymerType(parser.getText());
                break;
            case "category":
                parser.nextToken();
                currentMonomer.setCategory(parser.getText());
                break;
            case "shape":
                parser.nextToken();
                currentMonomer.setShape(parser.getText());
                break;
            case "fontColor":
                parser.nextToken();
                currentMonomer.setFontColor(parser.getText());
                break;
            case "backgroundColor":
                parser.nextToken();
                currentMonomer.setBackgroundColor(parser.getText());
                break;
            default:
                break;
            }
        }
        parser.nextToken();
    }

    return config;
}

From source file:com.microsoft.azure.storage.table.CEKReturn.java

/**
 * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the
 * specified input stream using the specified class type and optionally projects each entity result with the
 * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects.
 * // ww  w . ja  v a 2s  .c o  m
 * @param inStream
 *            The <code>InputStream</code> to read the data to parse from.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to
 *            <code>null</code> to ignore the returned entities and copy only response properties into the
 *            {@link TableResult} objects.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set
 *            to <code>null</code> to return the entities as instances of the class type <code>T</code>.
 * @param options
 *            A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation
 *         response.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 * @throws JsonParseException
 *             if an error occurs while parsing the stream.
 */
@SuppressWarnings("unchecked")
static <T extends TableEntity, R> ODataPayload<?> parseQueryResponse(final InputStream inStream,
        final TableRequestOptions options, final Class<T> clazzType, final EntityResolver<R> resolver,
        final OperationContext opContext) throws JsonParseException, IOException, InstantiationException,
        IllegalAccessException, StorageException {
    ODataPayload<T> corePayload = null;
    ODataPayload<R> resolvedPayload = null;
    ODataPayload<?> commonPayload = null;

    JsonParser parser = Utility.getJsonParser(inStream);

    try {

        if (resolver != null) {
            resolvedPayload = new ODataPayload<R>();
            commonPayload = resolvedPayload;
        } else {
            corePayload = new ODataPayload<T>();
            commonPayload = corePayload;
        }

        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        // move into data  
        parser.nextToken();

        // if there is a clazz type and if JsonNoMetadata, create a classProperties dictionary to use for type inference once 
        // instead of querying the cache many times
        HashMap<String, PropertyPair> classProperties = null;
        if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && clazzType != null) {
            classProperties = PropertyPair.generatePropertyPairs(clazzType);
        }

        while (parser.getCurrentToken() != null) {
            if (parser.getCurrentToken() == JsonToken.FIELD_NAME
                    && parser.getCurrentName().equals(ODataConstants.VALUE)) {
                // move to start of array
                parser.nextToken();

                JsonUtilities.assertIsStartArrayJsonToken(parser);

                // go to properties
                parser.nextToken();

                while (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                    final TableResult res = parseJsonEntity(parser, clazzType, classProperties, resolver,
                            options, opContext);
                    if (corePayload != null) {
                        corePayload.tableResults.add(res);
                    }

                    if (resolver != null) {
                        resolvedPayload.results.add((R) res.getResult());
                    } else {
                        corePayload.results.add((T) res.getResult());
                    }

                    parser.nextToken();
                }

                JsonUtilities.assertIsEndArrayJsonToken(parser);
            }

            parser.nextToken();
        }
    } finally {
        parser.close();
    }

    return commonPayload;
}

From source file:org.springframework.social.linkedin.api.impl.json.CodeDeserializer.java

@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    if (jp.hasCurrentToken() && jp.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.reader(JsonNode.class).readValue(jp);
        return node.has(VALUE) ? node.get(VALUE).textValue() : null;
    }/*from  w w w  .ja v a2  s  .co m*/

    throw ctxt.mappingException("Expected JSON object");
}

From source file:io.progix.dropwizard.patch.explicit.PatchInstructionDeserializer.java

/**
 * This method is responsible for deserialization of a {@link PatchInstruction}
 * <p/>/*from w ww.j  a va 2 s  .  c om*/
 * The value in a patch instruction is mapped to a TreeMap and can be later converted to a class of choice using
 * {@link JsonPatchValue}
 *
 * @see JsonDeserializer
 */
@Override
public PatchInstruction deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    untypedObjectDeserializer.resolve(ctxt);

    JsonNode node = jp.getCodec().readTree(jp);

    PatchOperation operation = PatchOperation.valueOf(node.get("op").asText().toUpperCase());

    String path = node.get("path").asText();

    String from = null;
    JsonNode fromNode = node.get("from");
    if (fromNode != null) {
        from = fromNode.asText();
    }

    List<Object> values = null;
    JsonNode valueNode = node.get("value");
    if (valueNode != null) {
        values = new ArrayList<>();
        if (valueNode.isArray()) {
            Iterator<JsonNode> iterator = valueNode.elements();
            while (iterator.hasNext()) {
                JsonNode elementNode = iterator.next();
                JsonParser p = elementNode.traverse();
                if (!p.hasCurrentToken()) {
                    p.nextToken();
                }
                Object element = untypedObjectDeserializer.deserialize(p, ctxt);
                values.add(element);
            }
        } else {
            JsonParser p = valueNode.traverse();
            if (!p.hasCurrentToken()) {
                p.nextToken();
            }
            Object value = untypedObjectDeserializer.deserialize(p, ctxt);
            values.add(value);
        }
    }

    return new PatchInstruction(operation, path, values, from);
}