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

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

Introduction

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

Prototype

public abstract String getText() throws IOException, JsonParseException;

Source Link

Document

Method for accessing textual representation of the current token; if no current token (before first call to #nextToken , or after encountering end-of-input), returns null.

Usage

From source file:com.pursuer.reader.easyrss.data.parser.TagJSONParser.java

public void parse() throws JsonParseException, IOException, IllegalStateException {
    final JsonFactory factory = new JsonFactory();
    final JsonParser parser = factory.createJsonParser(input);
    Tag tag = new Tag();
    int level = 0;
    boolean found = false;
    while (parser.nextToken() != null) {
        final String name = parser.getCurrentName();
        switch (parser.getCurrentToken()) {
        case START_OBJECT:
        case START_ARRAY:
            level++;/*from w  w  w  .  j  a v a2s  .co  m*/
            break;
        case END_OBJECT:
        case END_ARRAY:
            level--;
            break;
        case VALUE_STRING:
            if (level == 3) {
                if ("id".equals(name)) {
                    tag.setUid(parser.getText());
                } else if ("sortid".equals(name)) {
                    tag.setSortId(parser.getText());
                }
            }
        case FIELD_NAME:
            if (level == 1 && "tags".equals(name)) {
                found = true;
            }
        default:
        }
        if (level == 2) {
            if (tag.getUid() != null && listener != null) {
                listener.onTagRetrieved(tag);
            }
            tag = new Tag();
        }
    }
    parser.close();
    if (!found) {
        throw new IllegalStateException("Invalid JSON input");
    }
}

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  va 2 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.google.openrtb.json.OpenRtbNativeJsonReader.java

protected void readNativeRequestField(JsonParser par, NativeRequest.Builder req, String fieldName)
        throws IOException {
    switch (fieldName) {
    case "ver":
        req.setVer(par.getText());
        break;//from  w ww .  j av a2 s  . c o  m
    case "layout": {
        LayoutId value = LayoutId.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            req.setLayout(value);
        }
    }
        break;
    case "adunit": {
        AdUnitId value = AdUnitId.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            req.setAdunit(value);
        }
    }
        break;
    case "plcmtcnt":
        req.setPlcmtcnt(par.getIntValue());
        break;
    case "seq":
        req.setSeq(par.getIntValue());
        break;
    case "assets":
        for (startArray(par); endArray(par); par.nextToken()) {
            req.addAssets(readReqAsset(par));
        }
        break;
    case "context": {
        ContextType value = ContextType.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            req.setContext(value);
        }
    }
        break;
    case "contextsubtype": {
        ContextSubtype value = ContextSubtype.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            req.setContextsubtype(value);
        }
    }
        break;
    case "plcmttype": {
        PlacementType value = PlacementType.valueOf(par.getIntValue());
        if (checkEnum(value)) {
            req.setPlcmttype(value);
        }
    }
        break;
    default:
        readOther(req, par, fieldName);
    }
}

From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer.java

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

    String tokenValue = null;/* w  ww  .j a v  a 2  s.  com*/
    String tokenType = null;
    String refreshToken = null;
    Long expiresIn = null;
    Set<String> scope = null;
    Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();

    // TODO What should occur if a parameter exists twice
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String name = jp.getCurrentName();
        jp.nextToken();
        if (OAuth2AccessToken.ACCESS_TOKEN.equals(name)) {
            tokenValue = jp.getText();
        } else if (OAuth2AccessToken.TOKEN_TYPE.equals(name)) {
            tokenType = jp.getText();
        } else if (OAuth2AccessToken.REFRESH_TOKEN.equals(name)) {
            refreshToken = jp.getText();
        } else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) {
            try {
                expiresIn = jp.getLongValue();
            } catch (JsonParseException e) {
                expiresIn = Long.valueOf(jp.getText());
            }
        } else if (OAuth2AccessToken.SCOPE.equals(name)) {
            String text = jp.getText();
            scope = OAuth2Utils.parseParameterList(text);
        } else {
            additionalInformation.put(name, jp.readValueAs(Object.class));
        }
    }

    // TODO What should occur if a required parameter (tokenValue or tokenType) is missing?

    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenValue);
    accessToken.setTokenType(tokenType);
    if (expiresIn != null) {
        accessToken.setExpiration(new Date(System.currentTimeMillis() + (expiresIn * 1000)));
    }
    if (refreshToken != null) {
        accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken));
    }
    accessToken.setScope(scope);
    accessToken.setAdditionalInformation(additionalInformation);

    return accessToken;
}

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

public void parse(InputStream in) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    try {//w w w  .j  ava2s .com
        JsonParser jp = jsonFactory.createJsonParser(in);

        JsonToken t;
        while ((t = jp.nextToken()) != null) {
            if (t == JsonToken.START_OBJECT) {
                jp.nextToken();

                String name = jp.getCurrentName();
                jp.nextToken();

                if ("type".equals(name)) {
                    String type = jp.getText();

                    if ("node".equals(type))
                        parseNode(jp);

                    else if ("way".equals(type))
                        parseWay(jp);

                    else if ("relation".equals(type))
                        parseRelation(jp);
                }
            }
        }
    } catch (JsonParseException e) {
        e.printStackTrace();
    }
}

From source file:com.pursuer.reader.easyrss.data.parser.SubscriptionJSONParser.java

public void parse() throws JsonParseException, IOException, IllegalStateException {
    final JsonFactory factory = new JsonFactory();
    final JsonParser parser = factory.createJsonParser(input);
    Subscription sub = new Subscription();
    int level = 0;
    boolean found = false;
    while (parser.nextToken() != null) {
        final String name = parser.getCurrentName();
        switch (parser.getCurrentToken()) {
        case START_OBJECT:
        case START_ARRAY:
            level++;//from   w w w.  j a  v a  2s  .c o  m
            break;
        case END_OBJECT:
        case END_ARRAY:
            level--;
            break;
        case VALUE_STRING:
            if (level == 3) {
                if ("id".equals(name)) {
                    sub.setUid(parser.getText());
                } else if ("htmlUrl".equals(name)) {
                    sub.setUrl(parser.getText());
                } else if ("title".equals(name)) {
                    sub.setTitle(Html.fromHtml(parser.getText()).toString());
                } else if ("sortid".equals(name)) {
                    sub.setSortId(parser.getText());
                } else if ("firstitemmsec".equals(name)) {
                    sub.setFirstItemMsec(Long.valueOf(parser.getText()));
                }
            } else if (level == 5 && "id".equals(name)) {
                sub.addTag(parser.getText());
            }
            break;
        case FIELD_NAME:
            if (level == 1 && "subscriptions".equals(name)) {
                found = true;
            }
            break;
        default:
        }
        if (level == 2) {
            if (sub.getUid() != null && listener != null) {
                listener.onSubscriptionRetrieved(sub);
            }
            sub = new Subscription();
        }
    }
    parser.close();
    if (!found) {
        throw new IllegalStateException("Invalid JSON input");
    }
}

From source file:com.cedarsoft.serialization.serializers.jackson.LicenseSerializer.java

@Nonnull
@Override/*from ww  w . j a  v  a2 s .c o m*/
public License deserialize(@Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion)
        throws VersionException, IOException, JsonProcessingException {
    //If there is a subtype it *must* be cc
    JacksonParserWrapper parserWrapper = new JacksonParserWrapper(deserializeFrom);
    parserWrapper.nextToken();
    parserWrapper.verifyCurrentToken(JsonToken.FIELD_NAME);
    if (deserializeFrom.getCurrentName().equals(PROPERTY_SUB_TYPE)) {
        parserWrapper.nextToken();
        parserWrapper.verifyCurrentToken(JsonToken.VALUE_STRING);
        String subType = deserializeFrom.getText();

        if (!subType.equals(SUB_TYPE_CC)) {
            throw new IllegalStateException("Invalid sub type: " + subType);
        }
        parserWrapper.nextToken();
        parserWrapper.verifyCurrentToken(JsonToken.FIELD_NAME);
        String currentName = parserWrapper.getCurrentName();

        if (!PROPERTY_ID.equals(currentName)) {
            throw new JsonParseException(
                    "Invalid field. Expected <" + PROPERTY_ID + "> but was <" + currentName + ">",
                    parserWrapper.getCurrentLocation());
        }
    }

    //id
    assert deserializeFrom.getCurrentName().equals(PROPERTY_ID);
    parserWrapper.nextToken();
    parserWrapper.verifyCurrentToken(JsonToken.VALUE_STRING);
    String id = deserializeFrom.getText();
    //name
    parserWrapper.nextToken();
    parserWrapper.verifyCurrentToken(JsonToken.FIELD_NAME);
    String currentName1 = parserWrapper.getCurrentName();

    if (!PROPERTY_NAME.equals(currentName1)) {
        throw new JsonParseException(
                "Invalid field. Expected <" + PROPERTY_NAME + "> but was <" + currentName1 + ">",
                parserWrapper.getCurrentLocation());
    }
    parserWrapper.nextToken();
    String name = deserializeFrom.getText();
    //url
    parserWrapper.nextToken();
    parserWrapper.verifyCurrentToken(JsonToken.FIELD_NAME);
    String currentName = parserWrapper.getCurrentName();

    if (!PROPERTY_URL.equals(currentName)) {
        throw new JsonParseException(
                "Invalid field. Expected <" + PROPERTY_URL + "> but was <" + currentName + ">",
                parserWrapper.getCurrentLocation());
    }
    JsonToken token = deserializeFrom.nextToken();
    @Nullable
    URL url;
    if (token == JsonToken.VALUE_NULL) {
        url = null;
    } else {
        url = new URL(deserializeFrom.getText());
    }
    //Finally closing element
    parserWrapper.nextToken(JsonToken.END_OBJECT);

    //Constructing the deserialized object
    try {
        return License.get(id);
    } catch (IllegalArgumentException ignore) {
        return new License(id, name, url);
    }
}

From source file:ninja.leaping.configurate.json.JSONConfigurationLoader.java

private void parseValue(JsonParser parser, ConfigurationNode node) throws IOException {
    JsonToken token = parser.getCurrentToken();
    switch (token) {
    case START_OBJECT:
        parseObject(parser, node);//from ww  w.  ja va 2s  .c om
        break;
    case START_ARRAY:
        parseArray(parser, node);
        break;
    case VALUE_NUMBER_FLOAT:
        node.setValue(parser.getFloatValue());
        break;
    case VALUE_NUMBER_INT:
        node.setValue(parser.getIntValue());
        break;
    case VALUE_STRING:
        node.setValue(parser.getText());
        break;
    case VALUE_TRUE:
    case VALUE_FALSE:
        node.setValue(parser.getBooleanValue());
        break;
    case VALUE_NULL: // Ignored values
    case FIELD_NAME:
        break;
    default:
        throw new IOException("Unsupported token type: " + token + " (at " + parser.getTokenLocation() + ")");
    }
}

From source file:org.helm.notation2.wsadapter.NucleotideWSLoader.java

/**
 * Private routine to deserialize nucleotide Store JSON. This is done manually to give more freedom regarding data
 * returned by the webservice.//  w w w.java 2s .  co m
 * 
 * @param parser the JSONParser containing JSONData.
 * @return Map containing nucleotides
 * 
 * @throws JsonParseException
 * @throws IOException
 */
private Map<String, String> deserializeNucleotideStore(JsonParser parser)
        throws JsonParseException, IOException {
    Map<String, String> nucleotides = new HashMap<String, String>();
    String currentNucleotideSymbol = "";
    String currentNucleotideNotation = "";
    boolean foundSymbol = false;
    boolean foundNotation = false;

    parser.nextToken();
    while (parser.hasCurrentToken()) {
        String fieldName = parser.getCurrentName();

        if (fieldName != null) {
            switch (fieldName) {
            case "symbol":
                parser.nextToken();
                currentNucleotideSymbol = parser.getText();
                foundSymbol = true;
                break;
            case "notation":
                parser.nextToken();
                currentNucleotideNotation = parser.getText();
                foundNotation = true;
                break;
            default:
                break;
            }

            if (foundSymbol && foundNotation) {
                nucleotides.put(currentNucleotideSymbol, currentNucleotideNotation);
                foundNotation = false;
                foundSymbol = false;
            }
        }
        parser.nextToken();
    }

    return nucleotides;
}

From source file:net.floodlightcontroller.loadbalancer.MembersResource.java

protected LBMember jsonToMember(String json) throws IOException {
    MappingJsonFactory f = new MappingJsonFactory();
    JsonParser jp;
    LBMember member = new LBMember();

    try {//from   ww  w .  jav a  2  s  .c  om
        jp = f.createJsonParser(json);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new IOException("Expected START_OBJECT");
    }

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw new IOException("Expected FIELD_NAME");
        }

        String n = jp.getCurrentName();
        jp.nextToken();
        if (jp.getText().equals(""))
            continue;
        if (n.equals("id")) {
            member.id = jp.getText();
            continue;
        } else if (n.equals("address")) {
            member.address = IPv4.toIPv4Address(jp.getText());
            continue;
        } else if (n.equals("port")) {
            member.port = Short.parseShort(jp.getText());
            continue;
        } else if (n.equals("connection_limit")) {
            member.connectionLimit = Integer.parseInt(jp.getText());
            continue;
        } else if (n.equals("admin_state")) {
            member.adminState = Short.parseShort(jp.getText());
            continue;
        } else if (n.equals("status")) {
            member.status = Short.parseShort(jp.getText());
            continue;
        } else if (n.equals("pool_id")) {
            member.poolId = jp.getText();
            continue;
        }

        log.warn("Unrecognized field {} in " + "parsing Members", jp.getText());
    }
    jp.close();

    return member;
}