List of usage examples for com.google.gson JsonArray iterator
public Iterator<JsonElement> iterator()
From source file:imapi.OnlineDatabaseActions.java
License:Apache License
private int readJsonStartingUriAndValuePairs(InputStream inputStream, String startingUriName, String valueName, boolean checkForLang, Vector<DataRecord[]> returnVals) { try {/*from w ww.ja v a2 s . c o m*/ JsonReader rdr = new JsonReader(new InputStreamReader(inputStream)); JsonParser parser = new JsonParser(); JsonElement jElement = parser.parse(rdr); if (jElement.isJsonObject() == false) { showContentsOfInputStream(inputStream); return ApiConstants.IMAPIFailCode; } // read head/vars from json in order to get the names of the // select clause in the order that they were declared. // Store in headVarNames vector Vector<String> headVarNames = new Vector<String>(); JsonObject jRootObject = jElement.getAsJsonObject(); JsonArray jHeadVarsArray = jRootObject.get("head").getAsJsonObject().get("vars").getAsJsonArray(); Iterator<JsonElement> jVarsIter = jHeadVarsArray.iterator(); while (jVarsIter.hasNext()) { JsonElement jVarElement = jVarsIter.next(); if (jVarElement.isJsonPrimitive()) { headVarNames.add(jVarElement.getAsString()); } } if (jRootObject.has("results") == false || jRootObject.get("results").getAsJsonObject().has("bindings") == false) { return ApiConstants.IMAPIFailCode; } // loop over all json bindings JsonArray jBindingsArray = jRootObject.get("results").getAsJsonObject().get("bindings") .getAsJsonArray(); Iterator<JsonElement> jBindingsIter = jBindingsArray.iterator(); while (jBindingsIter.hasNext()) { // of the binding DataRecord start = null; DataRecord end = null; JsonElement jBindingElement = jBindingsIter.next(); if (jBindingElement.isJsonObject() == false) { continue; } JsonObject jBindingObject = jBindingElement.getAsJsonObject(); for (int k = 0; k < headVarNames.size(); k++) { String currentPropertyName = headVarNames.get(k); if (jBindingObject.has(currentPropertyName)) { JsonObject jObj = jBindingObject.get(currentPropertyName).getAsJsonObject(); String valStr = ""; String langStr = ""; if (jObj.has("value")) { valStr = jObj.get("value").getAsString(); } if (checkForLang) { //read lang if type is literal if (jObj.has("xml:lang")) { langStr = jObj.get("xml:lang").getAsString(); } } if (valStr == null || valStr.trim().length() == 0) { continue; } if (currentPropertyName.equals(startingUriName)) { start = new DataRecord(valStr, ""); } if (currentPropertyName.equals(valueName)) { end = new DataRecord(valStr, langStr); } } } if (start != null && end != null) { DataRecord[] newVal = { start, end }; returnVals.add(newVal); } // end of asking for all predicates of select clause head/vars names } // edn of while llop that iters across all bindings } catch (Exception ex) { Utilities.handleException(ex); return ApiConstants.IMAPIFailCode; } return ApiConstants.IMAPISuccessCode; }
From source file:io.kodokojo.bdd.stage.ApplicationThen.java
License:Open Source License
private void getUserDetails(String username, boolean complete) { OkHttpClient httpClient = new OkHttpClient(); UserInfo requesterUserInfo = currentUsers.get(currentUserLogin); UserInfo targetUserInfo = currentUsers.get(username); String url = getApiBaseUrl() + "/user"; if (!requesterUserInfo.getIdentifier().equals(targetUserInfo.getIdentifier())) { url += "/" + targetUserInfo.getIdentifier(); }//from www . jav a 2 s . c o m Request.Builder builder = new Request.Builder().get().url(url); Request request = HttpUserSupport.addBasicAuthentification(requesterUserInfo, builder).build(); Response response = null; try { response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); JsonParser parser = new JsonParser(); String body = response.body().string(); JsonObject json = (JsonObject) parser.parse(body); assertThat(json.getAsJsonPrimitive("name").getAsString()).isNotEmpty(); if (complete) { assertThat(json.getAsJsonPrimitive("password").getAsString()).isNotEmpty(); assertThat(json.getAsJsonPrimitive("email").getAsString()).isNotEmpty(); assertThat(json.getAsJsonPrimitive("sshPublicKey").getAsString()).isNotEmpty(); } else { assertThat(json.getAsJsonPrimitive("password").getAsString()).isEmpty(); } if (StringUtils.isNotBlank(projectConfigurationId)) { assertThat(json.has("projectConfigurationIds")); JsonArray projectConfigurationIds = json.getAsJsonArray("projectConfigurationIds"); assertThat(projectConfigurationIds).isNotEmpty(); boolean foundCurrentProjectConfigurationId = false; Iterator<JsonElement> projectConfigIt = projectConfigurationIds.iterator(); while (projectConfigIt.hasNext()) { JsonObject projectConfig = (JsonObject) projectConfigIt.next(); assertThat(projectConfig.has("projectConfigurationId")); foundCurrentProjectConfigurationId = projectConfigurationId .equals(projectConfig.getAsJsonPrimitive("projectConfigurationId").getAsString()); } assertThat(foundCurrentProjectConfigurationId).isTrue(); } } catch (IOException e) { fail("Unable to get User details on Url " + url, e); } finally { if (response != null) { try { response.body().close(); } catch (IOException e) { fail("Fail to close Http response.", e); } } } }
From source file:io.kodokojo.bdd.stage.ApplicationThen.java
License:Open Source License
private ProjectConfigDto getProjectConfigurationFromCurrentProjectConfigId() { OkHttpClient httpClient = new OkHttpClient(); UserInfo requesterUserInfo = currentUsers.get(currentUserLogin); Request.Builder builder = new Request.Builder() .url(getApiBaseUrl() + "/projectconfig/" + projectConfigurationId).get(); Request request = HttpUserSupport.addBasicAuthentification(requesterUserInfo, builder).build(); Response response = null;/*w w w. j av a 2 s .c o m*/ try { response = httpClient.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); String bodyResponse = response.body().string(); Gson gson = new GsonBuilder().create(); ProjectConfigDto projectConfigDto = gson.fromJson(bodyResponse, ProjectConfigDto.class); assertThat(projectConfigDto).isNotNull(); assertThat(projectConfigDto.getAdmins().get(0).getUsername()) .isEqualTo(requesterUserInfo.getUsername()); assertThat(projectConfigDto.getUsers()).isNotEmpty(); assertThat(projectConfigDto.getStackConfigs()).isNotEmpty(); JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(bodyResponse); assertThat(json.has("name")).isTrue(); assertThat(json.has("identifier")).isTrue(); assertThat(json.has("admins")).isTrue(); JsonArray admins = json.getAsJsonArray("admins"); assertThat(admins).isNotEmpty(); jsonUserAreValid(admins.iterator()); JsonArray users = json.getAsJsonArray("users"); jsonUserAreValid(users.iterator()); assertThat(users).isNotEmpty(); JsonArray stackConfigs = json.getAsJsonArray("stackConfigs"); assertThat(stackConfigs).isNotEmpty(); Iterator<JsonElement> stackConfigurationIt = stackConfigs.iterator(); while (stackConfigurationIt.hasNext()) { JsonObject stackConf = (JsonObject) stackConfigurationIt.next(); jsonStackConfigIsValid(stackConf); } return projectConfigDto; } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { closeQuietly(response.body()); } } return null; }
From source file:io.kodokojo.bdd.stage.ApplicationThen.java
License:Open Source License
private void jsonStackConfigIsValid(JsonObject stackConf) { assertThat(stackConf.has("name")).isTrue(); assertThat(stackConf.has("type")).isTrue(); JsonArray brickConfigs = stackConf.getAsJsonArray("brickConfigs"); assertThat(brickConfigs).isNotEmpty(); Iterator<JsonElement> brickConfigIt = brickConfigs.iterator(); while (brickConfigIt.hasNext()) { JsonObject brickConfig = (JsonObject) brickConfigIt.next(); jsonBrickIsValid(brickConfig);//from w w w. ja va2 s. c om } }
From source file:io.openvidu.client.OpenViduClient.java
License:Apache License
public Map<String, List<String>> joinRoom(String roomName, String userName) throws IOException { JsonObject params = new JsonObject(); params.addProperty(JOINROOM_ROOM_PARAM, roomName); params.addProperty(JOINROOM_USER_PARAM, userName); JsonElement result = client.sendRequest(JOINROOM_METHOD, params); Map<String, List<String>> peers = new HashMap<String, List<String>>(); JsonArray jsonPeers = JsonRoomUtils.getResponseProperty(result, "value", JsonArray.class); if (jsonPeers.size() > 0) { Iterator<JsonElement> peerIt = jsonPeers.iterator(); while (peerIt.hasNext()) { JsonElement peer = peerIt.next(); String peerId = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERID_PARAM, String.class); List<String> streams = new ArrayList<String>(); JsonArray jsonStreams = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERSTREAMS_PARAM, JsonArray.class, true); if (jsonStreams != null) { Iterator<JsonElement> streamIt = jsonStreams.iterator(); while (streamIt.hasNext()) { streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(), JOINROOM_PEERSTREAMID_PARAM, String.class)); }//from ww w . jav a2 s . co m } peers.put(peerId, streams); } } return peers; }
From source file:io.openvidu.client.ServerJsonRpcHandler.java
License:Apache License
private Notification participantPublished(Transaction transaction, Request<JsonObject> request) { String id = JsonRoomUtils.getRequestParam(request, ProtocolElements.PARTICIPANTPUBLISHED_USER_PARAM, String.class); JsonArray jsonStreams = JsonRoomUtils.getRequestParam(request, ProtocolElements.PARTICIPANTPUBLISHED_STREAMS_PARAM, JsonArray.class); Iterator<JsonElement> streamIt = jsonStreams.iterator(); List<String> streams = new ArrayList<String>(); while (streamIt.hasNext()) { streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(), ProtocolElements.PARTICIPANTPUBLISHED_STREAMID_PARAM, String.class)); }//w w w .j av a 2 s. c o m ParticipantPublishedInfo eventInfo = new ParticipantPublishedInfo(id, streams); log.debug("Recvd published event {}", eventInfo); return eventInfo; }
From source file:io.openvidu.server.kurento.core.KurentoTokenOptions.java
License:Apache License
public KurentoTokenOptions(JsonObject options) { if (options.has("videoMaxRecvBandwidth")) { this.videoMaxRecvBandwidth = options.get("videoMaxRecvBandwidth").getAsInt(); }//from w ww.ja v a2 s.c o m if (options.has("videoMinRecvBandwidth")) { this.videoMinRecvBandwidth = options.get("videoMinRecvBandwidth").getAsInt(); } if (options.has("videoMaxSendBandwidth")) { this.videoMaxSendBandwidth = options.get("videoMaxSendBandwidth").getAsInt(); } if (options.has("videoMinSendBandwidth")) { this.videoMinSendBandwidth = options.get("videoMinSendBandwidth").getAsInt(); } if (options.has("allowedFilters")) { JsonArray filters = options.get("allowedFilters").getAsJsonArray(); Iterator<JsonElement> it = filters.iterator(); while (it.hasNext()) { this.allowedFilters.put(it.next().getAsString(), true); } } }
From source file:io.urmia.md.model.job.JobDefinition.java
License:Open Source License
public JobDefinition(JsonElement root) { JsonObject rootObj = root.getAsJsonObject(); JsonArray phasesArray = rootObj.get("phases").getAsJsonArray(); Iterator<JsonElement> phasesIterator = phasesArray.iterator(); ImmutableList.Builder<Phase> b = ImmutableList.builder(); while (phasesIterator.hasNext()) b.add(new Phase(phasesIterator.next())); this.phases = b.build(); this.owner = rootObj.get("owner").getAsString(); this.json = root; }
From source file:javaeetutorial.web.websocketbot.decoders.NBADecoder.java
public List<NBA> decode(String string) { List<NBA> list = new ArrayList<NBA>(); Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonElement jsonEl = parser.parse(string); JsonObject jsonObject = null;//from w w w . j a v a2 s . c om jsonObject = jsonEl.getAsJsonObject(); String reason = jsonObject.get("reason").getAsString(); if (reason.equals("successed!")) { JsonElement resultElement = jsonObject.get("result"); if (resultElement.isJsonArray()) { JsonArray jsonArray = resultElement.getAsjsonArray(); NBA nba; for (Iterator iter = jsonArray.iterator(); iter.hasNext();) { JsonObject obj = (JsonObject) iter.next(); nba = new NBA(); nba = gson.formJson(obj, NBA.class); list.add(nba); } } return list; } else { return null; } }
From source file:jmm.api.tmdb.TMDBMovieWrapper.java
License:Open Source License
/** * Get the basic movie information for a specific movie id. <br/> * <b>Bold</b> parameters are <b>required</b>. * /* w ww . j a v a2s . c o m*/ * @param id <b>the movie id</b> * @param language ISO 639-1 code. * @param append_to_response Comma separated, any movie method * @return the movie wth the given id <br/>null, if no movie was found with the given id */ public TMDBVideoFile findMovie(String id, String language, String append_to_response) { paramsMap.clear(); //requiered parameters if (id == null) { throw new NullPointerException("Param: " + "id" + "must not be null"); } //optional parameters if (language != null) { paramsMap.put(PARAM_LANGUAGE, language); } if (append_to_response != null) { paramsMap.put(PARAM_APPEND, append_to_response); } String url = buildUrl(API_MOVIE + "/" + id); JsonElement element = callAPI(url); //handle response TMDBVideoFile searchResult = null; if (!element.isJsonNull()) { String title = element.getAsJsonObject().get("title").getAsString(); searchResult = new TMDBVideoFile(title); JsonElement value; value = element.getAsJsonObject().get("adult"); if (!value.isJsonNull()) { searchResult.setAdult(value.getAsBoolean()); if (searchResult.isAdult()) { searchResult.setFsk(VideoFile.FSK.FSK_18); } } value = element.getAsJsonObject().get("backdrop_path"); if (!value.isJsonNull()) { searchResult.setBackdropPath(API_BASE_IMAGEURL + Backdrop_Sizes.w780 + value.getAsString()); } //genres value = element.getAsJsonObject().get("genres"); if (!value.isJsonNull()) { JsonArray genres = value.getAsJsonArray(); if (genres.isJsonArray()) { Iterator<JsonElement> genresIterator = genres.iterator(); while (genresIterator.hasNext()) { JsonElement genreElement = genresIterator.next(); value = genreElement.getAsJsonObject().get("id"); if (!value.isJsonNull()) { int genreID = value.getAsInt(); Genre genre = Genre.getGenreByTMDBID(genreID); if (genre != null) { searchResult.addGenreKey(genre.getGenreKey()); } else { value = genreElement.getAsJsonObject().get("name"); String exceptionString; if (!value.isJsonNull()) { exceptionString = "Missing genre in resource bundle: " + value.getAsString() + " " + genreID; } else { exceptionString = "Missing genre in resource bundle: " + genreID; } LOG.warn(exceptionString); } } // value = genreElement.getAsJsonObject().get("name"); // if(!value.isJsonNull()){ // String localizedGenre = value.getAsString(); // String genreKey = LocaleManager.getInstance().determineGenreKeyByLocale(localizedGenre); // if(genreKey == null){ // MyExceptionHandler.uncaughtExceptionLogger.warning("Missing genre in resource bundle: " + localizedGenre); // }else{ // searchResult.addGenre(genreKey); // } // } } } } value = element.getAsJsonObject().get("id"); if (!value.isJsonNull()) { searchResult.setTmdbID(value.getAsString()); } value = element.getAsJsonObject().get("imdb_id"); if (!value.isJsonNull()) { searchResult.setImdbID(value.getAsString()); } value = element.getAsJsonObject().get("original_title"); if (!value.isJsonNull()) { searchResult.setOriginalTitle(value.getAsString()); } value = element.getAsJsonObject().get("overview"); if (!value.isJsonNull()) { searchResult.setDescription(value.getAsString()); } value = element.getAsJsonObject().get("poster_path"); if (!value.isJsonNull()) { searchResult.setImagePath(API_BASE_IMAGEURL + Poster_Sizes.w342 + value.getAsString()); } //Publisher value = element.getAsJsonObject().get("production_companies"); if (!value.isJsonNull()) { JsonArray publishers = value.getAsJsonArray(); if (publishers.isJsonArray()) { Iterator<JsonElement> publishersIterator = publishers.iterator(); while (publishersIterator.hasNext()) { //Set only the first publisher JsonElement publisherElement = publishersIterator.next(); value = publisherElement.getAsJsonObject().get("name"); if (!value.isJsonNull()) { String publisher = value.getAsString(); searchResult.setPublisher(publisher); break; } } } } value = element.getAsJsonObject().get("runtime"); if (!value.isJsonNull()) { searchResult.setPlaytime(value.getAsInt()); } value = element.getAsJsonObject().get("vote_average"); if (!value.isJsonNull()) { searchResult.setTmdbRating(value.getAsDouble()); searchResult.setOnlineRating(value.getAsDouble()); } //release date value = element.getAsJsonObject().get("release_date"); if (!value.isJsonNull()) { String rlsDateString = value.getAsString(); try { Date date = new SimpleDateFormat("yyyy-mm-dd").parse(rlsDateString); searchResult.setReleaseDate(date); String releaseYear = new SimpleDateFormat("yyyy").format(date); if (!releaseYear.isEmpty()) { searchResult.setReleaseYear(Integer.valueOf(releaseYear)); } } catch (ParseException | NumberFormatException ex) { LOG.warn("Release Year " + rlsDateString + "cannot be parsed into a valid format for title: " + title + ".", ex); searchResult.setReleaseYear(0); } } //{"adult":false,"backdrop_path":"/eZxahf9ATsv3oQPtvZPqSZkAO7V.jpg","belongs_to_collection":{"id":1241,"name":"Harry Potter Collection", //"poster_path":"/fuWOg0iLKPRGTlg7lq4tWDBt5tu.jpg","backdrop_path":"/tpDcuXZGqEoU6CxuJ7e4S2NTIoS.jpg"},"budget":250000000, //"genres":[{"id":12,"name":"Abenteuer"},{"id":18,"name":"Drama"},{"id":14,"name":"Fantasy"},{"id":10751,"name":"Familie"}], //"homepage":"http://harrypotter.warnerbros.de/hp7a/","id":12444,"imdb_id":"tt0926084","original_title":"Harry Potter and the Deathly Hallows: Part 1", //"overview":"Harry sieht sich einer vollkommen vernderten Welt gegenber. Die Todesesser haben das Zauberministerium unter ihre Kontrolle gebracht und es tobt ein offener Kampf zwischen den Mchten des Guten und Bsen. Harry hat sich mit Hermine (Emma Watson) und Ron (Rupert Grint) auf die Suche nach den Horkuxen, magischen Objekten, die die Unsterblichkeit von Lord Voldemort (Ralph Fiennes) garantieren und zerstrt werden mssen. Der dunkle Lord hat seinerseits ein Kopfgeld auf Harry ausgesetzt, dener will sich das Vergngen den Jungen der lebte mit den eigenen Hnden zu tten, nicht nehmen lassen. Unterdessen stt Harry auf die Legende von den Heiligtmern des Todes, die ihm im Kampf gegen seinen Erzfeind das Leben retten knnte. Und so strebt alles unaufhaltsam der finalen Konfrontation zwischen den beiden Magiern entegegen, auf die Harry sich seit Beginn seiner Schullaufbahn vorbereitet hat.", //"popularity":305437.691,"poster_path":"/3ssNt5cCFYGne7OrBFkFFUVq8Cx.jpg","production_companies":[{"name":"Warner Bros. Pictures","id":174}], //"production_countries":[{"iso_3166_1":"US","name":"United States of America"},{"iso_3166_1":"GB","name":"United Kingdom"}], //"release_date":"2010-11-19","revenue":954305868,"runtime":146, //"spoken_languages":[{"iso_639_1":"en","name":"English"},{"iso_639_1":"fr","name":"Franais"},{"iso_639_1":"ja","name":"???"}], //"status":"Released","tagline":"","title":"Harry Potter und die Heiligtmer des Todes - Teil 1","vote_average":8.3,"vote_count":74} if (append_to_response != null && append_to_response.equalsIgnoreCase("casts")) { addActorsAndDirector(element, searchResult); } } return searchResult; }