List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
From source file:com.confighub.core.store.diff.TeamDiffTracker.java
License:Open Source License
@PreUpdate public void preUpdate(APersisted obj) { OriginalTeam o = (OriginalTeam) getIfRecorded(obj); if (null == o || !(obj instanceof Team)) return;//w w w. jav a 2 s . co m Team team = (Team) obj; JsonObject json = new JsonObject(); if (!Utils.equal(team.getName(), o.name)) json.addProperty("name", o.name); if (team.isStopOnFirstMatch() != o.stopOnFirstMatch) json.addProperty("stopOnFirstMatch", o.stopOnFirstMatch); if (team.isUnmatchedEditable() != o.unmatchedEditable) json.addProperty("unmatchedEditable", o.unmatchedEditable); Set<UserAccount> currentMembers = team.getMembers(); if (null == o.members || o.members.size() == 0) { if (null != currentMembers && currentMembers.size() > 0) { JsonArray added = new JsonArray(); currentMembers.forEach(m -> added.add(userToJson(m))); json.add("newMembers", added); } } else { if (null == currentMembers || currentMembers.size() == 0) { JsonArray removed = new JsonArray(); o.members.forEach(m -> removed.add(userToJson(m))); json.add("removedMembers", removed); } else { Set<UserAccount> copyOfCurrent = new HashSet<>(); currentMembers.forEach(m -> copyOfCurrent.add(m)); copyOfCurrent.removeAll(o.members); if (copyOfCurrent.size() > 0) { JsonArray added = new JsonArray(); copyOfCurrent.forEach(m -> added.add(userToJson(m))); json.add("newMembers", added); } o.members.removeAll(currentMembers); if (o.members.size() > 0) { JsonArray removed = new JsonArray(); o.members.forEach(m -> removed.add(userToJson(m))); json.add("removedMembers", removed); } } } markForNotification(); team.diffJson = json.toString(); }
From source file:com.confighub.core.store.diff.TokenDiffTracker.java
License:Open Source License
@PreUpdate public void preUpdate(APersisted obj) { OriginalToken o = (OriginalToken) getIfRecorded(obj); if (null == o || !(obj instanceof Token)) return;// w ww .j a v a2 s . c o m Token token = (Token) obj; JsonObject json = new JsonObject(); if (!Utils.equal(token.getName(), o.name)) json.addProperty("name", o.name); if (token.isActive() != o.active) json.addProperty("active", o.active); if (!Utils.equal(token.getExpires(), o.expires)) json.addProperty("expires", null == o.expires ? "" : o.expires.toString()); if (token.isForceKeyPushEnabled() != o.forceKeyPushEnabled) json.addProperty("forceKeyPushEnabled", o.forceKeyPushEnabled); boolean hadSps = null != o.securityProfiles && o.securityProfiles.size() > 0; boolean hasSps = null != token.getSecurityProfiles() && token.getSecurityProfiles().size() > 0; if (!hadSps && !hasSps) ; else if (hadSps && !hasSps) { JsonArray sps = new JsonArray(); o.securityProfiles.forEach(sp -> sps.add(sp)); json.add("sps", sps); } else if (!hadSps && hasSps) { json.add("sps", new JsonArray()); } else { Set<String> current = new HashSet<>(); token.getSecurityProfiles().forEach(sp -> current.add(sp.getName())); current.removeAll(o.securityProfiles); if (current.size() > 0) { JsonArray sps = new JsonArray(); o.securityProfiles.forEach(sp -> sps.add(sp)); json.add("sps", sps); } else { Set<String> clone = new HashSet<>(); o.securityProfiles.forEach(sp -> clone.add(new String(sp))); current.clear(); token.getSecurityProfiles().forEach(sp -> clone.add(sp.getName())); clone.removeAll(current); if (clone.size() > 0) { JsonArray sps = new JsonArray(); o.securityProfiles.forEach(sp -> sps.add(sp)); json.add("sps", sps); } } } if (!Utils.equal(token.getTeamRules(), o.teamRules)) json.addProperty("rulesTeam", null == o.teamRules ? "" : o.teamRules.getName()); if (!Utils.equal(token.getManagingTeam(), o.managingTeam)) json.addProperty("managingTeam", null == o.managingTeam ? "" : o.managingTeam.getName()); if (!Utils.equal(token.getUser(), o.user)) json.addProperty("user", null == o.user ? "" : o.user.getUsername()); if (!Utils.equal(token.getManagedBy(), o.managedBy)) json.addProperty("managedBy", o.managedBy.name()); markForNotification(); token.diffJson = json.toString(); }
From source file:com.confighub.core.utils.Utils.java
License:Open Source License
public static String jsonMapToJsonList(String jsonMap) throws ConfigException { try {/* w w w .ja va 2 s . co m*/ Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> json = gson.fromJson(jsonMap, type); JsonArray arr = new JsonArray(); json.keySet().stream().forEach(k -> arr.add(String.format("%s :: %s", k, json.get(k)))); return gson.toJson(arr); } catch (Exception e) { throw new ConfigException(Error.Code.VALUE_DATA_TYPE_CONVERSION); } }
From source file:com.confighub.core.utils.Utils.java
License:Open Source License
public static String textToJsonList(String text) throws ConfigException { try {//from www.j a va 2 s . c o m JsonArray json = new JsonArray(); json.add(text); Gson gson = new Gson(); return gson.toJson(json); } catch (Exception e) { throw new ConfigException(Error.Code.VALUE_DATA_TYPE_CONVERSION); } }
From source file:com.continusec.client.ObjectHash.java
License:Apache License
private static final JsonElement shedArray(JsonArray o, String r) throws ContinusecException { JsonArray rv = new JsonArray(); for (JsonElement e : o) { rv.add(shedRedactable(e, r)); }// ww w . j av a 2 s. co m return rv; }
From source file:com.continuuity.loom.codec.json.current.ResourceCollectionCodec.java
License:Apache License
@Override public JsonElement serialize(ResourceCollection src, Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.add("automatortypes", new JsonObject()); out.add("providertypes", new JsonObject()); /*/*from w w w . j av a 2 s .c om*/ * Transform it into something like: * * "resources": { * "automatortypes": { * "chef-solo": { * "cookbooks": { * "format": "archive|file", * "active": [ * { * "name":"reactor", * "version":9 * } * ] * } * }, * ... * }, * } */ for (ImmutablePair<ResourceType, ResourceTypeFormat> key : src.getResources().keySet()) { ResourceType resourceType = key.getFirst(); ResourceTypeFormat format = key.getSecond(); String pluginTypeStr = pluginTypeToStr(resourceType.getPluginType()); String pluginName = resourceType.getPluginName(); String resourceTypeStr = resourceType.getTypeName(); // ex: json object for automatortypes JsonObject pluginTypeObj = out.getAsJsonObject(pluginTypeStr); if (!pluginTypeObj.has(pluginName)) { pluginTypeObj.add(pluginName, new JsonObject()); } // ex: json object for chef-solo JsonObject pluginObj = pluginTypeObj.getAsJsonObject(pluginName); if (!pluginObj.has(resourceTypeStr)) { pluginObj.add(resourceTypeStr, new JsonObject()); } // ex: json object for cookbooks JsonObject resourceListObj = pluginObj.getAsJsonObject(resourceTypeStr); // write the format resourceListObj.add("format", context.serialize(format)); // write the list of active resources JsonArray activeList = new JsonArray(); for (ResourceMeta meta : src.getResources().get(key)) { JsonObject metaObj = new JsonObject(); metaObj.addProperty("name", meta.getName()); metaObj.addProperty("version", meta.getVersion()); activeList.add(metaObj); } resourceListObj.add("active", activeList); } return out; }
From source file:com.continuuity.loom.http.handler.LoomClusterHandler.java
License:Apache License
/** * Get all clusters visible to the user. * * @param request Request for clusters.// w ww. ja va 2 s . co m * @param responder Responder for sending the response. */ @GET public void getClusters(HttpRequest request, HttpResponder responder) { Account account = getAndAuthenticateAccount(request, responder); if (account == null) { return; } List<Cluster> clusters = null; try { clusters = clusterStoreService.getView(account).getAllClusters(); } catch (IOException e) { responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Exception getting clusters."); } JsonArray jsonArray = new JsonArray(); for (Cluster cluster : clusters) { JsonObject obj = new JsonObject(); obj.addProperty("id", cluster.getId()); obj.addProperty("name", cluster.getName()); obj.addProperty("createTime", cluster.getCreateTime()); obj.addProperty("expireTime", cluster.getExpireTime()); obj.addProperty("clusterTemplate", cluster.getClusterTemplate() == null ? "..." : cluster.getClusterTemplate().getName()); obj.addProperty("numNodes", cluster.getNodes().size()); obj.addProperty("status", cluster.getStatus().name()); obj.addProperty("ownerId", cluster.getAccount().getUserId()); jsonArray.add(obj); } responder.sendJson(HttpResponseStatus.OK, jsonArray); }
From source file:com.continuuity.loom.http.handler.LoomClusterHandler.java
License:Apache License
/** * Get all plans for cluster operations that have taken place or are currently taking place on a cluster. * * @param request Request for cluster plans. * @param responder Responder for sending the response. * @param clusterId Id of the cluster whose plans we have to fetch. *//*from w w w. ja v a 2 s. co m*/ @GET @Path("/{cluster-id}/plans") public void getPlansForCluster(HttpRequest request, HttpResponder responder, @PathParam("cluster-id") String clusterId) { Account account = getAndAuthenticateAccount(request, responder); if (account == null) { return; } try { JsonArray jobsJson = new JsonArray(); List<ClusterJob> jobs = clusterStoreService.getView(account).getClusterJobs(clusterId, -1); if (jobs.isEmpty()) { responder.sendError(HttpResponseStatus.NOT_FOUND, "Plans for cluster " + clusterId + " not found."); return; } for (ClusterJob clusterJob : jobs) { jobsJson.add(formatJobPlan(clusterJob)); } responder.sendJson(HttpResponseStatus.OK, jobsJson); } catch (IllegalArgumentException e) { LOG.error("Exception getting plans for cluster {}.", clusterId, e); responder.sendError(HttpResponseStatus.BAD_REQUEST, e.getMessage()); } catch (IOException e) { responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Exception getting cluster plans."); } }
From source file:com.continuuity.loom.http.handler.LoomClusterHandler.java
License:Apache License
private JsonObject formatJobPlan(ClusterJob job) throws IOException { JsonObject jobJson = new JsonObject(); jobJson.addProperty("id", job.getJobId()); jobJson.addProperty("clusterId", job.getClusterId()); jobJson.addProperty("action", job.getClusterAction().name()); jobJson.addProperty("currentStage", job.getCurrentStageNumber()); JsonArray stagesJson = new JsonArray(); for (Set<String> stage : job.getStagedTasks()) { JsonArray stageJson = new JsonArray(); for (String taskId : stage) { ClusterTask task = clusterStore.getClusterTask(TaskId.fromString(taskId)); JsonObject taskJson = new JsonObject(); taskJson.addProperty("id", task.getTaskId()); taskJson.addProperty("taskName", task.getTaskName().name()); taskJson.addProperty("nodeId", task.getNodeId()); taskJson.addProperty("service", task.getService()); stageJson.add(taskJson); }//from w w w .jav a 2s . com stagesJson.add(stageJson); } jobJson.add("stages", stagesJson); return jobJson; }
From source file:com.continuuity.loom.http.handler.LoomRPCHandler.java
License:Apache License
/** * Get the cluster status for all clusters readable by the user making the request. * * @param request The request for cluster statuses. * @param responder Responder for sending the response. * @throws Exception/*from w w w. j a v a2s . c om*/ */ @POST @Path("/getClusterStatuses") public void getClusterStatuses(HttpRequest request, HttpResponder responder) throws Exception { Account account = getAndAuthenticateAccount(request, responder); if (account == null) { return; } // TODO: Improve this logic by using a table join instead of separate calls for cluster and jobId List<Cluster> clusters = clusterStoreService.getView(account).getAllClusters(); if (clusters.size() == 0) { responder.sendError(HttpResponseStatus.NOT_FOUND, String.format("No clusters found")); return; } JsonArray response = new JsonArray(); Map<JobId, Cluster> clusterMap = Maps.newHashMap(); for (Cluster cluster : clusters) { clusterMap.put(JobId.fromString(cluster.getLatestJobId()), cluster); } Map<JobId, ClusterJob> jobs = clusterStore.getClusterJobs(clusterMap.keySet(), account.getTenantId()); if (jobs.size() == 0) { responder.sendError(HttpResponseStatus.NOT_FOUND, String.format("No jobs found for clusters")); return; } for (JobId jobId : jobs.keySet()) { response.add(LoomClusterHandler.getClusterResponseJson(clusterMap.get(jobId), jobs.get(jobId))); } responder.sendJson(HttpResponseStatus.OK, response); }