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

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

Introduction

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

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Closes the parser so that no further iteration or data access can be made; will also close the underlying input source if parser either owns the input source, or feature Feature#AUTO_CLOSE_SOURCE is enabled.

Usage

From source file:org.eclipse.rdf4j.rio.rdfjson.RDFJSONParser.java

@Override
public void parse(final InputStream inputStream, final String baseUri)
        throws IOException, RDFParseException, RDFHandlerException {
    JsonParser jp = null;

    clear();//from   w ww  .ja  va  2s  .  c o m

    try {
        if (this.rdfHandler != null) {
            this.rdfHandler.startRDF();
        }

        jp = RDFJSONUtility.JSON_FACTORY.createParser(new BOMInputStream(inputStream, false));
        rdfJsonToHandlerInternal(this.rdfHandler, this.valueFactory, jp);
    } catch (final IOException e) {
        if (jp != null) {
            reportFatalError("Found IOException during parsing", e, jp.getCurrentLocation());
        } else {
            reportFatalError(e);
        }
    } finally {
        clear();
        if (jp != null) {
            try {
                jp.close();
            } catch (final IOException e) {
                reportFatalError("Found exception while closing JSON parser", e, jp.getCurrentLocation());
            }
        }
    }
    if (this.rdfHandler != null) {
        this.rdfHandler.endRDF();
    }
}

From source file:org.o3project.ocnrm.model.bind.OduBindingData.java

@Override
public void bind(String name, String resource) throws JsonParseException, JsonMappingException, IOException {
    JsonFactory factory = new JsonFactory();
    JsonParser jp = factory.createParser(resource.toString());
    jp.nextToken();//from ww  w  . java 2 s.  c  om
    OduMapping terminationPoint = new OduMapping();
    terminationPoint.setName(name);
    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        jp.nextToken();
        if ("dpid".equals(fieldname)) {
            terminationPoint.setDpid(jp.getText());
        } else if ("port".equals(fieldname)) {
            terminationPoint.setPort(jp.getText());
        } else if ("odutype".equals(fieldname)) {
            terminationPoint.setOdutype(jp.getText());
        } else if ("ts".equals(fieldname)) {
            String ts = jp.getText();
            terminationPoint.setTs(ts);
        } else if ("tpn".equals(fieldname)) {
            terminationPoint.setTpn(jp.getText());
        } else {
            throw new IllegalStateException("Unrecognized field '" + fieldname + "'!");
        }
        bindMap.put(terminationPoint.getName(), terminationPoint);
    }
    jp.close();
}

From source file:de.konqi.fitapi.auth.PublicKeysManager.java

/**
 * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}.
 *
 * <p>/*from  w ww  .  j  a  v  a  2s .  c  om*/
 * This method is automatically called from {@link #getPublicKeys()} if the public keys have not
 * yet been initialized or if the expiration time is very close, so normally this doesn't need to
 * be called. Only call this method to explicitly force the public keys to be updated.
 * </p>
 */
public PublicKeysManager refresh() throws GeneralSecurityException, IOException {
    lock.lock();
    try {
        publicKeys = new ArrayList<PublicKey>();
        // HTTP request to public endpoint
        CertificateFactory factory = SecurityUtils.getX509CertificateFactory();
        HttpResponse certsResponse = transport.createRequestFactory()
                .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute();
        expirationTimeMilliseconds = clock.currentTimeMillis()
                + getCacheTimeInSec(certsResponse.getHeaders()) * 1000;
        // parse each public key in the JSON response
        JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent());
        JsonToken currentToken = parser.getCurrentToken();
        // token is null at start, so get next token
        if (currentToken == null) {
            currentToken = parser.nextToken();
        }
        Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT);
        try {
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                parser.nextToken();
                String certValue = parser.getText();
                X509Certificate x509Cert = (X509Certificate) factory
                        .generateCertificate(new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue)));
                publicKeys.add(x509Cert.getPublicKey());
            }
            publicKeys = Collections.unmodifiableList(publicKeys);
        } finally {
            parser.close();
        }
        return this;
    } finally {
        lock.unlock();
    }
}

From source file:net.floodlightcontroller.cli.commands.ShowSwitchCmd.java

/**
 * Parses a JSON string and decomposes all JSON arrays and objects. Stores the
 * resulting strings in a nested Map of string objects.
 * //from  ww  w . jav a2s.  c  o  m
 * @param jsonString
 */
@SuppressWarnings("unchecked")
private List<Map<String, Object>> parseJson(String jsonString) throws IOException {
    /* The Jackson JSON parser. */
    JsonParser jp;
    /* The Jackson JSON factory. */
    JsonFactory f = new JsonFactory();
    /* The Jackson object mapper. */
    ObjectMapper mapper = new ObjectMapper();
    /* A list of JSON data objects retrieved by using the REST API. */
    List<Map<String, Object>> jsonData = new ArrayList<Map<String, Object>>();

    try {
        jp = f.createJsonParser(jsonString);
    } catch (JsonParseException e) {
        throw new IOException(e);
    }

    // Move to the first object in the array.
    jp.nextToken();
    if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
        throw new IOException("Expected START_ARRAY instead of " + jp.getCurrentToken());
    }

    // Retrieve the information from JSON
    while (jp.nextToken() == JsonToken.START_OBJECT) {
        jsonData.add(mapper.readValue(jp, Map.class));
    }

    // Close the JSON parser.
    jp.close();

    // Return.
    return jsonData;
}

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

static ArchivedSequence parseArchivedSequence(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 id = null;
        String type = null;
        String assembly = null;
        String release = null;
        String version = null;
        String latest = null;
        String peptide = null;
        boolean current = false;
        List<String> possibleReplacement = new ArrayList<String>();

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

            if ("id".equals(field)) {
                id = parser.getText();
            } else if ("type".equals(field)) {
                type = parser.getText();
            } else if ("assembly".equals(field)) {
                assembly = parser.getText();
            } else if ("release".equals(field)) {
                release = parser.getText();
            } else if ("version".equals(field)) {
                version = parser.getText();
            } else if ("latest".equals(field)) {
                latest = parser.getText();
            } else if ("peptide".equals(field)) {
                peptide = parser.getText();
            } else if ("is_current".equals(field)) {
                current = (Integer.parseInt(parser.getText()) > 0);
            } else if ("possible_replacement".equals(field)) {
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    possibleReplacement.add(parser.getText());
                }
            }
        }
        return new ArchivedSequence(id, type, assembly, release, version, latest, peptide, current,
                possibleReplacement.toArray(new String[possibleReplacement.size()]));
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

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 a 2  s .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.microsoft.azure.storage.table.TableStorageErrorDeserializer.java

/**
 * Gets the Extended Error information.//w  ww  .ja va2  s .  c  om
 * 
 * @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:org.h2gis.drivers.geojson.GeoJsonReaderDriver.java

/**
 * Parses the GeoJSON data and set the values to the table.
 *
 * @throws IOException//w ww .  ja  v  a 2 s . co m
 * @throws SQLException
 */
private void parseData() throws IOException, SQLException {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fileName);
        JsonParser jp = jsFactory.createParser(fis);

        jp.nextToken();//START_OBJECT
        jp.nextToken(); // field_name (type)
        jp.nextToken(); // value_string (FeatureCollection)
        String geomType = jp.getText();
        if (geomType.equalsIgnoreCase(GeoJsonField.FEATURECOLLECTION)) {
            parseFeatures(jp);
        } else {
            throw new SQLException(
                    "Malformed GeoJSON file. Expected 'FeatureCollection', found '" + geomType + "'");
        }
        jp.close();
    } catch (FileNotFoundException ex) {
        throw new SQLException(ex);

    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ex) {
            throw new SQLException(ex);
        }
    }
}

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

static List<Variation> parseOverlap(final JsonFactory jsonFactory, final InputStream inputStream)
        throws IOException {
    JsonParser parser = null;
    try {/*from  w w  w . j  a v a  2  s  .com*/
        parser = jsonFactory.createParser(inputStream);
        parser.nextToken();

        String id = null;
        String reference = null;
        List<String> alternateAlleles = new ArrayList<String>();
        String locationName = null;
        String coordinateSystem = "chromosome";
        int start = -1;
        int end = -1;
        int strand = -1;
        List<Variation> variationFeatures = new ArrayList<Variation>();
        while (parser.nextToken() != JsonToken.END_ARRAY) {
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                String field = parser.getCurrentName();
                parser.nextToken();
                if ("id".equals(field)) {
                    id = 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());
                } else if ("alt_alleles".equals(field)) {
                    int index = 0;
                    while (parser.nextToken() != JsonToken.END_ARRAY) {
                        if (index == 0) {
                            reference = parser.getText();
                        } else if (index == 1) {
                            alternateAlleles.add(parser.getText());
                        }
                        index++;
                    }
                }
            }
            variationFeatures.add(new Variation(id, reference, alternateAlleles,
                    new Location(locationName, coordinateSystem, start, end, strand)));
            id = null;
            reference = null;
            alternateAlleles.clear();
            locationName = null;
            start = -1;
            end = -1;
            strand = -1;
        }
        return variationFeatures;
    } finally {
        try {
            inputStream.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            parser.close();
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:eu.mondo.driver.mongo.util.MStatementDeserializer.java

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

    String objectString = null;//from  w w w .java 2  s.  c  om
    String predicateString = null;
    String subjectString = null;

    BigInteger subjectBI;
    BigInteger predicateBI;
    BigInteger objectBI;

    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(jp);

    subjectString = root.path("subject").textValue();
    predicateString = root.path("predicate").textValue();
    objectString = root.path("object").textValue();

    String subjectBIS = root.path("subjectBI").textValue();
    String predicateBIS = root.path("predicateBI").textValue();
    String objectBIS = root.path("objectBI").textValue();
    subjectBI = "".equals(subjectBIS) || subjectBIS == null ? new BigInteger("0", 10)
            : new BigInteger(subjectBIS, 16);
    predicateBI = "".equals(predicateBIS) || predicateBIS == null ? new BigInteger("0", 10)
            : new BigInteger(predicateBIS, 16);
    objectBI = "".equals(objectBIS) || objectBIS == null ? new BigInteger("0", 10)
            : new BigInteger(objectBIS, 16);

    //        URI subject = new URIImpl(subjectString);
    //        URI predicate = new URIImpl(predicateString);
    //
    //        Value object;
    //        try {
    //            object = new URIImpl(objectString);
    //        } catch (Exception e) {
    //            object = ValueFactoryImpl.getInstance().createLiteral(objectString);
    //        }

    jp.close();

    MStatement statement = new MStatement();
    statement.setSubject(subjectString);
    statement.setPredicate(predicateString);
    statement.setObject(objectString);
    statement.setSubjectBI(subjectBI);
    statement.setPredicateBI(predicateBI);
    statement.setObjectBI(objectBI);

    return statement;
}