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

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

Introduction

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

Prototype

public <T> Iterator<T> readValuesAs(TypeReference<?> valueTypeRef) throws IOException, JsonProcessingException 

Source Link

Document

Method for reading sequence of Objects from parser stream, all with same specified value type.

Usage

From source file:org.apache.parquet.cli.json.AvroJson.java

public static Iterator<JsonNode> parser(final InputStream stream) {
    try {//w w w.j a v a2  s.c  o m
        JsonParser parser = FACTORY.createParser(stream);
        parser.setCodec(new ObjectMapper());
        return parser.readValuesAs(JsonNode.class);
    } catch (IOException e) {
        throw new RuntimeIOException("Cannot read from stream", e);
    }
}

From source file:de.dsi8.dsi8acl.connection.impl.MessageListenerThread.java

/**
 * Converts the data from {@link InputStream} of {@link Socket} from
 * JSON format into a concrete {@link Message}.
 *///from ww w . j  av a  2s  . c om
@Override
public void run() {
    try {
        InputStream inputStream = initiator.getSocket().getInputStream();
        ObjectMapper objectMapper = initiator.getJsonObjectMapper();
        JsonFactory factory = objectMapper.getJsonFactory();

        JsonParser jsonParser = factory.createJsonParser(inputStream);
        Iterator<Message> iterator = jsonParser.readValuesAs(Message.class);

        while (!isInterrupted() && iterator.hasNext()) {
            Message msg = iterator.next();
            messageRecived(msg);
        }

        if (!isInterrupted()) {
            // The stream was closed but the thread wasn't stopped. That's bad.
            throw new IOException("Unexpected close of InputStream.");
        }
    } catch (Exception e) {
        connectionProblem(e);
    }
}

From source file:gate.corpora.DataSiftFormat.java

@Override
public void unpackMarkup(gate.Document doc) throws DocumentFormatException {
    if ((doc == null) || (doc.getSourceUrl() == null && doc.getContent() == null)) {
        throw new DocumentFormatException("GATE document is null or no content found. Nothing to parse!");
    }// w w w.j av a2 s  . c  o  m

    setNewLineProperty(doc);
    String jsonString = StringUtils.trimToEmpty(doc.getContent().toString());

    // TODO build the new content
    StringBuilder concatenation = new StringBuilder();

    try {
        ObjectMapper om = new ObjectMapper();

        JsonFactory factory = new JsonFactory(om);
        JsonParser parser = factory.createParser(jsonString);

        Map<DataSift, Long> offsets = new HashMap<DataSift, Long>();

        Iterator<DataSift> it = parser.readValuesAs(DataSift.class);
        while (it.hasNext()) {
            DataSift ds = it.next();
            offsets.put(ds, (long) concatenation.length());
            concatenation.append(ds.getInteraction().getContent()).append("\n\n");
        }

        // Set new document content
        DocumentContent newContent = new DocumentContentImpl(concatenation.toString());

        doc.edit(0L, doc.getContent().size(), newContent);

        AnnotationSet originalMarkups = doc.getAnnotations("Original markups");
        for (Map.Entry<DataSift, Long> item : offsets.entrySet()) {
            DataSift ds = item.getKey();
            Interaction interaction = ds.getInteraction();
            Long start = item.getValue();

            FeatureMap features = interaction.asFeatureMap();
            features.putAll(ds.getFurtherData());

            originalMarkups.add(start, start + interaction.getContent().length(), "Interaction", features);
        }

    } catch (InvalidOffsetException | IOException e) {
        throw new DocumentFormatException(e);
    }
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONEntryDeserializer.java

private String setInline(final String name, final String suffix, final ObjectNode tree, final ObjectCodec codec,
        final JSONLink link) throws IOException {

    final String entryNamePrefix = name.substring(0, name.indexOf(suffix));
    if (tree.has(entryNamePrefix)) {
        final JsonNode inline = tree.path(entryNamePrefix);

        if (inline instanceof ObjectNode) {
            final JsonParser inlineParser = inline.traverse();
            inlineParser.setCodec(codec);
            link.setInlineEntry(inlineParser.readValuesAs(JSONEntry.class).next());
        }/*from   www  .j  av  a  2s  . c o  m*/

        if (inline instanceof ArrayNode) {
            final JSONFeed feed = new JSONFeed();
            final Iterator<JsonNode> entries = ((ArrayNode) inline).elements();
            while (entries.hasNext()) {
                final JsonParser inlineParser = entries.next().traverse();
                inlineParser.setCodec(codec);
                feed.addEntry(inlineParser.readValuesAs(JSONEntry.class).next());
            }

            link.setInlineFeed(feed);
        }
    }
    return entryNamePrefix;
}

From source file:com.opentable.jaxrs.StreamedJsonResponseConverter.java

private <T> void doRead(Callback<T> callback, TypeReference<T> type, final JsonParser jp) throws IOException {
    expect(jp, jp.nextToken(), JsonToken.START_OBJECT);
    expect(jp, jp.nextToken(), JsonToken.FIELD_NAME);
    if (!"results".equals(jp.getCurrentName())) {
        throw new JsonParseException("expecting results field", jp.getCurrentLocation());
    }//from   ww  w .j a  v  a 2  s . c om
    expect(jp, jp.nextToken(), JsonToken.START_ARRAY);
    // As noted in a well-hidden comment in the MappingIterator constructor,
    // readValuesAs requires the parser to be positioned after the START_ARRAY
    // token with an empty current token
    jp.clearCurrentToken();

    Iterator<T> iter = jp.readValuesAs(type);

    while (iter.hasNext()) {
        try {
            callback.call(iter.next());
        } catch (CallbackRefusedException e) {
            LOG.debug("callback refused execution, finishing.", e);
            return;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Callback interrupted", e);
        } catch (Exception e) {
            Throwables.propagateIfPossible(e, IOException.class);
            throw new IOException("Callback failure", e);
        }
    }
    if (jp.nextValue() != JsonToken.VALUE_TRUE || !jp.getCurrentName().equals("success")) {
        throw new IOException("Streamed receive did not terminate normally; inspect server logs for cause.");
    }
}

From source file:org.seedstack.seed.core.internal.data.DataManagerImpl.java

private DataImporter<Object> consumeItems(JsonParser jsonParser, String group, String name, String acceptGroup,
        String acceptName) throws IOException {

    Map<String, DataImporterDefinition<Object>> dataImporterDefinitionMap = allDataImporters.get(group);

    if (dataImporterDefinitionMap == null) {
        throw SeedException.createNew(DataErrorCode.NO_IMPORTER_FOUND).put(GROUP, group).put(NAME, name);
    }// w  w w .  j a v  a 2s.c  om

    DataImporterDefinition<Object> currentImporterDefinition = dataImporterDefinitionMap.get(name);

    if (currentImporterDefinition == null) {
        throw SeedException.createNew(DataErrorCode.NO_IMPORTER_FOUND).put(GROUP, group).put(NAME, name);
    }

    if (!group.equals(currentImporterDefinition.getGroup())) {
        throw SeedException.createNew(DataErrorCode.UNEXPECTED_DATA_TYPE)
                .put(DATA_SET, String.format(CLASSES_MAP_KEY, group, name))
                .put(IMPORTER_CLASS, currentImporterDefinition.getDataImporterClass().getName());
    }

    if (!name.equals(currentImporterDefinition.getName())) {
        throw SeedException.createNew(DataErrorCode.UNEXPECTED_DATA_TYPE)
                .put(DATA_SET, String.format(CLASSES_MAP_KEY, group, name))
                .put(IMPORTER_CLASS, currentImporterDefinition.getDataImporterClass().getName());
    }

    DataImporter<Object> currentDataImporter = null;
    if ((acceptGroup == null || acceptGroup.equals(group)) && (acceptName == null || acceptName.equals(name))) {

        currentDataImporter = injector.getInstance(currentImporterDefinition.getDataImporterClass());

        // Check if items contains an array

        if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
            throw new IllegalArgumentException("Items should be an array");
        }

        jsonParser.nextToken();

        // If the array is not empty consume it
        if (jsonParser.getCurrentToken() != JsonToken.END_ARRAY) {
            Iterator<Object> objectIterator = jsonParser
                    .readValuesAs(currentImporterDefinition.getImportedClass());

            while (objectIterator.hasNext()) {
                currentDataImporter.importData(objectIterator.next());
            }

            // The array should end correctly
            if (jsonParser.getCurrentToken() != JsonToken.END_ARRAY) {
                throw new IllegalArgumentException("end array expected");
            }
        }
    }

    // the data importer containing the data
    return currentDataImporter;
}

From source file:org.talend.dataprep.api.dataset.DataSetDataReader.java

private Map<String, Map<String, String>> parseRecords(JsonParser jsonParser, RowMetadata rowMetadata,
        String joinOnColumn) throws IOException {

    try {/*from  ww w  .j  ava 2 s  . c  om*/
        JsonToken firstToken = jsonParser.nextToken(); // Read to array first element
        Validate.isTrue(firstToken == JsonToken.START_OBJECT, INCORRECT_OBJECT_STRUCTURE_ERROR_MESSAGE);

        Map<String, Map<String, String>> lookupDataset = new HashMap<>();
        Iterator<Map<String, String>> mapIterator = jsonParser
                .readValuesAs(new TypeReference<Map<String, String>>() {
                });

        while (mapIterator.hasNext()) {
            Map<String, String> recordMap = mapIterator.next();
            lookupDataset.put(recordMap.get(joinOnColumn), recordMap);
        }

        Validate.isTrue(!lookupDataset.isEmpty(),
                "No lookup record has been retrieved when trying to parse the retrieved data set.");

        return lookupDataset;
    } catch (IOException e) {
        throw new IOException("Unable to parse and retrieve the records of the data set", e);
    }
}