Example usage for com.fasterxml.jackson.core JsonFactory createParser

List of usage examples for com.fasterxml.jackson.core JsonFactory createParser

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory createParser.

Prototype

public JsonParser createParser(String content) throws IOException, JsonParseException 

Source Link

Document

Method for constructing parser for parsing contents of given String.

Usage

From source file:org.nuxeo.connect.tools.report.viewer.Viewer.java

public static void main(String[] varargs) throws IOException, ParseException {

    class Arguments {
        Options options = new Options()
                .addOption(Option.builder("i").longOpt("input").hasArg().argName("file")
                        .desc("report input file").build())
                .addOption(Option.builder("o").longOpt("output").hasArg().argName("file")
                        .desc("thread dump output file").build());
        final CommandLine commandline = new DefaultParser().parse(options, varargs);

        Arguments() throws ParseException {

        }/*from w  w w .  j a  v a  2  s.co m*/

        InputStream input() throws IOException {
            if (!commandline.hasOption('i')) {
                return System.in;
            }
            return Files.newInputStream(Paths.get(commandline.getOptionValue('i')));
        }

        PrintStream output() throws IOException {
            if (!commandline.hasOption('o')) {
                return System.out;
            }
            return new PrintStream(commandline.getOptionValue('o'));
        }

    }

    Arguments arguments = new Arguments();
    final JsonFactory jsonFactory = new JsonFactory();
    PrintStream output = arguments.output();
    JsonParser parser = jsonFactory.createParser(arguments.input());
    ObjectMapper mapper = new ObjectMapper();
    while (!parser.isClosed() && parser.nextToken() != JsonToken.NOT_AVAILABLE) {
        String hostid = parser.nextFieldName();
        output.println(hostid);
        {
            parser.nextToken();
            while (parser.nextToken() == JsonToken.FIELD_NAME) {
                if ("mx-thread-dump".equals(parser.getCurrentName())) {
                    parser.nextToken(); // start mx-thread-dump report
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            parser.nextToken();
                            printThreadDump(mapper.readTree(parser), output);
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else if ("mx-thread-deadlocked".equals(parser.getCurrentName())) {
                    parser.nextToken();
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            if (parser.nextToken() == JsonToken.START_ARRAY) {
                                printThreadDeadlocked(mapper.readerFor(Long.class).readValue(parser), output);
                            }
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else if ("mx-thread-monitor-deadlocked".equals(parser.getCurrentName())) {
                    parser.nextToken();
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            if (parser.nextToken() == JsonToken.START_ARRAY) {
                                printThreadMonitorDeadlocked(mapper.readerFor(Long.class).readValues(parser),
                                        output);
                            }
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
    }

}

From source file:innovimax.quixproc.datamodel.generator.json.AJSONGenerator.java

public static void main(String[] args)
        throws JsonParseException, IOException, InstantiationException, IllegalAccessException {

    /*/*ww w. j  a  v a 2  s  .c o m*/
     * final byte[][] patterns = { // empty object is allowed
     * 
     * "\"A\":1".getBytes(), // first used only once ",\"A\":1".getBytes()
     * }; BoxedArray baA = new BoxedArray(patterns, 1, 2); for (int i = 0; i
     * <Integer.MAX_VALUE; i++) { baA.nextUnique(); }
     * 
     * 
     * System.out.println(display(patterns[1]));
     */
    JsonFactory f = new JsonFactory();
    f.disable(Feature.ALLOW_COMMENTS);
    f.disable(Feature.ALLOW_SINGLE_QUOTES);
    // AGenerator generator = instance(ATreeGenerator.Type.HIGH_DENSITY);
    AGenerator generator = instance(FileExtension.JSON, TreeType.HIGH_NODE_DEPTH, SpecialType.STANDARD);

    InputStream is = generator.getInputStream(50, Unit.MBYTE, Variation.NO_VARIATION);
    if (false) {
        int c;
        while ((c = is.read()) != -1) {
            System.out.println(display((byte) (c & 0xFF)));
        }
    } else {
        JsonParser p = f.createParser(is);
        p.enable(Feature.STRICT_DUPLICATE_DETECTION);

        while (p.nextToken() != JsonToken.END_OBJECT) {
            //
        }
    }
}

From source file:cc.shanruifeng.functions.udfs.utils.JsonUtil.java

public static JsonParser createJsonParser(JsonFactory factory, Slice json) throws IOException {
    return factory.createParser((InputStream) json.getInput());
}

From source file:com.infinities.keystone4j.utils.JsonUtils.java

public static JsonNode convertToJsonNode(String text) throws JsonProcessingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory(); // since 2.1 use
    // mapper.getFactory()
    // instead// w  w  w.  ja v a  2  s.  c  om
    JsonParser jp = factory.createParser(text);
    JsonNode node = mapper.readTree(jp);
    return node;
}

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

static Sequence parseSequence(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException {
    JsonParser parser = null;//w  w w.  ja  v a 2 s .  c o  m
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String seq = null;
        String molecule = null;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();
            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("seq".equals(field)) {
                seq = parser.getText();
            } else if ("molecule".equals(field)) {
                molecule = parser.getText();
            }
        }
        return new Sequence(id, seq, molecule);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:org.talend.components.jira.datum.EntityParser.java

/**
 * Parses JSON and searches for total property
 * /*from   w  ww  . j a  v a 2 s  .c om*/
 * @param json JSON string
 * @return total property value, if it is exist or -1 otherwise
 */
static int getTotal(String json) {
    JsonFactory factory = new JsonFactory();
    try {
        JsonParser parser = factory.createParser(json);

        boolean totalFound = rewindToField(parser, "total");

        if (!totalFound) {
            return UNDEFINED;
        }

        // get total value
        String value = parser.getText();

        return Integer.parseInt(value);
    } catch (IOException e) {
        LOG.debug("Exception during JSON parsing. {}", e.getMessage());
    }
    return UNDEFINED;
}

From source file:io.seldon.spark.actions.JobUtils.java

public static ActionData getActionDataFromActionLogLine(String actionLogLine) {
    ActionData actionData = new ActionData();

    String[] parts = actionLogLine.split("\\s+", 3);
    String json = parts[2];/*from   w  w  w.j ava 2s .  co  m*/
    actionData.timestamp_utc = parts[0];

    JsonFactory jsonF = new JsonFactory();
    try {
        JsonParser jp = jsonF.createParser(json);
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            // Let's move to value
            jp.nextToken();
            if (fieldName.equals("client")) {
                actionData.client = jp.getText();
            } else if (fieldName.equals("client_userid")) {
                actionData.client_userid = jp.getText();
            } else if (fieldName.equals("userid")) {
                actionData.userid = jp.getValueAsInt();
            } else if (fieldName.equals("itemid")) {
                actionData.itemid = jp.getValueAsInt();
            } else if (fieldName.equals("client_itemid")) {
                actionData.client_itemid = jp.getText();
            } else if (fieldName.equals("rectag")) {
                actionData.rectag = jp.getText();
            } else if (fieldName.equals("type")) {
                actionData.type = jp.getValueAsInt();
            } else if (fieldName.equals("value")) {
                actionData.value = jp.getValueAsDouble();
            }
        }
        jp.close();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return actionData;
}

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

/**
 * Gets the Extended Error information./*from  ww  w . ja  va  2s.  c o  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);//  w w w  . j  a va 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.github.heuermh.ensemblrestclient.JacksonLookupConverter.java

static Lookup parseLookup(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException {
    JsonParser parser = null;/*from  ww  w  .  ja va 2  s . com*/
    try {
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String species = null;
        String type = null;
        String database = null;

        String locationName = null;
        String coordinateSystem = "chromosome"; // reasonable default?
        int start = -1;
        int end = -1;
        int strand = -1;

        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String field = parser.getCurrentName();
            parser.nextToken();
            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("species".equals(field)) {
                species = parser.getText();
            } else if ("object_type".equals(field)) {
                type = parser.getText();
            } else if ("db_type".equals(field)) {
                database = parser.getText();
            } else if ("seq_region_name".equals(field)) {
                locationName = parser.getText();
            } else if ("start".equals(field)) {
                start = Integer.parseInt(parser.getText());
            } else if ("end".equals(field)) {
                end = Integer.parseInt(parser.getText());
            } else if ("strand".equals(field)) {
                strand = Integer.parseInt(parser.getText());
            }
        }
        return new Lookup(id, species, type, database,
                new Location(locationName, coordinateSystem, start, end, strand));
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}