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

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

Introduction

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

Prototype

JsonToken START_OBJECT

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

Click Source Link

Document

START_OBJECT is returned when encountering '{' which signals starting of an Object value.

Usage

From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java

/**
 * Parse a single Resource//from   ww w . j ava2 s.  c om
 *
 * @return a single resource
 * @throws IOException
 */
private Resource parseResource() throws IOException {
    //current token is ready consumed by parseResources
    if (this.jsonParser.getCurrentToken() != JsonToken.START_OBJECT) {
        throw new JsonParseException("Not a Resource object", this.jsonParser.getCurrentLocation());
    }

    Resource resource = new Resource();

    while (this.jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = this.jsonParser.getCurrentName();

        switch (key) {
        default:
            resource.add(key, this.parseDefaultValue(key));
            break;
        }
    }

    return resource;
}

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

public void importCommentsContent(final JsonParser jsonParser, final Resource resource,
        final ResourceResolver resolver) throws ServletException, IOException {
    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken(); // advance to first key in the object - should be the id value of the old post
        while (jsonParser.getCurrentToken().equals(JsonToken.FIELD_NAME)) {
            extractTopic(jsonParser, resource, resolver, commentOperations);
            jsonParser.nextToken(); // get the next token - presumably a field name for the next post
        }/* ww w. j a v  a2s .c  o m*/
        jsonParser.nextToken(); // skip end token
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}

From source file:com.couchbase.lite.replicator.ChangeTracker.java

protected void runLoop() {
    paused = false;//ww  w . ja v  a 2  s  .c o m

    if (client == null) {
        // This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop()
        // directly afterwards.  What happens is that by the time the Changetracker thread fires up,
        // the cbpuller has already set this.client to null.  See issue #109
        Log.w(Log.TAG_CHANGE_TRACKER, "%s: ChangeTracker run() loop aborting because client == null", this);
        return;
    }

    if (mode == ChangeTrackerMode.Continuous) {
        // there is a failing unit test for this, and from looking at the code the Replication
        // object will never use Continuous mode anyway.  Explicitly prevent its use until
        // it is demonstrated to actually work.
        throw new RuntimeException("ChangeTracker does not correctly support continuous mode");
    }

    OkHttpClient httpClient = client.getOkHttpClient();

    backoff = new ChangeTrackerBackoff();

    while (running) {
        startTime = System.currentTimeMillis();

        Request.Builder builder = new Request.Builder();
        URL url = getChangesFeedURL();
        builder.url(url);
        if (usePOST) {
            builder.header("Content-Type", "application/json").addHeader("User-Agent", Manager.getUserAgent())
                    .addHeader("Accept-Encoding", "gzip").post(RequestBody.create(JSON, changesFeedPOSTBody()));
        }
        addRequestHeaders(builder);

        // Perform BASIC Authentication if needed
        builder = RequestUtils.preemptivelySetAuthCredentials(builder, url, authenticator);
        request = builder.build();

        try {
            String maskedRemoteWithoutCredentials = getChangesFeedURL().toString();
            maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll("://.*:.*@",
                    "://---:---@");
            Log.v(Log.TAG_CHANGE_TRACKER, "%s: Making request to %s", this, maskedRemoteWithoutCredentials);
            call = httpClient.newCall(request);
            Response response = call.execute();
            try {
                // In case response status is Error, ChangeTracker stops here
                if (isResponseFailed(response)) {
                    RequestUtils.closeResponseBody(response);
                    if (retryIfFailedPost(response))
                        continue;
                    break;
                }

                // Parse response body
                ResponseBody responseBody = response.body();

                Log.v(Log.TAG_CHANGE_TRACKER, "%s: got response. status: %s mode: %s", this, response.message(),
                        mode);
                if (responseBody != null) {
                    try {
                        Log.v(Log.TAG_CHANGE_TRACKER, "%s: /entity.getContent().  mode: %s", this, mode);
                        //inputStream = entity.getContent();
                        inputStream = responseBody.byteStream();
                        // decompress if contentEncoding is gzip
                        if (Utils.isGzip(response))
                            inputStream = new GZIPInputStream(inputStream);

                        if (mode == ChangeTrackerMode.LongPoll) { // continuous replications
                            // NOTE: 1. check content length, ObjectMapper().readValue() throws Exception if size is 0.
                            // NOTE: 2. HttpEntity.getContentLength() returns the number of bytes of the content, or a negative number if unknown.
                            // NOTE: 3. If Http Status is error, not parse response body
                            boolean responseOK = false; // default value
                            if (responseBody.contentLength() != 0 && response.code() < 300) {
                                try {
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue", this);
                                    Map<String, Object> fullBody = Manager.getObjectMapper()
                                            .readValue(inputStream, Map.class);
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue.  fullBody: %s", this,
                                            fullBody);
                                    responseOK = receivedPollResponse(fullBody);
                                } catch (JsonParseException jpe) {
                                    Log.w(Log.TAG_CHANGE_TRACKER, "%s: json parsing error; %s", this,
                                            jpe.toString());
                                } catch (JsonMappingException jme) {
                                    Log.w(Log.TAG_CHANGE_TRACKER, "%s: json mapping error; %s", this,
                                            jme.toString());
                                }
                            }
                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: responseOK: %s", this, responseOK);

                            if (responseOK) {
                                // TODO: this logic is questionable, there's lots
                                // TODO: of differences in the iOS changetracker code,
                                if (!caughtUp) {
                                    caughtUp = true;
                                    client.changeTrackerCaughtUp();
                                }
                                Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
                                backoff.resetBackoff();
                                continue;
                            } else {
                                long elapsed = (System.currentTimeMillis() - startTime) / 1000;
                                Log.w(Log.TAG_CHANGE_TRACKER,
                                        "%s: Longpoll connection closed (by proxy?) after %d sec", this,
                                        elapsed);
                                if (elapsed >= 30) {
                                    // Looks like the connection got closed by a proxy (like AWS' load balancer) while the
                                    // server was waiting for a change to send, due to lack of activity.
                                    // Lower the heartbeat time to work around this, and reconnect:
                                    this.heartBeatSeconds = Math.min(this.heartBeatSeconds,
                                            (int) (elapsed * 0.75));
                                    Log.v(Log.TAG_CHANGE_TRACKER, "%s: Starting new longpoll", this);
                                    backoff.resetBackoff();
                                    continue;
                                } else {
                                    Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (LongPoll)",
                                            this);
                                    client.changeTrackerFinished(this);
                                    break;
                                }
                            }
                        } else { // one-shot replications
                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: readValue (oneshot)", this);
                            JsonFactory factory = new JsonFactory();
                            JsonParser jp = factory.createParser(inputStream);
                            JsonToken token;
                            // nextToken() is null => no more token
                            while (((token = jp.nextToken()) != JsonToken.START_ARRAY) && (token != null)) {
                                // ignore these tokens
                            }
                            while (jp.nextToken() == JsonToken.START_OBJECT) {
                                Map<String, Object> change = (Map) Manager.getObjectMapper().readValue(jp,
                                        Map.class);
                                if (!receivedChange(change)) {
                                    Log.w(Log.TAG_CHANGE_TRACKER,
                                            "Received unparseable change line from server: %s", change);
                                }
                                // if not running state anymore, exit from loop.
                                if (!running)
                                    break;
                            }
                            if (jp != null)
                                jp.close();

                            Log.v(Log.TAG_CHANGE_TRACKER, "%s: /readValue (oneshot)", this);
                            client.changeTrackerCaughtUp();
                            if (isContinuous()) { // if enclosing replication is continuous
                                mode = ChangeTrackerMode.LongPoll;
                            } else {
                                Log.d(Log.TAG_CHANGE_TRACKER, "%s: Change tracker calling stop (OneShot)",
                                        this);
                                client.changeTrackerFinished(this);
                                break;
                            }
                        }
                        backoff.resetBackoff();
                    } finally {
                        try {
                            if (inputStream != null) {
                                inputStream.close();
                                inputStream = null;
                            }
                        } catch (IOException e) {
                        }
                    }
                }
            } finally {
                RequestUtils.closeResponseBody(response);
            }
        } catch (Exception e) {
            if (!running && e instanceof IOException) {
                // in this case, just silently absorb the exception because it
                // frequently happens when we're shutting down and have to
                // close the socket underneath our read.
            } else {
                Log.w(Log.TAG_CHANGE_TRACKER, this + ": Exception in change tracker", e);
                this.error = e;
            }
            backoff.sleepAppropriateAmountOfTime();
        }
    }
    Log.v(Log.TAG_CHANGE_TRACKER, "%s: Change tracker run loop exiting", this);
}

From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java

/**
 * Parse the event with key as default value.
 *
 * If the value is JSON null, then we will return null.
 * If the value is JSON object (of starting with START_ARRAY or START_OBject) , then we will convert the object to String.
 * If the value is JSON scalar value (non-structured object), then we will return simply return it as String.
 *
 * @param key//from   w ww.j a  v a 2  s .  c  om
 * @throws IOException
 */
private String parseDefaultValue(String key) throws IOException {
    this.jsonParser.nextToken();
    String value = null;
    JsonToken currentToken = this.jsonParser.getCurrentToken();
    if (currentToken != JsonToken.VALUE_NULL) {
        if (currentToken == JsonToken.START_ARRAY || currentToken == JsonToken.START_OBJECT) {
            JsonNode node = this.jsonParser.readValueAsTree();
            value = node.toString();
        } else {
            value = this.jsonParser.getValueAsString();
        }
    }
    return value;
}

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

public void importJournalContent(final JsonParser jsonParser, final Resource resource,
        final ResourceResolver resolver) throws IOException, ServletException {

    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        jsonParser.nextToken(); // advance to first key in the object - should be the id value of the old post
        while (jsonParser.getCurrentToken().equals(JsonToken.FIELD_NAME)) {
            extractTopic(jsonParser, resource, resolver, journalOperations);
            jsonParser.nextToken(); // get the next token - presumably a field name for the next post
        }//from   www. j av  a2 s  .c om
        jsonParser.nextToken(); // skip end token
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}

From source file:io.protostuff.JsonIOUtil.java

/**
 * Parses the {@code messages} from the parser using the given {@code schema}.
 *///from  www. j  a  v a2s . c  o  m
public static <T> List<T> parseListFrom(JsonParser parser, Schema<T> schema, boolean numeric)
        throws IOException {
    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new JsonInputException("Expected token: [ but was " + parser.getCurrentToken() + " on message: "
                + schema.messageFullName());
    }

    final JsonInput input = new JsonInput(parser, numeric);
    final List<T> list = new ArrayList<>();
    for (JsonToken t = parser.nextToken(); t != JsonToken.END_ARRAY; t = parser.nextToken()) {
        if (t != JsonToken.START_OBJECT) {
            throw new JsonInputException("Expected token: { but was " + parser.getCurrentToken()
                    + " on message " + schema.messageFullName());
        }

        final T message = schema.newMessage();
        schema.mergeFrom(input, message);

        if (parser.getCurrentToken() != JsonToken.END_OBJECT) {
            throw new JsonInputException("Expected token: } but was " + parser.getCurrentToken()
                    + " on message " + schema.messageFullName());
        }

        list.add(message);
        input.reset();
    }
    return list;
}

From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java

/**
 * Parse attributes as a Map, used in both parseWebIdentitySessionContext and parseSessionContext
 *
 * @return attributes for either session context or web identity session context
 * @throws IOException// ww w . j a  v a2s.  c  o  m
 */
private Map<String, String> parseAttributes() throws IOException {
    if (this.jsonParser.nextToken() != JsonToken.START_OBJECT) {
        throw new JsonParseException("Not a Attributes object", this.jsonParser.getCurrentLocation());
    }

    Map<String, String> attributes = new HashMap<>();

    while (this.jsonParser.nextToken() != JsonToken.END_OBJECT) {
        String key = this.jsonParser.getCurrentName();
        String value = this.jsonParser.nextTextValue();
        attributes.put(key, value);
    }

    return attributes;
}

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

public void importCalendarContent(final JsonParser jsonParser, final Resource resource) throws IOException {
    if (jsonParser.getCurrentToken().equals(JsonToken.START_ARRAY)) {
        jsonParser.nextToken(); // skip START_ARRAY here
    } else {/*from  w  ww .j a v a 2s .  c  om*/
        throw new IOException("Improperly formed JSON - expected an START_ARRAY token, but got "
                + jsonParser.getCurrentToken().toString());
    }
    if (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
        while (jsonParser.getCurrentToken().equals(JsonToken.START_OBJECT)) {
            extractEvent(jsonParser, resource);
            jsonParser.nextToken(); // get the next token - either a start object token or an end array token
        }
    } else {
        throw new IOException("Improperly formed JSON - expected an OBJECT_START token, but got "
                + jsonParser.getCurrentToken().toString());
    }
}

From source file:com.netflix.hollow.jsonadapter.HollowJsonAdapter.java

private int addUnstructuredMap(JsonParser parser, String mapTypeName, HollowMapWriteRecord mapRec)
        throws IOException {
    mapRec.reset();//  w ww  .  j ava  2 s .  com

    HollowMapSchema schema = (HollowMapSchema) hollowSchemas.get(mapTypeName);
    ObjectFieldMapping valueRec = null;
    ObjectMappedFieldPath fieldMapping = null;

    JsonToken token = parser.nextToken();

    while (token != JsonToken.END_OBJECT) {
        if (token != JsonToken.FIELD_NAME) {
            HollowObjectWriteRecord mapKeyWriteRecord = (HollowObjectWriteRecord) getWriteRecord(
                    schema.getKeyType());
            String fieldName = mapKeyWriteRecord.getSchema().getFieldName(0);
            mapKeyWriteRecord.reset();

            switch (mapKeyWriteRecord.getSchema().getFieldType(0)) {
            case STRING:
                mapKeyWriteRecord.setString(fieldName, parser.getCurrentName());
                break;
            case BOOLEAN:
                mapKeyWriteRecord.setBoolean(fieldName, Boolean.valueOf(parser.getCurrentName()));
                break;
            case INT:
                mapKeyWriteRecord.setInt(fieldName, Integer.parseInt(parser.getCurrentName()));
                break;
            case LONG:
                mapKeyWriteRecord.setLong(fieldName, Long.parseLong(parser.getCurrentName()));
                break;
            case DOUBLE:
                mapKeyWriteRecord.setDouble(fieldName, Double.parseDouble(parser.getCurrentName()));
                break;
            case FLOAT:
                mapKeyWriteRecord.setFloat(fieldName, Float.parseFloat(parser.getCurrentName()));
                break;
            default:
                throw new IOException("Cannot parse type " + mapKeyWriteRecord.getSchema().getFieldType(0)
                        + " as key in map (" + mapKeyWriteRecord.getSchema().getName() + ")");
            }

            int keyOrdinal = stateEngine.add(schema.getKeyType(), mapKeyWriteRecord);

            int valueOrdinal;

            if (token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) {
                valueOrdinal = parseSubType(parser, token, schema.getValueType());
            } else {
                if (valueRec == null) {
                    valueRec = getObjectFieldMapping(schema.getValueType());
                    fieldMapping = valueRec.getSingleFieldMapping();
                }
                addObjectField(parser, token, fieldMapping);
                valueOrdinal = valueRec.build(-1);
            }

            mapRec.addEntry(keyOrdinal, valueOrdinal);
        }
        token = parser.nextToken();
    }

    return stateEngine.add(schema.getName(), mapRec);
}