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

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

Introduction

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

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

From source file:org.mythdroid.services.GuideService.java

License:Open Source License

private void skipTo(JsonReader jr, JsonToken token) throws IOException {
    while (jr.hasNext() && jr.peek() != token)
        jr.skipValue();/*from w  w w . ja v  a2  s . com*/
}

From source file:org.mythdroid.services.VideoService.java

License:Open Source License

/**
 * Get a list of videos / directories in a given subdirectory
 * @param subdir the desired subdirectory or "ROOT" for the top-level
 * @return an ArrayList of Videos/*w w w  .  ja va  2s  .  c  o m*/
 */
public ArrayList<Video> getVideos(String subdir) throws IOException {

    ArrayList<Video> videos = new ArrayList<Video>(128);

    InputStream is = jc.GetStream("GetVideoList", null); //$NON-NLS-1$

    if (is == null)
        return null;

    JsonReader jreader = new JsonReader(new BufferedReader(new InputStreamReader(is, "UTF-8")) //$NON-NLS-1$
    );

    Video vid;
    final ArrayList<String> subdirs = new ArrayList<String>(16);

    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_OBJECT);
    jreader.beginObject();
    skipTo(jreader, JsonToken.BEGIN_ARRAY);
    jreader.beginArray();
    while (jreader.hasNext()) {
        jreader.beginObject();
        vid = gson.fromJson(jreader, Video.class);
        jreader.endObject();

        if (!subdir.equals("ROOT") && !vid.filename.startsWith(subdir)) //$NON-NLS-1$
            continue;

        String name = vid.filename;

        if (!subdir.equals("ROOT")) //$NON-NLS-1$
            name = vid.filename.substring(subdir.length() + 1);

        int slash;
        if ((slash = name.indexOf('/')) > 0) {
            String dir = name.substring(0, slash);
            if (!subdirs.contains(dir))
                subdirs.add(dir);
        } else
            videos.add(vid);
    }
    jreader.endArray();
    jreader.endObject();
    jreader.endObject();
    jreader.close();
    jc.endStream();

    for (String name : subdirs) {
        try {
            videos.add(new Video("-1 DIRECTORY " + name)); //$NON-NLS-1$
        } catch (IllegalArgumentException e) {
            ErrUtil.logWarn(e);
        }
    }

    videos.trimToSize();

    return videos;

}

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   www.jav  a  2 s.  com*/

    // 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  .j a v  a2  s . 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.opendaylight.controller.sal.rest.gson.JsonParser.java

License:Open Source License

public JsonElement read(JsonReader in) throws IOException {
    switch (in.peek()) {
    case STRING:/*from  w ww. jav  a 2  s .  co  m*/
        return new JsonPrimitive(in.nextString());
    case NUMBER:
        String number = in.nextString();
        return new JsonPrimitive(new LazilyParsedNumber(number));
    case BOOLEAN:
        return new JsonPrimitive(in.nextBoolean());
    case NULL:
        in.nextNull();
        return JsonNull.INSTANCE;
    case BEGIN_ARRAY:
        JsonArray array = new JsonArray();
        in.beginArray();
        while (in.hasNext()) {
            array.add(read(in));
        }
        in.endArray();
        return array;
    case BEGIN_OBJECT:
        JsonObject object = new JsonObject();
        in.beginObject();
        while (in.hasNext()) {
            final String childName = in.nextName();
            if (object.has(childName)) {
                throw new JsonSyntaxException("Duplicate name " + childName + " in JSON input.");
            }
            object.add(childName, read(in));
        }
        in.endObject();
        return object;
    case END_DOCUMENT:
    case NAME:
    case END_OBJECT:
    case END_ARRAY:
    default:
        throw new IllegalArgumentException();
    }
}

From source file:org.opendaylight.netconf.sal.rest.impl.JsonToPATCHBodyReader.java

License:Open Source License

private List<PATCHEntity> read(final JsonReader in, InstanceIdentifierContext path) throws IOException {

    boolean inEdit = false;
    boolean inValue = false;
    String operation = null;//  www  .  j a  v  a 2 s  .  c o  m
    String target = null;
    String editId = null;
    List<PATCHEntity> resultCollection = new ArrayList<>();

    while (in.hasNext()) {
        switch (in.peek()) {
        case STRING:
        case NUMBER:
            in.nextString();
            break;
        case BOOLEAN:
            Boolean.toString(in.nextBoolean());
            break;
        case NULL:
            in.nextNull();
            break;
        case BEGIN_ARRAY:
            in.beginArray();
            break;
        case BEGIN_OBJECT:
            if (inEdit && operation != null & target != null & inValue) {
                //let's do the stuff - find out target node
                //                      StringInstanceIdentifierCodec codec = new StringInstanceIdentifierCodec(path
                //                               .getSchemaContext());
                //                        if (path.getInstanceIdentifier().toString().equals("/")) {
                //                        final YangInstanceIdentifier deserialized = codec.deserialize(target);
                //                        }
                DataSchemaNode targetNode = ((DataNodeContainer) (path.getSchemaNode()))
                        .getDataChildByName(target.replace("/", ""));
                if (targetNode == null) {
                    LOG.debug("Target node {} not found in path {} ", target, path.getSchemaNode());
                    throw new RestconfDocumentedException("Error parsing input", ErrorType.PROTOCOL,
                            ErrorTag.MALFORMED_MESSAGE);
                } else {

                    final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
                    final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter
                            .from(resultHolder);

                    //keep on parsing json from place where target points
                    final JsonParserStream jsonParser = JsonParserStream.create(writer, path.getSchemaContext(),
                            path.getSchemaNode());
                    jsonParser.parse(in);

                    final YangInstanceIdentifier targetII = path.getInstanceIdentifier()
                            .node(targetNode.getQName());
                    resultCollection
                            .add(new PATCHEntity(editId, operation, targetII, resultHolder.getResult()));
                    inValue = false;

                    operation = null;
                    target = null;
                }
                in.endObject();
            } else {
                in.beginObject();
            }
            break;
        case END_DOCUMENT:
            break;
        case NAME:
            final String name = in.nextName();

            switch (name) {
            case "edit":
                inEdit = true;
                break;
            case "operation":
                operation = in.nextString();
                break;
            case "target":
                target = in.nextString();
                break;
            case "value":
                inValue = true;
                break;
            case "patch-id":
                patchId = in.nextString();
                break;
            case "edit-id":
                editId = in.nextString();
                break;
            }
            break;
        case END_OBJECT:
            in.endObject();
            break;
        case END_ARRAY:
            in.endArray();
            break;

        default:
            break;
        }
    }

    return ImmutableList.copyOf(resultCollection);
}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

private List<PATCHEntity> read(final JsonReader in, final InstanceIdentifierContext path) throws IOException {
    final List<PATCHEntity> resultCollection = new ArrayList<>();
    final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
            path.getSchemaContext());/*from ww  w  .j  av  a 2 s .c om*/
    final JsonToPATCHBodyReader.PatchEdit edit = new JsonToPATCHBodyReader.PatchEdit();

    while (in.hasNext()) {
        switch (in.peek()) {
        case STRING:
        case NUMBER:
            in.nextString();
            break;
        case BOOLEAN:
            Boolean.toString(in.nextBoolean());
            break;
        case NULL:
            in.nextNull();
            break;
        case BEGIN_ARRAY:
            in.beginArray();
            break;
        case BEGIN_OBJECT:
            in.beginObject();
            break;
        case END_DOCUMENT:
            break;
        case NAME:
            parseByName(in.nextName(), edit, in, path, codec, resultCollection);
            break;
        case END_OBJECT:
            in.endObject();
            break;
        case END_ARRAY:
            in.endArray();
            break;

        default:
            break;
        }
    }

    return ImmutableList.copyOf(resultCollection);
}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

/**
 * Switch value of parsed JsonToken.NAME and read edit definition or patch id
 * @param name value of token//from  w w w  .j a  va2s.  c o m
 * @param edit PatchEdit instance
 * @param in JsonReader reader
 * @param path InstanceIdentifierContext context
 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
 * @param resultCollection collection of parsed edits
 * @throws IOException
 */
private void parseByName(@Nonnull final String name, @Nonnull final PatchEdit edit,
        @Nonnull final JsonReader in, @Nonnull final InstanceIdentifierContext path,
        @Nonnull final StringModuleInstanceIdentifierCodec codec,
        @Nonnull final List<PATCHEntity> resultCollection) throws IOException {
    switch (name) {
    case "edit":
        if (in.peek() == JsonToken.BEGIN_ARRAY) {
            in.beginArray();

            while (in.hasNext()) {
                readEditDefinition(edit, in, path, codec);
                resultCollection.add(prepareEditOperation(edit));
                edit.clear();
            }

            in.endArray();
        } else {
            readEditDefinition(edit, in, path, codec);
            resultCollection.add(prepareEditOperation(edit));
            edit.clear();
        }

        break;
    case "patch-id":
        this.patchId = in.nextString();
        break;
    default:
        break;
    }
}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

/**
 * Read one patch edit object from Json input
 * @param edit PatchEdit instance to be filled with read data
 * @param in JsonReader reader/*from ww  w. j  av  a  2  s .  c o m*/
 * @param path InstanceIdentifierContext path context
 * @param codec Draft11StringModuleInstanceIdentifierCodec codec
 * @throws IOException
 */
private void readEditDefinition(@Nonnull final PatchEdit edit, @Nonnull final JsonReader in,
        @Nonnull final InstanceIdentifierContext path, @Nonnull final StringModuleInstanceIdentifierCodec codec)
        throws IOException {
    final StringBuffer value = new StringBuffer();
    in.beginObject();

    while (in.hasNext()) {
        final String editDefinition = in.nextName();
        switch (editDefinition) {
        case "edit-id":
            edit.setId(in.nextString());
            break;
        case "operation":
            edit.setOperation(in.nextString());
            break;
        case "target":
            // target can be specified completely in request URI
            final String target = in.nextString();
            if (target.equals("/")) {
                edit.setTarget(path.getInstanceIdentifier());
                edit.setTargetSchemaNode(path.getSchemaContext());
            } else {
                edit.setTarget(codec.deserialize(codec.serialize(path.getInstanceIdentifier()).concat(target)));
                edit.setTargetSchemaNode(
                        SchemaContextUtil.findDataSchemaNode(path.getSchemaContext(), codec.getDataContextTree()
                                .getChild(edit.getTarget()).getDataSchemaNode().getPath().getParent()));
            }

            break;
        case "value":
            // save data defined in value node for next (later) processing, because target needs to be read
            // always first and there is no ordering in Json input
            readValueNode(value, in);
            break;
        default:
            break;
        }
    }

    in.endObject();

    // read saved data to normalized node when target schema is already known
    edit.setData(
            readEditData(new JsonReader(new StringReader(value.toString())), edit.getTargetSchemaNode(), path));
}

From source file:org.opendaylight.restconf.jersey.providers.JsonToPATCHBodyReader.java

License:Open Source License

/**
 * Parse data defined in value node and saves it to buffer
 * @param value Buffer to read value node
 * @param in JsonReader reader//from ww  w .j a  v  a 2 s. c  o  m
 * @throws IOException
 */
private void readValueNode(@Nonnull final StringBuffer value, @Nonnull final JsonReader in) throws IOException {
    in.beginObject();
    value.append("{");

    value.append("\"" + in.nextName() + "\"" + ":");

    if (in.peek() == JsonToken.BEGIN_ARRAY) {
        in.beginArray();
        value.append("[");

        while (in.hasNext()) {
            readValueObject(value, in);
            if (in.peek() != JsonToken.END_ARRAY) {
                value.append(",");
            }
        }

        in.endArray();
        value.append("]");
    } else {
        readValueObject(value, in);
    }

    in.endObject();
    value.append("}");
}