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

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

Introduction

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

Prototype

public String nextName() throws IOException 

Source Link

Document

Returns the next token, a com.google.gson.stream.JsonToken#NAME property name , and consumes it.

Usage

From source file:org.netscan.core.json.IPv4JsonAdapter.java

License:Open Source License

@Override
public IPv4 read(JsonReader in) throws IOException {
    in.beginObject();//  w  w  w .j a  v  a2 s  . c o  m
    in.nextName();
    String ip = in.nextString();
    in.endObject();
    return new IPv4(ip);
}

From source file:org.objectpocket.gson.CustomTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

    TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // @Entity//from  w  ww  . ja va  2s  .  c o  m
    if (type.getRawType().getAnnotation(Entity.class) != null) {
        return new TypeAdapter<T>() {

            // SERIALIZE
            public void write(JsonWriter out, T obj) throws IOException {
                if (obj != null) {
                    String id = objectPocket.getIdForObject(obj);
                    // normalize
                    if (!objectPocket.isSerializeAsRoot(obj)) {
                        gson.toJson(new ProxyOut(obj.getClass().getTypeName(), id), ProxyOut.class, out);
                        return;
                    } else {
                        objectPocket.setSerializeAsRoot(obj, false);
                    }
                }
                // default serialization
                delegate.write(out, obj);
            };

            // DESERIALIZE
            @SuppressWarnings("unchecked")
            @Override
            public T read(JsonReader in) throws IOException {
                if (in.getPath().length() > 2) {
                    in.beginObject();
                    in.nextName();
                    StringBuilder sb = new StringBuilder(in.nextString());
                    String id = sb.substring(0, sb.indexOf("@"));
                    in.endObject();
                    T obj = null;
                    try {
                        obj = (T) ReflectionUtil.instantiateDefaultConstructor(type.getRawType());
                    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException
                            | NoSuchMethodException | InvocationTargetException e) {
                        throw new IOException("Could not instantiate class " + type.getRawType().getName()
                                + "\n" + "Might be that the class has no default constructor!", e);
                    }
                    objectPocket.addIdFromReadObject(obj, id);
                    return obj;
                } else {
                    T obj = delegate.read(in);
                    return obj;
                }
            }
        };
    }
    // All other
    else {
        return delegate;
    }
}

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  ww  w.j a  va2 s.c  o m*/

    // 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:/*from ww  w  .ja  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:/* ww w. j  a  va2 s.  com*/
        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;//from   w ww . j a  v a 2s.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  w w w.  j av  a 2 s.  co  m*/
    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

/**
 * Read one patch edit object from Json input
 * @param edit PatchEdit instance to be filled with read data
 * @param in JsonReader reader// w w w.j  a v a 2s. co 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//w w  w  .  ja va2 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("}");
}

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

License:Open Source License

/**
 * Parse one value object of data and saves it to buffer
 * @param value Buffer to read value object
 * @param in JsonReader reader//from w  w w .j a v  a 2s.com
 * @throws IOException
 */
private void readValueObject(@Nonnull final StringBuffer value, @Nonnull final JsonReader in)
        throws IOException {
    in.beginObject();
    value.append("{");

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

        if (in.peek() == JsonToken.STRING) {
            value.append("\"" + in.nextString() + "\"");
        } else {
            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);
            }
        }

        if (in.peek() != JsonToken.END_OBJECT) {
            value.append(",");
        }
    }

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