List of usage examples for com.google.gson.stream JsonReader hasNext
public boolean hasNext() throws IOException
From source file:com.sap.core.odata.core.ep.consumer.JsonPropertyConsumer.java
License:Apache License
@SuppressWarnings("unchecked") private Object readComplexProperty(final JsonReader reader, final EntityComplexPropertyInfo complexPropertyInfo, final Object typeMapping) throws EdmException, EntityProviderException, IOException { if (reader.peek().equals(JsonToken.NULL)) { reader.nextNull();//w w w . j ava2s . co m if (complexPropertyInfo.isMandatory()) { throw new EntityProviderException( EntityProviderException.INVALID_PROPERTY_VALUE.addContent(complexPropertyInfo.getName())); } return null; } reader.beginObject(); Map<String, Object> data = new HashMap<String, Object>(); Map<String, Object> mapping; if (typeMapping != null) { if (typeMapping instanceof Map) { mapping = (Map<String, Object>) typeMapping; } else { throw new EntityProviderException( EntityProviderException.INVALID_MAPPING.addContent(complexPropertyInfo.getName())); } } else { mapping = new HashMap<String, Object>(); } while (reader.hasNext()) { String childName = reader.nextName(); if (FormatJson.METADATA.equals(childName)) { reader.beginObject(); childName = reader.nextName(); if (!FormatJson.TYPE.equals(childName)) { throw new EntityProviderException(EntityProviderException.MISSING_ATTRIBUTE .addContent(FormatJson.TYPE).addContent(FormatJson.METADATA)); } String actualTypeName = reader.nextString(); String expectedTypeName = complexPropertyInfo.getType().getNamespace() + Edm.DELIMITER + complexPropertyInfo.getType().getName(); if (!expectedTypeName.equals(actualTypeName)) { throw new EntityProviderException(EntityProviderException.INVALID_ENTITYTYPE .addContent(expectedTypeName).addContent(actualTypeName)); } reader.endObject(); } else { EntityPropertyInfo childPropertyInfo = complexPropertyInfo.getPropertyInfo(childName); if (childPropertyInfo == null) { throw new EntityProviderException( EntityProviderException.INVALID_PROPERTY.addContent(childName)); } Object childData = readPropertyValue(reader, childPropertyInfo, mapping.get(childName)); if (data.containsKey(childName)) { throw new EntityProviderException( EntityProviderException.DOUBLE_PROPERTY.addContent(childName)); } data.put(childName, childData); } } reader.endObject(); return data; }
From source file:com.sap.core.odata.core.ep.consumer.JsonServiceDocumentConsumer.java
License:Apache License
private void readEntitySets(final JsonReader reader) throws IOException, EntityProviderException, EdmException { while (reader.hasNext()) { currentHandledObjectName = reader.nextString(); if (currentHandledObjectName != null) { // Looking for the last dot: "\\.(?=[^.]+$)" String[] names = currentHandledObjectName .split("\\" + Edm.DELIMITER + "(?=[^" + Edm.DELIMITER + "]+$)"); if (names.length == 1) { EntitySet entitySet = new EntitySet().setName(names[0]); EntityContainerInfo container = new EntityContainerInfo().setDefaultEntityContainer(true); EdmEntitySetInfo entitySetInfo = new EdmEntitySetInfoImplProv(entitySet, container); entitySets.add(entitySetInfo); } else { EntitySet entitySet = new EntitySet().setName(names[1]); EntityContainerInfo container = new EntityContainerInfo().setName(names[0]) .setDefaultEntityContainer(false); EdmEntitySetInfo entitySetInfo = new EdmEntitySetInfoImplProv(entitySet, container); entitySets.add(entitySetInfo); }/* ww w. j a va2s . c o m*/ } } }
From source file:com.solidfire.jsvcgen.serialization.ApiServerExceptionTypeAdapter.java
License:Open Source License
/** * {@inheritDoc}/*from ww w.j a va2 s . c om*/ */ @Override public ApiServerException read(JsonReader in) throws IOException { String name = null; String code = null; String message = null; in.beginObject(); while (in.hasNext()) { if (in.peek() != JsonToken.NAME) { in.skipValue(); continue; } switch (in.nextName()) { case "name": name = in.nextString(); break; case "code": code = in.nextString(); break; case "message": message = in.nextString(); break; } } in.endObject(); return new ApiServerException(name, code, message); }
From source file:com.suny.whereami.service.google.Place.java
License:Open Source License
/** * Read fields from a result object./* w ww . j a v a 2 s . c o m*/ * * @param fields * to read or 0 if all fields should be read * @param maxResults * maximum number of reviews, events, and photos to return */ Place(JsonReader in, int fields, int maxResults) throws IOException { in.beginObject(); while (in.hasNext()) { Key key = Key.get(in.nextName()); if (key == UNKNOWN || fields != 0 && key.mField != null && !key.mField.in(fields)) { /* unknown field or caller doesn't want it */ in.skipValue(); continue; } switch (key) { case id: mId = in.nextString(); break; case reference: mReference = in.nextString(); break; case icon: mIcon = in.nextString(); break; case url: mUrl = in.nextString(); break; case geometry: in.beginObject(); while (in.hasNext()) { if (in.nextName().equals("location")) { in.beginObject(); while (in.hasNext()) { switch (Key.get(in.nextName())) { case lat: mLat = in.nextDouble(); break; case lng: mLong = in.nextDouble(); break; default: in.skipValue(); } } in.endObject(); } else { in.skipValue(); // "viewport" } } in.endObject(); break; case name: mName = in.nextString(); break; case address_components: mAddress = new Address(in); break; case formatted_address: mFmtAddress = in.nextString(); break; case vicinity: mVicinity = in.nextString(); break; case international_phone_number: mIntlPhone = in.nextString(); break; case formatted_phone_number: mFmtPhone = in.nextString(); break; case website: mWebsite = in.nextString(); break; case types: types(in); break; case price_level: mPrice = in.nextInt(); break; case rating: mRating = (float) in.nextDouble(); break; case reviews: in.beginArray(); while (in.hasNext()) { if (mReviews == null) { int cap = Math.min(Math.max(0, maxResults), MAX_REVIEWS); mReviews = new ArrayList<Review>(cap > 0 ? cap : MAX_REVIEWS); } if (maxResults <= 0 || mReviews.size() < maxResults) { mReviews.add(new Review(in)); } else { in.skipValue(); } } in.endArray(); break; case opening_hours: in.beginObject(); while (in.hasNext()) { switch (Key.get(in.nextName())) { case open_now: mOpen = in.nextBoolean(); break; case periods: in.beginArray(); while (in.hasNext()) { if (mOpenHours == null) { mOpenHours = new ArrayList<OpeningHours>(); } mOpenHours.add(new OpeningHours(in)); } in.endArray(); break; default: in.skipValue(); } } in.endObject(); break; case events: in.beginArray(); while (in.hasNext()) { if (mEvents == null) { int cap = Math.min(Math.max(0, maxResults), MAX_EVENTS); mEvents = new ArrayList<Event>(cap > 0 ? cap : MAX_EVENTS); } if (maxResults <= 0 || mEvents.size() < maxResults) { mEvents.add(new Event(in)); } else { in.skipValue(); } } in.endArray(); break; case utc_offset: mUtcOffset = in.nextInt(); break; case photos: in.beginArray(); while (in.hasNext()) { if (mPhotos == null) { int cap = Math.min(Math.max(0, maxResults), MAX_PHOTOS); mPhotos = new ArrayList<Photo>(cap > 0 ? cap : MAX_PHOTOS); } if (maxResults <= 0 || mPhotos.size() < maxResults) { mPhotos.add(new Photo(in)); } else { in.skipValue(); } } in.endArray(); break; default: in.skipValue(); } } in.endObject(); }
From source file:com.suny.whereami.service.google.Place.java
License:Open Source License
/** * Read field values from a types array. *//*from w w w . j av a 2 s .c om*/ void types(JsonReader in) throws IOException { in.beginArray(); while (in.hasNext()) { if (mTypes == null) { mTypes = new ArrayList<String>(); } mTypes.add(in.nextString()); } in.endArray(); }
From source file:com.tapchatapp.android.client.TapchatService.java
License:Apache License
private void oobInclude(String path) throws Exception { mLoadingOobBacklog = true;/*from w w w . j a v a 2s . c om*/ Response response = mAPI.oobInclude(path.substring(1)); JsonReader reader = new JsonReader(new InputStreamReader(response.getBody().in())); reader.beginArray(); while (reader.hasNext()) { Message message = mGson.fromJson(reader, Message.class); handleMessage(message); } reader.endArray(); reader.close(); mLoadingOobBacklog = false; handleMessageCache(); }
From source file:com.teotigraphix.caustk.tone.ToneUtils.java
License:Apache License
/** * Reads and returns the {@link ToneType} from the JSON data. * // w ww . ja v a2 s .c om * @param data Valid serialized Tone data. * @throws IOException */ public static ToneType readToneType(String data) throws IOException { JsonReader reader = new JsonReader(new StringReader(data)); String type = null; try { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("toneType")) { type = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); } finally { reader.close(); } if (type != null) return ToneType.valueOf(type); return null; }
From source file:com.trellmor.berrymotes.sync.SubredditEmoteDownloader.java
License:Open Source License
private List<EmoteImage> downloadEmoteList() throws URISyntaxException, IOException, InterruptedException { checkInterrupted();// www . j a va2s. c o m Log.debug("Downloading " + mSubreddit + EMOTES); HttpRequestBase request = new HttpGet(); request.setURI(new URI(EmoteDownloader.HOST + mSubreddit + EMOTES)); request.setHeader("If-Modified-Since", DateUtils.formatDate(mLastModified)); mEmoteDownloader.checkCanDownload(); HttpResponse response = mEmoteDownloader.getHttpClient().execute(request); switch (response.getStatusLine().getStatusCode()) { case 200: Log.debug(mSubreddit + EMOTES + " loaded"); // Download ok Header[] lastModified = response.getHeaders("last-modified"); if (lastModified.length > 0) { try { mLastModified = DateUtils.parseDate(lastModified[0].getValue()); } catch (DateParseException e) { Log.error("Error parsing last-modified header", e); } } HttpEntity entity = response.getEntity(); if (entity != null) { checkInterrupted(); File tmpFile = File.createTempFile(mSubreddit, null, mContext.getCacheDir()); try { InputStream is = entity.getContent(); try { mEmoteDownloader.checkStorageAvailable(); StreamUtils.saveStreamToFile(is, tmpFile); } finally { StreamUtils.closeStream(is); } FileInputStream fis = null; BufferedInputStream bis = null; GZIPInputStream zis = null; Reader isr = null; JsonReader jsonReader = null; checkInterrupted(); try { fis = new FileInputStream(tmpFile); bis = new BufferedInputStream(fis); zis = new GZIPInputStream(bis); isr = new InputStreamReader(zis, "UTF-8"); jsonReader = new JsonReader(isr); jsonReader.beginArray(); Gson gson = new Gson(); ArrayList<EmoteImage> emotes = new ArrayList<EmoteImage>(); while (jsonReader.hasNext()) { EmoteImage emote = gson.fromJson(jsonReader, EmoteImage.class); emotes.add(emote); } jsonReader.endArray(); Log.info("Loaded " + mSubreddit + EMOTES + ", size: " + Integer.toString(emotes.size())); return emotes; } finally { StreamUtils.closeStream(jsonReader); StreamUtils.closeStream(isr); StreamUtils.closeStream(zis); StreamUtils.closeStream(bis); StreamUtils.closeStream(fis); } } finally { tmpFile.delete(); } } break; case 304: Log.info(mSubreddit + EMOTES + " already up to date (HTTP 304)"); break; case 403: case 404: Log.info(mSubreddit + " missing on server, removing emotes"); mEmoteDownloader.deleteSubreddit(mSubreddit, mContentResolver); break; default: throw new IOException("Unexpected HTTP response: " + response.getStatusLine().getReasonPhrase()); } return null; }
From source file:com.triarc.sync.SyncAdapter.java
License:Apache License
@SuppressLint("NewApi") private void readResponse(SyncTypeCollection typeCollection, InputStream inputStream, HttpResponse response) throws UnsupportedEncodingException, IOException, JSONException, Exception { long lastUpdate = 0; Header header = response.getFirstHeader("X-Application-Timestamp"); if (header != null) { String value = header.getValue(); lastUpdate = Long.parseLong(value); }/*from ww w . j av a 2 s . c o m*/ // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); JsonStreamParser parser = new JsonStreamParser(reader); JsonReader jsonReader = new JsonReader(reader); jsonReader.beginObject(); jsonReader.nextName(); jsonReader.beginObject(); while (jsonReader.hasNext()) { String syncName = jsonReader.nextName(); SyncType syncType = this.GetSyncType(typeCollection, syncName); JsonElement fromJson = new Gson().fromJson(jsonReader, JsonElement.class); updateLocalTypeData(fromJson.getAsJsonObject(), syncType, typeCollection, syncResult); notificationQueue.add(new SyncNotificationMessage(syncType, fromJson.toString())); // String path = jsonReader.getPath(); // String nextName = jsonReader.nextName(); // jsonReader.endObject(); } jsonReader.endObject(); // String json = getStringForReader(reader); // // // JSONObject syncChangeSets = new JSONObject(json) // .getJSONObject("changeSetPerType"); // // // first save all // for (SyncType syncType : typeCollection.getTypes()) { // syncResult.madeSomeProgress(); // String name = syncType.getName(); // // if (syncChangeSets.has(name)) { // JSONObject changeSetObject = syncChangeSets.getJSONObject(name); // updateLocalTypeData(changeSetObject, syncType, typeCollection, // syncResult); // notificationMap.put(syncType, changeSetObject); // } else { // Log.w(TAG, "Server does not support syncing of " + name); // sendLogs(); // } // } // store collection update timestamp PreferenceManager.getDefaultSharedPreferences(this.getContext()).edit() .putLong(typeCollection.getName(), lastUpdate).commit(); // then notify all notifyWebApp(); }
From source file:com.utad.flume.interceptor.InterceptorTwitter.java
License:Apache License
private byte[] readJsonStream(InputStream is) { byte[] body = null; try {/*from ww w . j a v a2 s . c o m*/ JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8")); try { long id = 0L; String text = null; String userName = null; String userScreenName = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("id")) { id = reader.nextLong(); } else if (name.equals("text")) { text = reader.nextString(); } else if (name.equals("user")) { reader.beginObject(); while (reader.hasNext()) { name = reader.nextName(); if (name.equals("name")) { userName = reader.nextString(); } else if (name.equals("screen_name")) { userScreenName = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); } else { reader.skipValue(); } } reader.endObject(); StringBuilder builder = new StringBuilder("ID:"); builder.append(id); builder.append("||"); if (outputText) { builder.append("TEXT:").append(text).append("||"); } if (outputUserName) { builder.append("USER:").append(userName).append("||"); } if (outputUserScreenName) { builder.append("SCREEN:").append(userScreenName).append("||"); } logger.debug("id: {}", id); logger.debug("text: {}", text); logger.debug("username: {}", userName); logger.debug("screenName: {}", userScreenName); body = builder.toString().getBytes("UTF-8"); } finally { reader.close(); } } catch (UnsupportedEncodingException e) { logger.error("UTF-8 is not supported on this runtime", e); } catch (IOException e) { logger.error("Caught an IOException", e); } return body; }