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

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

Introduction

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

Prototype

JsonToken START_ARRAY

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

Click Source Link

Document

START_ARRAY is returned when encountering '[' which signals starting of an Array value

Usage

From source file:org.zapto.samhippiemiddlepoolchecker.Values.java

PoolError update(String address, URL... urls) {
    //error is returned at the end
    PoolError error = PoolError.NONE;// ww w .ja  v  a2 s  .  com

    //Aborting the http to save data throws an error. This says if we should cover it up.
    boolean actualNetworkError = true;

    //reset the values. If they are never changed, then 0 is the most accurate number
    accepted = 0;
    rejected = 0;
    immature = 0;
    unexchanged = 0;
    balance = 0;
    paid = 0;

    try {
        //streaming the json
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(urls[0].toString());
        HttpResponse response = client.execute(request);
        InputStream in = response.getEntity().getContent();

        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(in);
        boolean addressFound = false;//see if we need to return and address not found error
        mainParse: //label for breaking when address is found
        while (parser.nextToken() != JsonToken.END_OBJECT)//finding "report"
        {
            if ("report".equals(parser.getCurrentName()))//beginning of report
            {
                boolean firstRun = true;
                while (parser.nextToken() == JsonToken.START_ARRAY)//each address has its own array
                {
                    if (firstRun)//this jumps over some junk at the begining
                    {
                        parser.nextToken();
                        firstRun = false;
                    }
                    parser.nextToken();//have to skip some junk each time
                    if (address.equals(parser.getText()))//we have found our address
                    {
                        addressFound = true;//this prevents an address not found error from being returned
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                            //getting each of our values from the array.
                            //having -420 as a default lets us see if the value is there while not using up 0

                            if ("megahashesPerSecond".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    accepted = value;
                                }
                            }

                            if ("rejectedMegahashesPerSecond".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    rejected = value;
                                }
                            }

                            if ("immatureBalance".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    immature = value;
                                }
                            }

                            if ("unexchangedBalance".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    unexchanged = value;
                                }
                            }

                            if ("bitcoinBalance".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    balance = value;
                                }
                            }

                            if ("paidOut".equals(parser.getCurrentName())) {
                                float value = (float) parser.getValueAsDouble(-420);
                                if (value > 0)//negative means wrong value
                                {
                                    paid = value;
                                }
                            }
                        }
                        break mainParse;//no need to download any more addresses
                    } else {
                        while (parser.nextToken() != JsonToken.END_ARRAY) {
                        } //skipping over an unwanted address
                    }
                }
            }
        }
        if (!addressFound)//we never found an address
        {
            error = PoolError.ADDRESS;
        }
        actualNetworkError = false;
        request.abort();//should stop any extra data usage, also forces ioexception (which is ignored)
        parser.close();
        in.close();
    } catch (MalformedURLException e) {
        if (actualNetworkError) {
            error = PoolError.NETWORK;
        }
    } catch (IOException e) {
        if (actualNetworkError) {
            error = PoolError.NETWORK;
        }
    }
    return error;
}

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

/**
 * Process all things that do not contain special ODataTags.
 *
 * @param jsonParser the parser/* w  w w.j a  v  a2  s  . c  om*/
 * @throws ODataUnmarshallingException If unable to unmarshall
 * @throws IOException If unable to read input parser
 */
private void process(JsonParser jsonParser) throws IOException, ODataUnmarshallingException {
    if (jsonParser.getCurrentToken() == JsonToken.FIELD_NAME) {
        LOG.info("Starting to parse {} token", jsonParser.getCurrentName());
        String key = jsonParser.getCurrentName();
        jsonParser.nextToken();

        JsonToken token = jsonParser.getCurrentToken();
        if (token == JsonToken.START_ARRAY) {
            if (JsonConstants.VALUE.equals(key)) {
                throw new ODataUnmarshallingException("Feed is not supported");
            }
            values.put(key, getCollectionValue(jsonParser));
        } else if (token == JsonToken.START_OBJECT) {
            values.put(key, getEmbeddedObject(jsonParser));
        } else {
            if (token.equals(JsonToken.VALUE_NULL)) {
                values.put(key, null);
            } else {
                values.put(key, jsonParser.getText());
            }
        }
    }
}

From source file:org.mongojack.internal.object.BsonObjectTraversingParser.java

public BsonObjectTraversingParser(JacksonDBCollection dbCollection, BSONObject o, ObjectCodec codec) {
    super(0);/*from www .  java  2 s.  co m*/
    this.dbCollection = dbCollection;
    objectCodec = codec;
    if (o instanceof Iterable) {
        nextToken = JsonToken.START_ARRAY;
        nodeCursor = new BsonObjectCursor.ArrayCursor((Iterable) o, null);
    } else {
        nextToken = JsonToken.START_OBJECT;
        nodeCursor = new BsonObjectCursor.ObjectCursor(o, null);
    }
}

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

@Override
public void process(final Reader reader) {
    STARTED = false;//from   www . j  a v a2  s.com
    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:com.nesscomputing.httpclient.response.StreamedJsonContentConverter.java

@Override
public Void convert(final HttpClientResponse response, final InputStream inputStream) throws IOException {
    switch (response.getStatusCode()) {
    case 201://  w w  w  . j a  v  a2  s .  c o  m
    case 204:
        LOG.debug("Return code is %d, finishing.", response.getStatusCode());
        return null;

    case 200:
        try (final JsonParser jp = mapper.getFactory().createJsonParser(inputStream)) {
            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());
            }
            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(typeRef);

            while (iter.hasNext()) {
                try {
                    callback.call(iter.next());
                } catch (CallbackRefusedException e) {
                    LOG.debug(e, "callback refused execution, finishing.");
                    return null;
                } 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.");
            }
            return null;
        }

    default:
        throw throwHttpResponseException(response);
    }
}

From source file:com.joliciel.jochre.search.highlight.Snippet.java

private void read(JsonParser jsonParser) {
    try {//  www  . j  a  v a2  s .  c o m
        if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT)
            throw new RuntimeException("Expected START_OBJECT, but was " + jsonParser.getCurrentToken() + " at "
                    + jsonParser.getCurrentLocation());
        while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jsonParser.getCurrentName();

            if (fieldName.equals("docId")) {
                this.docId = jsonParser.nextIntValue(0);
            } else if (fieldName.equals("field")) {
                this.field = jsonParser.nextTextValue();
            } else if (fieldName.equals("start")) {
                this.startOffset = jsonParser.nextIntValue(0);
            } else if (fieldName.equals("end")) {
                this.endOffset = jsonParser.nextIntValue(0);
            } else if (fieldName.equals("score")) {
                jsonParser.nextValue();
                this.score = jsonParser.getDoubleValue();
                this.scoreCalculated = true;
            } else if (fieldName.equals("terms")) {
                if (jsonParser.nextToken() != JsonToken.START_ARRAY)
                    throw new RuntimeException("Expected START_ARRAY, but was " + jsonParser.getCurrentToken()
                            + " at " + jsonParser.getCurrentLocation());
                while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                    if (jsonParser.getCurrentToken() != JsonToken.START_OBJECT)
                        throw new RuntimeException("Expected START_OBJECT, but was "
                                + jsonParser.getCurrentToken() + " at " + jsonParser.getCurrentLocation());
                    int termDocId = docId;
                    String termField = field;
                    int termStart = 0;
                    int termEnd = 0;
                    int pageIndex = 0;
                    int imageIndex = 0;
                    double weight = 0.0;
                    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
                        String termFieldName = jsonParser.getCurrentName();
                        if (termFieldName.equals("docId")) {
                            termDocId = jsonParser.nextIntValue(0);
                        } else if (termFieldName.equals("field")) {
                            termField = jsonParser.nextTextValue();
                        } else if (termFieldName.equals("start")) {
                            termStart = jsonParser.nextIntValue(0);
                        } else if (termFieldName.equals("end")) {
                            termEnd = jsonParser.nextIntValue(0);
                        } else if (termFieldName.equals("pageIndex")) {
                            pageIndex = jsonParser.nextIntValue(0);
                        } else if (termFieldName.equals("imageIndex")) {
                            imageIndex = jsonParser.nextIntValue(0);
                        } else if (termFieldName.equals("weight")) {
                            jsonParser.nextValue();
                            weight = jsonParser.getDoubleValue();
                        } else {
                            throw new RuntimeException("Unexpected term field name: " + termFieldName + " at "
                                    + jsonParser.getCurrentLocation());
                        }
                    }
                    HighlightTerm highlightTerm = new HighlightTerm(termDocId, termField, termStart, termEnd,
                            imageIndex, pageIndex);
                    highlightTerm.setWeight(weight);
                    this.highlightTerms.add(highlightTerm);
                }
            } else {
                throw new RuntimeException(
                        "Unexpected field name: " + fieldName + " at " + jsonParser.getCurrentLocation());
            }
        }
    } catch (JsonParseException e) {
        LOG.error(e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:org.onosproject.north.aaa.api.parser.impl.UserParser.java

private User jsonToUser(JsonParser jp) throws ParseException, IOException {
    User.Builder builder = User.builder();

    while (true) {
        JsonToken token = jp.nextToken();
        if (JsonToken.END_OBJECT.equals(token)) {
            // bail out
            break;
        }//from w w  w  .j  av a2 s  . c o m

        if (JsonToken.FIELD_NAME.equals(token) && "username".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildUsername(jp.getText());
        } else if (JsonToken.FIELD_NAME.equals(token) && "password".equals(jp.getCurrentName())) {
            jp.nextToken();
            builder.buildPassword(jp.getText());
        } else if (JsonToken.FIELD_NAME.equals(token) && "roles".equals(jp.getCurrentName())) {
            jp.nextToken();
            String roles = jp.getText();
            if ("admin".equals(roles) || "user".equals(roles)) {
                builder.buildRoles(roles);
            } else {
                // bail out
                throw new ParseException("roles must be set to either \"admin\" or \"user\"");
            }

        } else if (JsonToken.FIELD_NAME.equals(token) && "switches".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after switches");
            }
            Set<String> switches = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                switches.add(jp.getText());
            }
            builder.buildSwitches(switches);

        } else if (JsonToken.FIELD_NAME.equals(token) && "domains".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after domains");
            }
            Set<String> domains = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                domains.add(jp.getText());
            }
            builder.buildDomains(domains);

        } else if (JsonToken.FIELD_NAME.equals(token) && "scopes".equals(jp.getCurrentName())) {
            token = jp.nextToken();
            if (!JsonToken.START_ARRAY.equals(token)) {
                // bail out
                throw new ParseException("expected ARRAY after scopes");
            }
            Set<String> scopes = new HashSet<>();

            while (true) {
                token = jp.nextToken();
                if (JsonToken.END_ARRAY.equals(token)) {
                    // bail out
                    break;
                }
                scopes.add(jp.getText());
            }
            builder.buildScopes(scopes);

        } else if (JsonToken.FIELD_NAME.equals(token) && "email".equals(jp.getCurrentName())) {
            jp.nextToken();
            String email = jp.getText();

            // verify email by email regex
            Pattern emailPattern = Pattern.compile(EMAIL_PATTERN);
            if (!emailPattern.matcher(email).matches()) {
                // bail out
                throw new ParseException("email is not valid");
            }
            builder.buildEmail(email);
        }
    }
    return builder.buildAll();
}

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);
        }//from ww w .  j a va 2s. 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:org.mongojack.internal.object.BsonObjectCursor.java

private static JsonToken getToken(Object o) {
    if (o == null) {
        return JsonToken.VALUE_NULL;
    } else if (o instanceof Iterable) {
        return JsonToken.START_ARRAY;
    } else if (o instanceof BSONObject) {
        return JsonToken.START_OBJECT;
    } else if (o instanceof Number) {
        if (o instanceof Double || o instanceof Float || o instanceof BigDecimal) {
            return JsonToken.VALUE_NUMBER_FLOAT;
        } else {/*from  ww  w .  j av  a2  s .  c  om*/
            return JsonToken.VALUE_NUMBER_INT;
        }
    } else if (o instanceof Boolean) {
        if ((Boolean) o) {
            return JsonToken.VALUE_TRUE;
        } else {
            return JsonToken.VALUE_FALSE;
        }
    } else if (o instanceof CharSequence) {
        return JsonToken.VALUE_STRING;
    } else if (o instanceof ObjectId) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else if (o instanceof DBRef) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else if (o instanceof Date) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else if (o instanceof byte[]) {
        return JsonToken.VALUE_EMBEDDED_OBJECT;
    } else {
        throw new IllegalStateException("Don't know how to parse type: " + o.getClass());
    }
}

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

@SuppressWarnings("unchecked")
protected Object readObjectFromArray() throws IOException {
    Object value = null;/*from   w  ww .  jav a  2s .c  om*/
    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;
}