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.emfjson.jackson.streaming.StreamReader.java

protected EObject parseObject(JsonParser parser, EReference containment, EObject owner, EClass currentClass)
        throws IOException {

    EObject current = null;//from ww w. j  ava2  s  .  co m

    if (currentClass != null) {
        current = EcoreUtil.create(currentClass);
    }

    final TokenBuffer buffer = new TokenBuffer(parser);

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

        switch (fieldName) {
        case EJS_TYPE_KEYWORD:
            current = create(parser.nextTextValue());
            break;
        case EJS_UUID_ANNOTATION:
            if (resource instanceof UuidResource) {
                if (current != null) {
                    ((UuidResource) resource).setID(current, parser.nextTextValue());
                }
            }
            break;
        default:
            if (current == null && containment != null) {
                final EClass defaultType = containment.getEReferenceType();

                if (!defaultType.isAbstract()) {
                    current = EcoreUtil.create(defaultType);
                }
            }

            if (current != null) {
                readFeature(parser, current, fieldName);
            } else {
                buffer.copyCurrentStructure(parser);
            }
            break;
        }
    }

    buffer.close();

    if (current != null) {
        final JsonParser bufferedParser = buffer.asParser();

        while (bufferedParser.nextToken() != null) {
            readFeature(bufferedParser, current, bufferedParser.getCurrentName());
        }

        bufferedParser.close();
    }

    if (current != null && containment != null && owner != null) {
        EObjects.setOrAdd(owner, containment, current);
    }

    return current;
}

From source file:com.boundary.zoocreeper.Restore.java

/**
 * Restores ZooKeeper state from the specified backup stream.
 *
 * @param inputStream Input stream containing a JSON encoded ZooKeeper backup.
 * @throws InterruptedException If this method is interrupted.
 * @throws IOException If an error occurs reading from the backup stream.
 *///from www  . ja v  a 2s .  c  o  m
public void restore(InputStream inputStream) throws InterruptedException, IOException, KeeperException {
    ZooKeeper zk = null;
    JsonParser jp = null;
    try {
        jp = JSON_FACTORY.createParser(inputStream);
        zk = options.createZooKeeper(LOGGER);
        doRestore(jp, zk);
    } finally {
        if (zk != null) {
            zk.close();
        }
        if (jp != null) {
            jp.close();
        }
    }
}

From source file:io.seldon.spark.actions.JobUtils.java

public static ActionData getActionDataFromActionLogLine(String actionLogLine) {
    ActionData actionData = new ActionData();

    String[] parts = actionLogLine.split("\\s+", 3);
    String json = parts[2];/*  www. jav a 2 s  .c  om*/
    actionData.timestamp_utc = parts[0];

    JsonFactory jsonF = new JsonFactory();
    try {
        JsonParser jp = jsonF.createParser(json);
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            // Let's move to value
            jp.nextToken();
            if (fieldName.equals("client")) {
                actionData.client = jp.getText();
            } else if (fieldName.equals("client_userid")) {
                actionData.client_userid = jp.getText();
            } else if (fieldName.equals("userid")) {
                actionData.userid = jp.getValueAsInt();
            } else if (fieldName.equals("itemid")) {
                actionData.itemid = jp.getValueAsInt();
            } else if (fieldName.equals("client_itemid")) {
                actionData.client_itemid = jp.getText();
            } else if (fieldName.equals("rectag")) {
                actionData.rectag = jp.getText();
            } else if (fieldName.equals("type")) {
                actionData.type = jp.getValueAsInt();
            } else if (fieldName.equals("value")) {
                actionData.value = jp.getValueAsDouble();
            }
        }
        jp.close();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return actionData;
}

From source file:com.mozilla.bagheera.validation.Validator.java

public boolean isValidJson(String json) {
    boolean isValid = false;
    JsonParser parser = null;
    try {//ww w .j  a v a2 s . c o  m
        parser = jsonFactory.createJsonParser(json);
        while (parser.nextToken() != null) {
            // noop
        }
        isValid = true;
    } catch (JsonParseException ex) {
        LOG.error("JSON parse error");
    } catch (IOException e) {
        LOG.error("JSON IO error");
    } finally {
        if (parser != null) {
            try {
                parser.close();
            } catch (IOException e) {
                LOG.error("Error closing JSON parser", e);
            }
        }
    }

    return isValid;
}

From source file:io.pdef.json.JsonJacksonFormat.java

private <T> T read(final JsonParser parser, final DataTypeDescriptor<T> descriptor) throws Exception {
    Object jsonObject;//from w  w  w . jav  a2s . c o m

    try {
        parser.nextToken();
        jsonObject = read(parser);
    } finally {
        parser.close();
    }

    return objectFormat.read(jsonObject, descriptor);
}

From source file:org.jsfr.json.JacksonParserTest.java

@Test
public void testLargeJsonJackson() throws Exception {
    final AtomicLong counter = new AtomicLong();
    ObjectMapper om = new ObjectMapper();
    JsonFactory f = new JsonFactory();
    JsonParser jp = f.createParser(read("allthethings.json"));
    long start = System.currentTimeMillis();
    jp.nextToken();/*from  w w w .  j  av a2  s . c o  m*/
    jp.nextToken();
    jp.nextToken();
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        if (jp.nextToken() == JsonToken.START_OBJECT) {
            TreeNode tree = om.readTree(jp);
            counter.incrementAndGet();
            LOGGER.trace("value: {}", tree);
        }
    }
    jp.close();
    LOGGER.info("Jackson processes {} value in {} millisecond", counter.get(),
            System.currentTimeMillis() - start);
}

From source file:org.killbill.billing.plugin.meter.timeline.persistent.Replayer.java

@VisibleForTesting
public void read(final File file, final Function<SourceSamplesForTimestamp, Void> fn) throws IOException {
    final JsonParser smileParser = smileFactory.createJsonParser(file);
    if (smileParser.nextToken() != JsonToken.START_ARRAY) {
        return;//w  w  w.j  av  a 2 s . c  om
    }

    while (!shuttingDown.get() && smileParser.nextToken() != JsonToken.END_ARRAY) {
        final SourceSamplesForTimestamp sourceSamplesForTimestamp = smileParser
                .readValueAs(SourceSamplesForTimestamp.class);
        fn.apply(sourceSamplesForTimestamp);
    }

    smileParser.close();
}

From source file:com.mozilla.bagheera.consumer.validation.JsonValidator.java

@Override
public boolean isValid(byte[] data) {
    boolean isValid = false;
    JsonParser parser = null;
    try {/*from  w ww .j  av a 2s .c om*/
        parser = jsonFactory.createJsonParser(data);
        while (parser.nextToken() != null) {
            // noop
        }
        isValid = true;
    } catch (JsonParseException ex) {
        LOG.error("JSON parse error");
    } catch (IOException e) {
        LOG.error("JSON IO error");
    } catch (Exception e) {
        LOG.error("Generic error during validation: ", e);
    } finally {
        if (parser != null) {
            try {
                parser.close();
            } catch (IOException e) {
                LOG.error("Error closing JSON parser", e);
            }
        }
    }

    return isValid;
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.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 w  ww  .  ja  va  2 s  .  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 opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} object with the parsed operation response.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @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.
 */
private static <T extends TableEntity, R> TableResult parseSingleOpJsonResponse(final InputStream inStream,
        final int httpStatusCode, final Class<T> clazzType, final EntityResolver<R> resolver,
        final TableRequestOptions options, final OperationContext opContext) throws ParseException,
        InstantiationException, IllegalAccessException, StorageException, JsonParseException, IOException {
    JsonParser parser = createJsonParserFromStream(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.fluentd.jvmwatcher.JvmWatcher.java

/**
 * @param paramFilePath/*  w  w w  . ja va  2  s  . c o  m*/
 */
public void loadProperty(String paramFilePath) {
    if (null == paramFilePath) {
        return;
    }

    try {
        // load JSON property file.
        File file = new File(paramFilePath);

        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(file);

        JsonToken token = null;
        while ((token = parser.nextToken()) != null) {
            if (token == JsonToken.FIELD_NAME) {
                if (parser.getText().compareTo("target") == 0) {
                    this.loadTarget(parser);
                }
            }
        }
        parser.close();
    } catch (JsonParseException e) {
        log.error("Property parse error.", e);
    } catch (IOException e) {
        log.error("Property file open error.", e);
    } catch (Exception e) {
        log.error("Property file open error.", e);
    }
}