List of usage examples for com.google.gson JsonObject toString
@Override
public String toString()
From source file:com.adobe.acs.commons.oak.sql2scorer.impl.servlets.ExplainScoreServlet.java
License:Apache License
@Override protected void doPost(@Nonnull final SlingHttpServletRequest request, @Nonnull final SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=utf-8"); final long limit = ofNullable(request.getParameter(P_LIMIT)).map(Long::valueOf).orElse(10L); final long offset = ofNullable(request.getParameter(P_OFFSET)).map(Long::valueOf).orElse(0L); // require a query statement final String rawStatement = request.getParameter(P_STATEMENT); if (rawStatement == null) { JsonObject obj = new JsonObject(); obj.addProperty(KEY_ERROR, "please submit a valid JCR-SQL2 query in the `statement` parameter."); response.getWriter().write(obj.toString()); return;//from w ww . j ava2s . com } try { final Session session = request.getResourceResolver().adaptTo(Session.class); if (session == null || !session.isLive()) { throw new RepositoryException("failed to get a live JCR session from the request"); } final QueryManager qm = session.getWorkspace().getQueryManager(); // validate the syntax of the raw statement. Query rawQuery = qm.createQuery(rawStatement, Query.JCR_SQL2); rawQuery.setLimit(1L); rawQuery.execute(); // we can then expect the first SELECT to exist and be the instance we want to replace. (case-insensitive) final String statement = rawStatement.replaceFirst("(?i)SELECT", "SELECT [oak:scoreExplanation],"); // create a new query using our enhanced statement final Query query = qm.createQuery(statement, Query.JCR_SQL2); // set limit and offset query.setLimit(limit); query.setOffset(offset); // prepare Gson with QueryExecutingTypeAdapter Gson json = new GsonBuilder() .registerTypeHierarchyAdapter(Query.class, new QueryExecutingTypeAdapter(qm)).create(); // execute the query and write the response. response.getWriter().write(json.toJson(query)); } catch (final InvalidQueryException e) { JsonObject obj = new JsonObject(); obj.addProperty(KEY_ERROR, "please submit a valid JCR-SQL2 query in the `statement` parameter: " + e.getMessage()); response.getWriter().write(obj.toString()); } catch (final RepositoryException e) { JsonObject obj = new JsonObject(); obj.addProperty(KEY_ERROR, e.getMessage()); response.getWriter().write(obj.toString()); } }
From source file:com.adobe.acs.commons.packaging.impl.PackageHelperImpl.java
License:Apache License
/** * {@inheritDoc}/* w w w .j ava 2 s .c om*/ */ public String getSuccessJSON(final JcrPackage jcrPackage) throws RepositoryException { final JsonObject json = new JsonObject(); json.addProperty(KEY_STATUS, "success"); json.addProperty(KEY_PATH, jcrPackage.getNode().getPath()); JsonArray filterSetsArray = new JsonArray(); json.add(KEY_FILTER_SETS, filterSetsArray); final List<PathFilterSet> filterSets = jcrPackage.getDefinition().getMetaInf().getFilter().getFilterSets(); for (final PathFilterSet filterSet : filterSets) { final JsonObject jsonFilterSet = new JsonObject(); jsonFilterSet.addProperty(KEY_IMPORT_MODE, filterSet.getImportMode().name()); jsonFilterSet.addProperty(KEY_ROOT_PATH, filterSet.getRoot()); filterSetsArray.add(jsonFilterSet); } return json.toString(); }
From source file:com.adobe.acs.commons.packaging.impl.PackageHelperImpl.java
License:Apache License
/** * {@inheritDoc}/*from w w w. j a va2s . co m*/ */ public String getPathFilterSetPreviewJSON(final Collection<PathFilterSet> pathFilterSets) { final JsonObject json = new JsonObject(); json.addProperty(KEY_STATUS, "preview"); json.addProperty(KEY_PATH, "Not applicable (Preview)"); JsonArray filterSets = new JsonArray(); json.add(KEY_FILTER_SETS, filterSets); for (final PathFilterSet pathFilterSet : pathFilterSets) { final JsonObject tmp = new JsonObject(); tmp.addProperty(KEY_IMPORT_MODE, "Not applicable (Preview)"); tmp.addProperty(KEY_ROOT_PATH, pathFilterSet.getRoot()); filterSets.add(tmp); } return json.toString(); }
From source file:com.adobe.acs.commons.redirectmaps.impl.RedirectEntriesUtils.java
License:Apache License
protected static final void writeEntriesToResponse(SlingHttpServletRequest request, SlingHttpServletResponse response, String message) throws IOException { log.trace("writeEntriesToResponse"); log.debug("Requesting redirect maps from {}", request.getResource()); RedirectMapModel redirectMap = request.getResource().adaptTo(RedirectMapModel.class); response.setContentType(MediaType.JSON_UTF_8.toString()); JsonObject res = new JsonObject(); res.addProperty("message", message); if (redirectMap != null) { JsonElement entries = gson.toJsonTree(redirectMap.getEntries(), new TypeToken<List<MapEntry>>() { }.getType());// w ww . j a v a 2 s . co m res.add("entries", entries); res.add("invalidEntries", gson.toJsonTree(redirectMap.getInvalidEntries(), new TypeToken<List<MapEntry>>() { }.getType())); } else { throw new IOException("Failed to get redirect map from " + request.getResource()); } IOUtils.write(res.toString(), response.getOutputStream(), StandardCharsets.UTF_8); }
From source file:com.adobe.acs.commons.replication.impl.ReplicateVersionServlet.java
License:Apache License
@Override public final void doPost(SlingHttpServletRequest req, SlingHttpServletResponse res) throws ServletException, IOException { log.debug("Entering ReplicatePageVersionServlet.doPost(..)"); String[] rootPaths = req.getParameterValues("rootPaths"); Date date = getDate(req.getParameter("datetimecal")); String[] agents = req.getParameterValues("cmbAgent"); JsonObject obj = validate(rootPaths, agents, date); if (!obj.has(KEY_ERROR)) { log.debug("Initiating version replication"); List<ReplicationResult> response = replicateVersion.replicate(req.getResourceResolver(), rootPaths, agents, date);//from w w w .j ava 2s .c o m if (log.isDebugEnabled()) { for (final ReplicationResult replicationResult : response) { log.debug("Replication result: {} -- {}", replicationResult.getPath(), replicationResult.getStatus()); } } JsonArray arr = convertResponseToJson(response); obj = new JsonObject(); obj.add(KEY_RESULT, arr); } else { log.debug("Did not attempt to replicate version due to issue with input params"); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); obj.addProperty(KEY_STATUS, KEY_ERROR); } res.setContentType("application/json"); res.getWriter().print(obj.toString()); }
From source file:com.adobe.acs.commons.synth.children.ChildrenAsPropertyResource.java
License:Apache License
/** * Serializes all children data as JSON to the resource's propertyName. * * @throws InvalidDataFormatException/*from w ww .j a v a 2s . c om*/ */ private void serialize() throws InvalidDataFormatException { final long start = System.currentTimeMillis(); final ModifiableValueMap modifiableValueMap = this.resource.adaptTo(ModifiableValueMap.class); JsonObject childrenJSON = new JsonObject(); try { // Add the new entries to the JSON for (Resource childResource : this.orderedCache) { childrenJSON.add(childResource.getName(), this.serializeToJSON(childResource)); } if (childrenJSON.entrySet().size() > 0) { // Persist the JSON back to the Node modifiableValueMap.put(this.propertyName, childrenJSON.toString()); } else { // Nothing to persist; delete the property modifiableValueMap.remove(this.propertyName); } log.debug("Persist operation for [ {} ] in [ {} ms ]", this.resource.getPath() + "/" + this.propertyName, System.currentTimeMillis() - start); } catch (NoSuchMethodException e) { throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString()); } catch (IllegalAccessException e) { throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString()); } catch (InvocationTargetException e) { throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString()); } }
From source file:com.adobe.acs.commons.wcm.impl.CQIncludePropertyNamespaceServlet.java
License:Apache License
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); if (!this.accepts(request)) { response.setStatus(SlingHttpServletResponse.SC_NOT_FOUND); response.getWriter().write("{}"); }//from ww w. jav a2 s . c o m /* Servlet accepts this request */ RequestUtil.setRequestAttribute(request, REQ_ATTR, true); final String namespace = URLDecoder.decode(PathInfoUtil.getSelector(request, NAME_PROPERTY_SELECTOR_INDEX), "UTF-8"); final RequestDispatcherOptions options = new RequestDispatcherOptions(); options.setReplaceSelectors(AEM_CQ_INCLUDE_SELECTORS); final BufferingResponse bufferingResponse = new BufferingResponse(response); request.getRequestDispatcher(request.getResource(), options).forward(request, bufferingResponse); Gson gson = new Gson(); final JsonObject json = gson.toJsonTree(bufferingResponse.getContents()).getAsJsonObject(); final PropertyNamespaceUpdater propertyNamespaceUpdater = new PropertyNamespaceUpdater(namespace); propertyNamespaceUpdater.accept(json); response.getWriter().write(json.toString()); }
From source file:com.adobe.acs.commons.workflow.bulk.execution.impl.servlets.InitFormServlet.java
License:Apache License
@Override protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); final JsonObject json = new JsonObject(); // Runners/* w w w . j a v a2 s .c om*/ accumulate(json, KEY_RUNNER_TYPES, withLabelValue("AEM Workflow", AEMWorkflowRunnerImpl.class.getName())); accumulate(json, KEY_RUNNER_TYPES, withLabelValue("Synthetic Workflow (Single-threaded)", SyntheticWorkflowRunnerImpl.class.getName())); accumulate(json, KEY_RUNNER_TYPES, withLabelValue("Synthetic Workflow (Multi-threaded)", FastActionManagerRunnerImpl.class.getName())); // Query Types accumulate(json, KEY_QUERY_TYPES, withLabelValue("QueryBuilder", "queryBuilder")); accumulate(json, KEY_QUERY_TYPES, withLabelValue("List", "list")); accumulate(json, KEY_QUERY_TYPES, withLabelValue("xPath", "xpath")); accumulate(json, KEY_QUERY_TYPES, withLabelValue("JCR-SQL2", "JCR-SQL2")); accumulate(json, KEY_QUERY_TYPES, withLabelValue("JCR-SQL", "JCR-SQL")); // User Event Data accumulate(json, KEY_USER_EVENT_DATA, withLabelValue("Custom user-event-data", "")); accumulate(json, KEY_USER_EVENT_DATA, withLabelValue("changedByWorkflowProcess", "changedByWorkflowProcess")); accumulate(json, KEY_USER_EVENT_DATA, withLabelValue("acs-aem-commons.bulk-workflow-manager", "acs-aem-commons.bulk-workflow-manager")); // Workflow Models final WorkflowSession workflowSession = workflowService .getWorkflowSession(request.getResourceResolver().adaptTo(Session.class)); try { final WorkflowModel[] workflowModels = workflowSession.getModels(); for (final WorkflowModel workflowModel : workflowModels) { boolean transientWorkflow = isTransient(request.getResourceResolver(), workflowModel.getId()); String workflowLabel = workflowModel.getTitle(); if (transientWorkflow) { workflowLabel += " ( Transient )"; } JsonObject jsonWorkflow = withLabelValue(workflowLabel, workflowModel.getId()); jsonWorkflow.addProperty("transient", transientWorkflow); accumulate(json, "workflowModels", jsonWorkflow); } response.getWriter().write(json.toString()); } catch (WorkflowException e) { log.error("Could not create workflow model drop-down.", e); JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not collect workflows", e.getMessage()); } }
From source file:com.adssets.api.Scout24.java
@Override public String getLoans(String postalcode, String suburb) { try {/*from w w w. j a v a2 s .c om*/ // Make an API call... it is required to sign each request (see below) Boolean getGeoCode = false; URL url; if (postalcode != null) { url = new URL( "http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer?postalcode=" + postalcode); } else if (suburb != null) { getGeoCode = true; suburb = suburb.replace("_", "*"); url = new URL("https://rest.immobilienscout24.de/restapi/api/search/v1.0/region?q=" + suburb); } else { url = new URL("http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer"); } HttpURLConnection requestUrl = null; requestUrl = (HttpURLConnection) url.openConnection(); consumer.sign(requestUrl); requestUrl.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream())); StringBuilder sb = new StringBuilder(); String line; switch (requestUrl.getResponseCode()) { case 200: while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); try { JsonParser parser = new JsonParser(); JsonObject outObj = parser.parse(sb.toString()).getAsJsonObject(); //If a suburb is sent, get the geocode for that suburb if (getGeoCode) { System.out.println("GETGEOCODE"); //Get geoCodeId System.out.println(outObj.toString()); String geoCodeId = outObj.get("region.regions").getAsJsonArray().get(0).getAsJsonObject() .get("region").getAsJsonArray().get(0).getAsJsonObject().get("geoCodeId") .getAsString(); System.out.println(geoCodeId); //1276003001003 1276003001 url = new URL( "http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer?geocode=" + geoCodeId); requestUrl = null; requestUrl = (HttpURLConnection) url.openConnection(); consumer.sign(requestUrl); requestUrl.connect(); br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream())); sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line + "\n"); } outObj = parser.parse(sb.toString()).getAsJsonObject(); return sortData(outObj); } else { return sortData(outObj); } } catch (JSONException je) { je.printStackTrace(); return "{\"error\":2}"; } case 201: while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); try { JSONObject outObj = XML.toJSONObject(sb.toString()); return outObj.toString(); } catch (JSONException je) { je.printStackTrace(); return "{\"error\":2}"; } } } catch (Exception e) { e.printStackTrace(); } return "{\"error\":1}"; }
From source file:com.adssets.servlet.MarketServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//ww w . j a v a 2 s.co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "*"); ; try (PrintWriter out = response.getWriter()) { StringBuilder sb = new StringBuilder(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) sb.append(line); } catch (Exception e) { System.out.println( "com.adssets.servlet.MarketServlet.processRequestPost()" + " Could not read POST body"); } JsonObject jsonObject = (new JsonParser()).parse(sb.toString()).getAsJsonObject(); if (jsonObject.has("name") && jsonObject.has("description")) { String res = data.createMarket(jsonObject.toString()); out.println(res); } else { System.out.println( "com.adssets.servlet.MarketServlet.processRequestPost()" + " Missing fields in body"); } } }