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.quinsoft.zeidon.standardoe.ActivateOisFromJsonStream.java

private boolean readSimpleOi() throws Exception {
    JsonToken token = jp.getCurrentToken();

    // If we find the end of the OI array then that's the end of OIs.
    if (token == JsonToken.END_ARRAY || token == JsonToken.END_OBJECT)
        return false; // No more OIs in the stream.

    String fieldName = jp.getCurrentName();

    assert token == JsonToken.FIELD_NAME;
    assert lodDef.getRoot().getName().equalsIgnoreCase(fieldName);

    // If the token after reading the .oimeta is END_OBJECT then the OI is empty.
    if (token != JsonToken.END_OBJECT) {
        // readEntity expects the current token to be the opening { or [.
        // Skip over the field name.
        token = jp.nextToken();/*from  w w w.jav a  2s .  c  o  m*/
        readEntity(fieldName);
        token = jp.nextToken();
    }

    if (token != JsonToken.END_OBJECT)
        throw new ZeidonException("OI JSON stream doesn't end with object.");

    return true; // Keep looking for OIs in the stream.
}

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

/**
 * Read the first feature to create the table
 * @param jp/*from   w w w. j  a v  a 2  s  .c  o  m*/
 */
private void readFeatures(JsonParser jp, String geomType, StringBuilder metadataBuilder)
        throws IOException, SQLException {
    jp.nextToken(); // START_ARRAY [
    JsonToken token = jp.nextToken(); // START_OBJECT {
    if (token != JsonToken.END_ARRAY) {
        jp.nextToken(); // FIELD_NAME type"name"
        jp.nextToken(); // VALUE_STRING Feature
        geomType = jp.getText();
        if (geomType.equalsIgnoreCase(GeoJsonField.FEATURE)) {
            jp.nextToken(); // FIELD_NAME geometry
            String firstField = jp.getText();
            if (firstField.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
                parseGeometryMetadata(jp, metadataBuilder);
                hasGeometryField = true;
                fieldIndex++;
                jp.nextToken();//END_OBJECT } geometry
            } else if (firstField.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
                fieldIndex = parseMetadataProperties(jp, metadataBuilder, fieldIndex);
                hasProperties = true;
            }
            // If there is only one geometry field in the feature them the next
            // token corresponds to the end object of the feature.
            jp.nextToken();
            if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
                String secondParam = jp.getText();
                if (secondParam.equalsIgnoreCase(GeoJsonField.GEOMETRY)) {
                    parseGeometryMetadata(jp, metadataBuilder);
                    hasGeometryField = true;
                    fieldIndex++;
                    jp.nextToken();//END_OBJECT } geometry;
                } else if (secondParam.equalsIgnoreCase(GeoJsonField.PROPERTIES)) {
                    fieldIndex = parseMetadataProperties(jp, metadataBuilder, fieldIndex);
                    hasProperties = true;
                }
                jp.nextToken(); //END_OBJECT } feature
            }
            if (!hasProperties) {
                metadataBuilder.append("ID INT, PRIMARY KEY (ID)");
                fieldIndex++;
            }
            metadataBuilder.append(")");
        } else {
            throw new SQLException("Malformed GeoJSON file. Expected 'Feature', found '" + geomType + "'");
        }
    }
}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

/**
 * General version used when handling needs more advanced
 * features.//from  ww  w. j  av  a2s.  c o m
 */
@Override
public Object deserializeFromObject(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (_nonStandardCreation) {
        if (_unwrappedPropertyHandler != null) {
            return deserializeWithUnwrapped(jp, ctxt);
        }
        if (_externalTypeIdHandler != null) {
            return deserializeWithExternalTypeId(jp, ctxt);
        }
        return deserializeFromObjectUsingNonDefault(jp, ctxt);
    }
    final Object bean = _valueInstantiator.createUsingDefault(ctxt);
    if (jp.canReadObjectId()) {
        Object id = jp.getObjectId();
        if (id != null) {
            _handleTypedObjectId(jp, ctxt, bean, id);
        }
    }
    if (_injectables != null) {
        injectValues(ctxt, bean);
    }
    if (_needViewProcesing) {
        Class<?> view = ctxt.getActiveView();
        if (view != null) {
            return deserializeWithView(jp, ctxt, bean, view);
        }
    }
    beanDeserializerAdvice.before(bean, jp, ctxt);
    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        String propName = jp.getCurrentName();
        // Skip field name:
        jp.nextToken();

        if (beanDeserializerAdvice.intercept(bean, propName, jp, ctxt)) {
            continue;
        }

        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) { // normal case
            try {
                prop.deserializeAndSet(jp, ctxt, bean);
            } catch (Exception e) {
                wrapAndThrow(e, bean, propName, ctxt);
            }
            continue;
        }
        handleUnknownVanilla(jp, ctxt, bean, propName);
    }
    beanDeserializerAdvice.after(bean, jp, ctxt);
    return bean;
}

From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java

/**
 * Parse session context object/*from  ww w .  j  a va  2s .  c  o m*/
 *
 * @param userIdentity the {@link com.amazonaws.services.cloudtrail.processinglibrary.model.internal.UserIdentity}
 * @throws IOException
 * @throws JsonParseException
 */
private void parseSessionContext(UserIdentity userIdentity) throws IOException {
    if (this.jsonParser.nextToken() != JsonToken.START_OBJECT) {
        throw new JsonParseException("Not a SessionContext object", this.jsonParser.getCurrentLocation());
    }

    SessionContext sessionContext = new SessionContext();

    while (this.jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = this.jsonParser.getCurrentName();

        switch (key) {
        case "attributes":
            sessionContext.add(CloudTrailEventField.attributes.name(), this.parseAttributes());
            break;
        case "sessionIssuer":
            sessionContext.add(CloudTrailEventField.sessionIssuer.name(),
                    this.parseSessionIssuer(sessionContext));
            break;
        case "webIdFederationData":
            sessionContext.add(CloudTrailEventField.webIdFederationData.name(),
                    this.parseWebIdentitySessionContext(sessionContext));
            break;
        default:
            sessionContext.add(key, this.parseDefaultValue(key));
            break;
        }
    }

    userIdentity.add(CloudTrailEventField.sessionContext.name(), sessionContext);

}

From source file:io.apiman.manager.api.exportimport.json.JsonImportReader.java

public void readApiVersions() throws Exception {
    current = nextToken();//from   w  w w  .  j av a 2  s . c o m
    if (current == JsonToken.END_ARRAY) {
        return;
    }
    while (nextToken() != JsonToken.END_ARRAY) {
        // Traverse each api definition
        while (nextToken() != JsonToken.END_OBJECT) {
            if (jp.getCurrentName().equals(ApiVersionBean.class.getSimpleName())) {
                current = nextToken();
                ApiVersionBean apiBean = jp.readValueAs(ApiVersionBean.class);
                dispatcher.apiVersion(apiBean);
            } else {
                OrgElementsEnum fieldName = OrgElementsEnum.valueOf(jp.getCurrentName());
                current = nextToken();
                switch (fieldName) {
                case Policies:
                    processEntities(PolicyBean.class, dispatcher::apiPolicy);
                    break;
                default:
                    throw new RuntimeException("Unhandled entity " + fieldName + " with token " + current);
                }
            }
        }
    }
}

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

/**
 * Private routine to deserialize a JSON containing attachment data. This is
 * done manually to give more freedom regarding data returned by the
 * webservice.// w  w  w  . j a  va 2 s.c o m
 *
 * @param parser the JSONParser containing JSONData.
 * @param attachmentDB the attachments stored in the Toolkit
 * @return List containing attachments
 *
 * @throws JsonParseException
 * @throws IOException
 */
private List<Attachment> deserializeAttachmentList(JsonParser parser, Map<String, Attachment> attachmentDB)
        throws JsonParseException, IOException {
    List<Attachment> attachments = new ArrayList<Attachment>();
    Attachment currentAttachment = null;

    while (!JsonToken.END_ARRAY.equals(parser.nextToken())) {

        String fieldName = parser.getCurrentName();
        JsonToken token = parser.getCurrentToken();

        if (JsonToken.START_OBJECT.equals(token)) {
            currentAttachment = new Attachment();
        } else if (JsonToken.END_OBJECT.equals(token)) {
            currentAttachment.setCapGroupSMILES(
                    attachmentDB.get(currentAttachment.getAlternateId()).getCapGroupSMILES());
            attachments.add(currentAttachment);
        }

        if (fieldName != null) {
            switch (fieldName) {
            case "id":
                parser.nextToken();
                currentAttachment.setId(Integer.parseInt(parser.getText()));
                break;
            case "alternateId":
                parser.nextToken();
                currentAttachment.setAlternateId(parser.getText());
                break;
            case "label":
                parser.nextToken();
                currentAttachment.setLabel(parser.getText());
                break;
            case "capGroupName":
                parser.nextToken();
                currentAttachment.setCapGroupName(parser.getText());
                break;
            case "capGroupSMILES":
                parser.nextToken();
                currentAttachment.setCapGroupSMILES(parser.getText());
                break;
            default:
                break;
            }
        }

    }

    return attachments;
}

From source file:io.pdef.json.JsonJacksonFormat.java

private Map<String, Object> readMap(final JsonParser parser) throws IOException {
    JsonToken current = parser.getCurrentToken();
    if (current != JsonToken.START_OBJECT) {
        throw new JsonFormatException("Bad JSON string, failed to read an object");
    }// w ww  . j  a va  2 s  . c  o m

    Map<String, Object> map = new LinkedHashMap<String, Object>();
    while (true) {
        JsonToken next = parser.nextToken();
        if (next == null) {
            throw new JsonFormatException("End of file");
        } else if (next == JsonToken.END_OBJECT) {
            break;
        } else if (next != JsonToken.FIELD_NAME) {
            throw new JsonFormatException("Failed to read a field name from " + next);
        }

        String field = parser.getCurrentName();
        parser.nextToken();
        Object value = read(parser);
        map.put(field, value);
    }

    return map;
}

From source file:com.microsoft.azure.storage.table.CEKReturn.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. j a  va  2s . c om*/
 * @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 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
 *         A {@link TableResult} containing the parsed entity result of the operation.
 * @throws IOException
 *             if an error occurs while accessing 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, StorageException, InstantiationException,
        IllegalAccessException {
    final TableResult res = new TableResult();

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

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

    JsonUtilities.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);
        newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
        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) {
        tempProp.setDateBackwardCompatibility(false);
        timestamp = tempProp.getValueAsDate();

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

    // Deserialize the metadata property value to get the names of encrypted properties so that they can be parsed correctly below.
    Key cek = null;
    Boolean isJavaV1 = true;
    EncryptionData encryptionData = new EncryptionData();
    HashSet<String> encryptedPropertyDetailsSet = null;
    if (options.getEncryptionPolicy() != null) {
        EntityProperty propertyDetailsProperty = properties
                .get(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS);
        EntityProperty keyProperty = properties.get(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS);

        if (propertyDetailsProperty != null && !propertyDetailsProperty.getIsNull() && keyProperty != null
                && !keyProperty.getIsNull()) {
            // Decrypt the metadata property value to get the names of encrypted properties.
            CEKReturn cekReturn = options.getEncryptionPolicy().decryptMetadataAndReturnCEK(partitionKey,
                    rowKey, keyProperty, propertyDetailsProperty, encryptionData);

            cek = cekReturn.key;
            isJavaV1 = cekReturn.isJavaV1;
            properties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS,
                    propertyDetailsProperty);

            encryptedPropertyDetailsSet = parsePropertyDetails(propertyDetailsProperty);
        } else {
            if (options.requireEncryption() != null && options.requireEncryption()) {
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.ENCRYPTION_DATA_NOT_PRESENT_ERROR, null);
            }
        }
    }

    // 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)) {
        for (final Entry<String, EntityProperty> property : properties.entrySet()) {
            if (Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS.equals(property.getKey())) {
                // This and the following check are required because in JSON no-metadata, the type information for 
                // the properties are not returned and users are not expected to provide a type for them. So based 
                // on how the user defined property resolvers treat unknown properties, we might get unexpected results.
                final EntityProperty newProp = new EntityProperty(property.getValue().getValueAsString(),
                        EdmType.STRING);
                properties.put(property.getKey(), newProp);
            } else if (Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS
                    .equals(property.getKey())) {
                if (options.getEncryptionPolicy() == null) {
                    final EntityProperty newProp = new EntityProperty(property.getValue().getValueAsString(),
                            EdmType.BINARY);
                    properties.put(property.getKey(), newProp);
                }
            } else if (options.getPropertyResolver() != null) {
                final String key = property.getKey();
                final String value = property.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,
                            isEncrypted(encryptedPropertyDetailsSet, key) ? EdmType.BINARY : edmType);
                    newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
                    properties.put(property.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);
                }
                PropertyPair propPair = classProperties.get(property.getKey());
                if (propPair != null) {
                    EntityProperty newProp;
                    if (isEncrypted(encryptedPropertyDetailsSet, property.getKey())) {
                        newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.BINARY);
                    } else {
                        newProp = new EntityProperty(property.getValue().getValueAsString(), propPair.type);
                    }
                    newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility());
                    properties.put(property.getKey(), newProp);
                }
            }
        }
    }

    // set the result properties, now that they are appropriately parsed
    if (options.getEncryptionPolicy() != null && cek != null) {
        // decrypt properties, if necessary
        properties = options.getEncryptionPolicy().decryptEntity(properties, encryptedPropertyDetailsSet,
                partitionKey, rowKey, cek, encryptionData, isJavaV1);
    }
    res.setProperties(properties);

    // use resolver if provided, else create entity based on clazz type
    if (resolver != null) {
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, properties, 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(properties, opContext);

        res.setResult(entity);
    }

    return res;
}

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

/**
 * Tests reading an embedded document through
 * {@link BsonParser#readValueAsTree()}. Refers issue #9
 * @throws Exception if something went wrong
 * @author audistard//w w  w  .ja v  a2s. com
 */
@Test
public void parseEmbeddedDocumentAsTree() throws Exception {
    BSONObject o2 = new BasicBSONObject();
    o2.put("Int64", 10L);

    BSONObject o3 = new BasicBSONObject();
    o3.put("Int64", 11L);

    BSONObject o1 = new BasicBSONObject();
    o1.put("Obj2", o2);
    o1.put("Obj3", o3);

    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o1);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    ObjectMapper mapper = new ObjectMapper(fac);
    fac.setCodec(mapper);

    BsonParser dec = fac.createParser(bais);

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

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Obj2", dec.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, dec.nextToken());
    JsonNode obj2 = dec.readValueAsTree();
    assertEquals(1, obj2.size());
    assertNotNull(obj2.get("Int64"));
    assertEquals(10L, obj2.get("Int64").longValue());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Obj3", dec.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, dec.nextToken());

    assertEquals(JsonToken.FIELD_NAME, dec.nextToken());
    assertEquals("Int64", dec.getCurrentName());
    assertEquals(JsonToken.VALUE_NUMBER_INT, dec.nextToken());
    assertEquals(11L, dec.getLongValue());

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

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

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

private void expectObjectField(JsonParser parser, String name) throws IOException {
    expect(parser, JsonToken.FIELD_NAME);
    if (!parser.getCurrentName().equals(name)) {
        throw new RuntimeException("expected field " + name + ", got " + parser.getCurrentName());
    }//  w w w.  ja v  a2 s.  c  o  m
    expect(parser, JsonToken.START_OBJECT);
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        // empty
    }
}