Example usage for com.fasterxml.jackson.core JsonToken END_OBJECT

List of usage examples for com.fasterxml.jackson.core JsonToken END_OBJECT

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonToken END_OBJECT.

Prototype

JsonToken END_OBJECT

To view the source code for com.fasterxml.jackson.core JsonToken END_OBJECT.

Click Source Link

Document

END_OBJECT is returned when encountering '}' which signals ending of an Object value

Usage

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

@Override
public Genome parseGenomes(final InputStream inputStream) {
    checkNotNull(inputStream);//from   w w  w .j a  v  a  2s . c om
    JsonParser parser = null;
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String values = null;
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("genome".equals(field)) {
                values = parser.getText();
            }
        }
        return new Genome(id, values);
    } catch (IOException e) {
        logger.warn("could not parse genomes", e);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
    return null;
}

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

/**
 * Parse a JSON-Object with "Server/Config/*" which the Restrictions
 * //from  ww  w . j a  v a 2 s.  c  om
 * @param is
 * @return
 * @throws IOException
 */
public static Restrictions parseRestr(InputStream is) throws IOException {
    JsonParser jp = getJsonFactory().createParser(is);
    jp.nextToken();
    Restrictions restr = null;
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        // move to value, or START_OBJECT/START_ARRAY
        if (jp.nextToken() == null) {
            break;
        }
        if (SERVER_FIELD_NAME.equals(fieldname)) {
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String serverField = jp.getCurrentName();
                if (jp.nextToken() == null) {
                    break;
                }
                if (RequestGenerator.TAG_SERVER_CONFIG.equals(serverField)) {
                    restr = parseRestr(jp);
                }
            }
        }
    }
    return restr;
}

From source file:org.apache.lucene.server.handlers.AddDocumentHandler.java

/** Parse a Document using Jackson's streaming parser
 *  API.  The document should look like {indexName: 'foo',
 *  fields: {..., ...}} *///from  ww  w  . ja  v  a  2 s .com
public static Document parseDocument(IndexState state, JsonParser p) throws IOException {
    JsonToken token = p.nextToken();
    if (token == JsonToken.END_ARRAY) {
        // nocommit hackish.. caller should tell us this means "end"?
        return null;
    } else if (token != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON Object");
    }

    final Document doc = new Document();
    while (true) {
        token = p.nextToken();
        if (token == JsonToken.END_OBJECT) {
            break;
        }
        assert token == JsonToken.FIELD_NAME : token;

        String fieldName = p.getText();
        if (fieldName.equals("fields")) {
            parseFields(state, doc, p);
        } else {
            // Let a plugin handle it:
            boolean handled = false;
            for (PostHandle postHandle : postHandlers) {
                if (postHandle.invoke(state, fieldName, p, doc)) {
                    handled = true;
                    break;
                }
            }

            if (!handled) {
                throw new IllegalArgumentException("unrecognized field " + p.getText());
            }
        }

        // nocommit need test that same field name can't
        // appear more than once?  app must put all values for
        // a given field into an array (for a multi-valued
        // field) 
    }

    return doc;
}

From source file:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses the metadata properties./*from ww  w . ja  v  a 2 s .co  m*/
 *
 * @param jp
 * @return index
 */
private int parseMetadataProperties(JsonParser jp, StringBuilder metadataBuilder, int fieldIndex)
        throws IOException {
    jp.nextToken();//START_OBJECT {
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldName = jp.getText().toUpperCase(); //FIELD_NAME columnName            
        JsonToken value = jp.nextToken();
        if (value == JsonToken.VALUE_STRING) {
            metadataBuilder.append(fieldName).append(" VARCHAR");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_TRUE) {
            metadataBuilder.append(fieldName).append(" BOOLEAN");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_FALSE) {
            metadataBuilder.append(fieldName).append(" BOOLEAN");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_FLOAT) {
            metadataBuilder.append(fieldName).append(" DOUBLE");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NUMBER_INT) {
            metadataBuilder.append(fieldName).append(" INT");
            fieldIndex++;
        } else if (value == JsonToken.VALUE_NULL) {
            metadataBuilder.append(fieldName).append(" VARCHAR");
            fieldIndex++;
        } else {
            // TODO: ignore value.
        }
        metadataBuilder.append(",");
    }
    return fieldIndex;
}

From source file:com.github.heuermh.personalgenome.client.converter.JacksonPersonalGenomeConverter.java

List<Ancestry> parseSubPopulation(final String id, final List<Ancestry> ancestries, final JsonParser parser)
        throws IOException {
    String label = null;//  ww w.  ja  va2s.  c  o  m
    double proportion = 0.0d;
    double unassigned = 0.0d;
    List<Ancestry> subPopulations = new ArrayList<Ancestry>();
    while (parser.nextToken() != JsonToken.END_ARRAY) {
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();

            if ("label".equals(field)) {
                label = parser.getText();
            } else if ("proportion".equals(field)) {
                proportion = Double.parseDouble(parser.getText());
            } else if ("unassigned".equals(field)) {
                unassigned = Double.parseDouble(parser.getText());
            } else if ("sub_populations".equals(field)) {
                subPopulations = parseSubPopulation(id, subPopulations, parser);
            }
        }
        Ancestry ancestry = new Ancestry(id, label, proportion, unassigned, subPopulations);
        ancestries.add(ancestry);
        label = null;
        proportion = 0.0d;
        unassigned = 0.0d;
        subPopulations.clear();
    }
    return ancestries;
}

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

private static Restrictions parseRestr(JsonParser jp) throws IOException {
    int maxContacts = Integer.MAX_VALUE;
    int maxGroups = Integer.MAX_VALUE;
    boolean photoSyncSupported = false;
    Date validUntil = null;//  w w w. j  a va 2s.c  o  m

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String configName = jp.getCurrentName();
        if (jp.nextToken() == null) {
            break;
        }
        if (PARAM_IS_PHOTO_SYNC_ENABLED.equals(configName)) {
            photoSyncSupported = jp.getBooleanValue();
        } else if (PARAM_MAX_CONTACTS.equals(configName)) {
            maxContacts = jp.getIntValue();
        } else if (PARAM_MAX_GROUPS.equals(configName)) {
            maxGroups = jp.getIntValue();
        } else if (PARAM_VALID_UNTIL.equals(configName)) {
            validUntil = new Date(jp.getLongValue());
        }
    }
    return new Restrictions(maxContacts, maxGroups, photoSyncSupported, validUntil);
}

From source file:com.bazaarvoice.jackson.rison.RisonParser.java

/**
 * @return Next token from the stream, if any found, or null
 *   to indicate end-of-input/*from   ww  w .j  av  a2 s . co m*/
 */
@Override
public JsonToken nextToken() throws IOException, JsonParseException {
    _numTypesValid = NR_UNKNOWN;

    if (_currToken == null && _parsingContext.inRoot()) {
        if (isRisonEnabled(Feature.A_RISON)) {
            _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            return (_currToken = JsonToken.START_ARRAY);
        } else if (isRisonEnabled(Feature.O_RISON)) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
            return (_currToken = JsonToken.START_OBJECT);
        }
    }

    /* First: field names are special -- we will always tokenize
     * (part of) value along with field name to simplify
     * state handling. If so, can and need to use secondary token:
     */
    if (_currToken == JsonToken.FIELD_NAME) {
        return _nextAfterName();
    }
    if (_tokenIncomplete) {
        _skipString(); // only strings can be partial
    }
    int i = _nextChOrEnd();
    if (i < 0) { // end-of-input
        /* 19-Feb-2009, tatu: Should actually close/release things
         *    like input source, symbol table and recyclable buffers now.
         */
        close();
        if (_parsingContext.getParent().inRoot()) {
            if (isRisonEnabled(Feature.A_RISON) && _parsingContext.inArray()) {
                _parsingContext = _parsingContext.getParent();
                return (_currToken = JsonToken.END_ARRAY);
            }
            if (isRisonEnabled(Feature.O_RISON) && _parsingContext.inObject()) {
                _parsingContext = _parsingContext.getParent();
                return (_currToken = JsonToken.END_OBJECT);
            }
        }
        _handleEOF();
        return (_currToken = null);
    }

    /* First, need to ensure we know the starting location of token
     * after skipping leading white space
     */
    _tokenInputTotal = _currInputProcessed + _inputPtr - 1;
    _tokenInputRow = _currInputRow;
    _tokenInputCol = _inputPtr - _currInputRowStart - 1;

    // finally: clear any data retained so far
    _binaryValue = null;

    // Closing scope?
    if (i == ')') {
        if (_parsingContext.inArray()) {
            _parsingContext = _parsingContext.getParent();
            return (_currToken = JsonToken.END_ARRAY);
        }
        if (_parsingContext.inObject()) {
            _parsingContext = _parsingContext.getParent();
            return (_currToken = JsonToken.END_OBJECT);
        }
        _reportMismatchedEndMarker(i, ')');
    }

    // Nope: do we then expect a comma?
    if (_parsingContext.expectComma()) {
        if (i != INT_COMMA) {
            _reportUnexpectedChar(i,
                    "was expecting comma to separate " + _parsingContext.getTypeDesc() + " entries");
        }
        i = _nextCh();
    }

    /* And should we now have a name? Always true for
     * Object contexts, since the intermediate 'expect-value'
     * state is never retained.
     */
    boolean inObject = _parsingContext.inObject();
    if (inObject) {
        // First, field name itself:
        String name;
        if (i != INT_APOSTROPHE) {
            name = _parseUnquotedFieldName(i);
        } else {
            name = _parseFieldName(i);
        }
        _parsingContext.setCurrentName(name);
        _currToken = JsonToken.FIELD_NAME;
        i = _nextCh();
        if (i != INT_COLON) {
            _reportUnexpectedChar(i, "was expecting a colon to separate field name and value");
        }
        i = _nextCh();
    }

    // Ok: we must have a value... what is it?

    JsonToken t;

    switch (i) {
    case INT_APOSTROPHE:
        _tokenIncomplete = true;
        t = JsonToken.VALUE_STRING;
        break;
    case '(':
        if (!inObject) {
            _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol);
        }
        t = JsonToken.START_OBJECT;
        break;
    case ')':
        // Error: ')' is not valid at this point; valid closers have
        // been handled earlier
        _reportUnexpectedChar(i, "expected a value");

    case INT_MINUS:
        /* Should we have separate handling for plus? Although
        * it is not allowed per se, it may be erroneously used,
        * and could be indicate by a more specific error message.
        */
    case INT_0:
    case INT_1:
    case INT_2:
    case INT_3:
    case INT_4:
    case INT_5:
    case INT_6:
    case INT_7:
    case INT_8:
    case INT_9:
        t = parseNumberText(i);
        break;

    case '!':
        i = _nextCh();
        switch (i) {
        case '(':
            if (!inObject) {
                _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol);
            }
            t = JsonToken.START_ARRAY;
            break;
        case INT_t:
            t = JsonToken.VALUE_TRUE;
            break;
        case INT_f:
            t = JsonToken.VALUE_FALSE;
            break;
        case INT_n:
            t = JsonToken.VALUE_NULL;
            break;
        default:
            t = _handleUnexpectedValue(i);
            break;
        }
        break;
    default:
        if (IdentifierUtils.isIdStartLenient(i)) {
            t = JsonToken.VALUE_STRING;
            _inputPtr--; // push back the first char
            _parseUnquotedString();
        } else {
            t = _handleUnexpectedValue(i);
        }
        break;
    }

    if (inObject) {
        _nextToken = t;
        return _currToken;
    }
    _currToken = t;
    return t;
}

From source file:com.evolveum.midpoint.prism.lex.json.AbstractJsonLexicalProcessor.java

/**
 * Normally returns a MapXNode. However, JSON primitives/lists can be simulated by two-member object (@type + @value); in these cases we return respective XNode.
 *///from w  w w  . jav  a2s. c  om
@NotNull
private XNode parseJsonObject(JsonParsingContext ctx, IterativeParsingContext ipc)
        throws SchemaException, IOException {
    Validate.notNull(ctx.parser.currentToken());

    QName typeName = null;
    QNameUtil.QNameInfo elementNameInfo = null;

    Object tid = ctx.parser.getTypeId();
    if (tid != null) {
        typeName = tagToTypeName(tid, ctx);
    }

    final MapXNode map = new MapXNode();
    XNode wrappedValue = null;
    boolean defaultNamespaceDefined = false;
    QNameUtil.QNameInfo currentFieldNameInfo = null;

    for (;;) {
        if (ipc != null && ipc.abortProcessing) {
            break;
        }

        JsonToken token = ctx.parser.nextToken();
        if (token == null) {
            ctx.prismParsingContext.warnOrThrow(LOGGER,
                    "Unexpected end of data while parsing a map structure at " + getPositionSuffix(ctx));
            break;
        } else if (token == JsonToken.END_OBJECT) {
            break;
        } else if (token == JsonToken.FIELD_NAME) {
            String newFieldName = ctx.parser.getCurrentName();
            if (currentFieldNameInfo != null) {
                ctx.prismParsingContext.warnOrThrow(LOGGER,
                        "Two field names in succession: " + currentFieldNameInfo + " and " + newFieldName);
            }
            currentFieldNameInfo = QNameUtil.uriToQNameInfo(newFieldName, true);
        } else {
            assert currentFieldNameInfo != null;
            PrismContext prismContext = schemaRegistry.getPrismContext();
            // if we look for objects and found an entry different from c:objects
            boolean skipValue = false;
            if (ipc != null && !isSpecial(currentFieldNameInfo.name)
                    && (prismContext.getObjectsElementName() == null || !QNameUtil
                            .match(currentFieldNameInfo.name, prismContext.getObjectsElementName()))) {
                if (ipc.dataSent) {
                    ctx.prismParsingContext.warnOrThrow(LOGGER,
                            "Superfluous data after list of objects was found: " + currentFieldNameInfo.name);
                    skipValue = true;
                } else {
                    ipc = null;
                }
            }
            XNode valueXNode = parseValue(ctx, ipc);
            if (skipValue) {
                continue;
            }
            if (isSpecial(currentFieldNameInfo.name)) {
                if (isNamespaceDeclaration(currentFieldNameInfo.name)) {
                    if (defaultNamespaceDefined) {
                        ctx.prismParsingContext.warnOrThrow(LOGGER,
                                "Default namespace defined more than once at " + getPositionSuffix(ctx));
                    }
                    String namespaceUri = getStringValue(valueXNode, currentFieldNameInfo, ctx);
                    ctx.defaultNamespaces.put(map, namespaceUri);
                    defaultNamespaceDefined = true;
                    if (ipc != null) {
                        if (ipc.dataSent) {
                            ctx.prismParsingContext.warnOrThrow(LOGGER,
                                    "When parsing list of objects, default namespace was present after the objects "
                                            + getPositionSuffix(ctx));
                        } else {
                            ipc.defaultNamespace = namespaceUri; // there is a place for only one @ns declaration (at the level of "objects" map)
                        }
                    }
                } else if (isTypeDeclaration(currentFieldNameInfo.name)) {
                    if (typeName != null) {
                        ctx.prismParsingContext.warnOrThrow(LOGGER,
                                "Value type defined more than once at " + getPositionSuffix(ctx));
                    }
                    typeName = QNameUtil.uriToQName(getStringValue(valueXNode, currentFieldNameInfo, ctx),
                            true);
                } else if (isElementDeclaration(currentFieldNameInfo.name)) {
                    if (elementNameInfo != null) {
                        ctx.prismParsingContext.warnOrThrow(LOGGER,
                                "Element name defined more than once at " + getPositionSuffix(ctx));
                    }
                    elementNameInfo = QNameUtil
                            .uriToQNameInfo(getStringValue(valueXNode, currentFieldNameInfo, ctx), true);
                } else if (isValue(currentFieldNameInfo.name)) {
                    if (wrappedValue != null) {
                        ctx.prismParsingContext.warnOrThrow(LOGGER, "Value ('" + PROP_VALUE
                                + "') defined more than once at " + getPositionSuffix(ctx));
                    }
                    wrappedValue = valueXNode;
                }
            } else {
                Map.Entry<QName, XNode> entry = map.putReturningEntry(currentFieldNameInfo.name, valueXNode);
                if (currentFieldNameInfo.explicitEmptyNamespace) {
                    ctx.noNamespaceEntries.put(entry, null);
                }
            }
            currentFieldNameInfo = null;
        }
    }
    // Return either map or primitive value (in case of @type/@value)
    XNode rv;
    if (wrappedValue != null) {
        if (!map.isEmpty()) {
            ctx.prismParsingContext.warnOrThrow(LOGGER,
                    "Both '" + PROP_VALUE + "' and regular content present at " + getPositionSuffix(ctx));
            rv = map;
        } else {
            rv = wrappedValue;
        }
    } else {
        rv = map;
    }
    if (typeName != null) {
        if (wrappedValue != null && wrappedValue.getTypeQName() != null
                && !wrappedValue.getTypeQName().equals(typeName)) {
            ctx.prismParsingContext.warnOrThrow(LOGGER,
                    "Conflicting type names for '" + PROP_VALUE + "' (" + wrappedValue.getTypeQName()
                            + ") and regular content (" + typeName + ") present at " + getPositionSuffix(ctx));
        }
        rv.setTypeQName(typeName);
        rv.setExplicitTypeDeclaration(true);
    }
    if (elementNameInfo != null) {
        if (wrappedValue != null && wrappedValue.getElementName() != null) {
            boolean wrappedValueElementNoNamespace = ctx.noNamespaceElementNames.containsKey(wrappedValue);
            if (!wrappedValue.getElementName().equals(elementNameInfo.name)
                    || wrappedValueElementNoNamespace != elementNameInfo.explicitEmptyNamespace) {
                ctx.prismParsingContext.warnOrThrow(LOGGER,
                        "Conflicting element names for '" + PROP_VALUE + "' (" + wrappedValue.getElementName()
                                + "; no NS=" + wrappedValueElementNoNamespace + ") and regular content ("
                                + elementNameInfo.name + "; no NS=" + elementNameInfo.explicitEmptyNamespace
                                + ") present at " + getPositionSuffix(ctx));
            }
        }
        rv.setElementName(elementNameInfo.name);
        if (elementNameInfo.explicitEmptyNamespace) {
            ctx.noNamespaceElementNames.put(rv, null);
        }
    }
    return rv;
}

From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java

private int addStructuredMap(JsonParser parser, String mapTypeName, HollowMapWriteRecord mapRec)
        throws IOException {
    JsonToken token = parser.nextToken();
    mapRec.reset();//from www . j  a v a2s .  c  o m

    HollowMapSchema schema = (HollowMapSchema) hollowSchemas.get(mapTypeName);

    while (token != JsonToken.END_ARRAY) {
        if (token == JsonToken.START_OBJECT) {
            int keyOrdinal = -1, valueOrdinal = -1;
            while (token != JsonToken.END_OBJECT) {

                if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) {
                    if ("key".equals(parser.getCurrentName()))
                        keyOrdinal = parseSubType(parser, token, schema.getKeyType());
                    else if ("value".equals(parser.getCurrentName()))
                        valueOrdinal = parseSubType(parser, token, schema.getValueType());
                }

                token = parser.nextToken();
            }

            mapRec.addEntry(keyOrdinal, valueOrdinal);
        }

        token = parser.nextToken();
    }

    return stateEngine.add(schema.getName(), mapRec);
}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

/**
 * Checks if the parser returns a textual representation of arbitrary
 * tokens. See issue #23./*from  w ww .j  a v  a  2s. c  o  m*/
 * @throws Exception if something went wrong
 */
@Test
public void parseAsText() throws Exception {
    BSONObject o = new BasicBSONObject();
    o.put("Float", 5.0f);
    o.put("Int32", 1234);
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    BsonParser dec = fac.createParser(bais);

    assertEquals(JsonToken.START_OBJECT, dec.nextToken());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Float", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_FLOAT, dec.nextToken());
    assertEquals(5.0f, dec.getFloatValue(), 0.00001);
    assertEquals("5.0", dec.getText());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Int32", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_INT, dec.nextToken());
    assertEquals(1234, dec.getIntValue());
    assertEquals("1234", dec.getText());

    assertEquals(JsonToken.END_OBJECT, dec.nextToken());
}