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:io.protostuff.JsonIOUtil.java

/**
 * Parses the {@code messages} from the stream using the given {@code schema}.
 *///ww  w  . jav a2 s  . c o m
public static <T> List<T> parseListFrom(InputStream in, Schema<T> schema, boolean numeric) throws IOException {
    final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), in, false);
    final JsonParser parser = newJsonParser(in, context.allocReadIOBuffer(), 0, 0, true, context);
    // final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(in);
    try {
        return parseListFrom(parser, schema, numeric);
    } finally {
        parser.close();
    }
}

From source file:io.protostuff.JsonIOUtil.java

/**
 * Merges the {@code message} with the byte array using the given {@code schema}.
 *//*from   ww w.  j  ava 2 s  .co  m*/
public static <T> void mergeFrom(byte[] data, int offset, int length, T message, Schema<T> schema,
        boolean numeric) throws IOException {
    final IOContext context = new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), data, false);
    final JsonParser parser = newJsonParser(null, data, offset, offset + length, false, context);
    /*
     * final JsonParser parser = DEFAULT_JSON_FACTORY.createJsonParser(data, offset, length);
     */
    try {
        mergeFrom(parser, message, schema, numeric);
    } finally {
        parser.close();
    }
}

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

/**
 * Reserved for internal use. Parses the operation response as an entity. Reads entity data from the specified
 * <code>JsonParser</code> using the specified class type and optionally projects the entity result with the
 * specified resolver into a {@link TableResult} object.
 * //from  ww  w  . ja v  a 2s  .  c o m
 * @param parser
 *            The <code>JsonParser</code> to read the data to parse from.
 * @param httpStatusCode
 *            The HTTP status code returned with the operation response.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entitys as instance of the class type <code>T</code>.
 * @param options
 *            A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout
 *            settings for the operation.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} object with the parsed operation response.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 * @throws JsonParseException
 *             if an error occurs while parsing the stream.
 */
static <T extends TableEntity, R> TableResult parseSingleOpResponse(final InputStream inStream,
        final TableRequestOptions options, final int httpStatusCode, final Class<T> clazzType,
        final EntityResolver<R> resolver, final OperationContext opContext) throws JsonParseException,
        IOException, InstantiationException, IllegalAccessException, StorageException {
    JsonParser parser = Utility.getJsonParser(inStream);

    try {
        final TableResult res = parseJsonEntity(parser, clazzType,
                null /*HashMap<String, PropertyPair> classProperties*/, resolver, options, opContext);
        res.setHttpStatusCode(httpStatusCode);
        return res;
    } finally {
        parser.close();
    }
}

From source file:org.immutables.mongo.repository.internal.BsonEncoding.java

public static DBObject unwrapJsonable(String json) {
    try {/*from   w w w  .  jav a  2 s .  c om*/
        JsonParser parser = JSON_FACTORY.createParser(json);
        parser.nextToken();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BsonGenerator generator = BSON_FACTORY.createGenerator(outputStream);
        generator.copyCurrentStructure(parser);
        generator.close();
        parser.close();
        byte[] data = outputStream.toByteArray();
        return (DBObject) new LazyDBCallback(null).createObject(data, 0);
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}

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

static Sequence parseSequence(final JsonFactory jsonFactory, final InputStream inputStream) throws IOException {
    JsonParser parser = null;
    try {//ww w  .ja va2s. c  om
        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
        }
    }
}

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

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * /*from  w  w w  . java  2s .co  m*/
 * */
public static ContactGroup valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey)
        throws InvalidKeyException {
    try {
        String sourceId = null;
        Long rawId = null;

        if (values.containsKey(GroupConstants.SERVERROW_ID)) {
            sourceId = readRawString(values.get(GroupConstants.SERVERROW_ID));
        }

        if (sourceId == null || !sourceId.equals(rowId)) {
            // If ServerContactId is different, then rowId is the clientId
            rawId = Long.parseLong(rowId);
        }

        if (sourceId == null && rawId < 0) {
            throw new IllegalArgumentException("Missing RowId in data");
        }

        AEADBlockCipher cipher = CryptoHelper.getCipher();

        final boolean deleted = values.containsKey(GroupConstants.DELETED);

        final String textData = CryptoHelper.decodeStringValue(GroupConstants.TEXTDATA, values, cipher,
                privateKey);

        if (textData == null && !deleted) {
            LOG.error("No textdata found for row with Id:" + rowId);
            return null;
        }

        String title = null;
        String notes = null;

        if (!isEmpty(textData)) {
            JsonFactory fac = new JsonFactory();
            JsonParser jp = fac.createParser(textData);
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                // move to value, or START_OBJECT/START_ARRAY
                jp.nextToken();
                if (GroupConstants.TITLE.equals(fieldname)) {
                    title = jp.getValueAsString();
                } else if (GroupConstants.NOTES.equals(fieldname)) {
                    notes = jp.getValueAsString();
                } else {
                    LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname);
                }
            }
            jp.close();
        }

        String modStr = readRawString(values.get(GroupConstants.MODIFIED));
        Date lastModified = null;
        if (!isEmpty(modStr)) {
            lastModified = new Date(Long.parseLong(modStr));
        }

        return new ContactGroup(rawId, sourceId, title, notes, deleted, lastModified, -1);
    } catch (InvalidCipherTextException ex) {
        throw new InvalidKeyException("Invalid key detected.", ex);
    } catch (final Exception ex) {
        LOG.info("Error parsing contactgroup data. Reason:" + ex.toString(), ex);
    }
    return null;
}

From source file:com.microsoft.azure.storage.queue.CloudQueueEncryptedMessage.java

public static CloudQueueEncryptedMessage deserialize(String inputMessage)
        throws JsonProcessingException, IOException {
    JsonParser parser = Utility.getJsonParser(inputMessage);
    CloudQueueEncryptedMessage message = new CloudQueueEncryptedMessage();
    try {/*ww w .j a  v a2 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("EncryptedMessageContents")) {
                message.setEncryptedMessageContents(parser.getValueAsString());
            } else if (name.equals("EncryptionData")) {
                message.setEncryptionData(EncryptionData.deserialize(parser));
            }
            parser.nextToken();
        }

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

    return message;
}

From source file:org.openhab.binding.weather.internal.parser.JsonWeatherParser.java

@Override
public void parseInto(String r, Weather weather) throws Exception {
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(r);

    jp.nextValue();//from  ww w.j  av  a 2  s  . c o m
    handleToken(jp, null, weather);
    jp.close();

    super.parseInto(r, weather);
}

From source file:io.encoded.jersik.runtime.JsonCodec.java

public <T> T decode(InputStream in, ObjectCodec<T> codec) throws IOException {
    JsonParser parser = JSON_FACTORY.createParser(in);
    try {/*from   w  w  w. ja  va 2 s.com*/
        parser.nextToken();
        return codec.decode(parser);
    } finally {
        parser.close();
    }
}

From source file:com.rockagen.commons.util.JsonUtil.java

/**
 * Json string to java bean <br>//w  w  w.ja v a  2 s. c o  m
 * <p>
 * e.g:
 * </p>
 * <pre>
 * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}} 
 * </pre>
 * <p>
 * List,Array,Map... see {@link #toBean(String, TypeReference)}
 * </p>
 * 
 * @param jsonParser json parser
 * @param clazz class
 * @param <T> t
 * @return bean
 */
public static <T> T toBean(JsonParser jsonParser, Class<T> clazz) {
    if (clazz == null || jsonParser == null)
        return null;

    T obj = null;
    try {
        obj = getMapper().readValue(jsonParser, clazz);
    } catch (JsonParseException e) {
        log.error("{}", e.getMessage(), e);
    } catch (JsonMappingException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IOException e) {
        log.error("{}", e.getMessage(), e);
    } finally {
        try {
            jsonParser.close();
        } catch (IOException e) {
        }
    }
    return obj;

}