List of usage examples for com.google.gson JsonArray size
public int size()
From source file:com.controller.webServices.JsonTopKGroupNextPlaces.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); System.out.println("====== Group Next Places ======== "); JsonObject jsonResult = new JsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonArray errorArray = new JsonArray(); String date = request.getParameter("date"); String token = request.getParameter("token"); Timestamp ts = null;/*from ww w . j a v a 2 s . c o m*/ Timestamp tsBefore = null; Timestamp tsAfter = null; HashMap<String, Integer> finalMap = null; ArrayList<String[]> personCount = null; //validation - date if (date == null) { errorArray.add(new JsonPrimitive("missing date")); } else { try { DateTime ts2 = new DateTime(date); } catch (IllegalArgumentException e) { errorArray.add(new JsonPrimitive("invalid date")); } } //validation - token if (token == null) { errorArray.add(new JsonPrimitive("missing token")); } // } else if (token.equals("")) { // errorArray.add(new JsonPrimitive("blank token")); // } else { // try { // JWTUtility.verify(token, "ylleeg4t8"); // } catch (JWTException e) { // errorArray.add(new JsonPrimitive("invalid token")); // } // } // Validation: Semantic Places String place = request.getParameter("origin"); if (place == null) { errorArray.add(new JsonPrimitive("missing origin")); } else if (place.equals("")) { errorArray.add(new JsonPrimitive("blank origin")); } if (errorArray.size() > 0) { jsonResult.add("message", errorArray); out.println(gson.toJson(jsonResult)); return; } ArrayList<Group> finalGroup = null; if (errorArray.size() == 0) { String date1 = date.substring(0, date.indexOf("T")); String time = date.substring(date.indexOf("T") + 1, date.length()); try { LocalTime after = new LocalTime(Timestamp.valueOf(date1 + " " + time)); int hour = Integer.parseInt(time.substring(0, time.indexOf(":"))); int minute = Integer.parseInt(time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"))); int second = Integer.parseInt(time.substring(time.lastIndexOf(":") + 1, time.length())); if (hour >= 24 || minute >= 60 || second >= 60) { throw new Exception(); } ts = Timestamp.valueOf(date1 + " " + time); tsBefore = new Timestamp(ts.getTime() - 900000); tsAfter = new Timestamp(ts.getTime() + 900000); ArrayList<Group> groupList = new ArrayList<Group>(); finalMap = new HashMap<String, Integer>(); personCount = new ArrayList<String[]>(); AutoGroupDetectController agd = new AutoGroupDetectController(); System.out.println("Group next places: " + tsBefore.toString() + " " + ts.toString()); LocationLookupDAO llDAO = new LocationLookupDAO(); HashMap<String, String> referMap = llDAO.retrieveAll(); ArrayList<Group> firstGroup = agd.getFullGroups(tsBefore.toString(), ts.toString()); // if (firstGroup.size() == 0) { // request.setAttribute("results", personCount); // RequestDispatcher rd = request.getRequestDispatcher("group_next.jsp"); // rd.forward(request, response); // return; // } System.out.println("List size for group next places: " + firstGroup.size()); ArrayList<Group> midGroup = new ArrayList<Group>(); for (Group g : firstGroup) { String s = referMap.get(g.getLastPlace()); System.out.println(s); if (s.equals(place)) { midGroup.add(g); } } System.out.println("Mid list size for group next places: " + midGroup.size()); finalGroup = agd.getMatchingGroups(ts.toString(), tsAfter.toString(), midGroup); System.out.println("Final list size for group next places: " + finalGroup.size()); LocationLookupDAO lookupDAO = new LocationLookupDAO(); HashMap<String, String> lookupMap = lookupDAO.retrieveAll(); for (Group g : finalGroup) { ArrayList<Interval> groupInterList = new ArrayList<Interval>(); HashMap<Interval, Integer> tempMap = new HashMap<Interval, Integer>(); HashMap<String, ArrayList<Interval>> overlapMap = g.getLocOverlapMap(); for (String s : overlapMap.keySet()) { ArrayList<Interval> interList = overlapMap.get(s); groupInterList.addAll(interList); for (Interval in : interList) { Integer i = Integer.parseInt(s); tempMap.put(in, i); } } Collections.sort(groupInterList, new IntervalEndComparator(groupInterList)); for (Interval in : groupInterList) { if (Seconds.secondsIn(in).getSeconds() >= 300) { Integer i = tempMap.get(in); String semPlace = lookupMap.get(String.valueOf(i)); Integer groupCount = finalMap.get(semPlace); if (groupCount != null) { finalMap.put(semPlace, (groupCount + 1)); } else { finalMap.put(semPlace, 1); } break; } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } for (Entry<String, Integer> entry : finalMap.entrySet()) { String[] countArray = new String[] { entry.getKey(), entry.getValue().toString() }; personCount.add(countArray); } Collections.sort(personCount, new ValueComparator(personCount)); jsonResult.addProperty("status", "success"); jsonResult.addProperty("total-groups", finalGroup.size()); jsonResult.addProperty("total-next-place-groups", personCount.size()); JsonArray results = new JsonArray(); for (int i = 0; i < personCount.size(); i++) { String[] arr = personCount.get(i); JsonObject nextPlaceObject = new JsonObject(); nextPlaceObject.addProperty("rank", i + 1); nextPlaceObject.addProperty("semantic-place", arr[0]); nextPlaceObject.addProperty("num-groups", Integer.parseInt(arr[1])); results.add(nextPlaceObject); } jsonResult.add("results", results); out.println(gson.toJson(jsonResult)); // request.setAttribute("results", personCount); // RequestDispatcher rd = request.getRequestDispatcher("group_next.jsp"); // rd.forward(request, response); } }
From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java
License:Open Source License
@Override public Map<String, Bucket> getBuckets() throws RestApiException { JsonElement e;/* w ww . j av a 2 s . c o m*/ Map<String, Bucket> ret = new HashMap<String, Bucket>(); try { e = getJson(P_BUCKETS); } catch (IOException ex) { throw new RestApiException(ex); } JsonArray arr; if (!e.isJsonArray()) { throw new RestApiException("Expected JsonObject", e); } arr = e.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { JsonElement tmpElem = arr.get(i); if (!tmpElem.isJsonObject()) { throw new RestApiException("Expected JsonObject", tmpElem); } Bucket bucket = new Bucket(tmpElem.getAsJsonObject()); ret.put(bucket.getName(), bucket); } return ret; }
From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java
License:Open Source License
@Override public List<Node> getNodes() throws RestApiException { List<Node> ret = new ArrayList<Node>(); JsonElement e;//from w ww .j a v a 2s . c o m try { e = getJson(P_POOL_NODES); } catch (IOException ex) { throw new RestApiException(ex); } if (!e.isJsonObject()) { throw new RestApiException("Expected JsonObject", e); } JsonObject obj = e.getAsJsonObject(); JsonArray nodesArr; e = obj.get("nodes"); if (e == null) { throw new RestApiException("Expected 'nodes' array", obj); } nodesArr = e.getAsJsonArray(); for (int i = 0; i < nodesArr.size(); i++) { e = nodesArr.get(i); JsonObject nObj; if (!e.isJsonObject()) { throw new RestApiException("Malformed node entry", e); } nObj = e.getAsJsonObject(); Node n = new Node(nObj); ret.add(n); } return ret; }
From source file:com.createtank.payments.coinbase.CoinbaseApi.java
License:Apache License
/** * List bitcoin addresses associated with the current account * @param page the page of addresses to retrieve. Can be used to page through results * @param limit the maximum number of addresses to retrieve. Can't exceed 1000 * @param query string match to filter addresses. Matches the address itself and also * if the use has set a label on the address. * @return the list of bitcoin addresses associated with the current account * @throws IOException//from w ww. j av a2s. c om */ public Address[] getAddresses(int page, int limit, String query) throws IOException { Map<String, String> params = new HashMap<String, String>(); if (apiKey != null) params.put("api_key", apiKey); params.put("page", Integer.toString(page)); params.put("limit", Integer.toString(limit)); if (query != null) params.put("query", query); JsonObject response = RequestClient.get(this, "addresses", params, accessToken); JsonArray addresses = response.getAsJsonArray("addresses"); int size = addresses.size(); Address[] result = new Address[size]; for (int i = 0; i < size; ++i) { JsonObject addy = addresses.get(i).getAsJsonObject().getAsJsonObject("address"); result[i] = Address.fromJson(addy); } return result; }
From source file:com.createtank.payments.coinbase.CoinbaseApi.java
License:Apache License
/** * List the current user's recent transactions. * @param page Used to paginate through results. Thirty transactions are returned per page. * @return an array of Transaction objects * @throws IOException//from w w w . j a va2 s .c om */ public Transaction[] getTransactions(int page) throws IOException { Map<String, String> params = new HashMap<String, String>(); if (apiKey != null) params.put("api_key", apiKey); params.put("page", Integer.toString(page)); JsonObject response = RequestClient.get(this, "transactions", params, accessToken); JsonArray transactionsJson = response.getAsJsonArray("transactions"); Transaction[] transactions = new Transaction[transactionsJson.size()]; for (int i = 0; i < transactionsJson.size(); ++i) { JsonObject transactionJson = transactionsJson.get(i).getAsJsonObject().getAsJsonObject("transaction"); transactions[i] = Transaction.fromJson(transactionJson); } return transactions; }
From source file:com.customatics.leaptest_integration_for_bamboo.impl.PluginHandler.java
public boolean getScheduleState(String leaptestAddress, String scheduleId, String scheduleTitle, int currentScheduleIndex, String doneStatusValue, BuildLogger buildLogger, ScheduleCollection buildResult, ArrayList<InvalidSchedule> invalidSchedules) throws InterruptedException { boolean isScheduleStillRunning = true; String uri = String.format(Messages.GET_SCHEDULE_STATE_URI, leaptestAddress, scheduleId); try {/*from ww w. jav a 2s . co m*/ try { AsyncHttpClient client = new AsyncHttpClient(); Response response = client.prepareGet(uri).execute().get(); client = null; switch (response.getStatusCode()) { case 200: JsonParser parser = new JsonParser(); JsonObject jsonState = parser.parse(response.getResponseBody()).getAsJsonObject(); parser = null; String ScheduleId = jsonState.get("ScheduleId").getAsString(); if (isScheduleStillRunning(jsonState)) isScheduleStillRunning = true; else { isScheduleStillRunning = false; /////////Schedule Info JsonElement jsonLastRun = jsonState.get("LastRun"); JsonObject lastRun = jsonLastRun.getAsJsonObject(); String ScheduleTitle = lastRun.get("ScheduleTitle").getAsString(); buildResult.Schedules.get(currentScheduleIndex) .setTime(parseExecutionTimeToSeconds(lastRun.get("ExecutionTotalTime"))); int passedCount = caseStatusCount("PassedCount", lastRun); int failedCount = caseStatusCount("FailedCount", lastRun); int doneCount = caseStatusCount("DoneCount", lastRun); if (doneStatusValue.contentEquals("Failed")) failedCount += doneCount; else passedCount += doneCount; ///////////AutomationRunItemsInfo JsonArray jsonAutomationRunItems = lastRun.get("AutomationRunItems").getAsJsonArray(); ArrayList<String> automationRunId = new ArrayList<String>(); for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems) automationRunId.add( jsonAutomationRunItem.getAsJsonObject().get("AutomationRunId").getAsString()); ArrayList<String> statuses = new ArrayList<String>(); for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems) statuses.add(jsonAutomationRunItem.getAsJsonObject().get("Status").getAsString()); ArrayList<String> elapsed = new ArrayList<String>(); for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems) elapsed.add( defaultElapsedIfNull(jsonAutomationRunItem.getAsJsonObject().get("Elapsed"))); ArrayList<String> environments = new ArrayList<String>(); for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems) environments.add(jsonAutomationRunItem.getAsJsonObject().get("Environment") .getAsJsonObject().get("Title").getAsString()); ArrayList<String> caseTitles = new ArrayList<String>(); for (JsonElement jsonAutomationRunItem : jsonAutomationRunItems) { String caseTitle = Utils.defaultStringIfNull(jsonAutomationRunItem.getAsJsonObject() .get("Case").getAsJsonObject().get("Title"), "Null case Title"); if (caseTitle.contentEquals("Null case Title")) caseTitles.add(caseTitles.get(caseTitles.size() - 1)); else caseTitles.add(caseTitle); } makeCaseTitlesNonRepeatable(caseTitles); //this is required because Bamboo junit reporter does not suppose that there can be 2 or more case with the same name but different results for (int i = 0; i < jsonAutomationRunItems.size(); i++) { //double seconds = jsonArray.getJSONObject(i).getDouble("TotalSeconds"); double seconds = parseExecutionTimeToSeconds(elapsed.get(i)); buildLogger.addBuildLogEntry(Messages.CASE_CONSOLE_LOG_SEPARATOR); if (statuses.get(i).contentEquals("Failed") || (statuses.get(i).contentEquals("Done") && doneStatusValue.contentEquals("Failed")) || statuses.get(i).contentEquals("Error") || statuses.get(i).contentEquals("Cancelled")) { if (statuses.get(i).contentEquals("Error") || statuses.get(i).contentEquals("Cancelled")) failedCount++; JsonArray jsonKeyframes = jsonAutomationRunItems.get(i).getAsJsonObject() .get("Keyframes").getAsJsonArray(); //KeyframeInfo ArrayList<String> keyFrameTimeStamps = new ArrayList<String>(); for (JsonElement jsonKeyFrame : jsonKeyframes) keyFrameTimeStamps .add(jsonKeyFrame.getAsJsonObject().get("Timestamp").getAsString()); ArrayList<String> keyFrameLogMessages = new ArrayList<String>(); for (JsonElement jsonKeyFrame : jsonKeyframes) keyFrameLogMessages .add(jsonKeyFrame.getAsJsonObject().get("LogMessage").getAsString()); buildLogger.addBuildLogEntry(String.format(Messages.CASE_INFORMATION, caseTitles.get(i), statuses.get(i), elapsed.get(i))); String fullstacktrace = ""; int currentKeyFrameIndex = 0; for (JsonElement jsonKeyFrame : jsonKeyframes) { String level = Utils .defaultStringIfNull(jsonKeyFrame.getAsJsonObject().get("Level"), ""); if (!level.contentEquals("") && !level.contentEquals("Trace")) { String stacktrace = String.format(Messages.CASE_STACKTRACE_FORMAT, keyFrameTimeStamps.get(currentKeyFrameIndex), keyFrameLogMessages.get(currentKeyFrameIndex)); buildLogger.addBuildLogEntry(stacktrace); fullstacktrace += stacktrace; fullstacktrace += "
"; //fullstacktrace += '\n'; } currentKeyFrameIndex++; } fullstacktrace += "Environment: " + environments.get(i); buildLogger.addBuildLogEntry("Environment: " + environments.get(i)); buildResult.Schedules.get(currentScheduleIndex).Cases .add(new Case(caseTitles.get(i), statuses.get(i), seconds, fullstacktrace, ScheduleTitle/* + "[" + ScheduleId + "]"*/)); } else { buildLogger.addBuildLogEntry(String.format(Messages.CASE_INFORMATION, caseTitles.get(i), statuses.get(i), elapsed.get(i))); buildResult.Schedules.get(currentScheduleIndex).Cases .add(new Case(caseTitles.get(i), statuses.get(i), seconds, ScheduleTitle/* + "[" + ScheduleId + "]"*/)); } } buildResult.Schedules.get(currentScheduleIndex).setPassed(passedCount); buildResult.Schedules.get(currentScheduleIndex).setFailed(failedCount); if (buildResult.Schedules.get(currentScheduleIndex).getFailed() > 0) buildResult.Schedules.get(currentScheduleIndex).setStatus("Failed"); else buildResult.Schedules.get(currentScheduleIndex).setStatus("Passed"); } break; case 404: String errorMessage404 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(), response.getStatusText()); errorMessage404 += String.format("\n%1$s", String.format(Messages.NO_SUCH_SCHEDULE_WAS_FOUND, scheduleTitle, scheduleId)); throw new Exception(errorMessage404); case 445: String errorMessage445 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(), response.getStatusText()); errorMessage445 += String.format("\n%1$s", Messages.LICENSE_EXPIRED); throw new InterruptedException(errorMessage445); case 448: String errorMessage448 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(), response.getStatusText()); errorMessage448 += String.format("\n%1$s", String.format(Messages.CACHE_TIMEOUT_EXCEPTION, scheduleTitle, scheduleId)); isScheduleStillRunning = true; buildLogger.addErrorLogEntry(errorMessage448); break; case 500: String errorMessage500 = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(), response.getStatusText()); errorMessage500 += String.format("\n%1$s", Messages.CONTROLLER_RESPONDED_WITH_ERRORS); throw new Exception(errorMessage500); default: String errorMessage = String.format(Messages.ERROR_CODE_MESSAGE, response.getStatusCode(), response.getStatusText()); throw new Exception(errorMessage); } } catch (NoRouteToHostException e) { String connectionLostErrorMessage = String.format(Messages.CONNECTION_LOST, e.getCause().getMessage()); buildLogger.addErrorLogEntry(connectionLostErrorMessage); return true; } catch (ConnectException | UnknownHostException e) { String connectionErrorMessage = String.format(Messages.COULD_NOT_CONNECT_TO_BUT_WAIT, e.getMessage()); buildLogger.addErrorLogEntry(connectionErrorMessage); return true; } catch (ExecutionException e) { if (e.getCause() instanceof ConnectException || e.getCause() instanceof UnknownHostException) { String connectionErrorMessage = String.format(Messages.COULD_NOT_CONNECT_TO_BUT_WAIT, e.getCause().getMessage()); buildLogger.addErrorLogEntry(connectionErrorMessage); return true; } else if (e.getCause() instanceof NoRouteToHostException) { String connectionLostErrorMessage = String.format(Messages.CONNECTION_LOST, e.getCause().getMessage()); buildLogger.addErrorLogEntry(connectionLostErrorMessage); return true; } else { String executionExceptionMessage = String.format(Messages.EXECUTION_EXCEPTION, e.getMessage()); throw new Exception(executionExceptionMessage); } } catch (IOException e) { String ioExceptionMessage = String.format(Messages.IO_EXCEPTION, e.getMessage()); throw new Exception(ioExceptionMessage); } catch (Exception e) { throw e; } } catch (InterruptedException e) { throw new InterruptedException(e.getMessage()); } catch (Exception e) { String errorMessage = String.format(Messages.SCHEDULE_STATE_FAILURE, scheduleTitle, scheduleId); buildLogger.addErrorLogEntry(errorMessage); buildLogger.addErrorLogEntry(e.getMessage()); buildLogger.addErrorLogEntry(Messages.PLEASE_CONTACT_SUPPORT); buildResult.Schedules.get(currentScheduleIndex) .setError(String.format("%1$s\n%2$s", errorMessage, e.getMessage())); buildResult.Schedules.get(currentScheduleIndex).incErrors(); invalidSchedules .add(new InvalidSchedule(String.format(Messages.SCHEDULE_FORMAT, scheduleTitle, scheduleId), buildResult.Schedules.get(currentScheduleIndex).getError())); return false; } return isScheduleStillRunning; }
From source file:com.daa.verifier.Models.Verifier.java
/** * Turns a revocation list as JSON object into a set of big integers * @param json the revocation list as a JSON object * @param curve the curve used/*from w ww.j av a2 s . c o m*/ * @return the revocation list as a Set<BigInteger> */ public static Set<BigInteger> revocationListFromJson(String json, BNCurve curve) { Base64.Decoder decoder = Base64.getUrlDecoder(); JsonArray object = new JsonParser().parse(json).getAsJsonObject().getAsJsonArray(JSON_REVOCATION_LIST); Set<BigInteger> rl = new HashSet<BigInteger>(object.size()); for (JsonElement element : object) { rl.add(curve.bigIntegerFromB( decoder.decode(element.getAsJsonObject().get(JSON_REVOCATION_LIST_ENTRY).getAsString()))); } return rl; }
From source file:com.devamatre.core.JSONHelper.java
License:Open Source License
/** * Returns the list of the specified objects from the given JSON string. * //from w w w .j a va 2s.com * @param jsonString * @param classType * @return */ public static <T> List<T> listOfObjects(String jsonString, Class<T> classType) { List<T> objects = new ArrayList<T>(); JsonArray jsonArray = toJSONArray(jsonString); if (jsonArray != null) { for (int i = 0; i < jsonArray.size(); i++) { Gson gson = new Gson(); T object = gson.fromJson(jsonArray.get(i), classType); objects.add(object); } } return objects; }
From source file:com.devamatre.core.JSONHelper.java
License:Open Source License
/** * Returns the list of the specified objects from the given JSON string. * /* ww w. j av a2 s.c om*/ * @param jsonString * @param classType * @return */ public static List<?> listOfObjects(String jsonString, String key, Class<?>... classTypes) { List<Object> mixedObjects = new ArrayList<Object>(); if (jsonString == null || !isValidJSONString(jsonString)) { return mixedObjects; } JsonArray jsonArray = toJSONArray(jsonString); if (jsonArray != null) { for (int i = 0; i < jsonArray.size(); i++) { String objectJSONString = toJSONString(jsonArray.get(i)); for (int j = 0; j < classTypes.length; j++) { String value = (String) toMap(objectJSONString).get(key); if (value.equalsIgnoreCase(classTypes[j].getSimpleName())) { Object object = fromJSONString(objectJSONString, classTypes[j]); mixedObjects.add(object); break; } } } } return mixedObjects; }
From source file:com.devamatre.core.JSONHelper.java
License:Open Source License
/** * Returns the value for the given key from the given jsonArray. * //from www.ja v a2 s.com * @param jsonArray * @param key * @return */ public static String valueForKeyAsString(JsonArray jsonArray, String key) { String value = null; if (jsonArray != null && !CoreHelper.isNullOrEmpty(key)) { for (int i = 0; i < jsonArray.size(); i++) { JsonObject jsonObject = (JsonObject) jsonArray.get(i); if (jsonObject != null && getAsString(jsonObject, "name").equals(key)) { value = getAsString(jsonObject, "value"); break; } } } return value; }