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.apache.usergrid.chop.api.RunnerDeserializer.java

@Override
public Runner deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    RunnerBuilder builder = new RunnerBuilder();

    String tmp = jp.getText();/*from  ww  w . j  av  a  2s  . co  m*/
    validate(jp, tmp, "{");
    LOG.debug("First token is {}", tmp);

    jp.nextToken();
    tmp = jp.getText();
    LOG.debug("Second token is {}", tmp);

    while (jp.hasCurrentToken()) {

        tmp = jp.getText();
        LOG.debug("Current token text = {}", tmp);

        if (tmp.equals("ipv4Address")) {
            jp.nextToken();
            builder.setIpv4Address(jp.getText());
        } else if (tmp.equals("hostname")) {
            jp.nextToken();
            builder.setHostname(jp.getText());
        } else if (tmp.equals("url")) {
            jp.nextToken();
            builder.setUrl(jp.getText());
        } else if (tmp.equals("serverPort")) {
            jp.nextToken();
            builder.setServerPort(jp.getValueAsInt());
        } else if (tmp.equals("tempDir")) {
            jp.nextToken();
            builder.setTempDir(jp.getText());
        }

        jp.nextToken();

        if (jp.getText().equals("}")) {
            break;
        }
    }

    return builder.getRunner();
}

From source file:org.apache.usergrid.chop.api.ProjectDeserializer.java

@Override
public Project deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
    ProjectBuilder builder = new ProjectBuilder();

    String tmp = jp.getText();/*  w w  w.  j  a  va2s.  c  om*/
    validate(jp, tmp, "{");
    LOG.debug("First token is {}", tmp);

    jp.nextToken();
    tmp = jp.getText();
    LOG.debug("Second token is {}", tmp);

    while (jp.hasCurrentToken()) {

        tmp = jp.getText();
        LOG.debug("Current token text = {}", tmp);

        if (tmp.equals("testPackageBase")) {
            jp.nextToken();
            builder.setTestPackageBase(jp.getText());
        } else if (tmp.equals("chopVersion")) {
            jp.nextToken();
            builder.setChopVersion(jp.getText());
        } else if (tmp.equals("createTimestamp")) {
            jp.nextToken();
            builder.setCreateTimestamp(jp.getText());
        } else if (tmp.equals("vcsVersion")) {
            jp.nextToken();
            builder.setVcsVersion(jp.getText());
        } else if (tmp.equals("vcsRepoUrl")) {
            jp.nextToken();
            builder.setVcsRepoUrl(jp.getText());
        } else if (tmp.equals("groupId")) {
            jp.nextToken();
            builder.setGroupId(jp.getText());
        } else if (tmp.equals("artifactId")) {
            jp.nextToken();
            builder.setArtifactId(jp.getText());
        } else if (tmp.equals("projectVersion")) {
            jp.nextToken();
            builder.setProjectVersion(jp.getText());
        } else if (tmp.equals("md5")) {
            jp.nextToken();
            builder.setMd5(jp.getText());
        } else if (tmp.equals("loadKey")) {
            jp.nextToken();
            builder.setLoadKey(jp.getText());
        } else if (tmp.equals("loadTime")) {
            jp.nextToken();
            builder.setLoadTime(jp.getText());
        }

        jp.nextToken();

        if (jp.getText().equals("}")) {
            break;
        }
    }

    return builder.getProject();
}

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

/**
 * Private routine to deserialize nucleotide Store JSON. This is done manually to give more freedom regarding data
 * returned by the webservice./*  w  w  w .  j  a  v  a  2 s .  c  o m*/
 * 
 * @param parser the JSONParser containing JSONData.
 * @return Map containing nucleotides
 * 
 * @throws JsonParseException
 * @throws IOException
 */
private Map<String, String> deserializeNucleotideStore(JsonParser parser)
        throws JsonParseException, IOException {
    Map<String, String> nucleotides = new HashMap<String, String>();
    String currentNucleotideSymbol = "";
    String currentNucleotideNotation = "";
    boolean foundSymbol = false;
    boolean foundNotation = false;

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

        if (fieldName != null) {
            switch (fieldName) {
            case "symbol":
                parser.nextToken();
                currentNucleotideSymbol = parser.getText();
                foundSymbol = true;
                break;
            case "notation":
                parser.nextToken();
                currentNucleotideNotation = parser.getText();
                foundNotation = true;
                break;
            default:
                break;
            }

            if (foundSymbol && foundNotation) {
                nucleotides.put(currentNucleotideSymbol, currentNucleotideNotation);
                foundNotation = false;
                foundSymbol = false;
            }
        }
        parser.nextToken();
    }

    return nucleotides;
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.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.
 * //from w  w w . j  a  v  a 2  s.co 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 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 ParseException
 *             if an error occurs while parsing the stream.
 * @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")
private static <T extends TableEntity, R> ODataPayload<?> parseJsonQueryResponse(final InputStream inStream,
        final Class<T> clazzType, final EntityResolver<R> resolver, final TableRequestOptions options,
        final OperationContext opContext) throws ParseException, InstantiationException, IllegalAccessException,
        StorageException, JsonParseException, IOException {
    ODataPayload<T> corePayload = null;
    ODataPayload<R> resolvedPayload = null;
    ODataPayload<?> commonPayload = null;

    JsonParser parser = createJsonParserFromStream(inStream);

    try {

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

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

        ODataUtilities.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();

                ODataUtilities.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();
                }

                ODataUtilities.assertIsEndArrayJsonToken(parser);
            }

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

    return commonPayload;
}

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

/**
 * Private routine to deserialize monomer Store JSON. This is done manually to
 * give more freedom regarding data returned by the webservice.
 *
 * @param parser the JSONParser containing JSONData.
 * @param attachmentDB the attachments stored in the Toolkit
 * @return Map containing monomers/* w  w w. jav a  2s  . c  o m*/
 *
 * @throws JsonParseException
 * @throws IOException
 * @throws EncoderException
 */
private Map<String, Monomer> deserializeMonomerStore(JsonParser parser, Map<String, Attachment> attachmentDB)
        throws JsonParseException, IOException, EncoderException {
    Map<String, Monomer> monomers = new HashMap<String, Monomer>();
    Monomer currentMonomer = null;

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

        if (JsonToken.START_OBJECT.equals(token)) {
            currentMonomer = new Monomer();
        } else if (JsonToken.END_OBJECT.equals(token)) {
            monomers.put(currentMonomer.getAlternateId(), currentMonomer);
        }

        if (fieldName != null) {
            switch (fieldName) {
            // id is first field
            case "id":
                parser.nextToken();
                currentMonomer.setId(Integer.parseInt(parser.getText()));
                break;
            case "alternateId":
                parser.nextToken();
                currentMonomer.setAlternateId(parser.getText());
                break;
            case "naturalAnalog":
                parser.nextToken();
                currentMonomer.setNaturalAnalog(parser.getText());
                break;
            case "name":
                parser.nextToken();
                currentMonomer.setName(parser.getText());
                break;
            case "canSMILES":
                parser.nextToken();
                currentMonomer.setCanSMILES(parser.getText());
                break;
            case "molfile":
                parser.nextToken();
                currentMonomer.setMolfile(MolfileEncoder.decode(parser.getText()));
                break;
            case "monomerType":
                parser.nextToken();
                currentMonomer.setMonomerType(parser.getText());
                break;
            case "polymerType":
                parser.nextToken();
                currentMonomer.setPolymerType(parser.getText());
                break;
            case "attachmentList":
                currentMonomer.setAttachmentList(deserializeAttachmentList(parser, attachmentDB));
                break;
            case "newMonomer":
                parser.nextToken();
                currentMonomer.setNewMonomer(Boolean.parseBoolean(parser.getText()));
                break;
            case "adHocMonomer":
                parser.nextToken();
                currentMonomer.setAdHocMonomer(Boolean.parseBoolean(parser.getText()));
                break;
            default:
                break;
            }
        }
        parser.nextToken();
    }

    return monomers;
}

From source file:org.emfjson.jackson.databind.deser.ResourceDeserializer.java

@Override
public Resource deserialize(JsonParser jp, DeserializationContext ctxt, Resource intoValue) throws IOException {
    final Resource resource = getResource(ctxt, intoValue);
    if (resource == null) {
        throw new IllegalArgumentException("Invalid resource");
    }//from  ww w.j a  va2s  . c o m

    final ReferenceEntries entries = new ReferenceEntries();
    final EcoreTypeFactory ecoreType = new EcoreTypeFactory();
    final ResourceSet resourceSet = resource.getResourceSet();

    ctxt.setAttribute(RESOURCE, resource);
    ctxt.setAttribute(REFERENCE_ENTRIES, entries);
    ctxt.setAttribute(CACHE, new Cache());
    ctxt.setAttribute(TYPE_FACTORY, ecoreType);
    ctxt.setAttribute(RESOURCE_SET, resourceSet);

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

    final TypeFactory factory = TypeFactory.defaultInstance();
    final JsonDeserializer<Object> deserializer = ctxt
            .findRootValueDeserializer(factory.constructType(EObject.class));

    if (jp.getCurrentToken() == JsonToken.START_ARRAY) {

        while (jp.nextToken() != JsonToken.END_ARRAY) {

            EObject value = (EObject) deserializer.deserialize(jp, ctxt);
            if (value != null) {
                resource.getContents().add(value);
            }
        }

    } else if (jp.getCurrentToken() == JsonToken.START_OBJECT) {
        EObject value = (EObject) deserializer.deserialize(jp, ctxt);
        if (value != null) {
            resource.getContents().add(value);
        }
    }

    entries.resolve(resourceSet, uriHandler);

    return resource;
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the
 * specified stream in JSON format into a {@link TableResult} containing an entity of the specified class type
 * projected using the specified resolver.
 * //from   w w w . jav a 2 s . c  o m
 * @param parser
 *            The <code>JsonParser</code> to read the data to parse from.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entity as an instance of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} containing the parsed entity result of the operation.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @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.
 */
private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser,
        final Class<T> clazzType, HashMap<String, PropertyPair> classProperties,
        final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext)
        throws JsonParseException, IOException, ParseException, StorageException, InstantiationException,
        IllegalAccessException {
    final TableResult res = new TableResult();

    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

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

    ODataUtilities.assertIsStartObjectJsonToken(parser);

    parser.nextToken();

    // get all metadata, if present
    while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) {
        final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length());

        // get the value token
        parser.nextToken();

        if (name.equals(ODataConstants.ETAG)) {
            String etag = parser.getValueAsString();
            res.setEtag(etag);
        }

        // get the key token
        parser.nextToken();
    }

    if (resolver == null && clazzType == null) {
        return res;
    }

    // get object properties
    while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
        String key = Constants.EMPTY_STRING;
        String val = Constants.EMPTY_STRING;
        EdmType edmType = null;

        // checks if this property is preceded by an OData property type annotation
        if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata
                && parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) {
            parser.nextToken();
            edmType = EdmType.parse(parser.getValueAsString());

            parser.nextValue();
            key = parser.getCurrentName();
            val = parser.getValueAsString();
        } else {
            key = parser.getCurrentName();

            parser.nextToken();
            val = parser.getValueAsString();
            edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString());
        }

        final EntityProperty newProp = new EntityProperty(val, edmType);
        properties.put(key, newProp);

        parser.nextToken();
    }

    String partitionKey = null;
    String rowKey = null;
    Date timestamp = null;
    String etag = null;

    // Remove core properties from map and set individually
    EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        partitionKey = tempProp.getValueAsString();
    }

    tempProp = properties.remove(TableConstants.ROW_KEY);
    if (tempProp != null) {
        rowKey = tempProp.getValueAsString();
    }

    tempProp = properties.remove(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        timestamp = tempProp.getValueAsDate();

        if (res.getEtag() == null) {
            etag = getETagFromTimestamp(tempProp.getValueAsString());
            res.setEtag(etag);
        }
    }

    // do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType
    if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata
            && (options.getPropertyResolver() != null || clazzType != null)) {
        if (options.getPropertyResolver() != null) {
            for (final Entry<String, EntityProperty> p : properties.entrySet()) {
                final String key = p.getKey();
                final String value = p.getValue().getValueAsString();
                EdmType edmType;

                // try to use the property resolver to get the type
                try {
                    edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value);
                } catch (Exception e) {
                    throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW,
                            Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
                }

                // try to create a new entity property using the returned type
                try {
                    final EntityProperty newProp = new EntityProperty(value, edmType);
                    properties.put(p.getKey(), newProp);
                } catch (IllegalArgumentException e) {
                    throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE,
                            String.format(SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType),
                            Constants.HeaderConstants.HTTP_UNUSED_306, null, e);
                }
            }
        } else if (clazzType != null) {
            if (classProperties == null) {
                classProperties = PropertyPair.generatePropertyPairs(clazzType);
            }
            for (final Entry<String, EntityProperty> p : properties.entrySet()) {
                PropertyPair propPair = classProperties.get(p.getKey());
                if (propPair != null) {
                    final EntityProperty newProp = new EntityProperty(p.getValue().getValueAsString(),
                            propPair.type);
                    properties.put(p.getKey(), newProp);
                }
            }
        }
    }

    // set the result properties, now that they are appropriately parsed
    res.setProperties(properties);

    // use resolver if provided, else create entity based on clazz type
    if (resolver != null) {
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
    } else if (clazzType != null) {
        // Generate new entity and return
        final T entity = clazzType.newInstance();
        entity.setEtag(res.getEtag());

        entity.setPartitionKey(partitionKey);
        entity.setRowKey(rowKey);
        entity.setTimestamp(timestamp);

        entity.readEntity(res.getProperties(), opContext);

        res.setResult(entity);
    }

    return res;
}