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:com.microsoft.azure.storage.blob.BlobEncryptionData.java

public static BlobEncryptionData deserialize(String inputData) throws JsonProcessingException, IOException {
    JsonParser parser = Utility.getJsonParser(inputData);
    BlobEncryptionData data = new BlobEncryptionData();
    try {/*from ww  w  . j  a va  2 s  .c  o  m*/
        if (!parser.hasCurrentToken()) {
            parser.nextToken();
        }

        JsonUtilities.assertIsStartObjectJsonToken(parser);

        parser.nextToken();

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

            if (name.equals(Constants.EncryptionConstants.ENCRYPTION_MODE)) {
                data.setEncryptionMode(parser.getValueAsString());
            } else if (name.equals(Constants.EncryptionConstants.WRAPPED_CONTENT_KEY)) {
                data.setWrappedContentKey(WrappedContentKey.deserialize(parser));
            } else if (name.equals(Constants.EncryptionConstants.ENCRYPTION_AGENT)) {
                data.setEncryptionAgent(EncryptionAgent.deserialize(parser));
            } else if (name.equals(Constants.EncryptionConstants.CONTENT_ENCRYPTION_IV)) {
                data.setContentEncryptionIV(parser.getBinaryValue());
            } else if (name.equals(Constants.EncryptionConstants.KEY_WRAPPING_METADATA)) {
                data.setKeyWrappingMetadata(deserializeKeyWrappingMetadata(parser));
            } else {
                consumeJsonObject(parser);
            }
            parser.nextToken();
        }

        JsonUtilities.assertIsEndObjectJsonToken(parser);
    } finally {
        parser.close();
    }

    return data;
}

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

protected EObject postDeserialize(TokenBuffer buffer, EObject object, EClass defaultType,
        DeserializationContext ctxt) throws IOException {
    if (object == null && defaultType == null) {
        return null;
    }/*from w w w. j a  v a 2s . com*/

    if (object == null) {
        object = EcoreUtil.create(defaultType);
    }

    final Resource resource = getResource(ctxt);
    final JsonParser jp = buffer.asParser();
    final EObjectPropertyMap propertyMap = builder.construct(object.eClass());

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

        if (property != null) {
            property.deserializeAndSet(jp, object, ctxt, resource);
        } else {
            handleUnknownProperty(jp, resource, ctxt);
        }
    }
    jp.close();
    buffer.close();
    return object;
}

From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java

public void prettyPrint(List<File> inputFiles, File outputFile) throws IOException {
    JsonFactory factory = new JsonFactory();
    factory.disable(JsonFactory.Feature.INTERN_FIELD_NAMES);
    if (!strict) {
        factory.enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
        factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        factory.enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS);
        factory.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS);
        factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    }/*from   www . j a  v  a  2 s  .  co m*/

    ObjectMapper mapper = null;
    if (sortKeys) {
        mapper = new ObjectMapper(factory);
        mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    }

    // Open the output stream and create the Json emitter.
    JsonGenerator generator;
    File tempOutputFile = null;
    if (STDINOUT.equals(outputFile)) {
        generator = factory.createGenerator(stdout, JsonEncoding.UTF8);
    } else if (!caseInsensitiveContains(inputFiles, outputFile)) {
        generator = factory.createGenerator(outputFile, JsonEncoding.UTF8);
    } else {
        // Writing to an input file.. use a temp file to stage the output until we're done.
        tempOutputFile = getTemporaryFileFor(outputFile);
        generator = factory.createGenerator(tempOutputFile, JsonEncoding.UTF8);
    }
    try {
        // Separate top-level objects by a newline in the output.
        String newline = System.getProperty("line.separator");
        generator.setPrettyPrinter(new DefaultPrettyPrinter(newline));

        if (wrap) {
            generator.writeStartArray();
        }

        for (File inputFile : inputFiles) {
            JsonParser parser;
            if (STDINOUT.equals(inputFile)) {
                parser = factory.createParser(stdin);
            } else {
                parser = factory.createParser(inputFile);
            }
            try {
                while (parser.nextToken() != null) {
                    copyCurrentStructure(parser, mapper, 0, generator);
                }
            } finally {
                parser.close();
            }
        }

        if (wrap) {
            generator.writeEndArray();
        }

        generator.writeRaw(newline);
    } finally {
        generator.close();
    }
    if (tempOutputFile != null && !tempOutputFile.renameTo(outputFile)) {
        System.err.println("error: unable to rename temporary file to output: " + outputFile);
        System.exit(1);
    }
}

From source file:org.springframework.data.couchbase.core.convert.translation.JacksonTranslationService.java

/**
 * Decode a JSON string into the {@link CouchbaseStorable} structure.
 *
 * @param source the source formatted document.
 * @param target the target of the populated data.
 *
 * @return the decoded structure./*  w w w  .j  a v  a 2s  .com*/
 */
@Override
public final CouchbaseStorable decode(final Object source, final CouchbaseStorable target) {
    try {
        JsonParser parser = factory.createParser((String) source);
        while (parser.nextToken() != null) {
            JsonToken currentToken = parser.getCurrentToken();

            if (currentToken == JsonToken.START_OBJECT) {
                return decodeObject(parser, (CouchbaseDocument) target);
            } else if (currentToken == JsonToken.START_ARRAY) {
                return decodeArray(parser, new CouchbaseList());
            } else {
                throw new MappingException("JSON to decode needs to start as array or object!");
            }
        }
        parser.close();
    } catch (IOException ex) {
        throw new RuntimeException("Could not decode JSON", ex);
    }
    return target;
}

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

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

    String objectString = null;/*w  ww  .ja v  a 2  s . c  o m*/
    String predicateString = null;
    String subjectString = null;

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

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

    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();

    Statement statement = new StatementImpl(subject, predicate, object);

    return statement;
}

From source file:org.openrdf.rio.rdfjson.RDFJSONParser.java

@Override
public void parse(final Reader reader, final String baseUri)
        throws IOException, RDFParseException, RDFHandlerException {
    if (rdfHandler == null) {
        rdfHandler.startRDF();/*from w  ww.  ja  v  a  2  s  .  co m*/
    }
    JsonParser jp = null;

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

From source file:org.usrz.libs.webtools.resources.ServeResource.java

private Response produce(String path) throws Exception {

    /* Basic check for null/empty path */
    if ((path == null) || (path.length() == 0))
        return NOT_FOUND;

    /* Get our resource file, potentially a ".less" file for CSS */
    Resource resource = manager.getResource(path);
    if ((resource == null) && path.endsWith(".css")) {
        path = path.substring(0, path.length() - 4) + ".less";
        resource = manager.getResource(path);
    }/*from w w w.jav  a  2s .  com*/

    /* If the root is incorrect, log this, if not found, 404 it! */
    if (resource == null)
        return NOT_FOUND;

    /* Ok, we have a resource on disk, this can be potentially long ... */
    final String fileName = resource.getFile().getName();

    /* Check and validated our cache */
    Entry cached = cache.computeIfPresent(resource, (r, entry) -> entry.resource.hasChanged() ? null : entry);

    /* If we have no cache, we *might* want to cache something */
    if (cached == null) {

        /* What to do, what to do? */
        if ((fileName.endsWith(".css") && minify) || fileName.endsWith(".less")) {

            /* Lessify CSS and cache */
            xlog.debug("Lessifying resource \"%s\"", fileName);
            cached = new Entry(resource, lxess.convert(resource, minify), styleMediaType);

        } else if (fileName.endsWith(".js") && minify) {

            /* Uglify JavaScript and cache */
            xlog.debug("Uglifying resource \"%s\"", fileName);
            cached = new Entry(resource, uglify.convert(resource.readString(), minify, minify),
                    scriptMediaType);

        } else if (fileName.endsWith(".json")) {

            /* Strip comments and normalize JSON */
            xlog.debug("Normalizing JSON resource \"%s\"", fileName);

            /* All to do with Jackson */
            final Reader reader = resource.read();
            final StringWriter writer = new StringWriter();
            final JsonParser parser = json.createParser(reader);
            final JsonGenerator generator = json.createGenerator(writer);

            /* Not minifying? Means pretty printing! */
            if (!minify)
                generator.useDefaultPrettyPrinter();

            /* Get our schtuff through the pipeline */
            parser.nextToken();
            generator.copyCurrentStructure(parser);
            generator.flush();
            generator.close();
            reader.close();
            parser.close();

            /* Cached results... */
            cached = new Entry(resource, writer.toString(), jsonMediaType);

        }

        /* Do we have anything to cache? */
        if (cached != null) {
            xlog.debug("Caching resource \"%s\"", fileName);
            cache.put(resource, cached);
        }
    }

    /* Prepare our basic response from either cache or file */
    final ResponseBuilder response = Response.ok();
    if (cached != null) {

        /* Response from cache */
        xlog.trace("Serving cached resource \"%s\"", fileName);
        response.entity(cached.contents).lastModified(new Date(resource.lastModifiedAt())).type(cached.type);
    } else {

        /* Response from a file */
        xlog.trace("Serving file-based resource \"%s\"", fileName);

        /* If text/* or application/javascript, append encoding */
        MediaType type = MediaTypes.get(fileName);
        if (type.getType().equals("text") || scriptMediaType.isCompatible(type)) {
            type = type.withCharset(charsetName);
        }

        /* Our file is served! */
        response.entity(resource.getFile()).lastModified(new Date(resource.lastModifiedAt())).type(type);
    }

    /* Caching headers and build response */
    final Date expires = Date.from(Instant.now().plus(cacheDuration));
    return response.cacheControl(cacheControl).expires(expires).build();

}

From source file:org.openrdf.rio.rdfjson.RDFJSONParser.java

@Override
public void parse(final InputStream inputStream, final String baseUri)
        throws IOException, RDFParseException, RDFHandlerException {
    if (this.rdfHandler != null) {
        this.rdfHandler.startRDF();
    }//from w  w w. j  a  v  a  2  s.co m

    JsonParser jp = null;

    try {
        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:com.github.heuermh.ensemblrestclient.JacksonLookupConverter.java

static Lookup parseLookup(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException {
    JsonParser parser = null;
    try {//from   www .  j ava2  s  .com
        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
        }
    }
}

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

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

    clear();/*from   w  ww.  j  av a2 s  .  c o m*/

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

        jp = RDFJSONUtility.JSON_FACTORY.createParser(reader);
        rdfJsonToHandlerInternal(rdfHandler, 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 (rdfHandler != null) {
        rdfHandler.endRDF();
    }
}