List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.jd.survey.web.statistics.StatisticsController.java
License:Open Source License
void populateModel(Model uiModel, Long surveyDefinitionId, Question question, User user, String... args) { try {/* ww w.j ava2 s. com*/ // SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); //show all definition Set<SurveyDefinition> surveyDefinitions = surveySettingsService .surveyDefinition_findAllCompletedInternal(user); //show total digits SurveyStatistic surveyStatistic = surveyService.surveyStatistic_get(surveyDefinitionId, args); Long recordCount = surveyStatistic.getSubmittedCount(); uiModel.addAttribute("question", question); uiModel.addAttribute("questionId", question.getId()); uiModel.addAttribute("surveyDefinition", surveyDefinition); uiModel.addAttribute("surveyDefinitions", surveyDefinitions); uiModel.addAttribute("surveyStatistic", surveyStatistic); uiModel.addAttribute("recordCount", recordCount); List<QuestionStatistic> lq = surveyService.questionStatistic_getStatistics(question, recordCount, args); uiModel.addAttribute("questionStatistics", lq); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("questionText", question.getQuestionText()); jsonObject.addProperty("order", question.getOrder()); jsonObject.addProperty("visible", question.getVisible()); jsonObject.addProperty("required", question.getRequired()); jsonObject.addProperty("code", question.getType().getCode()); jsonObject.add("options", new JsonArray()); if ("SR".equals(question.getType().getCode()) || "MC".equals(question.getType().getCode())) { SortedSet<QuestionOption> options = question.getOptions(); for (QuestionOption row : options) { JsonObject optionJsonOject = new JsonObject(); jsonObject.getAsJsonArray("options").add(optionJsonOject); optionJsonOject.addProperty("text", row.getText()); optionJsonOject.addProperty("value", row.getValue()); optionJsonOject.addProperty("order", row.getOrder()); for (QuestionStatistic qs : lq) { if (qs.getEntry().equals(row.getValue())) { optionJsonOject.addProperty("frequency", qs.getFrequency()); break; } else { optionJsonOject.addProperty("frequency", 0); } } } } System.out.println(jsonObject.toString()); } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.jd.survey.web.surveys.SurveyController.java
License:Open Source License
/** * Shows a single Survey /*from ww w . ja v a2 s. com*/ * @param surveyId * @param principal * @param uiModel * @param httpServletRequest * @return */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "show", produces = "text/html") public String showSurvey(@PathVariable("id") Long surveyId, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("showSurvey surveyId=" + surveyId + " no pageOrder"); try { //Survey survey =surveyService.Survey_findById(surveyId); User user = userService.user_findByLogin(principal.getName()); SurveyEntry surveyEntry = surveyService.surveyEntry_get(surveyId); if (!securityService.userIsAuthorizedToManageSurvey(surveyEntry.getSurveyDefinitionId(), user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyId, messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale())); uiModel.addAttribute("surveyEntry", surveyEntry); uiModel.addAttribute("surveyPages", surveyPages); JsonArray pageArray = new JsonArray(); for (SurveyPage page : surveyPages) { JsonObject pageJsonObject = new JsonObject(); pageArray.add(pageJsonObject); pageJsonObject.addProperty("title", page.getTitle()); pageJsonObject.addProperty("instructions", page.getInstructions()); pageJsonObject.addProperty("order", page.getOrder()); pageJsonObject.add("questions", new JsonArray()); List<QuestionAnswer> questionAnswers = page.getQuestionAnswers(); for (QuestionAnswer qa : questionAnswers) { // qa.get JsonObject questionJsonObj = new JsonObject(); Question q = qa.getQuestion(); questionJsonObj.addProperty("code", q.getType().getCode()); // questionJsonObj.addProperty("questionText", q.getQuestionText()); // questionJsonObj.addProperty("questionOrder", q.getOrder()); // questionJsonObj.addProperty("direction", q.getDirection() + ""); // questionJsonObj.addProperty("visible", q.getVisible() + ""); // questionJsonObj.addProperty("required", q.getRequired() + ""); // questionJsonObj.addProperty("value", qa.getStringAnswerValue()); questionJsonObj.add("options", new JsonArray()); //// pageJsonObject.getAsJsonArray("questions").add(questionJsonObj); // page if ("ST".equals(q.getType().getCode())) { // } else if ("SR".equals(q.getType().getCode()) || "MC".equals(q.getType().getCode())) { //? SortedSet<QuestionOption> set = q.getOptions(); for (QuestionOption option : set) { JsonObject optionJsonObj = new JsonObject(); optionJsonObj.addProperty("text", option.getText()); optionJsonObj.addProperty("value", option.getValue()); optionJsonObj.addProperty("order", option.getOrder()); questionJsonObj.getAsJsonArray("options").add(optionJsonObj); } } } } System.out.println(pageArray.toString()); return "surveys/survey"; } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.kaltura.client.types.ListResponse.java
License:Open Source License
@SuppressWarnings("unchecked") public ListResponse(JsonObject jsonObject) throws APIException { if (jsonObject == null) return;/*from w w w . j av a2 s. c om*/ Class<ObjectBase> cls = ObjectBase.class; JsonPrimitive objectTypeElement = jsonObject.getAsJsonPrimitive("objectType"); if (objectTypeElement != null) { String objectType = objectTypeElement.getAsString().replaceAll("ListResponse$", ""); cls = GsonParser.getObjectClass(objectType, cls); } // set members values: totalCount = GsonParser.parseInt(jsonObject.get("totalCount")); objects = (List<T>) GsonParser.parseArray(jsonObject.getAsJsonArray("objects"), cls); }
From source file:com.kurtraschke.amtkgtfsrealtime.AMTKRealtimeProvider.java
License:Apache License
/** * This method downloads the latest vehicle data, processes each vehicle in * turn, and create a GTFS-realtime feed of trip updates and vehicle * positions as a result./*w w w . j a va 2s. com*/ */ private void refreshVehicles() throws IOException, ParseException { URL trainPositions = new URL( "https://www.googleapis.com/mapsengine/v1/tables/01382379791355219452-08584582962951999356/features?version=published&maxResults=250&key=" + _mapsEngineKey); JsonParser parser = new JsonParser(); JsonObject o = (JsonObject) parser.parse(new InputStreamReader(trainPositions.openStream())); JsonArray trains = o.getAsJsonArray("features"); for (JsonElement e : trains) { try { JsonObject train = e.getAsJsonObject(); JsonArray coordinates = train.getAsJsonObject("geometry").getAsJsonArray("coordinates"); JsonObject trainProperties = train.getAsJsonObject("properties"); String trainState = trainProperties.get("TrainState").getAsString(); if (!(trainState.equals("Active") || trainState.equals("Predeparture"))) { continue; } String trainNumber = trainProperties.get("TrainNum").getAsString(); String originTimestamp = trainProperties.get("OrigSchDep").getAsString(); String originTimezone = trainProperties.get("OriginTZ").getAsString(); String updateTimestamp = trainProperties.get("LastValTS").getAsString(); String updateTimezone = trainProperties.has("EventTZ") ? trainProperties.get("EventTZ").getAsString() : originTimezone; ServiceDate trainServiceDate = DateUtils.serviceDateForTimestamp(originTimestamp, originTimezone); String key = String.format("%s(%s)", trainNumber, trainServiceDate.getDay()); Date updateDate = DateUtils.parseTimestamp(updateTimestamp, updateTimezone); if (!lastUpdateByVehicle.containsKey(key) || updateDate.after(lastUpdateByVehicle.get(key))) { long updateTime = updateDate.getTime() / 1000L; /** * We construct a TripDescriptor and VehicleDescriptor, * which will be used in both trip updates and vehicle * positions to identify the trip and vehicle. */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); String tripId = tripForTrainAndDate(trainNumber, trainServiceDate); if (tripId == null) { continue; } tripDescriptor.setTripId(tripId); tripDescriptor.setStartDate(String.format("%04d%02d%02d", trainServiceDate.getYear(), trainServiceDate.getMonth(), trainServiceDate.getDay())); VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); vehicleDescriptor.setId(key); vehicleDescriptor.setLabel(trainNumber); TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); for (Entry<String, JsonElement> propEntry : trainProperties.entrySet()) { if (propEntry.getKey().startsWith("Station")) { StopTimeUpdate stu = stopTimeUpdateForStation(propEntry.getValue().getAsString()); if (stu != null) { tripUpdate.addStopTimeUpdate(stu); } } } tripUpdate.setTrip(tripDescriptor); tripUpdate.setVehicle(vehicleDescriptor); tripUpdate.setTimestamp(updateTime); /** * Create a new feed entity to wrap the trip update and add * it to the GTFS-realtime trip updates feed. */ FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(key); tripUpdateEntity.setTripUpdate(tripUpdate); /** * To construct our VehiclePosition, we create a position * for the vehicle. We add the position to a VehiclePosition * builder, along with the trip and vehicle descriptors. */ Position.Builder position = Position.newBuilder(); position.setLatitude(coordinates.get(1).getAsFloat()); position.setLongitude(coordinates.get(0).getAsFloat()); if (trainProperties.has("Heading") && !trainProperties.get("Heading").getAsString().equals("")) { position.setBearing(degreesForHeading(trainProperties.get("Heading").getAsString())); } if (trainProperties.has("Velocity") && !trainProperties.get("Velocity").getAsString().equals("")) { position.setSpeed(trainProperties.get("Velocity").getAsFloat() * 0.44704f); } VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder(); vehiclePosition.setTimestamp(updateTime); vehiclePosition.setPosition(position); vehiclePosition.setTrip(tripDescriptor); vehiclePosition.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the vehicle position and * add it to the GTFS-realtime vehicle positions feed. */ FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder(); vehiclePositionEntity.setId(key); vehiclePositionEntity.setVehicle(vehiclePosition); GtfsRealtimeIncrementalUpdate tripUpdateUpdate = new GtfsRealtimeIncrementalUpdate(); tripUpdateUpdate.addUpdatedEntity(tripUpdateEntity.build()); _tripUpdatesSink.handleIncrementalUpdate(tripUpdateUpdate); GtfsRealtimeIncrementalUpdate vehiclePositionUpdate = new GtfsRealtimeIncrementalUpdate(); vehiclePositionUpdate.addUpdatedEntity(vehiclePositionEntity.build()); _vehiclePositionsSink.handleIncrementalUpdate(vehiclePositionUpdate); if (trainProperties.has("StatusMsg")) { String statusMessage = trainProperties.get("StatusMsg").getAsString().trim(); Alert.Builder alert = Alert.newBuilder(); alert.setDescriptionText(GtfsRealtimeLibrary.getTextAsTranslatedString(statusMessage)); EntitySelector.Builder informedEntity = EntitySelector.newBuilder(); informedEntity.setTrip(tripDescriptor); alert.addInformedEntity(informedEntity); FeedEntity.Builder alertEntity = FeedEntity.newBuilder(); alertEntity.setId(key); alertEntity.setAlert(alert); GtfsRealtimeIncrementalUpdate alertUpdate = new GtfsRealtimeIncrementalUpdate(); alertUpdate.addUpdatedEntity(alertEntity.build()); _alertsSink.handleIncrementalUpdate(alertUpdate); } lastUpdateByVehicle.put(key, updateDate); } } catch (Exception ex) { _log.warn("Exception processing vehicle", ex); } } }
From source file:com.licensetokil.atypistcalendar.gcal.Syncer.java
private boolean remoteCalendarExists() throws IOException, JsonParseException, IllegalStateException { JsonObject serverReply = Utilities.parseToJsonObject(Utilities.sendJsonHttpsRequest( GOOGLE_REQUEST_URL_LIST_CALENDARS, Utilities.REQUEST_METHOD_GET, AuthenticationManager.getInstance().getAuthorizationHeader(), Utilities.EMPTY_REQUEST_BODY)); JsonArray calendarList = serverReply.getAsJsonArray(CALENDARS_LIST_RESOURCE_LABEL_ITEMS_ARRAY); for (JsonElement i : calendarList) { JsonObject currentCalendar = (JsonObject) i; boolean currentCalendarNameEqualsATypistsCalendar = Utilities .getJsonObjectValueOrEmptyString(currentCalendar, CALENDAR_RESOURCE_LABEL_SUMMARY) .equals("A Typist's Calendar"); if (currentCalendarNameEqualsATypistsCalendar) { SyncManager.getInstance().setRemoteCalendarId( Utilities.getJsonObjectValueOrEmptyString(currentCalendar, CALENDAR_RESOURCE_LABEL_ID)); return true; }//from w w w . j a v a 2 s .c o m } return false; }
From source file:com.licensetokil.atypistcalendar.gcal.Syncer.java
private void syncAllTasks(ArrayList<Task> localTasks, String pageToken) throws IOException, JsonParseException, IllegalStateException { logger.info("Getting remote task list with pageToken: " + pageToken); JsonObject serverReply = getRemoteTaskList(pageToken); logger.info("Iterating through the remote task list (for current page)."); JsonArray remoteTasksList = serverReply.getAsJsonArray(EVENTS_LIST_RESOURCE_LABEL_ITEMS_ARRAY); for (JsonElement i : remoteTasksList) { logger.info("Examining next remote task."); examineRemoteTask(localTasks, i.getAsJsonObject()); }//from w ww .ja va2 s .c o m logger.info("Completed iterating through remote task list (for current page)."); boolean nextPageTokenExists = Utilities.getJsonObjectValueOrEmptyString(serverReply, "nextPageToken") != EMPTY_PAGE_TOKEN; if (nextPageTokenExists) { logger.info("Next page for remote task list is avaliable, continuing on to next page."); syncAllTasks(localTasks, Utilities.getJsonObjectValueOrEmptyString(serverReply, "nextPageToken")); } else { logger.info("Already on last page for remote task list. Enqueuing all remaining local tasks (count = " + localTasks.size() + ") for either uploading to Google Calendar or deletion from local list."); for (Task currentLocalTask : localTasks) { boolean currentLocalTaskHasNoRemoteId = currentLocalTask.getRemoteId() == null; if (currentLocalTaskHasNoRemoteId) { logger.info("Adding local task, uniqueId = " + currentLocalTask.getUniqueId()); SyncManager.getInstance().addRemoteTask(currentLocalTask); } else { logger.info("Deleting local task, uniqueId = " + currentLocalTask.getUniqueId()); GoogleCalendarManager.getInstance() .deleteLocalTaskfromTasksManager(currentLocalTask.getUniqueId()); } } } }
From source file:com.licensetokil.atypistcalendar.gcal.Syncer.java
private boolean isIdenticalTodo(JsonObject remoteTask, Todo localTodo) { // TODO handle done/undone boolean locationIsIdentical = Utilities .getJsonObjectValueOrEmptyString(remoteTask, CALENDAR_RESOURCE_LABEL_LOCATION) .equals(localTodo.getPlace()); boolean summaryIsIdentical = Utilities .getJsonObjectValueOrEmptyString(remoteTask, EVENT_RESOURCE_LABEL_SUMMARY) .equals(TASK_DESCRIPTION_PREFIX_TODO + localTodo.getDescription()); boolean startTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_START) .equals(Utilities.createGoogleDateObject(SyncManager.REMOTE_TODO_START_END_DATE)); boolean endTimeIsIdentical = remoteTask.getAsJsonObject(EVENT_RESOURCE_LABEL_END) .equals(Utilities.createGoogleDateObject(SyncManager.REMOTE_TODO_START_END_DATE)); boolean recurrenceIsIdentical = false; if (remoteTask.get(EVENT_RESOURCE_LABEL_RECURRENCE) != null) { recurrenceIsIdentical = remoteTask.getAsJsonArray(EVENT_RESOURCE_LABEL_RECURRENCE) .equals(SyncManager.REMOTE_TODO_RECURRENCE_PROPERTY); }/*from w w w . ja v a 2 s. c o m*/ return locationIsIdentical && summaryIsIdentical && startTimeIsIdentical && endTimeIsIdentical && recurrenceIsIdentical; }
From source file:com.liferay.mobile.sdk.json.DiscoveryDeserializer.java
License:Open Source License
@Override public Discovery deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject root = json.getAsJsonObject(); String contextName = root.get("contextName").getAsString(); JsonArray jsonArray = root.getAsJsonArray("services"); try {/*from w w w .j a va 2 s. c o m*/ ArrayList<Action> services = JSONParser.fromJSON(jsonArray, new GenericListType<>(Action.class)); return new Discovery(contextName, services); } catch (Exception e) { throw new JsonParseException(e); } }
From source file:com.lunchareas.echomp.utils.MediaDataUtils.java
License:Open Source License
public static void updateSongMetadata(final long songId, final long albumId, final String url, final String path, final Context context) { // Get youtube ID and JSON object final String videoId = MusicDownloadUtils.getYoutubeId(url); /*//w w w . j a v a 2 s .c o m Update cover art from YT */ Thread image = new Thread(new Runnable() { @Override public void run() { try { // Connect to URL Log.e(TAG, "Connecting to YT API for data."); URL jsonUrl = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + Constants.YT_API_KEY + "&part=snippet"); HttpURLConnection request = (HttpURLConnection) jsonUrl.openConnection(); request.connect(); // Convert to json object JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new InputStreamReader((InputStream) request.getContent())); JsonObject object = root.getAsJsonObject(); JsonObject thumbnails = object.getAsJsonArray("items").get(0).getAsJsonObject() .getAsJsonObject("snippet").getAsJsonObject("thumbnails"); // Change artist name boolean standard = thumbnails.has("standard"); boolean maxres = thumbnails.has("maxres"); // Download highest quality image if (maxres) { String link = thumbnails.getAsJsonObject("maxres").get("url").toString(); link = link.substring(1, link.length() - 1); ImageDownloadUtils.downloadSongArt(link, songId, albumId, context); Log.e(TAG, "Downloading max res image."); } else if (standard) { String link = thumbnails.getAsJsonObject("standard").get("url").toString(); link = link.substring(1, link.length() - 1); ImageDownloadUtils.downloadSongArt(link, songId, albumId, context); Log.e(TAG, "Downloading standard res image."); } else { String link = thumbnails.getAsJsonObject("high").get("url").toString(); link = link.substring(1, link.length() - 1); ImageDownloadUtils.downloadSongArt(link, songId, albumId, context); Log.e(TAG, "Downloading low res image."); } } catch (Exception e) { e.printStackTrace(); } } }); /* Get data from Youtube API, key in Constants.java */ Thread metadata = new Thread(new Runnable() { @Override public void run() { try { // Connect to URL URL jsonUrl = new URL("https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + Constants.YT_API_KEY + "&part=snippet"); HttpURLConnection request = (HttpURLConnection) jsonUrl.openConnection(); request.connect(); // Convert to json object JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new InputStreamReader((InputStream) request.getContent())); JsonObject object = root.getAsJsonObject(); JsonObject snippet = object.getAsJsonArray("items").get(0).getAsJsonObject() .getAsJsonObject("snippet"); /* for (Map.Entry<String, JsonElement> entry: artistObject.entrySet()) { Log.e(TAG, entry.getKey()); if (entry.getKey().equals("channelTitle")) { MediaDataUtils.changeSongArtist(songId, entry.getValue().toString(), context); Log.e(TAG, "Changed artist to " + entry.getValue().toString() + "."); } } */ // Change artist name String artist = snippet.get("channelTitle").toString(); artist = artist.substring(1, artist.length() - 1); MediaDataUtils.changeSongArtist(songId, artist, context); // TODO Find better album names? String album = snippet.get("title").toString(); album = album.substring(1, album.length() - 1); MediaDataUtils.changeSongAlbum(songId, album, context); } catch (Exception e) { e.printStackTrace(); } } }); // Wait for completions metadata.start(); image.start(); try { metadata.join(); image.join(); } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, "Finished waiting for image and metadata change."); }
From source file:com.luorrak.ouroboros.api.JsonParser.java
License:Open Source License
public byte[] getMediaFiles(JsonObject threadJson) { if (threadJson.has(THREAD_TIM)) { ArrayList<Media> mediaArrayList = new ArrayList<>(); String height = getThreadImageHeight(threadJson); String width = getThreadImageWidth(threadJson); String tim = getThreadTim(threadJson); String ext = getThreadExt(threadJson); Media mediaItem = Util.createMediaItem(height, width, tim, ext); mediaArrayList.add(mediaItem);// ww w . j ava 2s. c o m if (threadJson.has(THREAD_EXTRA_FILES)) { JsonArray extraFiles = threadJson.getAsJsonArray(THREAD_EXTRA_FILES); for (JsonElement fileElement : extraFiles) { JsonObject extraFileJson = fileElement.getAsJsonObject(); height = getThreadImageHeight(extraFileJson); width = getThreadImageWidth(extraFileJson); tim = getThreadTim(extraFileJson); ext = getThreadExt(extraFileJson); mediaItem = Util.createMediaItem(height, width, tim, ext); mediaArrayList.add(mediaItem); } } return Util.serializeObject(mediaArrayList); } return null; }