List of usage examples for com.google.gson.stream JsonToken END_ARRAY
JsonToken END_ARRAY
To view the source code for com.google.gson.stream JsonToken END_ARRAY.
Click Source Link
From source file:BundleTypeAdapterFactory.java
License:Apache License
@SuppressWarnings("unchecked") @Override/*from w ww .j a v a2 s . c o m*/ public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { if (!Bundle.class.isAssignableFrom(type.getRawType())) { return null; } return (TypeAdapter<T>) new TypeAdapter<Bundle>() { @Override public void write(JsonWriter out, Bundle bundle) throws IOException { if (bundle == null) { out.nullValue(); return; } out.beginObject(); for (String key : bundle.keySet()) { out.name(key); Object value = bundle.get(key); if (value == null) { out.nullValue(); } else { gson.toJson(value, value.getClass(), out); } } out.endObject(); } @Override public Bundle read(JsonReader in) throws IOException { switch (in.peek()) { case NULL: in.nextNull(); return null; case BEGIN_OBJECT: return toBundle(readObject(in)); default: throw new IOException("expecting object: " + in.getPath()); } } private Bundle toBundle(List<Pair<String, Object>> values) throws IOException { Bundle bundle = new Bundle(); for (Pair<String, Object> entry : values) { String key = entry.first; Object value = entry.second; if (value instanceof String) { bundle.putString(key, (String) value); } else if (value instanceof Integer) { bundle.putInt(key, ((Integer) value).intValue()); } else if (value instanceof Long) { bundle.putLong(key, ((Long) value).longValue()); } else if (value instanceof Double) { bundle.putDouble(key, ((Double) value).doubleValue()); } else if (value instanceof Parcelable) { bundle.putParcelable(key, (Parcelable) value); } else if (value instanceof List) { List<Pair<String, Object>> objectValues = (List<Pair<String, Object>>) value; Bundle subBundle = toBundle(objectValues); bundle.putParcelable(key, subBundle); } else { throw new IOException("Unparcelable key, value: " + key + ", " + value); } } return bundle; } private List<Pair<String, Object>> readObject(JsonReader in) throws IOException { List<Pair<String, Object>> object = new ArrayList<Pair<String, Object>>(); in.beginObject(); while (in.peek() != JsonToken.END_OBJECT) { switch (in.peek()) { case NAME: String name = in.nextName(); Object value = readValue(in); object.add(new Pair<String, Object>(name, value)); break; case END_OBJECT: break; default: throw new IOException("expecting object: " + in.getPath()); } } in.endObject(); return object; } private Object readValue(JsonReader in) throws IOException { switch (in.peek()) { case BEGIN_ARRAY: return readArray(in); case BEGIN_OBJECT: return readObject(in); case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; case NUMBER: return readNumber(in); case STRING: return in.nextString(); default: throw new IOException("expecting value: " + in.getPath()); } } private Object readNumber(JsonReader in) throws IOException { double doubleValue = in.nextDouble(); if (doubleValue - Math.ceil(doubleValue) == 0) { long longValue = (long) doubleValue; if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) { return (int) longValue; } return longValue; } return doubleValue; } @SuppressWarnings("rawtypes") private List readArray(JsonReader in) throws IOException { List list = new ArrayList(); in.beginArray(); while (in.peek() != JsonToken.END_ARRAY) { Object element = readValue(in); list.add(element); } in.endArray(); return list; } }; }
From source file:bind.JsonTreeReader.java
License:Apache License
@Override public void endArray() throws IOException { expect(JsonToken.END_ARRAY); popStack(); // empty iterator popStack(); // array }
From source file:bind.JsonTreeReader.java
License:Apache License
@Override public boolean hasNext() throws IOException { JsonToken token = peek();// w ww . j a v a2 s .c o m return token != JsonToken.END_OBJECT && token != JsonToken.END_ARRAY; }
From source file:bind.JsonTreeReader.java
License:Apache License
@Override public JsonToken peek() throws IOException { if (stack.isEmpty()) { return JsonToken.END_DOCUMENT; }//from w ww . j ava 2s . c o m Object o = peekStack(); if (o instanceof Iterator) { Object secondToTop = stack.get(stack.size() - 2); boolean isObject = secondToTop instanceof JsonElement && ((JsonElement) secondToTop).isJsonObject(); Iterator<?> iterator = (Iterator<?>) o; if (iterator.hasNext()) { if (isObject) { return JsonToken.NAME; } else { stack.add(iterator.next()); return peek(); } } else { return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY; } } else if (o instanceof JsonElement) { JsonElement el = (JsonElement) o; if (el.isJsonObject()) { return JsonToken.BEGIN_OBJECT; } else if (el.isJsonArray()) { return JsonToken.BEGIN_ARRAY; } else if (el.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) o; if (primitive.isString()) { return JsonToken.STRING; } else if (primitive.isBoolean()) { return JsonToken.BOOLEAN; } else if (primitive.isNumber()) { return JsonToken.NUMBER; } else { throw new AssertionError(); } } else if (el.isJsonNull()) { return JsonToken.NULL; } throw new AssertionError(); } else if (o == SENTINEL_CLOSED) { throw new IllegalStateException("JsonReader is closed"); } else { throw new AssertionError(); } }
From source file:co.cask.cdap.client.StreamClient.java
License:Apache License
/** * Reads events from a stream//from ww w. ja v a 2s . c o m * * @param streamId ID of the stream * @param start Timestamp in milliseconds or now-xs format to start reading event from (inclusive) * @param end Timestamp in milliseconds or now-xs format for the last event to read (exclusive) * @param limit Maximum number of events to read * @param callback Callback to invoke for each stream event read. If the callback function returns {@code false} * upon invocation, it will stops the reading * @throws IOException If fails to read from stream * @throws StreamNotFoundException If the given stream does not exists */ public void getEvents(Id.Stream streamId, String start, String end, int limit, Function<? super StreamEvent, Boolean> callback) throws IOException, StreamNotFoundException, UnauthenticatedException { long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS); long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS); URL url = config.resolveNamespacedURLV3(streamId.getNamespace(), String .format("streams/%s/events?start=%d&end=%d&limit=%d", streamId.getId(), startTime, endTime, limit)); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); AccessToken accessToken = config.getAccessToken(); if (accessToken != null) { urlConn.setRequestProperty(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getValue()); } if (urlConn instanceof HttpsURLConnection && !config.isVerifySSLCert()) { try { HttpRequests.disableCertCheck((HttpsURLConnection) urlConn); } catch (Exception e) { // TODO: Log "Got exception while disabling SSL certificate check for request.getURL()" } } try { if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthenticatedException("Unauthorized status code received from the server."); } if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new StreamNotFoundException(streamId); } if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return; } // The response is an array of stream event object InputStream inputStream = urlConn.getInputStream(); JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8)); jsonReader.beginArray(); while (jsonReader.peek() != JsonToken.END_ARRAY) { Boolean result = callback.apply(GSON.<StreamEvent>fromJson(jsonReader, StreamEvent.class)); if (result == null || !result) { break; } } drain(inputStream); // No need to close reader, the urlConn.disconnect in finally will close all underlying streams } finally { urlConn.disconnect(); } }
From source file:co.cask.cdap.format.StructuredRecordStringConverter.java
License:Apache License
private static byte[] readBytes(JsonReader reader) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(128); reader.beginArray();/* www. ja v a2 s.c o m*/ while (reader.peek() != JsonToken.END_ARRAY) { os.write(reader.nextInt()); } reader.endArray(); return os.toByteArray(); }
From source file:co.cask.cdap.format.StructuredRecordStringConverter.java
License:Apache License
private static List<Object> readArray(JsonReader reader, Schema elementSchema) throws IOException { List<Object> result = new ArrayList<>(); reader.beginArray();/*from ww w. ja v a 2 s . com*/ while (reader.peek() != JsonToken.END_ARRAY) { result.add(readJson(reader, elementSchema)); } reader.endArray(); return result; }
From source file:co.cask.cdap.internal.io.SchemaTypeAdapter.java
License:Apache License
/** * Constructs {@link Schema.Type#UNION UNION} type schema from the json input. * * @param reader The {@link JsonReader} for streaming json input tokens. * @param knownRecords Set of record name already encountered during the reading. * @return A {@link Schema} of type {@link Schema.Type#UNION UNION}. * @throws IOException When fails to construct a valid schema from the input. *///from w w w .j a v a 2 s . c o m private Schema readUnion(JsonReader reader, Map<String, Schema> knownRecords) throws IOException { List<Schema> unionSchemas = new ArrayList<>(); reader.beginArray(); while (reader.peek() != JsonToken.END_ARRAY) { unionSchemas.add(read(reader, knownRecords)); } reader.endArray(); return Schema.unionOf(unionSchemas); }
From source file:co.cask.cdap.internal.io.SchemaTypeAdapter.java
License:Apache License
/** * Constructs {@link Schema.Type#ENUM ENUM} type schema from the json input. * * @param reader The {@link JsonReader} for streaming json input tokens. * @return A {@link Schema} of type {@link Schema.Type#ENUM ENUM}. * @throws IOException When fails to construct a valid schema from the input. *//*from w w w. j a v a2 s . c om*/ private Schema readEnum(JsonReader reader) throws IOException { if (!"symbols".equals(reader.nextName())) { throw new IOException("Property \"symbols\" missing for enum."); } List<String> enumValues = new ArrayList<>(); reader.beginArray(); while (reader.peek() != JsonToken.END_ARRAY) { enumValues.add(reader.nextString()); } reader.endArray(); return Schema.enumWith(enumValues); }
From source file:co.cask.cdap.internal.io.SchemaTypeAdapter.java
License:Apache License
/** * Constructs {@link Schema.Type#RECORD RECORD} type schema from the json input. * * @param reader The {@link JsonReader} for streaming json input tokens. * @param knownRecords Set of record name already encountered during the reading. * @return A {@link Schema} of type {@link Schema.Type#RECORD RECORD}. * @throws IOException When fails to construct a valid schema from the input. *//* w ww.j av a 2 s . com*/ private Schema readRecord(JsonReader reader, Map<String, Schema> knownRecords) throws IOException { if (!"name".equals(reader.nextName())) { throw new IOException("Property \"name\" missing for record."); } String recordName = reader.nextString(); // Read in fields schemas if (!"fields".equals(reader.nextName())) { throw new IOException("Property \"fields\" missing for record."); } /* put a null schema schema is null and in the map if this is a recursive reference. for example, if we are looking at the outer 'node' reference in the example below, when we get to the inner 'node' reference, we need some way to know that its a record type and not a Schema.Type. { "type": "record", "name": "node", "fields": [{ "name": "children", "type": [{ "type": "array", "items": ["node", "null"] }, "null"] }, { "name": "data", "type": "int" }] } the full schema will be put in at the end of this method */ knownRecords.put(recordName, null); List<Schema.Field> fieldBuilder = new ArrayList<>(); reader.beginArray(); while (reader.peek() != JsonToken.END_ARRAY) { reader.beginObject(); if (!"name".equals(reader.nextName())) { throw new IOException("Property \"name\" missing for record field."); } String fieldName = reader.nextString(); fieldBuilder.add(Schema.Field.of(fieldName, readInnerSchema(reader, "type", knownRecords))); reader.endObject(); } reader.endArray(); Schema schema = Schema.recordOf(recordName, fieldBuilder); knownRecords.put(recordName, schema); return schema; }