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:Service.java

public static void main(String[] args) {

    StringWriter sw = new StringWriter();
    try {/*from  w  ww  .  j a  v a  2 s . c o  m*/
        JsonGenerator g = factory.createGenerator(sw);
        g.writeStartObject();
        g.writeNumberField("code", 200);
        g.writeArrayFieldStart("languages");
        for (Language l : Languages.get()) {
            g.writeStartObject();
            g.writeStringField("name", l.getName());
            g.writeStringField("locale", l.getLocaleWithCountryAndVariant().toString());
            g.writeEndObject();
        }
        g.writeEndArray();
        g.writeEndObject();
        g.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    String languagesResponse = sw.toString();

    String errorResponse = codeResponse(500);
    String okResponse = codeResponse(200);

    Scanner sc = new Scanner(System.in);
    while (sc.hasNextLine()) {
        try {
            String line = sc.nextLine();
            JsonParser p = factory.createParser(line);
            String cmd = "";
            String text = "";
            String language = "";
            while (p.nextToken() != JsonToken.END_OBJECT) {
                String name = p.getCurrentName();
                if ("command".equals(name)) {
                    p.nextToken();
                    cmd = p.getText();
                }
                if ("text".equals(name)) {
                    p.nextToken();
                    text = p.getText();
                }
                if ("language".equals(name)) {
                    p.nextToken();
                    language = p.getText();
                }
            }
            p.close();

            if ("check".equals(cmd)) {
                sw = new StringWriter();
                JsonGenerator g = factory.createGenerator(sw);
                g.writeStartObject();
                g.writeNumberField("code", 200);
                g.writeArrayFieldStart("matches");
                for (RuleMatch match : new JLanguageTool(Languages.getLanguageForShortName(language))
                        .check(text)) {
                    g.writeStartObject();

                    g.writeNumberField("offset", match.getFromPos());

                    g.writeNumberField("length", match.getToPos() - match.getFromPos());

                    g.writeStringField("message", substituteSuggestion(match.getMessage()));

                    if (match.getShortMessage() != null) {
                        g.writeStringField("shortMessage", substituteSuggestion(match.getShortMessage()));
                    }

                    g.writeArrayFieldStart("replacements");
                    for (String replacement : match.getSuggestedReplacements()) {
                        g.writeString(replacement);
                    }
                    g.writeEndArray();

                    Rule rule = match.getRule();

                    g.writeStringField("ruleId", rule.getId());

                    if (rule instanceof AbstractPatternRule) {
                        String subId = ((AbstractPatternRule) rule).getSubId();
                        if (subId != null) {
                            g.writeStringField("ruleSubId", subId);
                        }
                    }

                    g.writeStringField("ruleDescription", rule.getDescription());

                    g.writeStringField("ruleIssueType", rule.getLocQualityIssueType().toString());

                    if (rule.getUrl() != null) {
                        g.writeArrayFieldStart("ruleUrls");
                        g.writeString(rule.getUrl().toString());
                        g.writeEndArray();
                    }

                    Category category = rule.getCategory();
                    CategoryId catId = category.getId();
                    if (catId != null) {
                        g.writeStringField("ruleCategoryId", catId.toString());

                        g.writeStringField("ruleCategoryName", category.getName());
                    }

                    g.writeEndObject();
                }
                g.writeEndArray();
                g.writeEndObject();
                g.flush();
                System.out.println(sw.toString());
            } else if ("languages".equals(cmd)) {
                System.out.println(languagesResponse);
            } else if ("quit".equals(cmd)) {
                System.out.println(okResponse);
                return;
            } else {
                System.out.println(errorResponse);
            }
        } catch (Exception e) {
            System.out.println(errorResponse);
        }
    }
}

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 ww  w.  java 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:com.msopentech.odatajclient.engine.data.metadata.edm.AbstractAnnotatedEdmUtils.java

public static void parseAnnotatedEdm(final AbstractAnnotatedEdm item, final JsonParser jp) throws IOException {
    if ("Documentation".equals(jp.getCurrentName())) {
        jp.nextToken();//  w w  w. j  a v  a 2s .c o m
        item.setDocumentation(jp.getCodec().readValue(jp, Documentation.class));
    } else if ("TypeAnnotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        item.getTypeAnnotations().add(jp.getCodec().readValue(jp, TypeAnnotation.class));
    } else if ("ValueAnnotation".equals(jp.getCurrentName())) {
        jp.nextToken();
        item.getValueAnnotations().add(jp.getCodec().readValue(jp, ValueAnnotation.class));
    }
}

From source file:com.microsoft.azure.storage.core.JsonUtilities.java

/***
 * Reserved for internal use. Asserts that the current name of the parser equals the expected value
 * //from  w w  w.j a  va  2 s  . c o m
 * @param parser
 *            The {@link JsonParser} whose current token to check.
 * @param expectedValue
 *            The expected current name of the parser's current token.
 */
public static void assertIsExpectedFieldName(final JsonParser parser, final String expectedValue)
        throws JsonParseException, IOException {
    final String actualValue = parser.getCurrentName();
    if (expectedValue == null) {
        if (actualValue != null) {
            throw new JsonParseException(String.format(SR.UNEXPECTED_FIELD_NAME, expectedValue, actualValue),
                    parser.getCurrentLocation());
        }
    } else {
        if (!expectedValue.equals(actualValue)) {
            throw new JsonParseException(String.format(SR.UNEXPECTED_FIELD_NAME, expectedValue, actualValue),
                    parser.getCurrentLocation());
        }
    }
}

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

/***
 * Reserved for internal use. Asserts that the current name of the parser equals the expected value
 * //from  ww w  .ja v a2  s . co m
 * @param parser
 *            The {@link JsonParser} whose current token to check.
 * @param expectedValue
 *            The expected current name of the parser's current token.
 */
protected static void assertIsExpectedFieldName(final JsonParser parser, final String expectedValue)
        throws JsonParseException, IOException {
    final String actualValue = parser.getCurrentName();
    if (expectedValue == null) {
        if (actualValue != null) {
            throw new JsonParseException(String.format(SR.UNEXPECTED_FIELD_NAME, expectedValue, actualValue),
                    parser.getCurrentLocation());
        }
    } else {
        if (!expectedValue.equals(actualValue)) {
            throw new JsonParseException(String.format(SR.UNEXPECTED_FIELD_NAME, expectedValue, actualValue),
                    parser.getCurrentLocation());
        }
    }
}

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

/**
 * Returns the current field name, or empty string if none.
 *//*from   www .j a  v a2  s .  c om*/
public static String getCurrentName(JsonParser par) throws IOException {
    String name = par.getCurrentName();
    return name == null ? "" : name;
}

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

/**
 * Consumes the next token from a JSON stream and checks that the token is a {@link JsonToken#FIELD_NAME}.
 * Throws {@link JsonParseException} if the token is not a {@link JsonToken#FIELD_NAME}.
 *
 * @param parser the parser to read from
 * @return the field name//  www .  j a v  a2 s.co  m
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static String nextFieldName(final JsonParser parser) throws IOException {

    if (parser.nextToken() == JsonToken.FIELD_NAME) {
        return parser.getCurrentName();
    }
    throw new JsonParseException("expected some field name", parser.getCurrentLocation());
}

From source file:org.nuxeo.client.test.marshallers.DocumentMarshaller.java

protected static void readProperties(JsonParser jp, Map<String, Object> props) throws IOException {
    JsonToken tok = jp.nextToken();/*from www  .j ava  2 s . c o m*/
    while (tok != null && tok != JsonToken.END_OBJECT) {
        String key = jp.getCurrentName();
        tok = jp.nextToken();
        switch (tok) {
        case START_ARRAY:
            props.put(key, readArrayProperty(jp));
            break;
        case START_OBJECT:
            props.put(key, readObjectProperty(jp));
            break;
        case VALUE_NULL:
            props.put(key, null);
            break;
        default:
            props.put(key, jp.getText());
        }
        tok = jp.nextToken();
    }
    if (tok == null) {
        throw new IllegalArgumentException("Unexpected end of stream.");
    }
}

From source file:com.microsoft.azure.storage.core.EncryptionAgent.java

public static EncryptionAgent deserialize(JsonParser parser) throws JsonParseException, IOException {
    JsonUtilities.assertIsStartObjectJsonToken(parser);

    parser.nextToken();//from  w  w  w .ja  va  2s . c o  m

    EncryptionAgent agent = new EncryptionAgent();
    while (parser.getCurrentToken() != JsonToken.END_OBJECT) {
        String name = parser.getCurrentName();
        parser.nextToken();

        if (name.equals("Protocol")) {
            agent.setProtocol(parser.getValueAsString());
        } else if (name.equals("EncryptionAlgorithm")) {
            agent.setEncryptionAlgorithm(EncryptionAlgorithm.valueOf(parser.getValueAsString()));
        }
        parser.nextToken();
    }

    JsonUtilities.assertIsEndObjectJsonToken(parser);

    return agent;
}

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

static Sequence parseSequence(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException {
    JsonParser parser = null;
    try {//  w w w  .  jav  a  2  s. c o m
        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
        }
    }
}