Java Code Examples for org.apache.sling.commons.json.JSONObject#put()

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