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

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

Introduction

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

Prototype

public abstract String getCurrentName() throws IOException, JsonParseException;

Source Link

Document

Method that can be called to get the name associated with the current token: for JsonToken#FIELD_NAME s it will be the same as what #getText returns; for field values it will be preceding field name; and for others (array values, root-level values) null.

Usage

From source file:com.world.watch.worldwatchcron.util.WWCron.java

public long extractLatestTimeStamp(String newsJson) {
    long maxTS = 0;
    JsonFactory factory = new JsonFactory();
    try {//from w  w w  . j  a  v  a  2  s  . co  m
        JsonParser parser = factory.createParser(newsJson);
        while (!parser.isClosed()) {
            JsonToken token = parser.nextToken();
            if (token == null) {
                break;
            }
            String fieldName = parser.getCurrentName();
            if (fieldName != null && fieldName.equals("date")) {
                parser.nextToken();
                long date = Long.parseLong(parser.getText());
                if (maxTS < date) {
                    maxTS = date;
                }
            }
        }
    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //logger.error("File not found ", e);
    }
    return maxTS;
}

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

protected EObject postDeserialize(TokenBuffer buffer, EObject object, EClass defaultType,
        DeserializationContext ctxt) throws IOException {
    if (object == null && defaultType == null) {
        return null;
    }//from  www.  ja v a  2s .  c o  m

    if (object == null) {
        object = EcoreUtil.create(defaultType);
    }

    final Resource resource = getResource(ctxt);
    final JsonParser jp = buffer.asParser();
    final EObjectPropertyMap propertyMap = builder.construct(object.eClass());

    while (jp.nextToken() != null) {
        final String field = jp.getCurrentName();
        final EObjectProperty property = propertyMap.findProperty(field);

        if (property != null) {
            property.deserializeAndSet(jp, object, ctxt, resource);
        } else {
            handleUnknownProperty(jp, resource, ctxt);
        }
    }
    jp.close();
    buffer.close();
    return object;
}

From source file:com.cedarsoft.serialization.test.performance.Bson4JacksonTest.java

@Test
public void testParse() throws Exception {
    JsonParser parser = jsonFactory.createJsonParser(Hex.decodeHex(BSON.toCharArray()));

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

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("id", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("Canon Raw", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("dependent", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_FALSE, parser.nextToken());
    assertFalse(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.START_OBJECT, parser.nextToken());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("extension", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals("cr2", parser.getText());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("default", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_TRUE, parser.nextToken());
    assertTrue(parser.getBooleanValue());

    assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
    assertEquals("delimiter", parser.getCurrentName());
    assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
    assertEquals(".", parser.getText());

    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertEquals(JsonToken.END_OBJECT, parser.nextToken());
    assertNull(parser.nextToken());//from ww  w .  j ava2s  .c o  m
}

From source file:com.wealdtech.jackson.modules.MessageObjectsDeserializer.java

@Override
public MessageObjects<? extends Object> deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {
    // This assumes a strict JSON format of userId and hint followed by _type followed by prior and current (if they exist)
    jp.nextToken();// w w  w . j a  va 2s .co m
    String fieldName = jp.getCurrentName();
    if (!"userid".equals(fieldName)) {
        throw new IOException("Unexpected key \"" + fieldName + "\"; expected userid");
    }
    jp.nextToken();
    final Long userId = Long.parseLong(jp.getText());

    final RequestHint hint;
    jp.nextToken();
    fieldName = jp.getCurrentName();
    if ("hint".equals(fieldName)) {
        // Hint is optional
        jp.nextToken();
        hint = WealdMapper.getMapper().readValue(jp, RequestHint.class);
        jp.nextToken();
    } else {
        hint = null;
    }

    fieldName = jp.getCurrentName();
    if (!"_type".equals(fieldName)) {
        throw new IOException("Unexpected key \"" + fieldName + "\"; expected _type");
    }

    jp.nextToken();
    final String typeStr = jp.getText();
    Class<? extends Object> objClass;
    try {
        objClass = Class.forName(typeStr);
    } catch (ClassNotFoundException cnfe) {
        LOGGER.error("MessageObjects has unknown class: \"{}\"", typeStr);
        throw new IOException("MessageObjects has unknown class: \"" + typeStr + "\"", cnfe);
    }

    // Now that we have the type we can deserialize the objects
    jp.nextToken();
    fieldName = jp.getCurrentName();

    Object prior = null;
    if ("prior".equals(fieldName)) {
        jp.nextToken();
        prior = WealdMapper.getMapper().readValue(jp, objClass);
        jp.nextToken();
        fieldName = jp.getCurrentName();
    }

    Object current = null;
    if ("current".equals(fieldName)) {
        jp.nextToken();
        current = WealdMapper.getMapper().readValue(jp, objClass);
    }

    // And build our return object
    try {
        return new MessageObjects<>(userId, hint, prior, current);
    } catch (DataError de) {
        LOGGER.error("Failed to instantiate MessageObjects: \"" + de.getLocalizedMessage() + "\"");
        throw new IOException("Failed to instantiate MessageObjects", de);
    }
}

From source file:com.azaptree.services.domain.entity.impl.DomainVersionedEntity.java

/**
 * Sub-classes should override this to parse sub-class specific fields.
 * /*from w  w  w.  jav  a 2 s.  c  o m*/
 * This is invoked by init(InputStream), when an unknown field is encountered
 * 
 * @param parser
 */
protected void init(JsonParser parser) throws IOException {
    LoggerFactory.getLogger(getClass()).warn("init(JsonParser parser) invoked to handle field: {}",
            parser.getCurrentName());
}

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

@Override
@SuppressWarnings("unchecked")
public EList<Map.Entry<?, ?>> deserialize(JsonParser jp, DeserializationContext ctxt,
        EList<Map.Entry<?, ?>> intoValue) throws IOException {
    final EReference reference = EMFContext.getReference(ctxt);

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

        while (jp.nextToken() != JsonToken.END_OBJECT) {
            final String key = jp.getCurrentName();
            jp.nextToken();/*w  ww .j  a v  a 2  s . c  om*/

            final Object value;
            if (jp.getCurrentToken() == JsonToken.START_OBJECT) {
                value = ctxt.readValue(jp, EObject.class);
            } else {
                value = ctxt.readValue(jp, Object.class);
            }

            // Dynamic objects do not use the EMap interface
            // but store entries in a DynamicEList instead.
            if (intoValue instanceof EMap) {
                ((EMap) intoValue).put(key, value);
            } else if (reference != null) {
                intoValue
                        .add((Map.Entry<?, ?>) EObjects.createEntry(key, value, reference.getEReferenceType()));
            }
        }
    }

    return intoValue;
}

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.
 * /*  ww w .j  a  v  a  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:com.msopentech.odatajclient.engine.data.metadata.edm.EntityKeyDeserializer.java

@Override
public EntityKey deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final EntityKey entityKey = new EntityKey();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();

        if (token == JsonToken.FIELD_NAME && "PropertyRef".equals(jp.getCurrentName())) {
            jp.nextToken();//from   ww w.ja va  2  s.  c o m
            entityKey.getPropertyRefs().add(jp.getCodec().readValue(jp, PropertyRef.class));
        }
    }

    return entityKey;
}

From source file:com.msopentech.odatajclient.engine.data.metadata.edm.EdmxDeserializer.java

@Override
public Edmx deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    final Edmx edmx = new Edmx();

    for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) {
        final JsonToken token = jp.getCurrentToken();
        if (token == JsonToken.FIELD_NAME) {
            if ("Version".equals(jp.getCurrentName())) {
                edmx.setVersion(jp.nextTextValue());
            } else if ("DataServices".equals(jp.getCurrentName())) {
                jp.nextToken();//from   w  w w.  j  ava 2 s.  c om
                edmx.setDataServices(jp.getCodec().readValue(jp, DataServices.class));
            }
        }
    }

    return edmx;
}

From source file:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * Initialize processor, automatically scanning the input JSON.
 * @throws ODataUnmarshallingException If unable to initialize
 *///from  ww w . j a  v a 2 s  .  c  o m
public void initialize() throws ODataUnmarshallingException {
    LOG.info("Parser is initializing");
    try {
        JsonParser jsonParser = JSON_FACTORY.createParser(inputJson);

        while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
            String token = jsonParser.getCurrentName();
            if (token != null) {
                if (token.startsWith(ODATA)) {
                    processSpecialTags(jsonParser);
                } else if (token.endsWith(ODATA_BIND)) {
                    processLinks(jsonParser);
                } else {
                    process(jsonParser);
                }
            }
        }
    } catch (IOException e) {
        throw new ODataUnmarshallingException("It is unable to unmarshall", e);
    }
}