List of usage examples for com.google.gson JsonArray JsonArray
public JsonArray()
From source file:com.controller.system.DepManager.java
/** * ?/*from ww w. j a va 2 s .c om*/ * * @param req * @param rps * @return * @throws Exception */ @RequestMapping(value = "/browse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String getBrowse(HttpServletRequest req, HttpServletResponse rps) throws Exception { JsonArray jsonArray = new JsonArray(); try { //?Service DepHeaderService depHeaderService = (DepHeaderService) ServiceFactory.getService("depHeaderService"); List<DepHeader> list = depHeaderService.findAll(); list.stream().map((DepHeader depObj) -> { JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("DepID", depObj.getDepID()); jsonObj.addProperty("DepName", depObj.getDepName()); jsonObj.addProperty("UnitLevel", UnitLevel.getName(depObj.getUnitLevel())); return jsonObj; }).forEach(jsonArray::add); } catch (Exception e) { throw e; } return jsonArray.toString(); }
From source file:com.controller.system.UserManager.java
/** * ?//from w w w .j a va 2 s .c o m * * @param req * @param rps * @return * @throws Exception */ @RequestMapping(value = "/browse", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String getBrowse(HttpServletRequest req, HttpServletResponse rps) throws Exception { JsonArray jsonArray = new JsonArray(); try { //?Service UserHeaderService userHeaderService = (UserHeaderService) ServiceFactory .getService("userHeaderService"); List<UserHeader> list = userHeaderService.findAll(); list.stream().map((UserHeader userObj) -> { JsonObject jsonObj = new JsonObject(); String depName = userObj.getDepHeader() == null ? "" : userObj.getDepHeader().getDepName(); jsonObj.addProperty("Account", userObj.getAccount()); jsonObj.addProperty("UserName", userObj.getUserName()); jsonObj.addProperty("Email", userObj.getEmail()); jsonObj.addProperty("Dep", depName); jsonObj.addProperty("UserLvl", UserLevel.getName(userObj.getUserLevel())); return jsonObj; }).forEach(jsonArray::add); } catch (Exception e) { throw e; } return jsonArray.toString(); }
From source file:com.controller.webServices.JsonAutoDetect.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); JsonObject jsonResult = new JsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonArray errorArray = new JsonArray(); String date = request.getParameter("date"); String token = request.getParameter("token"); //validation - date if (date == null) { errorArray.add(new JsonPrimitive("missing date")); } else {//from ww w . j ava 2 s.c om 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")); } } if (errorArray.size() > 0) { jsonResult.add("message", errorArray); out.println(gson.toJson(jsonResult)); return; } 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(); } Timestamp tsAfter = Timestamp.valueOf(date1 + " " + after); Timestamp tsBefore = new Timestamp(tsAfter.getTime() - 900000); ArrayList<Group> groupList = new ArrayList<Group>(); AutoGroupDetectController ac = new AutoGroupDetectController(); System.out.println(tsBefore.toString() + " " + tsAfter.toString()); groupList = ac.getFullGroups(tsBefore.toString(), tsAfter.toString()); jsonResult.addProperty("status", "success"); int count = 0; HashSet set = new HashSet(); for (Group g : groupList) { set.addAll(g.getIndivSet()); } count = set.size(); jsonResult.addProperty("total-groups", groupList.size()); jsonResult.addProperty("total-users", count); JsonArray groupArray = new JsonArray(); JsonArraySorter sorter = new JsonArraySorter(); for (Group g : groupList) { JsonObject groupObject = new JsonObject(); groupObject.addProperty("size", g.getIndivSet().size()); groupObject.addProperty("total-time-spent", g.getFullCount()); JsonArray memberArray = new JsonArray(); HashSet<FullUser> userSet = g.getIndivSet(); Iterator i = userSet.iterator(); while (i.hasNext()) { FullUser fullUser = (FullUser) i.next(); JsonObject memberObj = new JsonObject(); memberObj.addProperty("email", fullUser.getEmail()); memberObj.addProperty("mac-address", fullUser.getMacAddress()); memberArray.add(memberObj); } memberArray = sorter.sortAGDMembers(memberArray); groupObject.add("members", memberArray); // Add location objects JsonArray locationArray = new JsonArray(); HashMap<String, Integer> locationMapping = g.getLocTimeMap(); for (String s : locationMapping.keySet()) { JsonObject locationObject = new JsonObject(); locationObject.addProperty("location", s); locationObject.addProperty("time-spent", locationMapping.get(s)); locationArray.add(locationObject); } locationArray = sorter.sortAGDlocation(locationArray); groupObject.add("locations", locationArray); groupArray.add(groupObject); } groupArray = sorter.sortAGDGroup(groupArray); jsonResult.add("groups", groupArray); out.println(gson.toJson(jsonResult)); } catch (Exception e) { e.printStackTrace(); } } else { } // ======= End of Json Codes ======= }
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 w w w . j a va 2s. com 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 void allocateGroups(Map<NodeGroup, Collection<Node>> config, NodeGroupList existingGroups) throws RestApiException { Set<NodeGroup> groups;// ww w .j av a2s .c om if (existingGroups == null) { existingGroups = getGroupList(); } groups = new HashSet<NodeGroup>(existingGroups.getGroups()); if (config.keySet().size() > groups.size()) { throw new IllegalArgumentException("Too many groups specified"); } JsonObject payload = new JsonObject(); JsonArray groupsArray = new JsonArray(); payload.add("groups", groupsArray); Set<Node> changedNodes = new HashSet<Node>(); for (Collection<Node> ll : config.values()) { // Sanity for (Node nn : ll) { if (changedNodes.contains(nn)) { throw new IllegalArgumentException("Node " + nn + " specified twice"); } changedNodes.add(nn); } } // Now go through our existing groups and see which ones are to be modified for (NodeGroup group : groups) { JsonObject curJson = new JsonObject(); JsonArray nodesArray = new JsonArray(); groupsArray.add(curJson); curJson.addProperty("uri", group.getUri().toString()); curJson.add("nodes", nodesArray); Set<Node> nodes = new HashSet<Node>(group.getNodes()); if (config.containsKey(group)) { nodes.addAll(config.get(group)); } for (Node node : nodes) { boolean nodeRemains; /** * If the node was specified in the config, it either belongs to us * or it belongs to a different group. If it does not belong to us then * we skip it, otherwise it's placed back inside the group list. */ if (!changedNodes.contains(node)) { nodeRemains = true; } else if (config.containsKey(group) && config.get(group).contains(node)) { nodeRemains = true; } else { nodeRemains = false; } if (!nodeRemains) { continue; } // Is it staying with us, or is it moving? JsonObject curNodeJson = new JsonObject(); curNodeJson.addProperty("otpNode", node.getNSOtpNode()); nodesArray.add(curNodeJson); } } HttpPut putReq = new HttpPut(); try { putReq.setEntity(new StringEntity(new Gson().toJson(payload))); } catch (UnsupportedEncodingException ex) { throw new IllegalArgumentException(ex); } try { getResponseJson(putReq, existingGroups.getAssignmentUri().toString(), 200); } catch (IOException ex) { throw new RestApiException(ex); } }
From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java
License:Apache License
/** * ?slaves.// w w w. j a v a2s. c o m * * @return jsonArray */ public JsonArray findAllSlaves() { MesosEndpointService mesosEndpointService = MesosEndpointService.getInstance(); Optional<JsonObject> jsonObject = mesosEndpointService.slaves(JsonObject.class); if (!jsonObject.isPresent()) { return new JsonArray(); } JsonArray originalSlaves = jsonObject.get().getAsJsonArray("slaves"); JsonArray result = new JsonArray(); for (JsonElement each : originalSlaves) { result.add(buildSlave(each.getAsJsonObject())); } return result; }
From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java
License:Apache License
/** * ??roleNameslaves.//from w w w . j a va 2s .com * * @return jsonArray */ public JsonArray findSlavesContainsRole(final String roleName) { JsonArray result = new JsonArray(); for (JsonElement eachSlave : findAllSlaves()) { for (JsonElement eachRole : eachSlave.getAsJsonObject().getAsJsonArray("roles")) { if (eachRole.getAsJsonObject().get("role_name").getAsString().equalsIgnoreCase(roleName)) { result.add(eachSlave); break; } } } return result; }
From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java
License:Apache License
private JsonArray buildRoles(final JsonObject rootObject) { final Map<String, JsonObject> roleMap = new HashMap<>(); fillReservedResources(roleMap, rootObject.getAsJsonObject("reserved_resources_full")); fillUsedResources(roleMap, rootObject.getAsJsonArray("used_resources_full")); fillOfferedResources(roleMap, rootObject.getAsJsonArray("offered_resources_full")); JsonArray result = new JsonArray(); for (JsonObject each : roleMap.values()) { result.add(each);/*from w ww .ja va 2 s . co m*/ } return result; }
From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosStateService.java
License:Apache License
/** * ??.// w ww . ja v a2 s .c o m * * @param appName ?App?? * @return ? * @throws JSONException ?JSON? */ public JsonArray sandbox(final String appName) throws JSONException { JSONObject state = fetch(stateUrl); JsonArray result = new JsonArray(); for (JSONObject each : findExecutors(state.getJSONArray("frameworks"), appName)) { JSONArray slaves = state.getJSONArray("slaves"); String slaveHost = null; for (int i = 0; i < slaves.length(); i++) { JSONObject slave = slaves.getJSONObject(i); if (each.getString("slave_id").equals(slave.getString("id"))) { slaveHost = slave.getString("pid").split("@")[1]; } } Preconditions.checkNotNull(slaveHost); JSONObject slaveState = fetch(String.format("http://%s/state", slaveHost)); String workDir = slaveState.getJSONObject("flags").getString("work_dir"); Collection<JSONObject> executorsOnSlave = findExecutors(slaveState.getJSONArray("frameworks"), appName); for (JSONObject executorOnSlave : executorsOnSlave) { JsonObject r = new JsonObject(); r.addProperty("hostname", slaveState.getString("hostname")); r.addProperty("path", executorOnSlave.getString("directory").replace(workDir, "")); result.add(r); } } return result; }
From source file:com.databasserne.resources.MysqlResource.java
@GET @Path("author/{authorname}") @Produces("application/json") public Response searchBooksWithCitiesFromAuthor(@PathParam("authorname") String authorname) { JsonArray response = new JsonArray(); Map<Book, List<City>> books = booksRepo.getBooksWithCitiesFromAuthor(authorname); for (Map.Entry<Book, List<City>> entry : books.entrySet()) { Book key = entry.getKey(); List<City> value = entry.getValue(); // Book json JsonObject bookJson = new JsonObject(); bookJson.addProperty("name", key.getName()); JsonArray citiesForBook = new JsonArray(); for (City city : value) { JsonObject cityJson = new JsonObject(); cityJson.addProperty("name", city.getName()); cityJson.addProperty("geolat", city.getGeolat()); cityJson.addProperty("geolng", city.getGeolng()); citiesForBook.add(cityJson); }/*from w w w. j a va 2 s .c o m*/ bookJson.add("cities", citiesForBook); response.add(bookJson); } return Response.status(Response.Status.OK).entity(gson.toJson(response)).build(); }