org.apache.sling.commons.json.JSONObject Java Examples
The following examples show how to use
org.apache.sling.commons.json.JSONObject.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HealthCheckExecutorServlet.java From aem-healthcheck with Apache License 2.0 | 6 votes |
/** * Creates a JSON representation of the given HealthCheckExecutionResult list. * @param executionResults * @param resultJson * @return * @throws JSONException */ private static JSONObject generateResponse(List<HealthCheckExecutionResult> executionResults, JSONObject resultJson) throws JSONException { JSONArray resultsJsonArr = new JSONArray(); resultJson.put("results", resultsJsonArr); for (HealthCheckExecutionResult healthCheckResult : executionResults) { JSONObject result = new JSONObject(); result.put("name", healthCheckResult.getHealthCheckMetadata() != null ? healthCheckResult.getHealthCheckMetadata().getName() : ""); result.put("status", healthCheckResult.getHealthCheckResult().getStatus()); result.put("timeMs", healthCheckResult.getElapsedTimeInMs()); resultsJsonArr.put(result); } return resultJson; }
Example #2
Source File: AdminServlet.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * Send the JSON response. * * @param writer The PrintWriter. * @param header The header to send. * @param message The message to send. * @param data The data, probably JSON string */ protected void sendResponse(final PrintWriter writer, final String header, final String message, final String data) { try { JSONObject json = new JSONObject(); json.put("header", header); json.put("message", message); if (StringUtils.isNotBlank(data)) { json.put("data", data); } writer.write(json.toString()); } catch (JSONException e) { LOGGER.error("Could not write JSON", e); if (StringUtils.isNotBlank(data)) { writer.write(String.format("{\"header\" : \"%s\", \"message\" : \"%s\", \"data\" : \"%s\"}", header, message, data)); } else { writer.write(String.format("{\"header\" : \"%s\", \"message\" : \"%s\"}", header, message)); } } }
Example #3
Source File: JsonMessageFormatter.java From otroslogviewer with Apache License 2.0 | 6 votes |
@Override public String format(String message) { final ArrayList<SubText> jsonFragments = jsonFinder.findJsonFragments(message); StringBuilder sb = new StringBuilder(); int lastEnd = 0; for (SubText jsonFragment : jsonFragments) { sb.append(message.substring(lastEnd, jsonFragment.getStart())); final String group = jsonFragment.subString(message); String toAppend = group; try { JSONObject o = new JSONObject(group); final String jsonFormatted = o.toString(2); toAppend = jsonFormatted; } catch (JSONException e) { LOGGER.debug("There is no need to format {}", group); } if (!sb.toString().endsWith("\n")) { sb.append("\n"); } sb.append(toAppend).append("\n"); lastEnd = jsonFragment.getEnd(); } sb.append(message.substring(lastEnd)); return sb.toString().trim(); }
Example #4
Source File: JsonExtractor.java From otroslogviewer with Apache License 2.0 | 6 votes |
public List<String> extractFieldValues(String json, String field) { final List<String> lines = Arrays.stream(json.split("\n")).map(String::trim).collect(Collectors.toList()); StringBuilder buffer = new StringBuilder(); List<String> result = new ArrayList<>(); for (String line : lines) { buffer.append(line); if (isJson(buffer.toString())) { try { final JSONObject jsonObject = new JSONObject(buffer.toString()); buffer.setLength(0); Optional.ofNullable(toMap(jsonObject).get(field)) .ifPresent(result::add); } catch (JSONException ignore) { //; } } } return result; }
Example #5
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 6 votes |
private static String respStacks() { try { JSONObject response = new JSONObject(); JSONObject state = new JSONObject(); state.put("label", "OK"); state.put("id", "OK"); response.put("state", state); response.put("id", "1234"); response.put("stack", "1234"); response.put("name", "Appliance1"); response.put("projectUri", "http://test.com/cloud/api/projects/54346"); JSONObject stack = new JSONObject(); stack.put("id", "idValue"); response.put("stack", stack); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #6
Source File: AbstractStackRequest.java From development with Apache License 2.0 | 6 votes |
protected void put(String key, Object value) { if (key == null) { throw new IllegalArgumentException( "JSON object key must not be null!"); } if (!(value instanceof String) && !(value instanceof JSONObject)) { throw new IllegalArgumentException("Object type " + (value == null ? "NULL" : value.getClass().getName()) + " not allowed as JSON value."); } try { request.put(key, value); } catch (JSONException e) { // this can basically not happen throw new IllegalArgumentException(e.getMessage()); } }
Example #7
Source File: JsonExtractor.java From otroslogviewer with Apache License 2.0 | 5 votes |
/** * Tries to parse log event in json form using selected date format * * @param s log fragment * @param dateFormat instance of DateFormat * @return Optional of LogData if log event can be extracted, empty if not. */ protected Optional<LogData> parseJsonLog(String s, DateFormat dateFormat) { try { Validator.validate(s); final JSONObject jsonObject = new JSONObject(s); final Map<String, String> map = toMap(jsonObject); return mapToLogData(map, dateFormat); } catch (JSONException e) { return Optional.empty(); } }
Example #8
Source File: EmailServlet.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Send the JSON response. * * @param writer The PrintWriter. * @param status The status such as 200 or 500. * @param message The message to send. */ private void sendResponse(PrintWriter writer, int status, String message) { try { writer.write(new JSONObject() .put("status", status) .put("message", message) .toString()); } catch (JSONException e) { LOGGER.error("Could not write JSON", e); } }
Example #9
Source File: BackupServlet.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Get a JSONObject from the JCR package configured for the Angular model. * * @param jcrPackage The JCR Package to retrieve data from. * @return the JSON Object configured for the Angular model. * @throws JSONException * @throws RepositoryException * @throws IOException */ private JSONObject getJsonFromJcrPackage(final JcrPackage jcrPackage) throws JSONException, RepositoryException, IOException { final JSONObject json = new JSONObject(); final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); json.put(JSON_SIZE_PROPERTY, getSize(jcrPackage.getPackage().getSize())); json.put(JSON_DATE_PROPERTY, dateFormat.format(jcrPackage.getPackage().getCreated().getTime())); json.put(JSON_NAME_PROPERTY, jcrPackage.getDefinition().getId().getName()); json.put(JSON_PATH_PROPERTY, jcrPackage.getNode().getPath()); json.put(JSON_ID_PROPERTY, jcrPackage.getDefinition().getId().toString()); return json; }
Example #10
Source File: BackupServlet.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Return all packages on a GET request in order of newest to oldest. */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final PrintWriter writer = response.getWriter(); response.setCharacterEncoding(CharEncoding.UTF_8); response.setContentType("application/json"); List<JcrPackage> packages = packageService.getPackageList(request); try { JSONArray jsonArray = new JSONArray(); for (JcrPackage jcrPackage : packages) { final JSONObject json = getJsonFromJcrPackage(jcrPackage); jsonArray.put(json); } response.setStatus(SlingHttpServletResponse.SC_OK); writer.write(jsonArray.toString()); } catch (JSONException | RepositoryException e) { LOGGER.error("Could not write JSON", e); response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
Example #11
Source File: CommentServlet.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Return all comments on a GET request in order of newest to oldest. */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final PrintWriter writer = response.getWriter(); response.setCharacterEncoding(CharEncoding.UTF_8); response.setContentType("application/json"); List<Resource> comments = commentService.getComments(request); try { JSONArray jsonArray = new JSONArray(); for (Resource comment : comments) { final JSONObject json = new JSONObject(); final ValueMap properties = comment.getValueMap(); final Resource post = commentService.getParentPost(comment); json.put(PublickConstants.COMMENT_PROPERTY_COMMENT, properties.get(PublickConstants.COMMENT_PROPERTY_COMMENT, String.class)); json.put(JSON_ID, properties.get(JcrConstants.JCR_UUID, String.class)); json.put(JSON_EDITED, properties.get(PublickConstants.COMMENT_PROPERTY_EDITED, false)); json.put(JSON_REPLIES, commentService.numberOfReplies(comment)); json.put(JSON_SPAM, properties.get(PublickConstants.COMMENT_PROPERTY_SPAM, false)); json.put(JSON_POST, new JSONObject() .put(JSON_POST_TEXT, post.getValueMap().get(PublickConstants.COMMENT_PROPERTY_TITLE, String.class)) .put(JSON_POST_LINK, linkRewriter.rewriteLink(post.getPath(), request.getServerName()))); jsonArray.put(json); } response.setStatus(SlingHttpServletResponse.SC_OK); writer.write(jsonArray.toString()); } catch (JSONException e) { LOGGER.error("Could not write JSON", e); response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
Example #12
Source File: JsonPatternParserEditor.java From otroslogviewer with Apache License 2.0 | 5 votes |
private Map<String, String> toMap(StringBuilder sb) { final String text = sb.toString(); try { final JSONObject jsonObject = new JSONObject(text); return JsonExtractor.toMap(jsonObject); } catch (JSONException e) { return new HashMap<>(0); } }
Example #13
Source File: SessionDeserializer.java From otroslogviewer with Apache License 2.0 | 5 votes |
@Override public Optional<List<Session>> deserialize(String data) { final ArrayList<Session> sessions = new ArrayList<>(); try { final JSONArray array = new JSONArray(data); for (int i = 0; i < array.length(); i++) { final JSONObject jsonObject = array.getJSONObject(i); String name = jsonObject.getString("name"); final ArrayList<FileToOpen> fileToOpens = new ArrayList<>(); final JSONArray filesArray = jsonObject.optJSONArray("filesToOpen"); if (filesArray != null){ for (int j = 0; j < filesArray.length(); j++) { final JSONObject filesToOpen = filesArray.getJSONObject(j); String uri = filesToOpen.getString("uri"); Level level = Level.parse(filesToOpen.getString("level")); OpenMode openMode = OpenMode.valueOf(filesToOpen.getString("openMode")); String logImporter = filesToOpen.optString("logImporter", null); fileToOpens.add(new FileToOpen(uri, openMode, level, Optional.ofNullable(logImporter))); } } sessions.add(new Session(name, fileToOpens)); } } catch (JSONException e) { LOGGER.error("Can't deserialize sessions: ", e); Optional.empty(); } LOGGER.info("Returning deserialized sessions: " + sessions.size()); return Optional.of(sessions); }
Example #14
Source File: JsonExtractor.java From otroslogviewer with Apache License 2.0 | 5 votes |
private static Map<String, String> toMap(JSONObject j, Map<String, String> map, String prefix) throws JSONException { final Iterator<String> keys = j.keys(); while (keys.hasNext()) { final String key = keys.next(); final Object o = j.get(key); if (o instanceof JSONObject) { JSONObject jso = (JSONObject) o; toMap(jso, map, prefix + key + VALUES_SEPARATOR); } else { map.put(prefix + key, j.getString(key)); } } return map; }
Example #15
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 5 votes |
/** * @param string * @return */ public static String respFlavor(int id, String flavorName) { try { JSONObject response = new JSONObject(); JSONObject flavor = new JSONObject(); flavor.put("id", id); flavor.put("name", flavorName); response.put("flavor", flavor); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #16
Source File: PropertyHandlerTest.java From development with Apache License 2.0 | 5 votes |
@Test public void TestEmptySecurityGroup() { propertyHandler = new PropertyHandler(settings); final String SECURITY_GROUPS = "SG"; JSONObject parameters = propertyHandler.getTemplateParameters(); assertNotNull(parameters); assertTrue(!parameters.has(SECURITY_GROUPS)); }
Example #17
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 5 votes |
public static String respServerDetail(String serverName, String serverId, ServerStatus status, String tenant_id) { try { JSONObject response = new JSONObject(); JSONObject server = new JSONObject(); response.put("server", server); server.put("name", serverName); server.put("id", serverId); server.put("status", status); server.put("tenant_id", tenant_id); server.put("accessIPv4", "192.0.2.0"); JSONObject flavor = new JSONObject(); flavor.put("id", 1); server.put("flavor", flavor); JSONObject addresses = new JSONObject(); JSONArray networkDetail = new JSONArray(); JSONObject fixedNetwork = new JSONObject(); JSONObject floatingNetwork = new JSONObject(); fixedNetwork.put("OS-EXT-IPS-MAC:mac_addr", "fa:16:3e:e5:b7:f8"); fixedNetwork.put("version", "4"); fixedNetwork.put("addr", "192.168.0.4"); fixedNetwork.put("OS-EXT-IPS:type", "fixed"); floatingNetwork.put("OS-EXT-IPS-MAC:mac_addr", "fa:16:3e:e5:b7:f8"); floatingNetwork.put("version", "4"); floatingNetwork.put("addr", "133.162.161.216"); floatingNetwork.put("OS-EXT-IPS:type", "floating"); networkDetail.put(fixedNetwork); networkDetail.put(floatingNetwork); addresses.put(serverName + "-network", networkDetail); server.put("addresses", addresses); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #18
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 5 votes |
public static String respServer(String serverName, String serverId) { try { JSONObject response = new JSONObject(); JSONObject server = new JSONObject(); response.put("server", server); server.put("name", serverName); server.put("id", serverId); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #19
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 5 votes |
public static String respStacksResources(List<String> serverNames, String resourceType) { try { JSONObject response = new JSONObject(); JSONArray resources = new JSONArray(); response.put("resources", resources); JSONObject volume = new JSONObject(); volume.put("resource_name", "sys-vol"); volume.put("physical_resource_id", "12345"); volume.put("resource_type", "OS::Cinder::Volume"); resources.put(volume); for (int i = 0; i < serverNames.size(); i++) { JSONObject server = new JSONObject(); server.put("resource_name", serverNames.get(i)); server.put("physical_resource_id", Integer.toString(i) + "-Instance-" + serverNames.get(i)); server.put("resource_type", resourceType); resources.put(server); } return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #20
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 5 votes |
public static String respStacksInstanceName(StackStatus status, boolean withStatusReason, String... stackStatusReason) { String reason; if (stackStatusReason == null || stackStatusReason.length == 0) { reason = "SSR"; } else { reason = Arrays.toString(stackStatusReason); } try { JSONObject response = new JSONObject(); JSONObject stack = new JSONObject(); response.put("stack", stack); stack.put("stack_name", "SN"); stack.put("id", "ID"); stack.put("stack_status", status == null ? "bullshit" : status.name()); if (withStatusReason) { stack.put("stack_status_reason", reason); } JSONArray outputs = new JSONArray(); JSONObject output = new JSONObject(); output.put("output_key", "OK"); output.put("output_value", "OV"); outputs.put(output); stack.put("outputs", outputs); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #21
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 5 votes |
/** * @return */ private static String repServers(List<String> serverNames) { try { JSONObject response = new JSONObject(); JSONArray servers = new JSONArray(); for (int i = 0; i < serverNames.size(); i++) { JSONObject server = new JSONObject(); JSONArray links = new JSONArray(); JSONObject linkSelf = new JSONObject(); JSONObject linkBookmark = new JSONObject(); String instanceId = Integer.toString(i) + "-Instance-" + serverNames.get(i); server.put("id", instanceId); linkSelf.put("href", "http://novaendpoint/v2/servers/" + instanceId); linkSelf.put("rel", "self"); links.put(linkSelf); linkBookmark.put("href", "http://novaendpoint/servers/" + instanceId); linkBookmark.put("rel", "self"); links.put(linkBookmark); server.put("links", links); server.put("name", serverNames.get(i)); servers.put(server); } response.put("servers", servers); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #22
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 4 votes |
public static String respStackDeleted() { JSONObject response = new JSONObject(); return response.toString(); }
Example #23
Source File: PropertyHandler.java From development with Apache License 2.0 | 4 votes |
public JSONObject getTemplateParameters() { JSONObject parameters = new JSONObject(); // created security Group array , user can add security group separated // by comma JSONArray securityGroupSecurityGroup = new JSONArray(); Set<String> keySet = settings.getParameters().keySet(); String securityGroup = null; try { for (String key : keySet) { if (key.startsWith(TEMPLATE_PARAMETER_PREFIX)) { if (key.startsWith(TEMPLATE_PARAMETER_ARRAY_PREFIX)) { // below if execute only if technical service parameter // have a // security group parameters securityGroup = key.substring( TEMPLATE_PARAMETER_ARRAY_PREFIX.length()); String securityGroupArray[] = settings.getParameters() .get(key).getValue().split(","); for (String groupName : securityGroupArray) { securityGroupSecurityGroup.put(groupName); } parameters.put(securityGroup, securityGroupSecurityGroup); } else { parameters.put( key.substring( TEMPLATE_PARAMETER_PREFIX.length()), settings.getParameters().get(key).getValue()); } } } // remove the empty parameter from object parameters.remove(""); } catch (JSONException e) { // should not happen with Strings throw new RuntimeException( "JSON error when collection template parameters", e); } return parameters; }
Example #24
Source File: AbstractStackRequest.java From development with Apache License 2.0 | 4 votes |
public AbstractStackRequest withParameters(JSONObject parameters) { put("parameters", parameters); return this; }
Example #25
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 4 votes |
private static String respStacksInstance4sIdActions() { JSONObject response = new JSONObject(); return response.toString(); }
Example #26
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 4 votes |
public static String respServerActions() { JSONObject response = new JSONObject(); return response.toString(); }
Example #27
Source File: MockURLStreamHandler.java From development with Apache License 2.0 | 4 votes |
public static String respTokens(boolean addPublicURL, boolean addPublicURLNova, boolean https) { try { JSONObject response = new JSONObject(); JSONObject token = new JSONObject(); JSONArray serviceCatalog = new JSONArray(); JSONObject endpointsHeat = new JSONObject(); JSONArray endpointsListHeat = new JSONArray(); String httpMethod = https == true ? "https://" : "http://"; endpointsHeat.put("endpoints", endpointsListHeat); if (addPublicURL) { JSONObject publicUrl = new JSONObject(); publicUrl.put("name", KeystoneClient.TYPE_HEAT); publicUrl.put("url", httpMethod + "heatendpoint/"); publicUrl.put("interface", "public"); endpointsListHeat.put(publicUrl); } endpointsHeat.put("type", KeystoneClient.TYPE_HEAT); serviceCatalog.put(endpointsHeat); JSONObject endpointsNova = new JSONObject(); JSONArray endpointsListNova = new JSONArray(); endpointsNova.put("endpoints", endpointsListNova); if (addPublicURLNova) { JSONObject publicUrlNova = new JSONObject(); publicUrlNova.put("name", KeystoneClient.TYPE_NOVA); publicUrlNova.put("url", httpMethod + "novaendpoint/"); endpointsListNova.put(publicUrlNova); } endpointsNova.put("type", KeystoneClient.TYPE_NOVA); serviceCatalog.put(endpointsNova); token.put("id", "authId"); token.put("catalog", serviceCatalog); response.put("token", token); return response.toString(); } catch (JSONException ex) { throw new RuntimeException(ex); } }
Example #28
Source File: HealthCheckExecutorServlet.java From aem-healthcheck with Apache License 2.0 | 4 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); // parse query parameters String tagsStr = StringUtils.defaultString(request.getParameter(PARAM_TAGS)); String[] tags = tagsStr.split("[, ;]+"); String combineTagsOr = StringUtils.defaultString(request.getParameter(PARAM_COMBINE_TAGS_OR), "true"); // execute health checks HealthCheckExecutionOptions options = new HealthCheckExecutionOptions(); options.setCombineTagsWithOr(Boolean.valueOf(combineTagsOr)); options.setForceInstantExecution(true); List<HealthCheckExecutionResult> results = healthCheckExecutor.execute(options, tags); // check results boolean allOk = true; for(HealthCheckExecutionResult result : results) { if(!result.getHealthCheckResult().isOk()) { allOk = false; break; } } // set appropriate status code if(!allOk) { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { response.setStatus(HttpServletResponse.SC_OK); } // write out JSON response JSONObject resultJson = new JSONObject(); try { generateResponse(results, resultJson); } catch(JSONException ex) { logger.error("Could not serialize result into JSON", ex); } response.getWriter().write(resultJson.toString()); }
Example #29
Source File: JsonExtractor.java From otroslogviewer with Apache License 2.0 | 2 votes |
/** * Convert Json object to map representation. Nested object are represented by keys like xpath (dot separated) * * @param j Json object t convert * @return map representation of json object * @throws JSONException if log can't be parsed into JSON */ public static Map<String, String> toMap(JSONObject j) throws JSONException { return toMap(j, new HashMap<>(), StringUtils.EMPTY); }