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:org.apache.axis2.json.gson.GsonXMLStreamReader.java

License:Apache License

private void readEndObject() throws IOException, XMLStreamException {
    endObject();/*from  w w w  .  j ava  2  s. c  o  m*/
    tokenType = jsonReader.peek();
    if (tokenType == JsonToken.END_OBJECT) {
        removeStackObj();
        state = JsonState.EndObjectEndObject;
    } else if (tokenType == JsonToken.END_ARRAY) {
        readEndArray();
        removeStackObj();
    } else if (tokenType == JsonToken.NAME) {
        removeStackObj();
        state = JsonState.EndObjectName;
    } else if (tokenType == JsonToken.BEGIN_OBJECT) {
        state = JsonState.EndObjectBeginObject_END;
    } else if (tokenType == JsonToken.END_DOCUMENT) {
        removeStackObj();
        state = JsonState.EndObjectEndDocument;
    }
}

From source file:org.apache.hadoop.fs.http.client.ContentSummary.java

License:Apache License

public static TypeAdapter adapter() {
    return new TypeAdapter<ContentSummary>() {
        @Override//from  w ww.j a v  a 2 s.com
        public void write(JsonWriter out, ContentSummary value) throws IOException {
            /* not implemented */
        }

        @Override
        public ContentSummary read(JsonReader in) throws IOException {
            ContentSummary instance = null;
            in.setLenient(true);

            if (in.peek() == JsonToken.BEGIN_OBJECT) {
                in.beginObject();

                if (in.nextName().equalsIgnoreCase("ContentSummary")) {
                    String name;
                    in.beginObject();
                    instance = new ContentSummary();

                    while (in.hasNext()) {
                        name = in.nextName();

                        if (name.equalsIgnoreCase("directoryCount")) {
                            instance.directoryCount = in.nextInt();
                        } else if (name.equalsIgnoreCase("fileCount")) {
                            instance.fileCount = in.nextInt();
                        } else if (name.equalsIgnoreCase("length")) {
                            instance.length = in.nextInt();
                        } else if (name.equalsIgnoreCase("quota")) {
                            instance.quota = in.nextInt();
                        } else if (name.equalsIgnoreCase("spaceConsumed")) {
                            instance.spaceConsumed = in.nextInt();
                        } else if (name.equalsIgnoreCase("spaceQuota")) {
                            instance.spaceQuota = in.nextInt();
                        }
                    }

                    in.endObject();
                }

                in.endObject();
            }
            return instance;
        }
    };
}

From source file:org.apache.hadoop.fs.http.client.FileStatus.java

License:Apache License

public static TypeAdapter adapter() {
    return new TypeAdapter<FileStatus>() {
        @Override//w  w w  . jav  a  2 s  . c  o  m
        public void write(JsonWriter out, FileStatus value) throws IOException {
            /* not implemented */
        }

        @Override
        public FileStatus read(JsonReader in) throws IOException {
            FileStatus instance = null;
            in.setLenient(true);

            if (in.peek() == JsonToken.BEGIN_OBJECT) {
                in.beginObject();

                if (in.nextName().equalsIgnoreCase("FileStatus")) {
                    String name;
                    in.beginObject();
                    instance = new FileStatus();

                    while (in.hasNext()) {
                        name = in.nextName();

                        if (name.equalsIgnoreCase("accessTime")) {
                            instance.accessTime = in.nextLong();
                        } else if (name.equalsIgnoreCase("blockSize")) {
                            instance.blockSize = in.nextInt();
                        } else if (name.equalsIgnoreCase("length")) {
                            instance.length = in.nextLong();
                        } else if (name.equalsIgnoreCase("modificationTime")) {
                            instance.modTime = in.nextLong();
                        } else if (name.equalsIgnoreCase("replication")) {
                            instance.replication = in.nextInt();
                        } else if (name.equalsIgnoreCase("group")) {
                            instance.group = in.nextString();
                        } else if (name.equalsIgnoreCase("owner")) {
                            instance.owner = in.nextString();
                        } else if (name.equalsIgnoreCase("pathSuffix")) {
                            instance.suffix = in.nextString();
                        } else if (name.equalsIgnoreCase("permission")) {
                            instance.permission = in.nextString();
                        } else if (name.equalsIgnoreCase("type")) {
                            instance.type = FileType.valueOf(in.nextString());
                        }
                    }

                    in.endObject();
                }

                in.endObject();
            }
            return instance;
        }
    };
}

From source file:org.apache.jclouds.oneandone.rest.util.ServerFirewallPolicyAdapter.java

License:Apache License

@Override
public List<T> read(JsonReader reader) throws IOException {
    List<ServerFirewallPolicy> list = new ArrayList<ServerFirewallPolicy>();
    if (reader.peek() == JsonToken.BEGIN_OBJECT) {
        Type mapType = new TypeToken<Map<String, Object>>() {
        }.getType();//from   w w  w  . ja v a2s  .c  o m
        Map<String, String> jsonMap = gson.fromJson(reader, mapType);
        ServerFirewallPolicy inning = ServerFirewallPolicy.create(jsonMap.get("id"), jsonMap.get("name"));
        list.add(inning);

    } else if (reader.peek() == JsonToken.BEGIN_ARRAY) {

        reader.beginArray();
        while (reader.hasNext()) {
            Type mapType = new TypeToken<Map<String, Object>>() {
            }.getType();
            Map<String, String> jsonMap = gson.fromJson(reader, mapType);
            ServerFirewallPolicy inning = ServerFirewallPolicy.create(jsonMap.get("id"), jsonMap.get("name"));
            list.add(inning);
        }
        reader.endArray();

    } else {
        reader.skipValue();
    }
    return (List<T>) list;
}

From source file:org.apache.jclouds.oneandone.rest.util.SnapshotAdapter.java

License:Apache License

@Override
public List<T> read(JsonReader reader) throws IOException {
    List<Snapshot> list = new ArrayList<Snapshot>();
    if (reader.peek() == JsonToken.BEGIN_OBJECT) {
        Type mapType = new TypeToken<Map<String, Object>>() {
        }.getType();/*from  w ww.j  a  v  a 2  s  .co m*/
        Map<String, String> jsonMap = gson.fromJson(reader, mapType);
        Snapshot inning = Snapshot.create(jsonMap.get("id"), jsonMap.get("creation_date"),
                jsonMap.get("deletion_date"));
        list.add(inning);
    } else if (reader.peek() == JsonToken.BEGIN_ARRAY) {

        reader.beginArray();
        while (reader.hasNext()) {
            Type mapType = new TypeToken<Map<String, Object>>() {
            }.getType();
            Map<String, String> jsonMap = gson.fromJson(reader, mapType);
            Snapshot inning = Snapshot.create(jsonMap.get("id"), jsonMap.get("creation_date"),
                    jsonMap.get("deletion_date"));
            list.add(inning);
        }
        reader.endArray();
    } else {
        reader.skipValue();
    }
    return (List<T>) list;
}

From source file:org.apache.olingo.odata2.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));
    }//from   w  w w  .j ava2  s  . co m

    JsonToken peek = reader.peek();
    if (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())
                            .isValidatingFacets(readProperties.isValidatingFacets()).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);
                        resultEntry.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);
                        resultEntry.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 if (peek == JsonToken.NULL) {
        reader.nextNull();
    } 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())
                    .isValidatingFacets(readProperties.isValidatingFacets()).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);
            resultEntry.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:org.apache.olingo.odata2.core.ep.consumer.JsonErrorDocumentConsumer.java

License:Apache License

private void parseInnerError(final JsonReader reader, final ODataErrorContext errorContext) throws IOException {
    JsonToken token = reader.peek();/*  w  ww  .  j a  v  a2s .  com*/
    if (token == JsonToken.STRING) {
        // implementation for parse content as provided by JsonErrorDocumentProducer
        String innerError = reader.nextString();
        errorContext.setInnerError(innerError);
    } else if (token == JsonToken.BEGIN_OBJECT) {
        // implementation for OData v2 Section 2.2.8.1.2 JSON Error Response
        // (RFC4627 Section 2.2 -> https://www.ietf.org/rfc/rfc4627.txt))
        // currently partial provided
        errorContext.setInnerError(readJson(reader));
    }
}

From source file:org.apache.olingo.odata2.core.ep.consumer.JsonErrorDocumentConsumer.java

License:Apache License

private String readJson(final JsonReader reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    while (reader.hasNext()) {
        JsonToken token = reader.peek();
        if (token == JsonToken.NAME) {
            if (sb.length() > 0) {
                sb.append(",");
            }/*from  w ww  .  j  a v a2s  .c  om*/
            String name = reader.nextName();
            sb.append("\"").append(name).append("\"").append(":");
        } else if (token == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
            sb.append("{").append(readJson(reader)).append("}");
            reader.endObject();
        } else if (token == JsonToken.BEGIN_ARRAY) {
            reader.beginArray();
            sb.append("[").append(readJson(reader)).append("]");
            reader.endArray();
        } else {
            sb.append("\"").append(reader.nextString()).append("\"");
        }
    }

    return sb.toString();
}

From source file:org.apache.olingo.odata2.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 www. ja  v  a 2s . co  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:org.arl.fjage.remote.ArrayAdapterFactory.java

License:BSD License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isArray())
        return null;
    final Class<?> compType = rawType.getComponentType();
    if (compType == null)
        return null;
    if (!compType.isPrimitive())
        return null;
    if (!compType.equals(byte.class) && !compType.equals(int.class) && !compType.equals(short.class)
            && !compType.equals(long.class) && !compType.equals(float.class) && !compType.equals(double.class))
        return null;
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    return new TypeAdapter<T>() {

        @Override/*from   w  ww. j av a  2 s .  co m*/
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null)
                out.nullValue();
            else {
                byte[] data;
                if (compType.equals(byte.class))
                    data = (byte[]) value;
                else {
                    ByteBuffer buf = null;
                    if (compType.equals(int.class)) {
                        buf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE * ((int[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asIntBuffer().put((int[]) value);
                    } else if (compType.equals(short.class)) {
                        buf = ByteBuffer.allocate(Short.SIZE / Byte.SIZE * ((short[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asShortBuffer().put((short[]) value);
                    } else if (compType.equals(long.class)) {
                        buf = ByteBuffer.allocate(Long.SIZE / Byte.SIZE * ((long[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asLongBuffer().put((long[]) value);
                    } else if (compType.equals(float.class)) {
                        buf = ByteBuffer.allocate(Float.SIZE / Byte.SIZE * ((float[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asFloatBuffer().put((float[]) value);
                    } else if (compType.equals(double.class)) {
                        buf = ByteBuffer.allocate(Double.SIZE / Byte.SIZE * ((double[]) value).length)
                                .order(ByteOrder.LITTLE_ENDIAN);
                        buf.asDoubleBuffer().put((double[]) value);
                    }
                    data = buf.array();
                }
                if (bare)
                    out.value(Base64.getEncoder().encodeToString(data));
                else {
                    out.beginObject();
                    out.name("clazz").value(rawType.getName());
                    out.name("data").value(Base64.getEncoder().encodeToString(data));
                    out.endObject();
                }
            }
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonToken tok = in.peek();
            if (tok == JsonToken.NULL) {
                in.nextNull();
                return null;
            }
            if (tok == JsonToken.STRING)
                return decodeString(in.nextString());
            if (tok == JsonToken.BEGIN_ARRAY)
                return delegate.read(in);
            if (tok != JsonToken.BEGIN_OBJECT)
                return null;
            T rv = null;
            in.beginObject();
            while (in.hasNext()) {
                String name = in.nextName();
                if (name.equals("data"))
                    rv = decodeString(in.nextString());
                else
                    in.skipValue();
            }
            in.endObject();
            return rv;
        }

        private T decodeString(String s) {
            byte[] data = Base64.getDecoder().decode(s);
            if (compType.equals(byte.class))
                return (T) data;
            ByteBuffer buf = ByteBuffer.wrap(data);
            if (compType.equals(int.class)) {
                IntBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asIntBuffer();
                int[] array = new int[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(short.class)) {
                ShortBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asShortBuffer();
                short[] array = new short[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(long.class)) {
                LongBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asLongBuffer();
                long[] array = new long[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(float.class)) {
                FloatBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN)
                        .asFloatBuffer();
                float[] array = new float[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            if (compType.equals(double.class)) {
                DoubleBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s))
                        .order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer();
                double[] array = new double[buf2.limit()];
                buf2.get(array);
                return (T) array;
            }
            return null;
        }

    };
}