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

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

Introduction

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

Prototype

public abstract JsonToken nextToken() throws IOException, JsonParseException;

Source Link

Document

Main iteration method, which will advance stream enough to determine type of the next token, if any.

Usage

From source file:com.ntsync.shared.RequestGenerator.java

/**
 * /*from  ww  w . ja v a2 s . co  m*/
 * @param key
 * @param clientId
 * @param response
 * @return
 * @throws HeaderParseException
 */
public static SyncResponse processServerResponse(SecretKey key, String clientId, final byte[] response)
        throws HeaderParseException {
    short version = SyncDataHelper.readShort(response, 0);
    SyncState syncState = null;

    Map<Long, String> newGroupIdMap = null;
    Map<Long, String> newContactIdMap = null;
    SyncAnchor newSyncAnchor = new SyncAnchor();
    int skippedRows = 0;
    List<RawContact> serverContactList = new ArrayList<RawContact>();
    List<ContactGroup> serverGroupList = new ArrayList<ContactGroup>();

    String newClientId = clientId;
    Restrictions restr = null;
    if (version == RequestGenerator.PROT_VERSION) {
        int headerLength = SyncDataHelper.readInt(response, 2);

        JsonParser jp = null;
        try {
            jp = getJsonFactory().createParser(response, HEADER_POS, headerLength);
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                // move to value, or START_OBJECT/START_ARRAY
                if (jp.nextToken() == null) {
                    break;
                }
                if (CLIENT_FIELD_NAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String clientField = jp.getCurrentName();
                        if (jp.nextToken() == null) {
                            break;
                        }
                        if (PARAM_SYNC_ANCHOR.equals(clientField)) {
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                String anchorType = jp.getCurrentName();
                                if (jp.nextToken() == null) {
                                    break;
                                }
                                long syncAnchor = jp.getLongValue();
                                if (anchorType != null && anchorType.length() > 0) {
                                    newSyncAnchor.setAnchor((byte) anchorType.charAt(0), syncAnchor);
                                }
                            }
                        } else if (PARAM_CLIENTID.equals(clientField)) {
                            newClientId = jp.getValueAsString();
                        } else if (TAG_GROUPIDS.equals(clientField)) {
                            newGroupIdMap = extractNewIdList(jp);
                        } else if (TAG_CONTACTIDS.equals(clientField)) {
                            newContactIdMap = extractNewIdList(jp);
                        } else {
                            LOG.warn("Unsupported Client-Header-Field: {}", clientField);
                        }
                    }
                } else if (SERVER_FIELD_NAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String serverField = jp.getCurrentName();
                        if (jp.nextToken() == null) {
                            break;
                        }
                        if (RequestGenerator.SYNCSTATE_FIELD_NAME.equals(serverField)) {
                            String syncStateStr = jp.getValueAsString();
                            if (syncStateStr != null && syncStateStr.length() > 0) {
                                syncState = SyncState.fromErrorVal(syncStateStr);
                            }
                        } else if (RequestGenerator.TAG_SERVER_CONFIG.equals(serverField)) {
                            restr = parseRestr(jp);
                        }
                    }

                }
            }

            final int respLen = response.length;

            if (respLen > headerLength + HEADER_POS) {
                skippedRows = getUpdatedRows(key, serverContactList, serverGroupList, response, headerLength,
                        respLen);
            }
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (JsonParseException ex) {
            throw new HeaderParseException(ex);
        } catch (IOException e) {
            throw new HeaderParseException(e);
        } finally {
            if (jp != null) {
                try {
                    jp.close();
                } catch (IOException ex) {
                    LOG.warn("Could not close JSONParser", ex);
                }
            }
        }
    }

    return new SyncResponse(syncState, serverContactList, serverGroupList, newSyncAnchor, newClientId,
            newGroupIdMap, newContactIdMap, skippedRows, restr);
}

From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

public static Map<String, Object> extractSubmap(final JsonParser jsonParser) throws IOException {
    jsonParser.nextToken(); // skip the START_OBJECT token
    final Map<String, Object> subMap = new HashMap<String, Object>();
    while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
        final String label = jsonParser.getCurrentName(); // get the current label
        final JsonToken token = jsonParser.nextToken(); // get the current value
        if (!token.isScalarValue()) {
            if (token.equals(JsonToken.START_OBJECT)) {
                // if the next token starts a new object, recurse into it
                subMap.put(label, extractSubmap(jsonParser));
            } else if (token.equals(JsonToken.START_ARRAY)) {
                final List<String> subArray = new ArrayList<String>();
                jsonParser.nextToken(); // skip the START_ARRAY token
                while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
                    subArray.add(jsonParser.getValueAsString());
                    jsonParser.nextToken();
                }/*w  w  w  .  j a  v  a2  s .c  om*/
                subMap.put(label, subArray);
                jsonParser.nextToken(); // skip the END_ARRAY token
            }
        } else {
            // either a string, boolean, or long value
            if (token.isNumeric()) {
                subMap.put(label, jsonParser.getValueAsLong());
            } else {
                final String value = jsonParser.getValueAsString();
                if (value.equals("true") || value.equals("false")) {
                    subMap.put(label, jsonParser.getValueAsBoolean());
                } else {
                    subMap.put(label, value);
                }
            }
        }
        jsonParser.nextToken(); // next token will either be an "END_OBJECT" or a new label
    }
    jsonParser.nextToken(); // skip the END_OBJECT token
    return subMap;
}

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.
 * //from   w ww .j av a  2s  . c  om
 * @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:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

protected static void getAttachments(final JsonParser jsonParser, final List attachments) throws IOException {

    JsonToken token = jsonParser.nextToken(); // skip START_ARRAY token
    String filename;//from   w ww  .j  av  a  2 s.  c o m
    String mimeType;
    InputStream inputStream;
    while (token.equals(JsonToken.START_OBJECT)) {
        filename = null;
        mimeType = null;
        inputStream = null;
        byte[] databytes = null;
        token = jsonParser.nextToken();
        while (!token.equals(JsonToken.END_OBJECT)) {
            final String label = jsonParser.getCurrentName();
            jsonParser.nextToken();
            if (label.equals("filename")) {
                filename = URLDecoder.decode(jsonParser.getValueAsString(), "UTF-8");
            } else if (label.equals("jcr:mimeType")) {
                mimeType = jsonParser.getValueAsString();
            } else if (label.equals("jcr:data")) {
                databytes = Base64.decodeBase64(jsonParser.getValueAsString());
                inputStream = new ByteArrayInputStream(databytes);
            }
            token = jsonParser.nextToken();
        }
        if (filename != null && mimeType != null && inputStream != null) {
            attachments.add(
                    new UGCImportHelper.AttachmentStruct(filename, inputStream, mimeType, databytes.length));
        } else {
            // log an error
            LOG.error(
                    "We expected to import an attachment, but information was missing and nothing was imported");
        }
        token = jsonParser.nextToken();
    }
}

From source file:com.adobe.communities.ugc.migration.importer.UGCImportHelper.java

public static void extractTally(final Resource post, final JsonParser jsonParser,
        final ModifyingResourceProvider srp, final TallyOperationsService tallyOperationsService)
        throws IOException {
    jsonParser.nextToken(); // should be start object, but would be end array if no objects were present
    while (!jsonParser.getCurrentToken().equals(JsonToken.END_ARRAY)) {
        Long timestamp = null;//from w  w  w .j  a  v  a 2 s . c  o m
        String userIdentifier = null;
        String response = null;
        String tallyType = null;
        jsonParser.nextToken(); // should make current token by "FIELD_NAME" but could be END_OBJECT if this were
        // an empty object
        while (!jsonParser.getCurrentToken().equals(JsonToken.END_OBJECT)) {
            final String label = jsonParser.getCurrentName();
            jsonParser.nextToken(); // should be FIELD_VALUE
            if (label.equals(TallyConstants.TIMESTAMP_PROPERTY)) {
                timestamp = jsonParser.getValueAsLong();
            } else {
                final String responseValue = jsonParser.getValueAsString();
                if (label.equals("response")) {
                    response = URLDecoder.decode(responseValue, "UTF-8");
                } else if (label.equals("userIdentifier")) {
                    userIdentifier = URLDecoder.decode(responseValue, "UTF-8");
                } else if (label.equals("tallyType")) {
                    tallyType = responseValue;
                }
            }
            jsonParser.nextToken(); // should make current token be "FIELD_NAME" unless we're at the end of our
            // loop and it's now "END_OBJECT" instead
        }
        if (timestamp != null && userIdentifier != null && response != null && tallyType != null) {
            createTally(srp, post, tallyType, userIdentifier, timestamp, response, tallyOperationsService);
        }
        jsonParser.nextToken(); // may advance to "START_OBJECT" if we're not finished yet, but might be
        // "END_ARRAY" now
    }
}

From source file:org.labkey.freezerpro.export.ExportUserFieldsResponse.java

/**
 * Position the parser to the start of the data array object
 * @param parser// w w  w  . jav  a  2  s .  c  o m
 * @param dataNodeName
 * @return
 * @throws java.io.IOException
 */
protected boolean ensureDataNode(JsonParser parser, String dataNodeName) throws IOException {
    parser.nextToken();
    JsonUtil.expectObjectStart(parser);

    return true;
}

From source file:com.addthis.codec.jackson.CaseIgnoringEnumDeserializer.java

@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    JsonToken curr = jp.getCurrentToken();

    if ((curr == JsonToken.VALUE_STRING) || (curr == JsonToken.FIELD_NAME) || (curr == JsonToken.VALUE_FALSE)
            || (curr == JsonToken.VALUE_TRUE)) {
        String name = jp.getText();
        if (_lookupByName.find(name) != null) {
            return super.deserialize(jp, ctxt);
        }/*from  w w  w . j a  va 2 s  .  c  o m*/
        TextNode upperName = ctxt.getNodeFactory().textNode(name.toUpperCase());

        JsonParser treeParser = jp.getCodec().treeAsTokens(upperName);
        treeParser.nextToken();
        return super.deserialize(treeParser, ctxt);
    } else {
        return super.deserialize(jp, ctxt);
    }
}

From source file:io.encoded.jersik.runtime.JsonCodec.java

public <T> T decode(InputStream in, ObjectCodec<T> codec) throws IOException {
    JsonParser parser = JSON_FACTORY.createParser(in);
    try {/*  w  w w.j av a 2  s. com*/
        parser.nextToken();
        return codec.decode(parser);
    } finally {
        parser.close();
    }
}

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

public static Value parseValue(JsonParser parser, DeserializationContext ctxt) throws IOException {
    JsonToken token = getToken(parser);/*from www  .j av a  2s  .c o m*/
    if (token != null) {
        Value result;
        switch (token) {
        case VALUE_STRING:
            result = Value.of(parser.getValueAsString());
            break;
        case VALUE_NUMBER_FLOAT:
            result = Value.of(parser.getDoubleValue());
            break;
        case VALUE_NUMBER_INT:
            result = Value.of(parser.getBigIntegerValue());
            break;
        case VALUE_NULL:
            result = NullValueImpl.NULL;
            break;
        case VALUE_TRUE:
            result = Value.of(Boolean.TRUE);
            break;
        case VALUE_FALSE:
            result = Value.of(Boolean.FALSE);
            break;
        case START_OBJECT: {
            ValueMap values = ValueMap.newInstance();
            while (parser.nextToken() == JsonToken.FIELD_NAME) {
                String key = parser.getCurrentName();
                parser.nextToken();
                Value v = parseValue(parser, ctxt);
                if (v == null) {
                    throw ctxt.wrongTokenException(parser, JsonToken.START_OBJECT, "Expected Value");
                }
                values.put(key, v);
            }
            if (getToken(parser) == JsonToken.END_OBJECT) {
                parser.clearCurrentToken();
            } else {
                throw ctxt.wrongTokenException(parser, JsonToken.END_OBJECT, null);
            }
            result = values;
        }
            break;
        case START_ARRAY: {
            ValueList values = ValueList.newInstance();
            while (parser.nextToken() != JsonToken.END_ARRAY) {
                Value v = parseValue(parser, ctxt);
                if (v == null) {
                    throw ctxt.wrongTokenException(parser, JsonToken.START_OBJECT, "Expected Value");
                }
                values.add(v);
            }
            if (getToken(parser) == JsonToken.END_ARRAY) {
                parser.clearCurrentToken();
            } else {
                throw ctxt.wrongTokenException(parser, JsonToken.END_ARRAY, null);
            }
            result = values;
        }
            break;
        default:
            throw ctxt.wrongTokenException(parser, JsonToken.START_OBJECT, "Expected Value");
        }
        return result;
    } else {
        return null;
    }
}

From source file:org.o3project.ocnrm.model.bind.OduBindingData.java

@Override
public void bind(String name, String resource) throws JsonParseException, JsonMappingException, IOException {
    JsonFactory factory = new JsonFactory();
    JsonParser jp = factory.createParser(resource.toString());
    jp.nextToken();
    OduMapping terminationPoint = new OduMapping();
    terminationPoint.setName(name);//from   w w  w . j  av a 2  s .  c om
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        jp.nextToken();
        if ("dpid".equals(fieldname)) {
            terminationPoint.setDpid(jp.getText());
        } else if ("port".equals(fieldname)) {
            terminationPoint.setPort(jp.getText());
        } else if ("odutype".equals(fieldname)) {
            terminationPoint.setOdutype(jp.getText());
        } else if ("ts".equals(fieldname)) {
            String ts = jp.getText();
            terminationPoint.setTs(ts);
        } else if ("tpn".equals(fieldname)) {
            terminationPoint.setTpn(jp.getText());
        } else {
            throw new IllegalStateException("Unrecognized field '" + fieldname + "'!");
        }
        bindMap.put(terminationPoint.getName(), terminationPoint);
    }
    jp.close();
}