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.elasticsearch.client.sniff.ElasticsearchNodesSniffer.java

static List<Node> readHosts(HttpEntity entity, Scheme scheme, JsonFactory jsonFactory) 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");
        }// w  w  w  .  jav a2s.c  o m
        List<Node> nodes = 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();
                        Node node = readNode(nodeId, parser, scheme);
                        if (node != null) {
                            nodes.add(node);
                        }
                    }
                } else {
                    parser.skipChildren();
                }
            }
        }
        return nodes;
    }
}

From source file:org.n52.movingcode.runtime.processors.config.ProcessorConfig.java

/**
 * Parsing routine for processor objects
 * //from ww  w .jav a2  s. c  o m
 * @param jp
 * @return
 * @throws JsonParseException
 * @throws IOException
 */
private static final ProcessorDescription parseProcessorJSON(JsonParser jp)
        throws JsonParseException, IOException {
    ProcessorDescription p = new ProcessorDescription();
    while (jp.nextToken() != END_OBJECT) {
        JsonToken jt = jp.getCurrentToken();

        // look for ID and parse it
        if (jp.getCurrentName().equalsIgnoreCase(KEY_ID) && jt == VALUE_STRING) {
            p.setId(jp.getValueAsString());
        }

        // look for temp workspace and parse it
        if (jp.getCurrentName().equalsIgnoreCase(KEY_TEMPWORKSPACE) && jt == VALUE_STRING) {
            p.setTempWorkspace(jp.getValueAsString());
        }

        // look for containers and parse them (Value Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_SUPPORTED_CONTAINER) && jt == VALUE_STRING) {
            p.addContainer(jp.getValueAsString());
        }

        // look for containers and parse them (Array Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_SUPPORTED_CONTAINER) && jt == START_ARRAY) {
            while (jp.nextToken() != END_ARRAY) {
                if (jp.getCurrentToken() == VALUE_STRING) {
                    p.addPlatform(jp.getValueAsString());
                }
            }
        }

        // look for platforms and parse them (Array Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_AVAILABLE_PLATFORMS) && jt == JsonToken.START_ARRAY) {
            while (jp.nextToken() != END_ARRAY) {
                if (jp.getCurrentToken() == VALUE_STRING) {
                    p.addPlatform(jp.getValueAsString());
                }
            }
        }

        // look for platforms and parse them (Value Case)
        if (jp.getCurrentName().equalsIgnoreCase(KEY_AVAILABLE_PLATFORMS) && jt == JsonToken.VALUE_STRING) {
            p.addPlatform(jp.getValueAsString());
        }

        // look for properties and parse them
        if (jp.getCurrentName().equalsIgnoreCase(KEY_PROPERTIES) && jt == JsonToken.START_ARRAY) {
            HashMap<String, String> props = new HashMap<String, String>();
            while (jp.nextToken() != END_ARRAY) {
                if (jp.getCurrentToken() == FIELD_NAME) {
                    props.put(jp.getCurrentName(), jp.nextTextValue());
                }

            }

            p.setProperties(props);

        }
    }

    return p;
}

From source file:com.github.heuermh.ensemblrestclient.JacksonVariationConverter.java

static Variation parseVariation(final JsonFactory jsonFactory, final InputStream inputStream)
        throws IOException {
    JsonParser parser = null;
    try {/* w  ww  .  j  a va  2 s . com*/
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String identifier = null;
        String referenceAllele = null;
        List<String> alternateAlleles = new ArrayList<String>();

        String locationName = null;
        String coordinateSystem = "chromosome";
        int start = -1;
        int end = -1;
        int strand = -1;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();
            if ("name".equals(field)) {
                identifier = parser.getText();
            } else if ("mappings".equals(field)) {
                // todo:  will only catch last mapping
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    while (parser.nextToken() != JsonToken.END_OBJECT) {
                        String mappingsField = parser.getCurrentName();
                        parser.nextToken();

                        if ("seq_region_name".equals(mappingsField)) {
                            locationName = parser.getText();
                        } else if ("start".equals(mappingsField)) {
                            start = Integer.parseInt(parser.getText());
                        } else if ("end".equals(mappingsField)) {
                            end = Integer.parseInt(parser.getText());
                        } else if ("strand".equals(mappingsField)) {
                            strand = Integer.parseInt(parser.getText());
                        } else if ("allele_string".equals(mappingsField)) {
                            String[] tokens = parser.getText().split("/");
                            // todo:  check ref here against ancestral_allele
                            referenceAllele = tokens[0];
                            for (int i = 1; i < tokens.length; i++) {
                                alternateAlleles.add(tokens[i]);
                            }
                        }
                    }
                }
            } else if ("synonyms".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    // ignore
                }
            } else if ("evidence".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    // ignore
                }
            }
        }
        return new Variation(identifier, referenceAllele, alternateAlleles,
                new Location(locationName, coordinateSystem, start, end, strand));
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:com.microsoft.azure.storage.table.TableStorageErrorDeserializer.java

/**
 * Gets the Extended Error information./*from w w w. j  a v  a2  s. co  m*/
 * 
 * @return the Extended Error information.
 * 
 * @param reader
 *            the input stream to read error details from.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing
 * @throws IOException
 *             if an error occurs while accessing the stream with Json.
 * @throws JsonParseException
 *             if an error occurs while parsing the stream.
 */
public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader,
        final TablePayloadFormat format) throws JsonParseException, IOException {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser parser = jsonFactory.createParser(reader);
    try {
        final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation();

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

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);
        JsonUtilities.assertIsExpectedFieldName(parser, "odata.error");

        // start getting extended error information
        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        // get code
        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE);
        errorInfo.setErrorCode(parser.getValueAsString());

        // get message
        parser.nextToken();
        JsonUtilities.assertIsFieldNameJsonToken(parser);
        JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE);

        parser.nextToken();
        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, "lang");

        parser.nextValue();
        JsonUtilities.assertIsExpectedFieldName(parser, "value");
        errorInfo.setErrorMessage(parser.getValueAsString());

        parser.nextToken();
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        parser.nextToken();

        // get innererror if it exists
        if (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
            JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR);
            errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser));
            parser.nextToken();
        }

        // end code object
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        // end odata.error object
        parser.nextToken();
        JsonUtilities.assertIsEndObjectJsonToken(parser);

        return errorInfo;
    } finally {
        parser.close();
    }
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClientTest.java

private static String reformatJson(@Nullable String input) throws IOException {
    checkNotNull(input);//from ww  w  .j a  v  a 2  s  .  c om

    JsonFactory jsonFactory = new JsonFactory();

    JsonParser parser = jsonFactory.createParser(input);
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createGenerator(writer);
    generator.useDefaultPrettyPrinter();

    while (parser.nextToken() != null) {
        generator.copyCurrentEvent(parser);
    }

    generator.close();

    return writer.toString();
}

From source file:com.teamlazerbeez.crm.sf.rest.HttpApiClientTest.java

private static String reformatJson(String input) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();

    JsonParser parser = jsonFactory.createJsonParser(input);
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createJsonGenerator(writer);
    generator.useDefaultPrettyPrinter();

    while (parser.nextToken() != null) {
        generator.copyCurrentEvent(parser);
    }//from  ww  w. ja v a 2s  .  c o m

    generator.close();

    return writer.toString();
}

From source file:org.mashti.jetson.util.JsonParserUtil.java

/**
 * Reads a field value as the provided type. This method supports parametrised types.
 *
 * @param parser the parser//from ww w.jav  a  2 s .  c om
 * @param expected_type the expected type of the value
 * @return the value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static Object readValueAs(final JsonParser parser, final Type expected_type) throws IOException {

    final Object value;
    if (expected_type.equals(Void.TYPE)) {
        expectNullValue(parser);
        value = null;
    } else {
        parser.nextToken();
        value = parser.readValueAs(toTypeReference(expected_type));
    }
    return value;
}

From source file:com.google.openrtb.json.OpenRtbJsonUtils.java

/**
 * Reads from either a JSON Value String (containing CSV) or a JSON Array.
 * The dual input format is needed because some fields (e.g. keywords) were allowed
 * to be of either type in OpenRTB 2.2; now in 2.3 they are all CSV strings only.
 * TODO: Simplify this to only accept CSV strings after 2.2 compatibility is dropped.
 *//*  w  w  w.ja v a 2s .com*/
public static String readCsvString(JsonParser par) throws IOException {
    JsonToken currentToken = par.getCurrentToken();
    if (currentToken == JsonToken.START_ARRAY) {
        StringBuilder keywords = new StringBuilder();
        for (startArray(par); endArray(par); par.nextToken()) {
            if (keywords.length() != 0) {
                keywords.append(',');
            }
            keywords.append(par.getText());
        }
        return keywords.toString();
    } else if (currentToken == JsonToken.VALUE_STRING) {
        return par.getText();
    } else {
        throw new JsonParseException(par, "Expected string or array");
    }
}

From source file:org.mashti.jetson.util.JsonParserUtil.java

/**
 * Reads a field value as the provided type.
 *
 * @param <Value> the value type//from w w  w  . ja  v a  2 s . co  m
 * @param parser the parser
 * @param expected_type the expected type of the value
 * @return the value
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static <Value> Value readValueAs(final JsonParser parser, final Class<Value> expected_type)
        throws IOException {

    final Value value;
    if (expected_type.equals(Void.TYPE)) {
        expectNullValue(parser);
        value = null;
    } else {
        parser.nextToken();
        value = parser.readValueAs(expected_type);
    }
    return value;
}

From source file:org.oscim.utils.overpass.OverpassAPIReader.java

private static TagSet parseTags(JsonParser jp) throws JsonParseException, IOException {

    TagSet tags = null;//from   w  ww.j ava 2s .  com

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String key = jp.getCurrentName();
        jp.nextToken();
        String val = jp.getText();
        if (tags == null)
            tags = new TagSet(4);

        tags.add(new Tag(key, val, false));

    }

    return tags;
}