org.apache.sling.commons.json.JSONArray Java Examples

The following examples show how to use org.apache.sling.commons.json.JSONArray. 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 vote down vote up
/**
 * 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: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @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 #3
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
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 #4
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
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 #5
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 5 votes vote down vote up
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 #6
Source File: SessionDeserializer.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
@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 #7
Source File: CommentServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #8
Source File: BackupServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #9
Source File: PropertyHandler.java    From development with Apache License 2.0 4 votes vote down vote up
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 #10
Source File: MockURLStreamHandler.java    From development with Apache License 2.0 4 votes vote down vote up
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);
    }
}