Example usage for com.google.gson.stream JsonReader skipValue

List of usage examples for com.google.gson.stream JsonReader skipValue

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader skipValue.

Prototype

public void skipValue() throws IOException 

Source Link

Document

Skips the next value recursively.

Usage

From source file:org.ohmage.OhmageApi.java

License:Apache License

private Response parseStreamingReadResponse(String url, HttpResponse response,
        StreamingResponseListener listener) {
    Result result = Result.HTTP_ERROR;
    String[] errorCodes = null;//from  w ww .java2 s.c om

    // the response object that will be returned; its type is decided by outputType
    // it's also populated by a call to populateFromJSON() which transforms the server response into the Response object
    Response candidate = new Response();
    CountingInputStream inputstream = null;

    if (response != null) {
        Log.v(TAG, response.getStatusLine().toString());
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                try {

                    JsonParser parser = new JsonParser();
                    JsonReader reader = new JsonReader(new InputStreamReader(
                            new CountingInputStream(responseEntity.getContent()), "UTF-8"));
                    reader.beginObject();

                    // expecting: {result: "<status>", data: [{},{},{}...]}
                    while (reader.hasNext()) {
                        String name = reader.nextName();
                        if ("result".equals(name)) {
                            if (reader.nextString().equalsIgnoreCase("success")) {
                                result = Result.SUCCESS;
                            } else {
                                result = Result.FAILURE;
                            }
                        } else if ("data".equals(name)) {
                            reader.beginArray();

                            // do pre-read init
                            listener.beforeRead();

                            while (reader.hasNext()) {
                                JsonElement elem = parser.parse(reader);
                                listener.readObject(elem.getAsJsonObject());
                            }

                            // do post-read cleanup
                            listener.afterRead();

                            reader.endArray();
                        } else if ("errors".equals(name)) {
                            reader.beginArray();

                            List<String> errorList = new ArrayList<String>();

                            while (reader.hasNext()) {
                                // read off each of the errors and stick it
                                // into the error array
                                JsonElement elem = parser.parse(reader);
                                errorList.add(elem.getAsJsonObject().get("code").getAsString());
                            }

                            errorCodes = errorList.toArray(new String[errorList.size()]);

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

                    reader.endObject();

                    // and we're done!
                } catch (IOException e) {
                    Log.e(TAG, "Problem reading response body", e);
                    result = Result.INTERNAL_ERROR;
                }

                try {
                    responseEntity.consumeContent();
                } catch (IOException e) {
                    Log.e(TAG, "Error consuming content", e);
                }

            } else {
                Log.e(TAG, "No response entity in response");
                result = Result.HTTP_ERROR;
            }
        } else {
            Log.e(TAG, "Returned status code: " + String.valueOf(response.getStatusLine().getStatusCode()));
            result = Result.HTTP_ERROR;
        }

    } else {
        Log.e(TAG, "Response is null");
        result = Result.HTTP_ERROR;
    }

    if (inputstream != null && result == Result.SUCCESS)
        Analytics.network(mContext, url, inputstream.amountRead());

    listener.readResult(result, errorCodes);
    candidate.setResponseStatus(result, errorCodes);

    return candidate;
}

From source file:org.onos.yangtools.yang.data.codec.gson.JsonParserStream.java

License:Open Source License

public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
    switch (in.peek()) {
    case STRING://ww w . ja va2s  .  c o  m
    case NUMBER:
        setValue(parent, in.nextString());
        break;
    case BOOLEAN:
        setValue(parent, Boolean.toString(in.nextBoolean()));
        break;
    case NULL:
        in.nextNull();
        setValue(parent, null);
        break;
    case BEGIN_ARRAY:
        in.beginArray();
        while (in.hasNext()) {
            if (parent instanceof LeafNodeDataWithSchema) {
                read(in, parent);
            } else {
                final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
                read(in, newChild);
            }
        }
        in.endArray();
        return;
    case BEGIN_OBJECT:
        final Set<String> namesakes = new HashSet<>();
        in.beginObject();
        /*
         * This allows parsing of incorrectly /as showcased/
         * in testconf nesting of list items - eg.
         * lists with one value are sometimes serialized
         * without wrapping array.
         *
         */
        if (isArray(parent)) {
            parent = newArrayEntry(parent);
        }
        while (in.hasNext()) {
            final String jsonElementName = in.nextName();
            final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
            final String localName = namespaceAndName.getName();
            addNamespace(namespaceAndName.getUri());
            if (namesakes.contains(jsonElementName)) {
                throw new JsonSyntaxException("Duplicate name " + jsonElementName + " in JSON input.");
            }
            namesakes.add(jsonElementName);
            final Deque<DataSchemaNode> childDataSchemaNodes = findSchemaNodeByNameAndNamespace(
                    parent.getSchema(), localName, getCurrentNamespace());
            if (childDataSchemaNodes.isEmpty()) {
                throw new IllegalStateException("Schema for node with name " + localName + " and namespace "
                        + getCurrentNamespace() + " doesn't exist.");
            }

            final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent)
                    .addChild(childDataSchemaNodes);
            /*
             * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
             * will be able to load anyxml which conforms to YANG data using these
             * parser, for other anyxml will be harder.
             */
            if (newChild instanceof AnyXmlNodeDataWithSchema) {
                in.skipValue();
            } else {
                read(in, newChild);
            }
            removeNamespace();
        }
        in.endObject();
        return;
    case END_DOCUMENT:
    case NAME:
    case END_OBJECT:
    case END_ARRAY:
        break;
    }
}

From source file:org.openstreetmap.josm.plugins.openstreetcam.service.photo.adapter.PhotoTypeAdapter.java

License:LGPL

@Override
public Photo read(final JsonReader reader) throws IOException {
    Double latitude = null;// ww  w.j  av  a  2  s.co m
    Double longitude = null;
    final PhotoBuilder builder = new PhotoBuilder();
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
        case PHOTO_ID:
            builder.id(ReaderUtil.readLong(reader));
            break;
        case PHOTO_SEQUENCE_ID:
            builder.sequenceId(ReaderUtil.readLong(reader));
            break;
        case PHOTO_SEQUENCE_IDX:
            builder.sequenceIndex(ReaderUtil.readInt(reader));
            break;
        case PHOTO_LATITUDE:
            latitude = ReaderUtil.readDouble(reader);
            break;
        case PHOTO_LONGITUDE:
            longitude = ReaderUtil.readDouble(reader);
            break;
        case PHOTO_NAME:
            builder.name(ReaderUtil.readString(reader));
            break;
        case PHOTO_LTH_NAME:
            builder.largeThumbnailName(ReaderUtil.readString(reader));
            break;
        case PHOTO_TH_NAME:
            builder.thumbnailName(ReaderUtil.readString(reader));
            break;
        case PHOTO_ORI_NAME:
            builder.oriName(ReaderUtil.readString(reader));
            break;
        case PHOTO_TIMESTAMP:
            builder.timestamp(ReaderUtil.readLong(reader));
            break;
        case PHOTO_HEADING:
            final String value = ReaderUtil.readString(reader);
            final Double heading = value != null && !value.isEmpty() ? Double.parseDouble(value) : null;
            builder.heading(heading);
            break;
        case PHOTO_USERNAME:
            builder.username(ReaderUtil.readString(reader));
            break;
        case WAY_ID:
            final String wayIdValue = ReaderUtil.readString(reader);
            final Long wayId = wayIdValue != null && !wayIdValue.isEmpty() ? Long.parseLong(wayIdValue) : null;
            builder.wayId(wayId);
            break;
        case PHOTO_SHOT_DATE:
            builder.shotDate(ReaderUtil.readString(reader));
            break;
        default:
            reader.skipValue();
            break;
        }
    }
    if (latitude != null && longitude != null) {
        builder.point(latitude, longitude);
    }
    reader.endObject();
    return builder.build();
}

From source file:org.openstreetmap.josm.plugins.openstreetcam.service.photo.adapter.SegmentTypeAdapter.java

License:LGPL

@Override
public Segment read(final JsonReader reader) throws IOException {
    final SegmentBuilder builder = new SegmentBuilder();
    reader.beginObject();//from w w  w  .  ja v  a2 s .  com
    while (reader.hasNext()) {
        switch (reader.nextName()) {
        case SEGMENT_ID:
            builder.id(ReaderUtil.readString(reader));
            break;
        case SEGMENT_FROM:
            builder.from(ReaderUtil.readLong(reader));
            break;
        case SEGMENT_TO:
            builder.to(ReaderUtil.readLong(reader));
            break;
        case WAY_ID:
            builder.wayId(ReaderUtil.readLong(reader));
            break;
        case SEGMENT_COVERAGE:
            builder.coverage(ReaderUtil.readInt(reader));
            break;
        case SEGMENT_GEOMETRY:
            builder.geometry(ReaderUtil.readGeometry(reader));
            break;
        default:
            reader.skipValue();
            break;
        }
    }
    reader.endObject();
    return builder.build();
}

From source file:org.openstreetmap.josm.plugins.openstreetcam.service.PhotoTypeAdapter.java

License:Apache License

@Override
public Photo read(final JsonReader reader) throws IOException {
    Long id = null;/*from w  w w.  j  a v a  2 s.  c  om*/
    Long sequenceId = null;
    Integer sequenceIdx = null;
    Double latitude = null;
    Double longitude = null;
    String name = null;
    String largeThumbnailName = null;
    String thumbnailName = null;
    Long timestamp = null;
    String headingVal = null;
    String username = null;
    reader.beginObject();

    while (reader.hasNext()) {
        switch (reader.nextName()) {
        case ID:
            id = readLong(reader);
            break;
        case SEQUENCE_ID:
            sequenceId = readLong(reader);
            break;
        case SEQUENCE_IDX:
            sequenceIdx = readInt(reader);
            break;
        case LATITUDE:
            latitude = readDouble(reader);
            break;
        case LONGITUDE:
            longitude = readDouble(reader);
            break;
        case NAME:
            name = readString(reader);
            break;
        case LTH_NAME:
            largeThumbnailName = readString(reader);
            break;
        case TH_NAME:
            thumbnailName = readString(reader);
            break;
        case TIMESTAMP:
            timestamp = readLong(reader);
            break;
        case HEADING:
            headingVal = readString(reader);
            break;
        case USERNAME:
            username = readString(reader);
            break;
        default:
            reader.skipValue();
            break;
        }
    }
    reader.endObject();
    final Double heading = headingVal != null && !headingVal.isEmpty() ? Double.parseDouble(headingVal) : null;
    return new Photo(id, sequenceId, sequenceIdx, latitude, longitude, name, largeThumbnailName, thumbnailName,
            timestamp, heading, username);
}

From source file:org.project.openbaton.nubomedia.paas.model.openshift.MetadataTypeAdapter.java

License:Apache License

@Override
public Metadata read(JsonReader in) throws IOException {

    String name = "", selfLink = "", resourceVersion = "", namespace = "";
    in.beginObject();/*from  ww  w .  j  a  v a 2s  . c  o m*/

    while (in.hasNext()) {
        String nameObj = in.nextName();

        switch (nameObj) {
        case "name":
            name = in.nextString();
            break;
        case "selfLink":
            selfLink = in.nextString();
            break;
        case "resourceVersion":
            resourceVersion = in.nextString();
            break;
        case "namespace":
            namespace = in.nextString();
            break;
        default:
            in.skipValue();
            break;
        }
    }

    in.endObject();

    return new Metadata(name, selfLink, resourceVersion, namespace);
}

From source file:org.sensorhub.impl.security.gxoauth.OAuthAuthenticator.java

License:Mozilla Public License

private String parseUserInfoJson(JsonReader reader) throws IOException {
    String userId = null;//from w  w w  . j  a  v a  2  s.  com

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if ("id".equals(name) || "user_id".equals(name) || "uid".equals(name))
            userId = reader.nextString();
        else
            reader.skipValue();
    }
    reader.endObject();

    return userId;
}

From source file:org.sonarsource.sonarlint.core.container.connected.update.SettingsDownloader.java

License:Open Source License

private static void parseProperty(BiPredicate<String, String> filter, BiConsumer<String, String> consumer,
        JsonReader reader) throws IOException {
    String key = null;/* www .  ja  v a2  s  .  com*/
    String value = null;
    while (reader.hasNext()) {
        String propName = reader.nextName();
        switch (propName) {
        case "key":
            key = reader.nextString();
            break;
        case "value":
            value = reader.nextString();
            break;
        default:
            reader.skipValue();
        }
    }
    // Storage optimisation: don't store properties having same value than global properties
    if (filter.test(key, value)) {
        consumer.accept(key, value);
    }
}

From source file:org.sprintapi.hyperdata.gson.HyperDataTypeAdapter.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*  w w  w .  j a v a  2  s  .c om*/
public Object read(JsonReader in) throws IOException {
    if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
    }

    Object instance = constructor.construct();

    BoundField metadataField = null;
    if (metadataAccess != null) {
        metadataField = boundFields.get(metadataAccess.fieldName);
    }

    Object meta = null;
    Map<String, BoundField> metaBoundFields = null;

    try {
        in.beginObject();
        while (in.hasNext()) {
            String name = in.nextName();
            if ((name != null) && (metadataField != null) && (name.startsWith(Constants.META_CHAR))) {
                if (meta == null) {
                    meta = constructorConstructor.get(metadataField.type).construct();
                    if (!Map.class.isAssignableFrom(meta.getClass())) {
                        metaBoundFields = reflectiveFactory.getBoundFields(gson, metadataField.type,
                                metadataField.type.getRawType());
                    }
                }

                if (metaBoundFields != null) {
                    BoundField field = metaBoundFields.get(name.substring(1));
                    if (field == null || !field.deserialized) {
                        in.skipValue();
                    } else {
                        field.read(in, meta);
                    }
                } else {
                    TypeAdapter<Object> ta = gson.getAdapter(Object.class);
                    Object value = ta.read(in);
                    ((Map) meta).put(name.substring(1), value);
                }

            } else if ((name != null) && (!name.equals(metadataAccess.fieldName))) {
                BoundField field = boundFields.get(name);
                if (field == null || !field.deserialized) {
                    in.skipValue();
                } else {
                    field.read(in, instance);
                }
            }
        }
        if (metadataAccess.setter != null) {
            metadataAccess.setter.invoke(instance, meta);
            //TODO
        }

    } catch (IllegalStateException e) {
        throw new JsonSyntaxException(e);
    } catch (IllegalAccessException e) {
        throw new AssertionError(e);
    } catch (IllegalArgumentException e) {
        throw new AssertionError(e);
    } catch (InvocationTargetException e) {
        throw new AssertionError(e);
    }
    in.endObject();
    return instance;
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

private String readResult(Map<String, String> params, boolean login, boolean retry) throws IOException {
    InputStream in = doRequest(params);
    if (in == null)
        return null;

    JsonReader reader = null;
    String ret = "";
    try {/*  ww  w  . j  av a2  s.co m*/
        reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        // Check if content contains array or object, array indicates login-response or error, object is content

        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (!name.equals("content")) {
                reader.skipValue();
                continue;
            }

            JsonToken t = reader.peek();
            if (!t.equals(JsonToken.BEGIN_OBJECT))
                continue;

            JsonObject object = new JsonObject();
            reader.beginObject();
            while (reader.hasNext()) {
                object.addProperty(reader.nextName(), reader.nextString());
            }
            reader.endObject();

            if (object.get(SESSION_ID) != null) {
                ret = object.get(SESSION_ID).getAsString();
            }
            if (object.get(STATUS) != null) {
                ret = object.get(STATUS).getAsString();
            }
            if (this.apiLevel == -1 && object.get(API_LEVEL) != null) {
                this.apiLevel = object.get(API_LEVEL).getAsInt();
            }
            if (object.get(VALUE) != null) {
                ret = object.get(VALUE).getAsString();
            }
            if (object.get(ERROR) != null) {
                String message = object.get(ERROR).getAsString();
                Context ctx = MyApplication.context();

                switch (message) {
                case API_DISABLED:
                    lastError = ctx.getString(R.string.Error_ApiDisabled, Controller.getInstance().username());
                    break;
                case NOT_LOGGED_IN:
                case LOGIN_ERROR:
                    if (!login && retry && login())
                        return readResult(params, false, false); // Just do the same request again
                    else
                        lastError = ctx.getString(R.string.Error_LoginFailed);
                    break;
                case INCORRECT_USAGE:
                    lastError = ctx.getString(R.string.Error_ApiIncorrectUsage);
                    break;
                case UNKNOWN_METHOD:
                    lastError = ctx.getString(R.string.Error_ApiUnknownMethod);
                    break;
                default:
                    lastError = ctx.getString(R.string.Error_ApiUnknownError);
                    break;
                }

                hasLastError = true;
                Log.e(TAG, message);
                return null;
            }

        }
    } finally {
        if (reader != null)
            reader.close();
    }
    if (ret.startsWith("\""))
        ret = ret.substring(1, ret.length());
    if (ret.endsWith("\""))
        ret = ret.substring(0, ret.length() - 1);

    return ret;
}