Example usage for com.google.gson.stream JsonToken BEGIN_OBJECT

List of usage examples for com.google.gson.stream JsonToken BEGIN_OBJECT

Introduction

In this page you can find the example usage for com.google.gson.stream JsonToken BEGIN_OBJECT.

Prototype

JsonToken BEGIN_OBJECT

To view the source code for com.google.gson.stream JsonToken BEGIN_OBJECT.

Click Source Link

Document

The opening of a JSON object.

Usage

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

public BasicDBObject parseDocument() throws IOException {

    // Different cases:
    // {} /*from   ww w  .  j  a  v  a 2 s.c om*/
    // ^^ many of these
    // [ {}, {}, {} ]
    // For each of these 2/3 cases, you might either want to grab the entire object, or a field
    // within the object

    try {
        while (true) { // (use exceptions to get outta here) 

            try {
                tok = reader.peek();
            } catch (Exception e) {
                // EOF or end of object, keep going and find out...
                tok = reader.peek();
            }
            //TESTED

            if (JsonToken.BEGIN_ARRAY == tok) {
                if (!_inTopLevelArray) {
                    reader.beginArray();
                    _inTopLevelArray = true;
                }
                if (objectIdentifiers.isEmpty()) {
                    while (reader.hasNext()) {
                        JsonElement meta = parser.parse(reader);
                        BasicDBObject currObj = convertJsonToDocument(meta);

                        if (null != currObj) {
                            return currObj;
                        } //(else carry on...)
                    }
                } //TESTED
                else {
                    while (reader.hasNext()) {
                        BasicDBObject currObj = getDocumentFromJson(false);
                        if (null != currObj) {
                            return currObj;
                        } //(else carry on...)
                    }
                } //TESTED
            } else if (JsonToken.BEGIN_OBJECT == tok) {
                if (objectIdentifiers.isEmpty()) {
                    JsonElement meta = parser.parse(reader);
                    BasicDBObject currObj = convertJsonToDocument(meta);

                    if (null != currObj) {
                        return currObj;
                    } //(else carry on...)

                } //TESTED (single and multiple doc case)
                else {
                    BasicDBObject currObj = getDocumentFromJson(false);
                    if (null != currObj) {
                        return currObj;
                    } //(else carry on...)

                } //TESTED (single and multiple doc case)   
            } else if ((JsonToken.END_DOCUMENT == tok) || (JsonToken.END_ARRAY == tok)
                    || (JsonToken.END_OBJECT == tok)) {
                return null;
            } else { // Must be recursing through the next level(s)
                BasicDBObject currObj = getDocumentFromJson(false);
                if (null != currObj) {
                    return currObj;
                } //(else carry on...)               
            }
        } // (end loop forever - exception out)
    } catch (Exception e) {
    } // This is our EOF

    return null;
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputJsonParser.java

License:Apache License

private BasicDBObject getDocumentFromJson(boolean bRecursing) throws IOException {
    if (!_inSecondaryObject) {
        reader.beginObject();/*from w  ww . j a va2 s.c o m*/
        _inSecondaryObject = true;
    }

    while (reader.hasNext()) {
        String name = reader.nextName();

        boolean bMatch = false;
        if (bRecursing) {
            bMatch = recursiveObjectIdentifiers.contains(name.toLowerCase());
        } else {
            bMatch = objectIdentifiers.contains(name.toLowerCase());
        } //TESTED

        if (bMatch) {
            JsonElement meta = parser.parse(reader);

            if (meta.isJsonObject()) {

                BasicDBObject currObj = convertJsonToDocument(meta);
                if (null != currObj) {
                    return currObj;
                }
            } //TESTED
            else if (meta.isJsonArray()) {
                _secondaryArray = meta.getAsJsonArray();
                _posInSecondaryArray = 0;
                for (JsonElement meta2 : _secondaryArray) {
                    _posInSecondaryArray++;
                    BasicDBObject currObj = convertJsonToDocument(meta2);
                    if (null != currObj) {
                        return currObj;
                    }
                }
                _secondaryArray = null;
            } //TESTED

        } //TESTED
        else {
            if (bRecurse) { //TODO (INF-2469): Not currently supported, it gets a bit tricky? (need to convert to a stack)

                JsonToken tok = reader.peek();
                if (JsonToken.BEGIN_OBJECT == tok) {
                    BasicDBObject currObj = getDocumentFromJson(true);
                    if (null != currObj) {
                        return currObj;
                    }
                } //TESTED
                else if (JsonToken.BEGIN_ARRAY == tok) {
                    reader.beginArray();
                    while (reader.hasNext()) {
                        JsonToken tok2 = reader.peek();

                        if (JsonToken.BEGIN_OBJECT == tok2) {
                            BasicDBObject currObj = getDocumentFromJson(true);
                            if (null != currObj) {
                                return currObj;
                            }
                        } else {
                            reader.skipValue();
                        } //TESTED

                    } //TESTED      
                    reader.endArray();
                } else {
                    reader.skipValue();
                } //TESTED
            } else {
                reader.skipValue();
            } //TESTED
        }

    } //(end loop over reader)

    reader.endObject();
    _inSecondaryObject = false;

    return null;

}

From source file:com.magnet.android.mms.request.JsonUtils.java

License:Open Source License

private static boolean isJson(Reader reader) {
    boolean result = false;
    try {//  w w  w .ja  va  2 s.  co m
        JsonReader jr = new JsonReader(reader);
        jr.setLenient(true);
        JsonToken token = jr.peek();
        result = token.equals(JsonToken.BEGIN_OBJECT) || token.equals(JsonToken.BEGIN_ARRAY);
    } catch (Exception e) {
        Log.w(LOG_TAG, "JsonReader exception:" + e.getMessage());
    }
    return result;
}

From source file:com.magnet.android.mms.request.marshall.GsonStreamReader.java

License:Open Source License

@Override
public int getTokenType() throws MarshallingException {
    int result = TOKEN_TYPE_FIELD_VALUE;
    JsonToken tokenType;/*from   ww w  . j  a v a 2 s.co m*/
    try {
        tokenType = jr.peek();
    } catch (Exception e) {
        throw new MarshallingException(e);
    }
    if (tokenType == JsonToken.BEGIN_OBJECT) {
        result = TOKEN_TYPE_START_OBJECT;
    } else if (tokenType == JsonToken.BEGIN_ARRAY) {
        result = TOKEN_TYPE_START_ARRAY;
    } else if (tokenType == JsonToken.END_OBJECT) {
        result = TOKEN_TYPE_END_OBJECT;
    } else if (tokenType == JsonToken.END_ARRAY) {
        result = TOKEN_TYPE_END_ARRAY;
    } else if (tokenType == JsonToken.NAME) {
        result = TOKEN_TYPE_FIELD_NAME;
    } else if (tokenType == JsonToken.NULL) {
        result = TOKEN_TYPE_NULL;
    } else if (tokenType == JsonToken.END_DOCUMENT) {
        result = TOKEN_TYPE_END_DOCUMENT;
    }
    return result;
}

From source file:com.nridge.core.io.gson.JSONDocument.java

License:Open Source License

private boolean isNextTokenAnObject(JsonReader aReader) throws IOException {
    JsonToken jsonToken = aReader.peek();

    return (jsonToken == JsonToken.BEGIN_OBJECT);
}

From source file:com.nridge.core.io.gson.JSONDocument.java

License:Open Source License

private void loadDocumentArray(JsonReader aReader, Document aDocument) throws IOException {
    JsonToken jsonToken;/*w ww  .j  av  a2  s .c  om*/
    Document childDocument;

    do {
        childDocument = new Document(aDocument.getType());
        childDocument.setName(aDocument.getName());
        aDocument.addRelationship(aDocument.getTitle(), childDocument);
        loadDocument(aReader, childDocument);
        jsonToken = aReader.peek();
    } while (jsonToken == JsonToken.BEGIN_OBJECT);
}

From source file:com.quarterfull.newsAndroid.reader.owncloud.OwnCloudReaderMethods.java

License:Open Source License

private static JSONObject getJSONObjectFromReader(JsonReader jsonReader) {
    JSONObject jObj = new JSONObject();
    JsonToken tokenInstance;//from   w  w  w .ja  va2s . co  m
    try {
        tokenInstance = jsonReader.peek();
        if (tokenInstance == JsonToken.BEGIN_OBJECT)
            jsonReader.beginObject();
        else if (tokenInstance == JsonToken.BEGIN_ARRAY)
            jsonReader.beginArray();

        while (jsonReader.hasNext()) {
            JsonToken token;
            String name;
            try {
                name = jsonReader.nextName();
                token = jsonReader.peek();

                //Log.d(TAG, token.toString());

                switch (token) {
                case NUMBER:
                    jObj.put(name, jsonReader.nextLong());
                    break;
                case NULL:
                    jsonReader.skipValue();
                    break;
                case BOOLEAN:
                    jObj.put(name, jsonReader.nextBoolean());
                    break;
                case BEGIN_OBJECT:
                    //jsonReader.beginObject();
                    jObj.put(name, getJSONObjectFromReader(jsonReader));
                    //jsonReader.endObject();
                    break;
                case BEGIN_ARRAY:
                    jsonReader.skipValue();
                    break;
                default:
                    jObj.put(name, jsonReader.nextString());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                jsonReader.skipValue();
            }
        }

        if (tokenInstance == JsonToken.BEGIN_OBJECT)
            jsonReader.endObject();
        else if (tokenInstance == JsonToken.BEGIN_ARRAY)
            jsonReader.endArray();

        return jObj;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sap.core.odata.core.ep.consumer.JsonEntryConsumer.java

License:Apache License

private void readNavigationProperty(final String navigationPropertyName)
        throws IOException, EntityProviderException, EdmException {
    NavigationPropertyInfo navigationPropertyInfo = eia.getNavigationPropertyInfo(navigationPropertyName);
    if (navigationPropertyInfo == null) {
        throw new EntityProviderException(
                EntityProviderException.ILLEGAL_ARGUMENT.addContent(navigationPropertyName));
    }//w  w  w  .j a  va 2 s . c o m

    if (reader.peek() == JsonToken.BEGIN_OBJECT) {
        reader.beginObject();
        String name = reader.nextName();
        if (FormatJson.DEFERRED.equals(name)) {
            reader.beginObject();
            String uri = reader.nextName();
            if (FormatJson.URI.equals(uri)) {
                String value = reader.nextString();
                entryMetadata.putAssociationUri(navigationPropertyInfo.getName(), value);
            } else {
                throw new EntityProviderException(EntityProviderException.ILLEGAL_ARGUMENT.addContent(uri));
            }
            reader.endObject();
        } else {
            EdmNavigationProperty navigationProperty = (EdmNavigationProperty) eia.getEntityType()
                    .getProperty(navigationPropertyName);
            EdmEntitySet inlineEntitySet = eia.getEntitySet().getRelatedEntitySet(navigationProperty);
            EntityInfoAggregator inlineEia = EntityInfoAggregator.create(inlineEntitySet);
            EntityProviderReadProperties inlineReadProperties;
            OnReadInlineContent callback = readProperties.getCallback();
            try {
                if (callback == null) {
                    inlineReadProperties = EntityProviderReadProperties.init()
                            .mergeSemantic(readProperties.getMergeSemantic()).build();

                } else {
                    inlineReadProperties = callback.receiveReadProperties(readProperties, navigationProperty);
                }

                if (navigationProperty.getMultiplicity() == EdmMultiplicity.MANY) {
                    JsonFeedConsumer inlineConsumer = new JsonFeedConsumer(reader, inlineEia,
                            inlineReadProperties);
                    ODataFeed feed = inlineConsumer.readStartedInlineFeed(name);
                    updateExpandSelectTree(navigationPropertyName, feed);
                    if (callback == null) {
                        properties.put(navigationPropertyName, feed);
                        entryResult.setContainsInlineEntry(true);
                    } else {
                        ReadFeedResult result = new ReadFeedResult(inlineReadProperties, navigationProperty,
                                feed);
                        callback.handleReadFeed(result);
                    }
                } else {
                    JsonEntryConsumer inlineConsumer = new JsonEntryConsumer(reader, inlineEia,
                            inlineReadProperties);
                    ODataEntry entry = inlineConsumer.readInlineEntry(name);
                    updateExpandSelectTree(navigationPropertyName, entry);
                    if (callback == null) {
                        properties.put(navigationPropertyName, entry);
                        entryResult.setContainsInlineEntry(true);
                    } else {
                        ReadEntryResult result = new ReadEntryResult(inlineReadProperties, navigationProperty,
                                entry);
                        callback.handleReadEntry(result);
                    }
                }

            } catch (ODataApplicationException e) {
                throw new EntityProviderException(
                        EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
            }
        }
        reader.endObject();
    } else {
        final EdmNavigationProperty navigationProperty = (EdmNavigationProperty) eia.getEntityType()
                .getProperty(navigationPropertyName);
        final EdmEntitySet inlineEntitySet = eia.getEntitySet().getRelatedEntitySet(navigationProperty);
        final EntityInfoAggregator inlineInfo = EntityInfoAggregator.create(inlineEntitySet);
        OnReadInlineContent callback = readProperties.getCallback();
        EntityProviderReadProperties inlineReadProperties;
        if (callback == null) {
            inlineReadProperties = EntityProviderReadProperties.init()
                    .mergeSemantic(readProperties.getMergeSemantic()).build();
        } else {
            try {
                inlineReadProperties = callback.receiveReadProperties(readProperties, navigationProperty);
            } catch (final ODataApplicationException e) {
                throw new EntityProviderException(
                        EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
            }
        }
        ODataFeed feed = new JsonFeedConsumer(reader, inlineInfo, inlineReadProperties)
                .readInlineFeedStandalone();
        updateExpandSelectTree(navigationPropertyName, feed);
        if (callback == null) {
            properties.put(navigationPropertyName, feed);
            entryResult.setContainsInlineEntry(true);
        } else {
            ReadFeedResult result = new ReadFeedResult(inlineReadProperties, navigationProperty, feed);
            try {
                callback.handleReadFeed(result);
            } catch (final ODataApplicationException e) {
                throw new EntityProviderException(
                        EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass().getSimpleName()), e);
            }
        }
    }
}

From source file:com.sap.core.odata.core.ep.util.JsonUtils.java

License:Apache License

public static int startJson(final JsonReader reader) throws EntityProviderException {
    //The enclosing "d" and "results" are optional - so we cannot check for the presence
    //but we have to read over them in case they are present.
    JsonToken token;/*from  w w  w  .j a v  a 2  s  .  c o m*/
    try {
        token = reader.peek();
        int openJsonObjects = 0;
        if (JsonToken.BEGIN_OBJECT == token) {
            reader.beginObject();
            openJsonObjects++;
            token = reader.peek();
            if (JsonToken.NAME == token) {
                String name = reader.nextName();
                if (!("d".equals(name) ^ "results".equals(name))) {
                    //TODO I18N
                    throw new EntityProviderException(EntityProviderException.COMMON,
                            name + " not expected, only d or results");
                }
            }

            token = reader.peek();
            if (JsonToken.BEGIN_OBJECT == token) {
                reader.beginObject();
                openJsonObjects++;
            } else if (JsonToken.BEGIN_ARRAY == token) {
                //TODO I18N
                throw new EntityProviderException(EntityProviderException.COMMON, "Array not expected");
            }
        }

        return openJsonObjects;
    } catch (IOException e) {
        //TODO I18N
        throw new EntityProviderException(EntityProviderException.COMMON, e);
    }
}

From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java

License:Apache License

/**
 * Calls the CoreServices API with custom JSON writer to write the result to. Uses
 * streaming APIs to handle large paylods of JSON response and write them to writer.
 *
 * @param method GET or POST/*  w ww.j  ava 2  s. c  o  m*/
 * @param params HTTP Params to be sent
 * @param timeoutMillis Timeout for connection/socket timeout. Use -1 for the default
 *     timeout.
 * @param writer Writer to write the JSON result
 * @throws HttpException when network or other IO issues occur
 * @throws CallErrorException when server or semantics errors occur
 */
void call(String method, JsonElement params, String token, int timeoutMillis, JsonWriter writer)
        throws HttpException, CallErrorException {
    JsonObject header = new JsonObject();
    header.addProperty("user", user);
    if (token != null) {
        header.addProperty("token", token);
    }
    header.addProperty("client", client);

    JsonObject request = new JsonObject();
    request.addProperty("id", uuidGenerator.generate().toString());
    request.addProperty("method", method);
    request.add("params", params);
    request.add("header", header);

    final int effectiveTimeoutMillis = (timeoutMillis > 0) ? timeoutMillis : this.timeoutMillis;

    log.debug("Calling method " + method + " (user: " + user + ")");

    InputStream responseStream = requestFactory.createPostJson(apiUrl, request)
            .setReadTimeoutMillis(effectiveTimeoutMillis).executeAndStream().getBodyAsStream();
    log.debug("Method " + method + " done (user: " + user + ")");

    if (responseStream == null) {
        log.info("Empty response while executing request to " + apiUrl);
        return;
    }

    // We're interested only in `result` and `error` properties of the response JSON
    JsonObject errorObject = null;
    try (JsonReader reader = getJsonReader(responseStream)) {
        if (reader.hasNext()) {
            if (reader.peek() == JsonToken.BEGIN_OBJECT) {
                reader.beginObject();
                while (reader.peek() != JsonToken.END_OBJECT) {
                    String name = reader.nextName();
                    if ("error".equals(name)) {
                        if (reader.peek() == JsonToken.BEGIN_OBJECT) {
                            errorObject = gsonBuilder.create().fromJson(reader, JsonObject.class);
                        } else {
                            reader.skipValue();
                        }
                    } else if ("result".equals(name)) {
                        pushToWriter(reader, writer);
                    } else {
                        reader.skipValue();
                    }
                }
                reader.endObject();
            } else {
                log.warn("Response received is not a JSON object, ignoring. Requsest:" + apiUrl);
            }
        } else {
            log.warn("Received empty response while executing the request to " + apiUrl);
        }
    } catch (IOException e) {
        throw new HttpException("Failed to execute request to '" + apiUrl + "'", e);
    }
    if (errorObject != null && !errorObject.isJsonNull()) {
        throw new CallErrorException("Error: " + errorObject.toString());
    }
}