Example usage for com.fasterxml.jackson.core JsonToken END_ARRAY

List of usage examples for com.fasterxml.jackson.core JsonToken END_ARRAY

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonToken END_ARRAY.

Prototype

JsonToken END_ARRAY

To view the source code for com.fasterxml.jackson.core JsonToken END_ARRAY.

Click Source Link

Document

END_ARRAY is returned when encountering ']' which signals ending of an Array value

Usage

From source file:com.adobe.communities.ugc.migration.importer.SocialGraphImportServlet.java

private void importFile(final JsonParser jsonParser, final SlingHttpServletRequest request)
        throws ServletException, IOException {

    JsonToken token = jsonParser.nextToken();
    while (!token.equals(JsonToken.END_OBJECT)) {
        if (!token.equals(JsonToken.FIELD_NAME)) {
            throw new ServletException("Expected a field name, got " + token);
        }//w  w  w. j  a  v a2 s . co  m
        final String userId = jsonParser.getCurrentName();
        token = jsonParser.nextToken();
        if (!token.equals(JsonToken.START_ARRAY)) {
            throw new ServletException("Expected an array start token, got " + token);
        }
        token = jsonParser.nextToken();
        final Resource tmpParent = request.getResourceResolver().getResource("/tmp");
        while (!token.equals(JsonToken.END_ARRAY)) {
            final Map<String, Object> props = new HashMap<String, Object>();
            props.put("resourceType", Following.RESOURCE_TYPE);
            props.put("userId", userId);
            props.put("followedId", jsonParser.getValueAsString());
            Resource resource;
            resource = request.getResourceResolver().create(tmpParent, "following", props);
            final SocialComponentFactory factory = componentFactoryManager
                    .getSocialComponentFactory(Following.RESOURCE_TYPE);
            final Following following = (Following) factory.getSocialComponent(resource, request);
            request.getResourceResolver().delete(resource); // need to delete it so we can create it again next time
            final Vertex node = following.userNode();
            final Vertex other = following.followedNode();
            final String relType = "USER";
            try {
                node.createRelationshipTo(other, Edge.FOLLOWING_RELATIONSHIP_TYPE, relType);
                following.socialGraph().save();
            } catch (final IllegalArgumentException e) {
                // The relationship already exists. Do nothing.
            }
            token = jsonParser.nextToken();
        }
        token = jsonParser.nextToken(); // skip over END_ARRAY
    }
}

From source file:com.ning.metrics.serialization.smile.SmileEnvelopeEventDeserializer.java

private boolean _hasNextEvent() throws IOException {
    if (hasFailed) {
        return false;
    }/*from   w w w  .ja  va2 s  .  c  om*/

    // don't advance nextToken if you don't have to

    if (nextToken == null) {
        // get next token
        nextToken = parser.nextToken();
        // and if it's the end of array (or input), close explicitly
        if (nextToken == null || nextToken == JsonToken.END_ARRAY) {
            parser.close();
        }
    }
    // could verify that it is JsonToken.START_OBJECT?
    return nextToken != JsonToken.END_ARRAY && nextToken != null;
}

From source file:com.streamsets.pipeline.lib.json.StreamingJsonParser.java

@SuppressWarnings("unchecked")
protected Object readObjectFromArray() throws IOException {
    Object value = null;//from  ww w .  j  a  v  a2s . co m
    if (starting) {
        starting = false;
        JsonToken token = jsonParser.nextToken();
        rootContext = jsonParser.getParsingContext();
        if (token != JsonToken.START_ARRAY) {
            throw new JsonParseException(Utils.format("JSON array expected but stream starts with '{}'", token),
                    jsonParser.getTokenLocation());
        }
    }
    JsonToken token = jsonParser.nextToken();
    if (token != null) {
        if (token != JsonToken.END_ARRAY) {
            value = jsonParser.readValueAs(Object.class);
        }
    }
    return value;
}

From source file:com.netflix.spectator.tdigest.Json.java

private TDigestMeasurement decode(JsonParser parser) throws IOException {
    expect(parser, JsonToken.START_OBJECT);
    require("name".equals(parser.nextFieldName()), "expected name");
    Id id = registry.createId(parser.nextTextValue());
    while (parser.nextToken() == JsonToken.FIELD_NAME) {
        id = id.withTag(parser.getText(), parser.nextTextValue());
    }/*from   www  .  j av  a  2  s.c  o m*/
    long t = parser.nextLongValue(-1L);
    expect(parser, JsonToken.VALUE_EMBEDDED_OBJECT);
    TDigest v = AVLTreeDigest.fromBytes(ByteBuffer.wrap(parser.getBinaryValue()));
    expect(parser, JsonToken.END_ARRAY);
    return new TDigestMeasurement(id, t, v);
}

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;//ww w  . j  a  va2 s .c  o m
    }

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

    smileParser.close();
}

From source file:com.sdl.odata.unmarshaller.json.core.JsonProcessor.java

/**
 * Parse the complex values./*from   w  w w .  j  a va  2 s . c o m*/
 *
 * @param jsonParser the parser
 * @return list of parsed result objects
 * @throws IOException If unable to read input parser
 */
private List<Object> getCollectionValue(JsonParser jsonParser) throws IOException {
    LOG.info("Start parsing {} array", jsonParser.getCurrentName());
    List<Object> list = new ArrayList<>();
    while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
        if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) {
            Object embedded = getEmbeddedObject(jsonParser);
            list.add(embedded);
        }
        if (!"}".equals(jsonParser.getText())) {
            list.add(jsonParser.getText());
        } else {
            LOG.info("Array is over.");
        }
    }
    return list;
}

From source file:eu.project.ttc.readers.TermSuiteJsonCasDeserializer.java

public static void deserialize(InputStream inputStream, CAS cas, String encoding) {
    Preconditions.checkNotNull(inputStream, "Paramater input stream is null");
    Preconditions.checkNotNull(inputStream, "Paramater CAS is null");

    try {//w  w w . ja  va 2  s . c om

        JsonFactory factory = new JsonFactory();
        parser = factory.createParser(inputStream);

        SourceDocumentInformation sdi = (SourceDocumentInformation) cas
                .createAnnotation(cas.getJCas().getCasType(SourceDocumentInformation.type), 0, 0);
        WordAnnotation wa = (WordAnnotation) cas.createAnnotation(cas.getJCas().getCasType(WordAnnotation.type),
                0, 0);
        TermOccAnnotation toa = (TermOccAnnotation) cas
                .createAnnotation(cas.getJCas().getCasType(TermOccAnnotation.type), 0, 0);
        FixedExpression fe = (FixedExpression) cas
                .createAnnotation(cas.getJCas().getCasType(FixedExpression.type), 0, 0);
        boolean inSdi = false;
        boolean inWa = false;
        boolean inToa = false;
        boolean inFe = false;
        boolean inCoveredText = false;

        while ((token = parser.nextToken()) != null) {

            if (inSdi) {

                if (token == JsonToken.END_OBJECT) {
                    inSdi = false;
                } else {
                    fillSdi(parser, token, sdi);
                }
            }

            else if (inWa) {
                if (token == JsonToken.END_ARRAY) {
                    inWa = false;
                } else if (token == JsonToken.END_OBJECT) {
                    wa.addToIndexes();
                    wa = (WordAnnotation) cas.createAnnotation(cas.getJCas().getCasType(WordAnnotation.type), 0,
                            0);
                }
                fillWordAnnotations(parser, token, wa);
            }

            else if (inToa) {
                if (token == JsonToken.END_ARRAY && Objects.equals(parser.getParsingContext().getCurrentName(),
                        "term_occ_annotations")) {
                    inToa = false;
                } else if (token == JsonToken.END_OBJECT) {
                    toa.addToIndexes();
                    toa = (TermOccAnnotation) cas
                            .createAnnotation(cas.getJCas().getCasType(TermOccAnnotation.type), 0, 0);
                }
                FillTermOccAnnotations(parser, token, toa, cas);
            }

            else if (inFe) {
                if (token == JsonToken.END_ARRAY
                        && Objects.equals(parser.getParsingContext().getCurrentName(), "fixed_expressions")) {
                    inFe = false;
                } else if (token == JsonToken.END_OBJECT) {
                    fe.addToIndexes();
                    fe = (FixedExpression) cas.createAnnotation(cas.getJCas().getCasType(FixedExpression.type),
                            0, 0);
                }
                FillFixedExpressions(parser, token, fe, cas);
            }

            else if (inCoveredText) {
                if (token == JsonToken.VALUE_STRING) {
                    String text = parser.getText();
                    cas.setDocumentText(text);
                }
            }

            else if ("sdi".equals(parser.getParsingContext().getCurrentName())) {
                inSdi = true;
            }

            else if ("word_annotations".equals(parser.getParsingContext().getCurrentName())) {
                inWa = true;
            }

            else if ("term_occ_annotations".equals(parser.getParsingContext().getCurrentName())) {
                inToa = true;
            }

            else if ("fixed_expressions".equals(parser.getParsingContext().getCurrentName())) {
                inFe = true;
            }

            else if ("covered_text".equals(parser.getParsingContext().getCurrentName())) {
                inCoveredText = true;
            }
        }
        sdi.addToIndexes();
    } catch (IOException | CASException e) {
        logger.error("An error occurred during TermSuite Json Cas parsing", e);
    }
}

From source file:org.hbz.oerworldmap.JsonDecoder.java

@Override
public void process(final Reader reader) {
    STARTED = false;/*from  w  w w. j  a v  a2  s  . c o m*/
    JsonDecoder.LOG.debug("############################ New");
    // necessary if it is JSONP
    String text;
    try {
        text = CharStreams.toString(reader);
        this.jsonParser = new JsonFactory().createParser(text);
        // find start
        JsonToken currentToken = null;
        try {
            currentToken = this.jsonParser.nextToken();
        } catch (final JsonParseException e) {
            // assuming JSONP :
            final String callbackString = text.substring(0, text.indexOf(JsonDecoder.JSON_START_CHAR) - 1);
            text = text.substring(text.indexOf(JsonDecoder.JSON_START_CHAR), text.length() - 1);
            this.jsonParser = new JsonFactory().createParser(text);
            JsonDecoder.LOG.debug("key=" + JsonDecoder.JSON_CALLBACK + " value=" + callbackString);
            getReceiver().startRecord("");
            STARTED = true;
            JSONP = true;
            getReceiver().literal(JsonDecoder.JSON_CALLBACK, callbackString);
            JsonDecoder.LOG.debug("Text=" + text);
            currentToken = this.jsonParser.nextToken();
        }
        while (JsonToken.START_OBJECT != currentToken) {
            this.jsonParser.nextToken();
        }

        String key = null;
        while (currentToken != null) {
            if (JsonToken.START_OBJECT == currentToken) {
                if (!STARTED) {
                    getReceiver().startRecord("");
                    STARTED = true;
                }
                currentToken = this.jsonParser.nextToken();
                while (currentToken != null) {
                    if (JsonToken.FIELD_NAME == currentToken) {
                        key = this.jsonParser.getCurrentName();
                    }
                    if (JsonToken.START_ARRAY == currentToken) {
                        if (this.JSONP) {
                            currentToken = this.jsonParser.nextToken();
                            currentToken = this.jsonParser.nextToken();
                        } else {
                            currentToken = this.jsonParser.nextToken();
                            // treat objects in arrays as new objects
                            if (JsonToken.START_OBJECT == currentToken) {
                                break;
                            }
                            // values of arrays are submitted with an index
                            // so
                            // you can handle
                            // semantics in the morph
                            int i = 0;
                            while (JsonToken.END_ARRAY != currentToken) {
                                final String value = this.jsonParser.getText();
                                JsonDecoder.LOG.debug("key=" + key + i + " valueArray=" + value);
                                getReceiver().literal(key + i, value);
                                currentToken = this.jsonParser.nextToken();
                                i++;
                            }
                        }
                    }
                    if (JsonToken.START_OBJECT == currentToken) {
                        if (this.jsonParser.getCurrentName() == null) {
                            break;
                        }
                    } else {
                        handleValue(currentToken, key);
                    }
                    try {
                        currentToken = this.jsonParser.nextToken();
                    } catch (JsonParseException jpe) {
                        LOG.info(
                                "JsonParseException happens at the end of an non JSON object, e.g. if it is JSONP",
                                jpe.getMessage());
                        currentToken = null;
                        break;
                    }
                }
            }
            JsonDecoder.LOG.debug("############################ End");
            if (STARTED) {
                getReceiver().endRecord();
                STARTED = false;

            }
        }
    } catch (final IOException e) {
        throw new MetafactureException(e);

    }
}

From source file:org.mashti.jetson.util.JsonParserUtil.java

/**
 * Consumes the next token from a JSON stream and checks that the token is a {@link JsonToken#START_ARRAY}.
 * Throws {@link JsonParseException} if the token is not a {@link JsonToken#START_ARRAY}.
 *
 * @param parser the parser to read from
 * @throws IOException Signals that an I/O exception has occurred.
 *///from w  ww  .  ja va 2  s . c om
private static void expectEndArray(final JsonParser parser) throws IOException {

    if (parser.nextToken() != JsonToken.END_ARRAY) {
        throw new JsonParseException("expected end array", parser.getCurrentLocation());
    }
}

From source file:org.apache.lucene.server.handlers.BulkUpdateDocumentHandler.java

@Override
public String handleStreamed(Reader reader, Map<String, List<String>> params) throws Exception {
    JsonFactory jfactory = new JsonFactory();

    JsonParser parser = jfactory.createJsonParser(reader);

    if (parser.nextToken() != JsonToken.START_OBJECT) {
        throw new IllegalArgumentException("expected JSON object");
    }/* www .  jav  a 2  s .c  o  m*/
    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (!parser.getText().equals("indexName")) {
        throw new IllegalArgumentException("expected indexName first");
    }
    if (parser.nextToken() != JsonToken.VALUE_STRING) {
        throw new IllegalArgumentException("indexName should be string");
    }

    IndexState indexState = globalState.get(parser.getText());
    indexState.verifyStarted(null);

    ShardState shardState = indexState.getShard(0);

    if (parser.nextToken() != JsonToken.FIELD_NAME) {
        throw new IllegalArgumentException("expected documents next");
    }
    if (!parser.getText().equals("documents")) {
        throw new IllegalArgumentException("expected documents after indexName");
    }
    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalArgumentException("documents should be a list");
    }

    IndexingContext ctx = new IndexingContext();

    AddDocumentHandler addDocHandler = (AddDocumentHandler) globalState.getHandler("addDocument");

    // Parse any number of documents to update:
    int count = 0;

    while (true) {
        JsonToken token = parser.nextToken();
        if (token == JsonToken.END_ARRAY) {
            break;
        }
        if (token != JsonToken.START_OBJECT) {
            throw new IllegalArgumentException("missing object");
        }

        // Parse term: and fields:
        Term updateTerm = null;

        final Document doc = new Document();

        while (true) {
            token = parser.nextToken();
            if (token == JsonToken.END_OBJECT) {
                break;
            }
            if (token != JsonToken.FIELD_NAME) {
                throw new IllegalArgumentException("missing field name");
            }
            String f = parser.getText();
            if (f.equals("term")) {
                if (parser.nextToken() != JsonToken.START_OBJECT) {
                    throw new IllegalArgumentException("missing object");
                }

                // TODO: allow field to be specified only once, then
                // only text per document

                String field = null, term = null;

                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String f2 = parser.getText();
                    if (f2.equals("field")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        field = parser.getText();
                        // Ensure field is valid:
                        indexState.getField(field);
                    } else if (f2.equals("term")) {
                        if (parser.nextToken() != JsonToken.VALUE_STRING) {
                            throw new IllegalArgumentException("missing string value");
                        }
                        term = parser.getText();
                    } else {
                        throw new IllegalArgumentException("unexpected field " + f);
                    }
                }
                updateTerm = new Term(field, term);
            } else if (f.equals("fields")) {
                addDocHandler.parseFields(indexState, doc, parser);
            } else {
                boolean handled = false;
                for (AddDocumentHandler.PostHandle postHandle : addDocHandler.postHandlers) {
                    if (postHandle.invoke(indexState, f, parser, doc)) {
                        handled = true;
                        break;
                    }
                }
                if (!handled) {
                    throw new IllegalArgumentException("unrecognized field " + parser.getText());
                }
            }
        }

        if (updateTerm == null) {
            throw new IllegalArgumentException("missing term");
        }

        // TODO: this is dup'd code ... share better w/ AddDocHandler
        globalState.submitIndexingTask(shardState.getAddDocumentJob(count, updateTerm, doc, ctx));
        count++;
    }

    // nocommit this is ... lameish:
    while (true) {
        if (ctx.addCount.get() == count) {
            break;
        }
        Thread.sleep(1);
    }

    JSONObject o = new JSONObject();
    o.put("indexGen", shardState.writer.getMaxCompletedSequenceNumber());
    o.put("indexedDocumentCount", count);
    return o.toString();
}