Search in sources :

Example 6 with JSONException

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

the class VanityDuplicateCheckServlet method doGet.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    try {
        final ResourceResolver resolver = request.getResourceResolver();
        final String vanityPath = request.getParameter("vanityPath");
        final String pagePath = request.getParameter("pagePath");
        log.debug("vanity path parameter passed is {}; page path parameter passed is {}", vanityPath, pagePath);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        JSONWriter jsonWriter = new JSONWriter(response.getWriter());
        jsonWriter.array();
        if (StringUtils.isNotBlank(vanityPath)) {
            String xpath = "//element(*)[" + NameConstants.PN_SLING_VANITY_PATH + "='" + vanityPath + "']";
            @SuppressWarnings("deprecation") Iterator<Resource> resources = resolver.findResources(xpath, Query.XPATH);
            while (resources.hasNext()) {
                Resource resource = resources.next();
                String path = resource.getPath();
                if (path.startsWith("/content") && !path.equals(pagePath)) {
                    jsonWriter.value(path);
                }
            }
        }
        jsonWriter.endArray();
    } catch (JSONException e) {
        throw new ServletException("Unable to generate JSON result", e);
    }
}
Also used : JSONWriter(org.apache.sling.commons.json.io.JSONWriter) ServletException(javax.servlet.ServletException) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) JSONException(org.apache.sling.commons.json.JSONException)

Example 7 with JSONException

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

the class QuicklyServlet method doGet.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    final Command cmd = new Command(request);
    response.setHeader("Content-Type", " application/json; charset=UTF-8");
    try {
        response.getWriter().append(quicklyEngine.execute(request, response, cmd).toString());
    } catch (JSONException e) {
        response.sendError(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().print("{\"status:\": \"error\"}");
    }
}
Also used : Command(com.adobe.acs.commons.quickly.Command) JSONException(org.apache.sling.commons.json.JSONException)

Example 8 with JSONException

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

the class CQIncludePropertyNamespaceServlet method doGet.

// @formatter:on
@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(new JSONObject().toString());
    }
    /* 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);
    try {
        final JSONObject json = new JSONObject(bufferingResponse.getContents());
        final PropertyNamespaceUpdater propertyNamespaceUpdater = new PropertyNamespaceUpdater(namespace);
        propertyNamespaceUpdater.accept(json);
        response.getWriter().write(json.toString());
    } catch (JSONException e) {
        log.error("Error composing the cqinclude JSON representation of the widget overlay for [ {} ]", request.getRequestURI(), e);
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(new JSONObject().toString());
    }
}
Also used : BufferingResponse(com.adobe.acs.commons.util.BufferingResponse) RequestDispatcherOptions(org.apache.sling.api.request.RequestDispatcherOptions) JSONObject(org.apache.sling.commons.json.JSONObject) JSONException(org.apache.sling.commons.json.JSONException)

Example 9 with JSONException

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

the class MultiFieldPanelFunctions method getMultiFieldPanelValues.

/**
 * Extract the value of a MultiFieldPanel property into a list of maps. Will never return
 * a null map, but may return an empty one. Invalid property values are logged and skipped.
 *
 * @param resource the resource
 * @param name the property name
 * @return a list of maps.
 */
@Function
public static List<Map<String, String>> getMultiFieldPanelValues(Resource resource, String name) {
    ValueMap map = resource.adaptTo(ValueMap.class);
    List<Map<String, String>> results = new ArrayList<Map<String, String>>();
    if (map != null && map.containsKey(name)) {
        String[] values = map.get(name, new String[0]);
        for (String value : values) {
            try {
                JSONObject parsed = new JSONObject(value);
                Map<String, String> columnMap = new HashMap<String, String>();
                for (Iterator<String> iter = parsed.keys(); iter.hasNext(); ) {
                    String key = iter.next();
                    String innerValue = parsed.getString(key);
                    columnMap.put(key, innerValue);
                }
                results.add(columnMap);
            } catch (JSONException e) {
                log.error(String.format("Unable to parse JSON in %s property of %s", name, resource.getPath()), e);
            }
        }
    }
    return results;
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ArrayList(java.util.ArrayList) JSONException(org.apache.sling.commons.json.JSONException) ValueMap(org.apache.sling.api.resource.ValueMap) HashMap(java.util.HashMap) Map(java.util.Map) Function(tldgen.Function)

Example 10 with JSONException

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

the class StatusServlet method doGet.

@Override
@SuppressWarnings({ "squid:S3776", "squid:S1192" })
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss aaa");
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    Config config = request.getResource().adaptTo(Config.class);
    Workspace workspace = config.getWorkspace();
    final JSONObject json = new JSONObject();
    try {
        json.put("initialized", workspace.isInitialized());
        json.put("status", workspace.getStatus());
        if (workspace.getSubStatus() != null) {
            json.put("subStatus", workspace.getSubStatus());
        }
        json.put("runnerType", config.getRunnerType());
        json.put("queryType", config.getQueryType());
        json.put("queryStatement", config.getQueryStatement());
        json.put("workflowModel", StringUtils.removeEnd(config.getWorkflowModelId(), "/jcr:content/model"));
        json.put("batchSize", config.getBatchSize());
        json.put("autoThrottle", config.isAutoThrottle());
        json.put("purgeWorkflow", config.isPurgeWorkflow());
        json.put("interval", config.getInterval());
        json.put("retryCount", config.getRetryCount());
        json.put("timeout", config.getTimeout());
        json.put("throttle", config.getThrottle());
        json.put("message", workspace.getMessage());
        if (config.isUserEventData()) {
            json.put("userEventData", config.getUserEventData());
        }
        ActionManager actionManager = actionManagerFactory.getActionManager(workspace.getActionManagerName());
        if (actionManager != null && !Status.COMPLETED.equals(workspace.getStatus())) {
            // If Complete, then look to JCR for final accounts as ActionManager may be gone
            addActionManagerTrackedCounts(workspace.getActionManagerName(), json);
            for (com.adobe.acs.commons.fam.Failure failure : actionManager.getFailureList()) {
                JSONObject failureJSON = new JSONObject();
                failureJSON.put(Failure.PN_PAYLOAD_PATH, failure.getNodePath());
                failureJSON.put(Failure.PN_FAILED_AT, sdf.format(failure.getTime().getTime()));
                json.accumulate("failures", failureJSON);
            }
        } else {
            addWorkspaceTrackedCounts(workspace, json);
            // Failures
            for (Failure failure : workspace.getFailures()) {
                json.accumulate("failures", failure.toJSON());
            }
        }
        // Times
        if (workspace.getStartedAt() != null) {
            json.put("startedAt", sdf.format(workspace.getStartedAt().getTime()));
            json.put("timeTakenInMillis", (Calendar.getInstance().getTime().getTime() - workspace.getStartedAt().getTime().getTime()));
        }
        if (workspace.getStoppedAt() != null) {
            json.put("stoppedAt", sdf.format(workspace.getStoppedAt().getTime()));
            json.put("timeTakenInMillis", (workspace.getStoppedAt().getTime().getTime() - workspace.getStartedAt().getTime().getTime()));
        }
        if (workspace.getCompletedAt() != null) {
            json.put("completedAt", sdf.format(workspace.getCompletedAt().getTime()));
            json.put("timeTakenInMillis", (workspace.getCompletedAt().getTime().getTime() - workspace.getStartedAt().getTime().getTime()));
        }
        if (AEMWorkflowRunnerImpl.class.getName().equals(config.getRunnerType())) {
            for (Payload payload : config.getWorkspace().getActivePayloads()) {
                json.accumulate("activePayloads", payload.toJSON());
            }
        }
        json.put("systemStats", getSystemStats());
        response.getWriter().write(json.toString());
    } catch (JSONException e) {
        log.error("Could not collect Bulk Workflow status due to: {}", e);
        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not collect Bulk Workflow status.", e.getMessage());
    }
}
Also used : Config(com.adobe.acs.commons.workflow.bulk.execution.model.Config) JSONException(org.apache.sling.commons.json.JSONException) AEMWorkflowRunnerImpl(com.adobe.acs.commons.workflow.bulk.execution.impl.runners.AEMWorkflowRunnerImpl) ActionManager(com.adobe.acs.commons.fam.ActionManager) JSONObject(org.apache.sling.commons.json.JSONObject) Payload(com.adobe.acs.commons.workflow.bulk.execution.model.Payload) SimpleDateFormat(java.text.SimpleDateFormat) Failure(com.adobe.acs.commons.workflow.bulk.execution.model.Failure) Workspace(com.adobe.acs.commons.workflow.bulk.execution.model.Workspace)

Aggregations

JSONException (org.apache.sling.commons.json.JSONException)25 JSONObject (org.apache.sling.commons.json.JSONObject)15 Resource (org.apache.sling.api.resource.Resource)10 ServletException (javax.servlet.ServletException)9 RepositoryException (javax.jcr.RepositoryException)6 ValueMap (org.apache.sling.api.resource.ValueMap)6 HashMap (java.util.HashMap)5 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Config (com.adobe.acs.commons.workflow.bulk.execution.model.Config)3 Map (java.util.Map)3 Page (com.day.cq.wcm.api.Page)2 PageManager (com.day.cq.wcm.api.PageManager)2 PathFilterSet (org.apache.jackrabbit.vault.fs.api.PathFilterSet)2 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)2 JSONArray (org.apache.sling.commons.json.JSONArray)2 JSONWriter (org.apache.sling.commons.json.io.JSONWriter)2 ActionManager (com.adobe.acs.commons.fam.ActionManager)1 FormImpl (com.adobe.acs.commons.forms.impl.FormImpl)1