List of usage examples for com.google.gson JsonArray JsonArray
public JsonArray()
From source file:com.confighub.core.utils.Utils.java
License:Open Source License
public static String jsonMapToJsonList(String jsonMap) throws ConfigException { try {/*from w w w . ja v a2 s. c om*/ 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 w w w . j a va2 s . co 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));// w w w.java2 s .c o 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()); /*// w w w. j a v a 2s . c o m * 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 w w .ja v a 2 s .c o 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 www .j a v a2 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.j av a2 s. c o m*/ } 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 a 2 s . 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); }
From source file:com.continuuity.loom.macro.Expander.java
License:Apache License
/** * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree, * recursively traverse all elements, and expand all String typed right hand side values. If a macro cannot be * expanded due to the cluster object missing certain data, that macro will be left unexpanded. * * @param json A JSON tree//from w w w. j a v a2 s . co m * @param path the path to expand under * @param cluster the cluster to use for expanding macros. * @param nodes the cluster nodes to use for expanding macros. * @param node the cluster node to use for expanding macros. * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise. * @throws SyntaxException if a macro expression is ill-formed. * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros. */ public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster, Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException { // if path is given, if (path != null && !path.isEmpty()) { String first = path.get(0); if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonElement json1 = object.get(first); if (json1 != null) { JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node); if (expanded != json1) { // only construct new json object if actual expansion happened JsonObject object1 = new JsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue()); } return object1; } } } // path was given, but either no corresponding subtree was found or no expansion happened... return json; } if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { String value = primitive.getAsString(); String expanded = expand(value, cluster, nodes, node); if (!expanded.equals(value)) { // only return a new json element if actual expansion happened return new JsonPrimitive(expanded); } } } if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); JsonArray array1 = new JsonArray(); boolean expansionHappened = false; for (JsonElement element : array) { JsonElement expanded = expand(element, path, cluster, nodes, node); if (expanded != element) { expansionHappened = true; } array1.add(expanded); } // only return a new json array if actual expansion happened if (expansionHappened) { return array1; } } if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonObject object1 = new JsonObject(); boolean expansionHappened = false; for (Map.Entry<String, JsonElement> entry : object.entrySet()) { JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node); if (expanded != entry.getValue()) { expansionHappened = true; } object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node)); } if (expansionHappened) { return object1; } } return json; }
From source file:com.controller.dialog.ShowNewAnnDetail.java
/** * /*from ww w .j av a 2 s .co m*/ * * @return * @throws Exception */ @RequestMapping(params = "query", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody public String doQuery(HttpServletRequest req) throws Exception { JsonArray jsonArray = new JsonArray(); String queryStr = req.getParameter("queryStr").trim(); JsonObject rtnJson = new JsonObject(); try { //?Service AnnouncementHeaderService announcementHeaderService = (AnnouncementHeaderService) ServiceFactory .getService("announcementHeaderService"); List<AnnouncementHeader> list; if (queryStr.isEmpty()) { list = announcementHeaderService.findAll(); } else { AnnouncementHeader annHeader = new AnnouncementHeader(); annHeader.setAnnouncementDesc(queryStr); list = announcementHeaderService.query(annHeader); } if (list != null && !list.isEmpty()) { list.stream().map((AnnouncementHeader annObj) -> { JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("AnnouncementDesc", annObj.getAnnouncementDesc() + "<input type='hidden' id='hidAnnID' value='" + annObj.getAnnID() + "' />"); jsonObj.addProperty("BegTime", String.valueOf(annObj.getBegTime())); return jsonObj; }).forEach(jsonArray::add); } if (jsonArray.size() == 0) { rtnJson.addProperty("fail", "??"); } else { rtnJson.addProperty("success", jsonArray.toString()); } } catch (Exception e) { throw e; } return rtnJson.toString(); }