List of usage examples for com.google.gson JsonObject add
public void add(String property, JsonElement value)
From source file:com.adobe.acs.commons.workflow.bulk.execution.impl.servlets.InitFormServlet.java
License:Apache License
private JsonObject accumulate(JsonObject obj, String key, JsonElement value) { if (obj.has(key)) { JsonElement existingValue = obj.get(key); if (existingValue instanceof JsonArray) { ((JsonArray) existingValue).add(value); } else {// ww w . j a va 2 s. co m JsonArray array = new JsonArray(); array.add(existingValue); obj.add(key, array); } } else { JsonArray array = new JsonArray(); array.add(value); obj.add(key, array); } return obj; }
From source file:com.adobe.acs.commons.workflow.bulk.execution.impl.servlets.StatusServlet.java
License:Apache License
@Override @SuppressWarnings({ "squid:S3776", "squid:S1192" }) protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss aaa"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); Config config = request.getResource().adaptTo(Config.class); Workspace workspace = config.getWorkspace(); final JsonObject json = new JsonObject(); json.addProperty("initialized", workspace.isInitialized()); json.addProperty("status", workspace.getStatus().name()); if (workspace.getSubStatus() != null) { json.addProperty("subStatus", workspace.getSubStatus().name()); }/* w w w. j av a2 s .c om*/ json.addProperty("runnerType", config.getRunnerType()); json.addProperty("queryType", config.getQueryType()); json.addProperty("queryStatement", config.getQueryStatement()); json.addProperty("workflowModel", StringUtils.removeEnd(config.getWorkflowModelId(), "/jcr:content/model")); json.addProperty("batchSize", config.getBatchSize()); json.addProperty("autoThrottle", config.isAutoThrottle()); json.addProperty("purgeWorkflow", config.isPurgeWorkflow()); json.addProperty("interval", config.getInterval()); json.addProperty("retryCount", config.getRetryCount()); json.addProperty("timeout", config.getTimeout()); json.addProperty("throttle", config.getThrottle()); json.addProperty("message", workspace.getMessage()); if (config.isUserEventData()) { json.addProperty("userEventData", config.getUserEventData()); } ActionManager actionManager = actionManagerFactory.getActionManager(workspace.getActionManagerName()); if (actionManager != null && !Status.COMPLETED.equals(workspace.getStatus())) { JsonArray failures = new JsonArray(); json.add("failures", failures); // If Complete, then look to JCR for final accounts as ActionManager may be gone addActionManagerTrackedCounts(workspace.getActionManagerName(), json); for (com.adobe.acs.commons.fam.Failure failure : actionManager.getFailureList()) { JsonObject failureJSON = new JsonObject(); failureJSON.addProperty(Failure.PN_PAYLOAD_PATH, failure.getNodePath()); failureJSON.addProperty(Failure.PN_FAILED_AT, sdf.format(failure.getTime().getTime())); failures.add(failureJSON); } } else { addWorkspaceTrackedCounts(workspace, json); JsonArray failures = new JsonArray(); json.add("failures", failures); // Failures for (Failure failure : workspace.getFailures()) { failures.add(failure.toJSON()); } } // Times if (workspace.getStartedAt() != null) { json.addProperty("startedAt", sdf.format(workspace.getStartedAt().getTime())); json.addProperty("timeTakenInMillis", (Calendar.getInstance().getTime().getTime() - workspace.getStartedAt().getTime().getTime())); } if (workspace.getStoppedAt() != null) { json.addProperty("stoppedAt", sdf.format(workspace.getStoppedAt().getTime())); json.addProperty("timeTakenInMillis", (workspace.getStoppedAt().getTime().getTime() - workspace.getStartedAt().getTime().getTime())); } if (workspace.getCompletedAt() != null) { json.addProperty("completedAt", sdf.format(workspace.getCompletedAt().getTime())); json.addProperty("timeTakenInMillis", (workspace.getCompletedAt().getTime().getTime() - workspace.getStartedAt().getTime().getTime())); } if (AEMWorkflowRunnerImpl.class.getName().equals(config.getRunnerType())) { JsonArray activePayloads = new JsonArray(); json.add("activePayloads", activePayloads); for (Payload payload : config.getWorkspace().getActivePayloads()) { activePayloads.add(payload.toJSON()); } } json.add("systemStats", getSystemStats()); Gson gson = new Gson(); gson.toJson(json, response.getWriter()); }
From source file:com.adobe.acs.commons.workflow.bulk.removal.impl.servlets.InitServlet.java
License:Apache License
@Override public final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); final JsonObject json = new JsonObject(); try {// w w w .j av a 2s. co m // Only populate the form if removal is not running. json.add("form", this.getFormJSONObject(request.getResourceResolver())); Gson gson = new Gson(); gson.toJson(json, response.getWriter()); } catch (Exception e) { response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(e.getMessage()); } }
From source file:com.adobe.acs.commons.workflow.bulk.removal.impl.servlets.InitServlet.java
License:Apache License
/** * Get the JSON data to populate the Workflow Removal form. * * @param resourceResolver/*from w w w . j a v a2 s . c o m*/ * @return * @throws WorkflowException */ private JsonObject getFormJSONObject(final ResourceResolver resourceResolver) throws WorkflowException { final JsonObject json = new JsonObject(); final WorkflowSession workflowSession = workflowService .getWorkflowSession(resourceResolver.adaptTo(Session.class)); final WorkflowModel[] workflowModels = workflowSession.getModels(); JsonArray models = new JsonArray(); json.add("workflowModels", models); for (final WorkflowModel workflowModel : workflowModels) { final JsonObject jsonWorkflow = new JsonObject(); jsonWorkflow.addProperty("title", workflowModel.getTitle()); jsonWorkflow.addProperty("id", workflowModel.getId()); models.add(jsonWorkflow); } Gson gson = new Gson(); json.add("statuses", gson.toJsonTree(Arrays.asList(WORKFLOW_STATUSES))); return json; }
From source file:com.adssets.api.Scout24.java
public String sortData(JsonObject outObj) { List<JsonObject> jsonValues = new ArrayList<>(); for (int i = 0; i < outObj.get("offer").getAsJsonArray().size(); i++) { if (outObj.get("offer").getAsJsonArray().get(i).getAsJsonObject().has("amortizationData")) { JsonObject obj = new JsonObject(); obj.add("amortizationData", outObj.get("offer").getAsJsonArray().get(i).getAsJsonObject().get("amortizationData")); obj.add("distanceToSearchLocation", outObj.get("offer").getAsJsonArray().get(i).getAsJsonObject() .get("distanceToSearchLocation")); obj.add("logo", outObj.get("offer").getAsJsonArray().get(i).getAsJsonObject() .get("mortgageProvider").getAsJsonObject().get("logo")); obj.add("landingPageUrl", outObj.get("offer").getAsJsonArray().get(i).getAsJsonObject() .get("mortgageProvider").getAsJsonObject().get("landingPageUrl")); obj.add("footnote", outObj.get("offer").getAsJsonArray().get(i).getAsJsonObject().get("footnote")); jsonValues.add(obj);// ww w. j a v a2 s .c om } } Collections.sort(jsonValues, new Comparator<JsonObject>() { private static final String KEY_NAME = "distanceToSearchLocation"; @Override public int compare(JsonObject a, JsonObject b) { int valA; int valB; try { if (!a.get(KEY_NAME).isJsonNull() && !b.get(KEY_NAME).isJsonNull()) { valA = (Integer) a.get(KEY_NAME).getAsInt(); valB = (Integer) b.get(KEY_NAME).getAsInt(); return valA - valB; } else { return -1; } } catch (Exception e) { System.err.println(a); System.err.println(b); System.err.println(e); } return -1; } }); return jsonValues.toString(); }
From source file:com.adssets.ejb.DataAccess.java
@Override public String buildFeedForMarket(String marketId, String lazyLoad) { JsonArray jsonArray = new JsonArray(); JsonParser parser = new JsonParser(); // Feed feed = feedFacade.find(marketId); Market market = marketFacade.find(Integer.valueOf(marketId)); List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market) .getResultList();/* ww w. j av a2 s .co m*/ if (feeds.size() > 0) { for (Feed feed : feeds) { JsonObject obj = new JsonObject(); obj.addProperty("id", feed.getId()); obj.addProperty("marketId", feed.getIdmarket().getId()); obj.addProperty("json", feed.getJson()); jsonArray.add(obj); } JsonObject obj = jsonArray.get(0).getAsJsonObject(); String objArray = obj.get("json").getAsString(); JsonArray objArrayParsed = parser.parse(objArray).getAsJsonArray(); JsonArray objData = new JsonArray(); for (JsonElement objId : objArrayParsed) { JsonObject objElmParsed = parser.parse(objId.toString()).getAsJsonObject(); System.out.println(objElmParsed); // try{ // isInteger(objId.getAsString()); String value = objElmParsed.get("type").getAsString(); System.out.println(value); //CHANGE ADPICTURE TO THE PICTURE STORED IN THE DATABASE if (value.equals("object")) { String result = scout24.getApartments(objElmParsed.get("objectid").getAsString()); if (!result.equals("{\"error\":1}")) { JsonObject resultObj = parser.parse(result).getAsJsonObject(); String link = "{\"link\": \"https://www.immobilienscout24.de/expose/" + objElmParsed.get("objectid").getAsInt() + "?referrer=\"}"; JsonObject clickLink = parser.parse(link).getAsJsonObject(); resultObj.add("clickLink", clickLink); resultObj.add("objectId", objElmParsed.get("objectid")); resultObj.add("marketId", parser.parse(marketId)); // Use the selected image as ad image JsonObject objHref = new JsonObject(); objHref.add("href", objElmParsed.get("url")); resultObj.add("adpicture", objHref); //If lazyLoad = yes dont return "allpictures" LazyLoad=yes is the parameter the ad will send so it does not get unneccesary data if (lazyLoad.equals("yes")) { resultObj.remove("allpictures"); } objData.add(resultObj); } } else { objData.add(objId); } // }catch(UnsupportedOperationException ex){ // objData.add(objId); // } } return objData.toString(); } else { return new JsonArray().toString(); } }
From source file:com.afspq.model.Results.java
License:Apache License
/** * Creates the Json object for the keywords space tree visualization. * //from www . j a v a 2 s . c om * @param query * @param search * @param searchResults */ @SuppressWarnings("unchecked") private void createKeywordsTree(String query, Search search, SearchResults searchResults) { ArrayList<?> visualizationList = search.getVisualizations(searchResults); HashMap<String, HashSet<String>> keywordsTreeMap = (HashMap<String, HashSet<String>>) visualizationList .get(1); if (keywordsTreeMap == null) { return; } keywordsTreeJson = new JsonObject(); keywordsTreeJson.addProperty("id", "query"); keywordsTreeJson.addProperty("name", query); JsonArray children = new JsonArray(); keywordsTreeJson.add("children", children); int i = 0; for (String title : keywordsTreeMap.keySet()) { if (!keywordsTreeMap.get(title).isEmpty()) { JsonArray grandChildren = new JsonArray(); JsonObject resultTitle = new JsonObject(); String truncatedTitle = ""; // Long titles don't fit nicely in the visualization tree node // so if the title is longer than 20 characters truncate it and // add "..." if (title.length() > 20) { truncatedTitle = title.substring(0, 21).concat("..."); } else { truncatedTitle = title; } resultTitle.addProperty("id", title); resultTitle.addProperty("name", truncatedTitle); resultTitle.add("children", grandChildren); HashSet<String> keywords = keywordsTreeMap.get(title); for (String keyword : keywords) { JsonObject key = new JsonObject(); key.addProperty("id", "k" + i++); key.addProperty("name", keyword); grandChildren.add(key); } children.add(resultTitle); } } }
From source file:com.afspq.model.Results.java
License:Apache License
/** * Creates the Json object for the page rank graph visualizaiton. * //from w ww . j ava2 s. c o m * @param query * @param search * @param searchResults */ @SuppressWarnings("unchecked") private void createPageRankGraph(String query, Search search, SearchResults searchResults) { ArrayList<?> visualizationList = search.getVisualizations(searchResults); HashMap<String, EdgeLinks> pageRankMap = (HashMap<String, EdgeLinks>) visualizationList.get(2); if (pageRankMap == null) { return; } nodesArr = new JsonArray(); // Colors for the nodes. Selected randomly. String[] colorsArr = { "#003DF5", "#B800F5", "#F500B8", "#00B8F5", "#3366FF", "#F5003D", "#00F5B8", "#FFCC33", "#F53D00", "#00F53D", "#B8F500", "#F5B800" }; HashMap<Integer, String> colorMap = new HashMap<Integer, String>(); for (int i = 0; i < colorsArr.length; i++) { colorMap.put(i, colorsArr[i]); } SecureRandom sr = new SecureRandom(); for (Map.Entry<String, EdgeLinks> urlEntry : pageRankMap.entrySet()) { String key = urlEntry.getKey(); EdgeLinks value = urlEntry.getValue(); double dim = value.getPageRank() * 15000 / 23; // Adjusting the diameter of the node. dim = (dim > 70) ? dim / 15 : dim; JsonObject node = new JsonObject(); JsonArray adjArr = new JsonArray(); JsonObject data = new JsonObject(); data.addProperty("$type", "circle"); data.addProperty("$color", colorMap.get(sr.nextInt(colorsArr.length))); data.addProperty("$dim", dim); HashMap<String, Double> assocUrls = value.getEdgeUrls(); int i = 0; int ranAdj = sr.nextInt(15); // Each node should have at least 3 edge connections if possible. ranAdj = (ranAdj < 3) ? 3 : ranAdj; for (Map.Entry<String, Double> urlEdge : assocUrls.entrySet()) { if (i < ranAdj) { i++; JsonObject adj = new JsonObject(); JsonObject empData = new JsonObject(); adj.addProperty("nodeTo", urlEdge.getKey()); adj.addProperty("nodeFrom", key); adj.add("data", empData); adjArr.add(adj); } else break; } node.add("adjacencies", adjArr); node.add("data", data); node.addProperty("id", key); node.addProperty("name", key); nodesArr.add(node); } }
From source file:com.agateau.pixelwheels.stats.JsonGameStatsIO.java
License:Open Source License
@Override public void save() { Assert.check(mGameStats != null, "setGameStats() has not been called"); JsonObject root = new JsonObject(); JsonObject trackStatsObject = new JsonObject(); root.add("trackStats", trackStatsObject); for (Map.Entry<String, TrackStats> kv : mGameStats.mTrackStats.entrySet()) { trackStatsObject.add(kv.getKey(), createJsonForTrack(kv.getValue())); }//from w w w.ja va 2 s . c o m String json = mGson.toJson(root); mHandle.writeString(json, false /* append */); }
From source file:com.agateau.pixelwheels.stats.JsonGameStatsIO.java
License:Open Source License
private JsonObject createJsonForTrack(TrackStats trackStats) { JsonObject root = new JsonObject(); root.add("lap", createJsonForResults(trackStats.get(TrackStats.ResultType.LAP))); root.add("total", createJsonForResults(trackStats.get(TrackStats.ResultType.TOTAL))); return root;//ww w . j av a 2s. c om }