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

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

Introduction

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

Prototype

public abstract JsonToken nextToken() throws IOException, JsonParseException;

Source Link

Document

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

Usage

From source file:org.example.testcases.BasicTypesDeSerializer.java

private BasicTypes readObject(JsonParser jp) throws IOException {
    BasicTypes basicTypes = new BasicTypes();
    for (JsonToken jsonToken; (jsonToken = jp.nextToken()) != null && (jsonToken != END_OBJECT);) {
        if (FIELD_NAME != jsonToken)
            continue;
        final String fieldName = jp.getCurrentName();
        switch (fieldName) {
        case "aString":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aString = jp.getText();
            break;
        case "aBoolean":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aBoolean = jp.getBooleanValue();
            break;
        case "aFloat":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aFloat = jp.getFloatValue();
            break;
        case "aDouble":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aDouble = jp.getDoubleValue();
            break;
        case "aInt":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aInt = jp.getIntValue();
            break;
        case "aShort":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aShort = jp.getShortValue();
            break;
        case "aByte":
            jsonToken = jp.nextToken(); // read value
            basicTypes.aByte = jp.getByteValue();
            break;
        default:/*from  w w  w .j a  va  2  s  .  c o  m*/
            // decide what to do;
        }
    }
    return basicTypes;
}

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

public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
    super(WampMessageType.CALL);

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }/*from w  w  w . jav  a2  s. c  o m*/
    this.callID = jp.getValueAsString();

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }
    this.procURI = replacePrefix(jp.getValueAsString(), wampSession);

    List<Object> args = new ArrayList<>();
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        args.add(jp.readValueAs(Object.class));
    }

    if (!args.isEmpty()) {
        this.arguments = Collections.unmodifiableList(args);
    } else {
        this.arguments = null;
    }
}

From source file:com.cinnober.msgcodec.json.TypeScannerJsonParserTest.java

private void assertNextFloatValue(double exp, JsonParser p) throws IOException {
    assertEquals(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());
    assertEquals(exp, p.getDoubleValue(), 1e-4);
}

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 av  a 2  s. 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:javaslang.jackson.datatype.deserialize.MultimapDeserializer.java

@Override
public Multimap<?, ?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    final java.util.List<Tuple2<Object, Object>> result = new java.util.ArrayList<>();
    while (p.nextToken() != JsonToken.END_OBJECT) {
        String name = p.getCurrentName();
        Object key = keyDeserializer.deserializeKey(name, ctxt);
        p.nextToken();/* w  w w  .j  av  a  2s .c  o  m*/
        ArrayList<?> list = (ArrayList<?>) containerDeserializer.deserialize(p, ctxt);
        for (Object elem : list) {
            result.add(Tuple.of(key, elem));
        }
    }
    if (TreeMultimap.class.isAssignableFrom(handledType())) {
        return TreeMultimap.withSeq().ofEntries(keyComparator, result);
    }
    if (LinkedHashMultimap.class.isAssignableFrom(handledType())) {
        return LinkedHashMultimap.withSeq().ofEntries(result);
    }
    // default deserialization [...] -> Map
    return HashMultimap.withSeq().ofEntries(result);
}

From source file:org.hawkular.alerts.rest.json.LinkDeserializer.java

@Override
public Link deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {

    String tmp = jp.getText(); // {
    validate(jp, tmp, "{");
    jp.nextToken(); // skip over { to the rel
    String rel = jp.getText();//from  ww  w.j a  va 2 s  . c  o  m
    validateText(jp, rel);
    jp.nextToken(); // skip over  {
    tmp = jp.getText();
    validate(jp, tmp, "{");
    jp.nextToken(); // skip over "href"
    tmp = jp.getText();
    validate(jp, tmp, "href");
    jp.nextToken(); // skip to "http:// ... "
    String href = jp.getText();
    validateText(jp, href);
    jp.nextToken(); // skip }
    tmp = jp.getText();
    validate(jp, tmp, "}");
    jp.nextToken(); // skip }
    tmp = jp.getText();
    validate(jp, tmp, "}");

    Link link = new Link(rel, href);

    return link;
}

From source file:org.mashti.jetson.json.JsonRequestDecoder.java

@Override
protected void beforeDecode(final ChannelHandlerContext context, final ByteBuf buffer)
        throws TransportException {

    super.beforeDecode(context, buffer);
    final Channel channel = context.channel();
    final ByteBufInputStream in = new ByteBufInputStream(buffer);
    try {/*  ww w  .j av a2 s .  c  o m*/
        final JsonParser parser = json_factory.createParser(in);
        parser.nextToken();
        channel.attr(PARSER_ATTRIBUTE_KEY).set(parser);
    } catch (IOException e) {
        throw new TransportException(e);
    }
}

From source file:com.basistech.AfterburnerOopsTest.java

@Test
public void oops() throws Exception {
    SmileFactory smileFactory = new SmileFactory();
    ObjectMapper mapper = new ObjectMapper(smileFactory);
    mapper = AnnotatedDataModelModule.setupObjectMapper(mapper);

    EntityMention em = new EntityMention();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    List<EntityMention> mentions = Lists.newArrayList();
    mentions.add(em);//from  w  ww  .  j a v a2s. com
    mapper.writeValue(byteArrayOutputStream, mentions);

    mapper = AnnotatedDataModelModule.setupObjectMapper(new ObjectMapper(smileFactory));
    mapper.registerModule(new AfterburnerModule());
    JsonParser jp = smileFactory.createParser(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    jp.setCodec(mapper);

    JsonToken current;
    current = jp.nextToken();
    if (current != JsonToken.START_ARRAY) {
        System.err.println("Error: root should be array: quiting.");
        return;
    }

    while (jp.nextToken() != JsonToken.END_ARRAY) {
        jp.readValueAs(EntityMention.class);
    }

}

From source file:org.elasticsearch.client.sniff.ElasticsearchHostsSniffer.java

private List<HttpHost> readHosts(HttpEntity entity) throws IOException {
    try (InputStream inputStream = entity.getContent()) {
        JsonParser parser = jsonFactory.createParser(inputStream);
        if (parser.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("expected data to start with an object");
        }//from w  w w. j  a  v  a2 s. c  o  m
        List<HttpHost> hosts = new ArrayList<>();
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            if (parser.getCurrentToken() == JsonToken.START_OBJECT) {
                if ("nodes".equals(parser.getCurrentName())) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        JsonToken token = parser.nextToken();
                        assert token == JsonToken.START_OBJECT;
                        String nodeId = parser.getCurrentName();
                        HttpHost sniffedHost = readHost(nodeId, parser, this.scheme);
                        if (sniffedHost != null) {
                            logger.trace("adding node [" + nodeId + "]");
                            hosts.add(sniffedHost);
                        }
                    }
                } else {
                    parser.skipChildren();
                }
            }
        }
        return hosts;
    }
}

From source file:YDExtAttriReader.java

@Override
protected void read(OpenRtb.BidResponse.SeatBid.Bid.Builder message, JsonParser par) throws IOException {
    if (Constants.EXTEND_ATTRI_FIELD_NAME.equals(getCurrentName(par))) {
        List<Integer> attris = new ArrayList<>();
        for (startArray(par); endArray(par); par.nextToken())
            try {
                int battri = Integer.parseInt(par.getText());
                attris.add(battri);// w  ww  .ja va 2 s.c  o  m
            } catch (Exception e) {
                logger.warn("attri is not a int value.", e);
            }
        if (attris.isEmpty())
            return;
        message.setExtension(OpenRtbYDExtForDsp.attri, attris);
    }
}