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

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

Introduction

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

Prototype

public abstract JsonToken getCurrentToken();

Source Link

Document

Accessor to find which token parser currently points to, if any; null will be returned if none.

Usage

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

/**
 * Handle each of the importable types of ugc content
 * @param jsonParser - the parsing stream
 * @param resource - the parent resource of whatever it is we're importing (must already exist)
 * @throws ServletException//  w ww .  j  a va 2  s .c o m
 * @throws IOException
 */
protected void importFile(final JsonParser jsonParser, final Resource resource, final ResourceResolver resolver)
        throws ServletException, IOException {
    final UGCImportHelper importHelper = new UGCImportHelper();
    JsonToken token1 = jsonParser.getCurrentToken();
    importHelper.setSocialUtils(socialUtils);
    if (token1.equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken();
        if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT_TYPE)) {
            jsonParser.nextToken();
            final String contentType = jsonParser.getValueAsString();
            if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) {
                importHelper.setQnaForumOperations(qnaForumOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) {
                importHelper.setForumOperations(forumOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) {
                importHelper.setCalendarOperations(calendarOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) {
                importHelper.setJournalOperations(journalOperations);
            } else if (contentType.equals(ContentTypeDefinitions.LABEL_FILELIBRARY)) {
                importHelper.setFileLibraryOperations(fileLibraryOperations);
            }
            importHelper.setTallyService(tallyOperationsService); // (everything potentially needs tally)
            importHelper.setCommentOperations(commentOperations); // nearly anything can have comments on it
            jsonParser.nextToken(); // content
            if (jsonParser.getCurrentName().equals(ContentTypeDefinitions.LABEL_CONTENT)) {
                jsonParser.nextToken();
                token1 = jsonParser.getCurrentToken();
                if (token1.equals(JsonToken.START_OBJECT) || token1.equals(JsonToken.START_ARRAY)) {
                    if (!resolver.isLive()) {
                        throw new ServletException("Resolver is already closed");
                    }
                } else {
                    throw new ServletException("Start object token not found for content");
                }
                if (token1.equals(JsonToken.START_OBJECT)) {
                    try {
                        if (contentType.equals(ContentTypeDefinitions.LABEL_QNA_FORUM)) {
                            importHelper.importQnaContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_FORUM)) {
                            importHelper.importForumContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_COMMENTS)) {
                            importHelper.importCommentsContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_JOURNAL)) {
                            importHelper.importJournalContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_FILELIBRARY)) {
                            importHelper.importFileLibrary(jsonParser, resource, resolver);
                        } else {
                            LOG.info("Unsupported content type: {}", contentType);
                            jsonParser.skipChildren();
                        }
                        jsonParser.nextToken();
                    } catch (final IOException e) {
                        throw new ServletException(e);
                    }
                    jsonParser.nextToken(); // skip over END_OBJECT
                } else {
                    try {
                        if (contentType.equals(ContentTypeDefinitions.LABEL_CALENDAR)) {
                            importHelper.importCalendarContent(jsonParser, resource, resolver);
                        } else if (contentType.equals(ContentTypeDefinitions.LABEL_TALLY)) {
                            importHelper.importTallyContent(jsonParser, resource, resolver);
                        } else {
                            LOG.info("Unsupported content type: {}", contentType);
                            jsonParser.skipChildren();
                        }
                        jsonParser.nextToken();
                    } catch (final IOException e) {
                        throw new ServletException(e);
                    }
                    jsonParser.nextToken(); // skip over END_ARRAY
                }
            } else {
                throw new ServletException("Content not found");
            }
        } else {
            throw new ServletException("No content type specified");
        }
    } else {
        throw new ServletException("Invalid Json format");
    }
}

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 a v a 2 s .  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:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * Process an embedded object./*from  ww w . j a va  2  s  .  c  o m*/
 *
 * @param jsonParser the parser
 * @return map with embedded object key:values
 * @throws IOException If unable to read input parser
 */
private Object getEmbeddedObject(JsonParser jsonParser) throws IOException {
    LOG.info("Start parsing an embedded object.");
    Map<String, Object> embeddedMap = new HashMap<>();
    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = jsonParser.getText();
        jsonParser.nextToken();
        JsonToken token = jsonParser.getCurrentToken();
        if (token == JsonToken.START_ARRAY) {
            Object embeddedArray = getCollectionValue(jsonParser);
            embeddedMap.put(key, embeddedArray);
        } else if (token == JsonToken.START_OBJECT) {
            Object embeddedObject = getEmbeddedObject(jsonParser);
            embeddedMap.put(key, embeddedObject);
        } else {
            if (token.equals(JsonToken.VALUE_NULL)) {
                embeddedMap.put(key, null);
            } else {
                embeddedMap.put(key, jsonParser.getText());
            }
        }
    }
    return embeddedMap;
}

From source file:io.protostuff.JsonInput.java

private <T> int readFieldNumber(final Schema<T> schema, final JsonParser parser) throws IOException {
    for (;;) {/*from   ww w  .j a  v  a  2  s .  co m*/
        if (parser.nextToken() == END_OBJECT)
            return 0;

        if (parser.getCurrentToken() != FIELD_NAME) {
            throw new JsonInputException("Expected token: $field: but was " + parser.getCurrentToken()
                    + " on message " + schema.messageFullName());
        }

        final String name = parser.getCurrentName();

        // move to the next token
        if (parser.nextToken() == START_ARRAY) {
            JsonToken jt = parser.nextToken();

            // if empty array, read the next field
            if (jt == END_ARRAY)
                continue;

            if (jt == VALUE_NULL) {
                // skip null elements
                while (VALUE_NULL == (jt = parser.nextToken()))
                    ;

                // all elements were null.
                if (jt == END_ARRAY)
                    continue;
            }

            final int number = numeric ? Integer.parseInt(name) : schema.getFieldNumber(name);

            if (number == 0) {
                // unknown field
                if (parser.getCurrentToken().isScalarValue()) {
                    // skip the scalar elements
                    while (parser.nextToken() != END_ARRAY)
                        ;

                    continue;
                }

                throw new JsonInputException(
                        "Unknown field: " + name + " on message " + schema.messageFullName());
            }

            lastRepeated = true;
            lastName = name;
            lastNumber = number;

            return number;
        }

        // skip null value
        if (parser.getCurrentToken() == VALUE_NULL)
            continue;

        final int number = numeric ? Integer.parseInt(name) : schema.getFieldNumber(name);

        if (number == 0) {
            // we can skip this unknown field
            if (parser.getCurrentToken().isScalarValue())
                continue;

            throw new JsonInputException("Unknown field: " + name + " on message " + schema.messageFullName());
        }

        lastName = name;
        lastNumber = number;

        return number;
    }
}

From source file:net.opentsdb.utils.TestJSON.java

/** Helper to parse an input stream into a map */
private HashMap<String, String> parseToMap(final JsonParser jp) throws Exception {
    HashMap<String, String> map = new HashMap<String, String>();
    String field = "";
    String value;// w w w .j a v  a  2s  .  c o m
    while (jp.nextToken() != null) {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName() != null) {
            field = jp.getCurrentName();
        } else if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            value = jp.getText();
            map.put(field, value);
        }
    }
    return map;
}

From source file:net.opentsdb.utils.TestJSON.java

/** Helper to parse an input stream into a map */
private HashMap<String, String> parseToMap(final InputStream is) throws Exception {
    JsonParser jp = JSON.parseToStream(is);
    HashMap<String, String> map = new HashMap<String, String>();
    String field = "";
    String value;/*  ww w  .  j  a v a2s . c  om*/
    while (jp.nextToken() != null) {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME && jp.getCurrentName() != null) {
            field = jp.getCurrentName();
        } else if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            value = jp.getText();
            map.put(field, value);
        }
    }
    return map;
}

From source file:org.mongojack.internal.object.BsonObjectGenerator.java

@Override
public void copyCurrentEvent(JsonParser jp) throws IOException {
    JsonToken t = jp.getCurrentToken();
    switch (t) {/*from w w w. ja  v a  2  s  . c om*/
    case START_OBJECT:
        writeStartObject();
        break;
    case END_OBJECT:
        writeEndObject();
        break;
    case START_ARRAY:
        writeStartArray();
        break;
    case END_ARRAY:
        writeEndArray();
        break;
    case FIELD_NAME:
        writeFieldName(jp.getCurrentName());
        break;
    case VALUE_STRING:
        if (jp.hasTextCharacters()) {
            writeString(jp.getTextCharacters(), jp.getTextOffset(), jp.getTextLength());
        } else {
            writeString(jp.getText());
        }
        break;
    case VALUE_NUMBER_INT:
        switch (jp.getNumberType()) {
        case INT:
            writeNumber(jp.getIntValue());
            break;
        case BIG_INTEGER:
            writeNumber(jp.getBigIntegerValue());
            break;
        default:
            writeNumber(jp.getLongValue());
        }
        break;
    case VALUE_NUMBER_FLOAT:
        switch (jp.getNumberType()) {
        case BIG_DECIMAL:
            writeNumber(jp.getDecimalValue());
            break;
        case FLOAT:
            writeNumber(jp.getFloatValue());
            break;
        default:
            writeNumber(jp.getDoubleValue());
        }
        break;
    case VALUE_TRUE:
        writeBoolean(true);
        break;
    case VALUE_FALSE:
        writeBoolean(false);
        break;
    case VALUE_NULL:
        writeNull();
        break;
    case VALUE_EMBEDDED_OBJECT:
        writeObject(jp.getEmbeddedObject());
        break;
    }
}

From source file:com.amazonaws.services.sns.util.SignatureChecker.java

private Map<String, String> parseJSON(String jsonmessage) {
    Map<String, String> parsed = new HashMap<String, String>();
    JsonFactory jf = new JsonFactory();
    try {/*from ww  w  . ja va2 s .co m*/
        JsonParser parser = jf.createJsonParser(jsonmessage);
        parser.nextToken(); //shift past the START_OBJECT that begins the JSON
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldname = parser.getCurrentName();
            parser.nextToken(); // move to value, or START_OBJECT/START_ARRAY
            String value;
            if (parser.getCurrentToken() == JsonToken.START_ARRAY) {
                value = "";
                boolean first = true;
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    if (!first)
                        value += ",";
                    first = false;
                    value += parser.getText();
                }
            } else {
                value = parser.getText();
            }
            parsed.put(fieldname, value);
        }
    } catch (JsonParseException e) {
        // JSON could not be parsed
        e.printStackTrace();
    } catch (IOException e) {
        // Rare exception
    }
    return parsed;
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private void parseDownloadUrls(JsonParser parser, ContentValues result) throws JsonParseException, IOException {
    // parser points at begin object token right now
    if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
        while (parser.nextValue() != JsonToken.END_OBJECT) {
            String fieldName = parser.getCurrentName();

            if (downloadUrlFields.contains(fieldName)) {
                result.put(fieldName + "url", parser.getValueAsString());
            }//from   w w w. j  a  v a  2 s .  c o m
        }
    }
    //      else we must not have any download urls (null, '', something like that.)
}

From source file:ch.rasc.wampspring.message.PublishMessage.java

public PublishMessage(JsonParser jp, WampSession wampSession) throws IOException {
    super(WampMessageType.PUBLISH);

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }//w  w  w  .  j  a  va2 s .c o  m
    setTopicURI(replacePrefix(jp.getValueAsString(), wampSession));

    jp.nextToken();
    this.event = jp.readValueAs(Object.class);

    if (jp.nextToken() != JsonToken.END_ARRAY) {
        if (jp.getCurrentToken() == JsonToken.VALUE_TRUE || jp.getCurrentToken() == JsonToken.VALUE_FALSE) {
            this.excludeMe = jp.getValueAsBoolean();

            this.exclude = null;

            this.eligible = null;

            if (jp.nextToken() != JsonToken.END_ARRAY) {
                // Wrong message format, excludeMe should not be followed by
                // any value
                throw new IOException();
            }
        } else {
            this.excludeMe = null;

            TypeReference<Set<String>> typRef = new TypeReference<Set<String>>() {
                // nothing here
            };

            if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
                throw new IOException();
            }
            this.exclude = jp.readValueAs(typRef);

            if (jp.nextToken() == JsonToken.START_ARRAY) {
                this.eligible = jp.readValueAs(typRef);
            } else {
                this.eligible = null;
            }
        }
    } else {
        this.excludeMe = null;
        this.exclude = null;
        this.eligible = null;
    }

}