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:org.onosproject.north.aaa.api.parser.impl.ApplicationParser.java

@Override
public Set<Application> parseJson(InputStream stream) throws IOException, ParseException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(stream);
    JsonParser jp = jsonNode.traverse();
    Set<Application> applicationSet = new HashSet<>();

    // continue parsing the token till the end of input is reached
    while (!jp.isClosed()) {
        // get the token
        JsonToken token = jp.nextToken();
        // if its the last token then we are done
        if (token == null) {
            break;
        }//from w w  w .ja  v a2 s . c o m

        if (JsonToken.FIELD_NAME.equals(token) && "applications".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after applications");
            }

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }

                if (JsonToken.START_OBJECT.equals(token)) {
                    Application app = jsonToApplication(jp);
                    applicationSet.add(app);
                }
            }
        }
    }
    return applicationSet;
}

From source file:org.onosproject.north.aaa.api.parser.impl.UserParser.java

private User jsonToUser(JsonParser jp) throws ParseException, IOException {
    User.Builder builder = User.builder();

    while (true) {
        JsonToken token = jp.nextToken();
        if (JsonToken.END_OBJECT.equals(token)) {
            // bail out
            break;
        }//from   w w w.  jav  a 2 s  . com

        if (JsonToken.FIELD_NAME.equals(token) && "username".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildUsername(jp.getText());
        } else if (JsonToken.FIELD_NAME.equals(token) && "password".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildPassword(jp.getText());
        } else if (JsonToken.FIELD_NAME.equals(token) && "roles".equals(jp.getCurrentName())) {
            jp.nextToken();
            String roles = jp.getText();
            if ("admin".equals(roles) || "user".equals(roles)) {
                builder.buildRoles(roles);
            } else {
                // bail out
                throw new ParseException("roles must be set to either \"admin\" or \"user\"");
            }

        } else if (JsonToken.FIELD_NAME.equals(token) && "switches".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after switches");
            }
            Set<String> switches = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                switches.add(jp.getText());
            }
            builder.buildSwitches(switches);

        } else if (JsonToken.FIELD_NAME.equals(token) && "domains".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after domains");
            }
            Set<String> domains = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                domains.add(jp.getText());
            }
            builder.buildDomains(domains);

        } else if (JsonToken.FIELD_NAME.equals(token) && "scopes".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after scopes");
            }
            Set<String> scopes = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                scopes.add(jp.getText());
            }
            builder.buildScopes(scopes);

        } else if (JsonToken.FIELD_NAME.equals(token) && "email".equals(jp.getCurrentName())) {
            jp.nextToken();
            String email = jp.getText();

            // verify email by email regex
            Pattern emailPattern = Pattern.compile(EMAIL_PATTERN);
            if (!emailPattern.matcher(email).matches()) {
                // bail out
                throw new ParseException("email is not valid");
            }
            builder.buildEmail(email);
        }
    }
    return builder.buildAll();
}

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

private void expectObjectField(JsonParser parser, String name) throws IOException {
    expect(parser, JsonToken.FIELD_NAME);
    if (!parser.getCurrentName().equals(name)) {
        throw new RuntimeException("expected field " + name + ", got " + parser.getCurrentName());
    }//www  . ja v  a2s . c  o  m
    expect(parser, JsonToken.START_OBJECT);
    while (parser.nextToken() != JsonToken.END_OBJECT) {
        // empty
    }
}

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

@Override
public EObject deserialize(JsonParser jp, DeserializationContext ctxt, EObject intoValue) throws IOException {
    if (intoValue == null) {
        return null;
    }//from  w  w w. j  a va  2 s .  co m

    EMFContext.prepare(ctxt);
    EObjectPropertyMap propertyMap = builder.construct(intoValue.eClass());

    final Resource resource = getResource(ctxt);

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

        if (property != null) {
            property.deserializeAndSet(jp, intoValue, ctxt, resource);
        } else {
            handleUnknownProperty(jp, resource, ctxt);
        }
    }

    return intoValue;
}

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

static VariationConsequences parseVariationConsequences(final JsonFactory jsonFactory,
        final InputStream inputStream) throws IOException {
    JsonParser parser = null;
    try {//from   w w w.  j a  v  a2 s .  co  m
        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;

        List<TranscriptConsequences> transcriptConsequences = new ArrayList<TranscriptConsequences>();

        String alternateAllele = null;
        int transcriptStrand = -1;
        boolean canonical = false;
        String geneId = null;
        String transcriptId = null;
        String translationId = null;
        String transcriptAlleleString = null;
        String codons = null;
        String hgvsc = null;
        String aminoAcids = null;
        String hgvsp = null;
        List<String> consequenceTerms = new ArrayList<String>();

        while (parser.nextToken() != JsonToken.END_ARRAY) {
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                String field = parser.getCurrentName();
                parser.nextToken();

                if ("id".equals(field)) {
                    identifier = parser.getText();
                } else if ("seq_region_name".equals(field)) {
                    locationName = parser.getText();
                } else if ("start".equals(field)) {
                    start = parser.getIntValue();
                } else if ("end".equals(field)) {
                    end = parser.getIntValue();
                } else if ("strand".equals(field)) {
                    strand = parser.getIntValue();
                } else if ("allele_string".equals(field)) {
                    String[] tokens = parser.getText().split("/");
                    referenceAllele = tokens[0];
                    for (int i = 1; i < tokens.length; i++) {
                        alternateAlleles.add(tokens[i]);
                    }
                } else if ("transcript_consequences".equals(field)) {
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        while (parser.nextToken() != JsonToken.END_OBJECT) {
                            String transcriptField = parser.getCurrentName();
                            parser.nextToken();

                            if ("variant_allele".equals(transcriptField)) {
                                alternateAllele = parser.getText();
                            } else if ("strand".equals(transcriptField)) {
                                transcriptStrand = parser.getIntValue();
                            } else if ("canonical".equals(transcriptField)) {
                                canonical = (Integer.parseInt(parser.getText()) > 0);
                            } else if ("gene_id".equals(transcriptField)) {
                                geneId = parser.getText();
                            } else if ("transcript_id".equals(transcriptField)) {
                                transcriptId = parser.getText();
                            } else if ("protein_id".equals(transcriptField)) {
                                translationId = parser.getText();
                            } else if ("codons".equals(transcriptField)) {
                                codons = parser.getText();
                            } else if ("hgvsc".equals(transcriptField)) {
                                hgvsc = parser.getText();
                            } else if ("amino_acids".equals(transcriptField)) {
                                aminoAcids = parser.getText();
                            } else if ("hgvsp".equals(transcriptField)) {
                                hgvsp = parser.getText();
                            } else if ("consequence_terms".equals(transcriptField)) {
                                while (parser.nextToken() != JsonToken.END_ARRAY) {
                                    consequenceTerms.add(parser.getText());
                                }
                            }
                        }

                        transcriptConsequences.add(new TranscriptConsequences(alternateAllele, transcriptStrand,
                                canonical, geneId, transcriptId, translationId, codons, hgvsc, aminoAcids,
                                hgvsp, consequenceTerms));

                        alternateAllele = null;
                        transcriptStrand = -1;
                        canonical = false;
                        geneId = null;
                        transcriptId = null;
                        translationId = null;
                        transcriptAlleleString = null;
                        codons = null;
                        hgvsc = null;
                        aminoAcids = null;
                        hgvsp = null;
                        consequenceTerms.clear();
                    }
                } else if ("colocated_variants".equals(field)) {
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        while (parser.nextToken() != JsonToken.END_OBJECT) {
                            // ignore
                        }
                    }
                }
            }
        }
        Location location = new Location(locationName, coordinateSystem, start, end, strand);
        return new VariationConsequences(identifier, referenceAllele, alternateAlleles, location,
                transcriptConsequences);
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

private void parseField(List<String> fieldNames, List<Primitive> fieldTypes, Row.RowBuilder rowBuilder,
        JsonParser parser) throws IOException {
    final String fieldName = parser.getCurrentName();

    // Move to next token, which is name's value
    JsonToken token = parser.nextToken();
    int i = fieldNames.indexOf(fieldName);
    if (i < 0) {
        return;// w  w  w  .j  a va2 s . co m
    }
    switch (token) {
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
        Primitive type = fieldTypes.get(i);
        if (type == null) {
            if (token == JsonToken.VALUE_NUMBER_INT) {
                type = Primitive.INT;
            } else {
                type = Primitive.FLOAT;
            }
        }
        switch (type) {
        case BYTE:
            rowBuilder.set(i, parser.getIntValue());
            break;
        case SHORT:
            rowBuilder.set(i, parser.getShortValue());
            break;
        case INT:
            rowBuilder.set(i, parser.getIntValue());
            break;
        case LONG:
            rowBuilder.set(i, parser.getLongValue());
            break;
        case FLOAT:
            rowBuilder.set(i, parser.getFloatValue());
            break;
        case DOUBLE:
            rowBuilder.set(i, parser.getDoubleValue());
            break;
        }
        break;
    case VALUE_TRUE:
        rowBuilder.set(i, true);
        break;
    case VALUE_FALSE:
        rowBuilder.set(i, false);
        break;
    case VALUE_NULL:
        break;
    default:
        rowBuilder.set(i, parser.getText());
    }
}

From source file:com.ntsync.shared.RawContact.java

private static List<RawImData> readImList(String rowId, List<RawImData> imAddresses, JsonParser jp)
        throws IOException {
    List<RawImData> newImAddresses = imAddresses;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        ImType type = null;/* www.j  av  a2s .  com*/
        ImProtocolType proType = null;
        String customProctocolName = null;
        String imAddress = null;
        String imTypeLabel = null;
        boolean isSuperPrimary = false;
        boolean isPrimary = false;
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String namefield = jp.getCurrentName();
            // move to value
            if (jp.nextToken() == null) {
                throw new JsonParseException("Invalid JSON-Structure. End of Object missing.",
                        jp.getCurrentLocation());
            }
            if (ContactConstants.DATA.equals(namefield)) {
                imAddress = jp.getValueAsString();
            } else if (ContactConstants.TYPE.equals(namefield)) {
                type = ImType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.SUPERPRIMARY.equals(namefield)) {
                isSuperPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.PRIMARY.equals(namefield)) {
                isPrimary = jp.getValueAsBoolean();
            } else if (ContactConstants.LABEL.equals(namefield)) {
                imTypeLabel = jp.getValueAsString();
            } else if (ContactConstants.PROTOCOL_TYPE.equals(namefield)) {
                proType = ImProtocolType.fromVal(jp.getValueAsInt());
            } else if (ContactConstants.PROTOCOL_CUSTOM_PROT.equals(namefield)) {
                customProctocolName = jp.getValueAsString();
            } else {
                LOG.error(JSON_FIELDNOTRECOGNIZED + rowId + " Fieldname:" + namefield);
            }
        }
        if (newImAddresses == null) {
            newImAddresses = new ArrayList<RawImData>();
        }
        if (type == null) {
            type = ImType.TYPE_OTHER;
        }

        newImAddresses.add(new RawImData(imAddress, type, imTypeLabel, isPrimary, isSuperPrimary, proType,
                customProctocolName));
    }
    return newImAddresses;
}

From source file:com.tage.calcite.adapter.druid.DruidConnectionImpl.java

private void expectScalarField(JsonParser parser, String name) throws IOException {
    expect(parser, JsonToken.FIELD_NAME);
    if (!parser.getCurrentName().equals(name)) {
        throw new RuntimeException("expected field " + name + ", got " + parser.getCurrentName());
    }//from www.  j a v  a2 s  .  c  o m
    final JsonToken t = parser.nextToken();
    switch (t) {
    case VALUE_NULL:
    case VALUE_FALSE:
    case VALUE_TRUE:
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
    case VALUE_STRING:
        break;
    default:
        throw new RuntimeException("expected scalar field, got  " + t);
    }
}

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

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

    JsonToken t = jp.getCurrentToken();/*from   w  w w  .  j  a v  a  2  s  .  co  m*/
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

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");
        }//  w w  w.  j a v a  2 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;
    }
}