Search in sources :

Example 61 with JSONObject

use of org.apache.sling.commons.json.JSONObject in project acs-aem-commons by Adobe-Consulting-Services.

the class CustomPollingImporterListServlet method doGet.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    XSSAPI xssApi = request.adaptTo(XSSAPI.class);
    try {
        JSONObject result = new JSONObject();
        JSONArray list = new JSONArray();
        result.put("list", list);
        ServiceReference[] services = tracker.getServiceReferences();
        if (services != null) {
            for (ServiceReference service : services) {
                String displayName = PropertiesUtil.toString(service.getProperty("displayName"), null);
                String[] schemes = PropertiesUtil.toStringArray(service.getProperty(Importer.SCHEME_PROPERTY));
                if (displayName != null && schemes != null) {
                    for (String scheme : schemes) {
                        JSONObject obj = new JSONObject();
                        obj.put("qtip", "");
                        obj.put("text", displayName);
                        obj.put("text_xss", xssApi.encodeForJSString(displayName));
                        obj.put("value", scheme);
                        list.put(obj);
                    }
                }
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        result.write(response.getWriter());
    } catch (JSONException e) {
        throw new ServletException("Unable to generate importer list", e);
    }
}
Also used : XSSAPI(org.apache.sling.xss.XSSAPI) ServletException(javax.servlet.ServletException) JSONObject(org.apache.sling.commons.json.JSONObject) JSONArray(org.apache.sling.commons.json.JSONArray) JSONException(org.apache.sling.commons.json.JSONException) ServiceReference(org.osgi.framework.ServiceReference)

Example 62 with JSONObject

use of org.apache.sling.commons.json.JSONObject in project acs-aem-commons by Adobe-Consulting-Services.

the class JsonEventLogger method constructMessage.

/**
 * Serializes an OSGi {@link org.osgi.service.event.Event} into a JSON object string
 *
 * @param event the event to be serialized as
 * @return a serialized JSON object
 * @throws org.apache.sling.commons.json.JSONException
 */
protected static String constructMessage(Event event) throws JSONException {
    JSONObject obj = new JSONObject();
    for (String prop : event.getPropertyNames()) {
        Object val = event.getProperty(prop);
        Object converted = convertValue(val);
        obj.put(prop, converted == null ? val : converted);
    }
    obj.put(PROP_TIMESTAMP, ISO8601.format(Calendar.getInstance()));
    return obj.toString();
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) JSONObject(org.apache.sling.commons.json.JSONObject)

Example 63 with JSONObject

use of org.apache.sling.commons.json.JSONObject in project acs-aem-commons by Adobe-Consulting-Services.

the class RemoveServlet method doPost.

@Override
public final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    List<String> statuses = new ArrayList<String>();
    List<String> models = new ArrayList<String>();
    List<Pattern> payloads = new ArrayList<Pattern>();
    Calendar olderThan = null;
    try {
        JSONObject params = new JSONObject(request.getParameter("params"));
        JSONArray jsonArray = params.optJSONArray(PARAM_WORKFLOW_STATUSES);
        for (int i = 0; i < jsonArray.length(); i++) {
            statuses.add(jsonArray.getString(i));
        }
        jsonArray = params.optJSONArray(PARAM_WORKFLOW_MODELS);
        for (int i = 0; i < jsonArray.length(); i++) {
            models.add(jsonArray.getString(i));
        }
        jsonArray = params.optJSONArray(PARAM_WORKFLOW_PAYLOADS);
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject tmp = jsonArray.getJSONObject(i);
            final String pattern = tmp.optString("pattern");
            if (StringUtils.isNotBlank(pattern)) {
                payloads.add(Pattern.compile(pattern));
            }
        }
        final Long ts = params.optLong(PARAM_OLDER_THAN);
        if (ts != null && ts > 0) {
            olderThan = Calendar.getInstance();
            olderThan.setTimeInMillis(ts * MS_IN_SECOND);
        }
        int batchSize = params.optInt(PARAM_BATCH_SIZE);
        if (batchSize < 1) {
            batchSize = DEFAULT_BATCH_SIZE;
        }
        int maxDuration = params.optInt(PARAM_MAX_DURATION);
        if (maxDuration < 1) {
            maxDuration = DEFAULT_MAX_DURATION;
        }
        workflowInstanceRemover.removeWorkflowInstances(request.getResourceResolver(), models, statuses, payloads, olderThan, batchSize, maxDuration);
    } catch (WorkflowRemovalForceQuitException e) {
        response.setStatus(599);
        response.getWriter().write("Workflow removal force quit");
    } catch (Exception e) {
        log.error("An error occurred while attempting to remove workflow instances.", e);
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        if (response.getWriter() != null) {
            response.getWriter().write(e.getMessage());
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) JSONObject(org.apache.sling.commons.json.JSONObject) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) JSONArray(org.apache.sling.commons.json.JSONArray) ServletException(javax.servlet.ServletException) WorkflowRemovalForceQuitException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalForceQuitException) IOException(java.io.IOException) WorkflowRemovalForceQuitException(com.adobe.acs.commons.workflow.bulk.removal.WorkflowRemovalForceQuitException)

Example 64 with JSONObject

use of org.apache.sling.commons.json.JSONObject in project acs-aem-commons by Adobe-Consulting-Services.

the class JSONErrorUtil method sendJSONError.

public static void sendJSONError(SlingHttpServletResponse response, int statusCode, String title, String message) throws IOException {
    response.setStatus(statusCode);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    JSONObject json = new JSONObject();
    try {
        json.put("title", title);
        json.put("message", message);
        response.getWriter().write(json.toString());
    } catch (JSONException e) {
        String jsonString = "{title: \"Error constructing error message\"}";
        response.getWriter().write(jsonString);
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) JSONException(org.apache.sling.commons.json.JSONException)

Example 65 with JSONObject

use of org.apache.sling.commons.json.JSONObject in project acs-aem-commons by Adobe-Consulting-Services.

the class StartServlet method doPost.

@Override
@SuppressWarnings("squid:S1192")
protected final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    try {
        final JSONObject params = new JSONObject(request.getParameter("params"));
        final ModifiableValueMap properties = request.getResource().adaptTo(ModifiableValueMap.class);
        properties.put("runnerType", params.getString("runnerType"));
        properties.put("queryType", params.getString("queryType"));
        properties.put("queryStatement", params.getString("queryStatement"));
        properties.put("relativePath", StringUtils.removeStart(params.optString("relativePath", ""), "/"));
        properties.put("workflowModel", params.getString("workflowModelId"));
        properties.put("interval", params.optInt("interval", 10));
        properties.put("timeout", params.optInt("timeout", 30));
        properties.put("throttle", params.optInt("throttle", 10));
        properties.put("retryCount", params.optInt("retryCount", 0));
        properties.put("batchSize", params.optInt("batchSize", 10));
        String userEventData = params.optString("userEventData", null);
        if (userEventData != null && !userEventData.isEmpty()) {
            properties.put("userEventData", userEventData);
        }
        properties.put("purgeWorkflow", params.optBoolean("purgeWorkflow", false));
        properties.put("autoThrottle", params.optBoolean("autoThrottle", true));
        if (AEMWorkflowRunnerImpl.class.getName().equals(properties.get("runnerType", String.class)) && isTransient(request.getResourceResolver(), properties.get("workflowModel", String.class))) {
            properties.put("runnerType", AEMTransientWorkflowRunnerImpl.class.getName());
        }
        // If FAM retires are enabled, then force BatchSize to be 1
        if (FastActionManagerRunnerImpl.class.getName().equals(properties.get("runnerType", "")) && properties.get("retryCount", 0) > 0) {
            properties.put("batchSize", 1);
        }
        request.getResourceResolver().commit();
        Config config = request.getResource().adaptTo(Config.class);
        bulkWorkflowEngine.initialize(config);
        bulkWorkflowEngine.start(config);
        response.sendRedirect(request.getResourceResolver().map(request, request.getResource().getPath()) + ".status.json");
    } catch (JSONException e) {
        log.error("Could not parse HTTP Request params: {}", e);
        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not initialize Bulk Workflow due to invalid parameters." + " Please review the form and try again.", e.getMessage());
    } catch (RepositoryException e) {
        log.error("Could not initialize Bulk Workflow: {}", e);
        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not initialize Bulk Workflow.", e.getMessage());
    } catch (IllegalArgumentException e) {
        log.warn("Could not initialize Bulk Workflow due to invalid arguments: {}", e);
        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not initialize Bulk Workflow due to invalid arguments.", e.getMessage());
    } catch (Exception e) {
        log.error("Could not initialize Bulk Workflow due to unexpected error: {}", e);
        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not start Bulk Workflow.", e.getMessage());
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) Config(com.adobe.acs.commons.workflow.bulk.execution.model.Config) JSONException(org.apache.sling.commons.json.JSONException) RepositoryException(javax.jcr.RepositoryException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) JSONException(org.apache.sling.commons.json.JSONException) RepositoryException(javax.jcr.RepositoryException) AEMTransientWorkflowRunnerImpl(com.adobe.acs.commons.workflow.bulk.execution.impl.runners.AEMTransientWorkflowRunnerImpl)

Aggregations

JSONObject (org.apache.sling.commons.json.JSONObject)74 JSONArray (org.apache.sling.commons.json.JSONArray)22 Test (org.junit.Test)20 JSONException (org.apache.sling.commons.json.JSONException)16 HashMap (java.util.HashMap)15 ValueMap (org.apache.sling.api.resource.ValueMap)9 Map (java.util.Map)8 ArrayList (java.util.ArrayList)6 ServletException (javax.servlet.ServletException)6 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)6 Resource (org.apache.sling.api.resource.Resource)6 RepositoryException (javax.jcr.RepositoryException)5 Calendar (java.util.Calendar)4 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)4 Config (com.adobe.acs.commons.workflow.bulk.execution.model.Config)3 IOException (java.io.IOException)3 LinkedHashMap (java.util.LinkedHashMap)3 Session (javax.jcr.Session)3 ModifiableValueMapDecorator (org.apache.sling.api.wrappers.ModifiableValueMapDecorator)3 Form (com.adobe.acs.commons.forms.Form)2