Search in sources :

Example 1 with JSONException

use of org.apache.sling.commons.json.JSONException in project sling by apache.

the class NodeTypesJSONServlet method doGet.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter writer = response.getWriter();
    Resource resource = request.getResource();
    Node currentNode = resource.adaptTo(Node.class);
    try {
        NodeTypeIterator nodeTypeIterator = currentNode.getSession().getWorkspace().getNodeTypeManager().getAllNodeTypes();
        JSONObject nodeTypes = new JSONObject();
        while (nodeTypeIterator.hasNext()) {
            NodeType nodeType = nodeTypeIterator.nextNodeType();
            if (nodeType.getName() != null) {
                JSONNodeType jsonNodeType = new JSONNodeType(nodeType);
                nodeTypes.put(nodeType.getName(), jsonNodeType.getJson());
            }
        }
        writer.println(nodeTypes.toString(2));
        writer.flush();
        writer.close();
    } catch (RepositoryException e) {
        log.error("Could not generate the node types.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (JSONException e) {
        log.error("Could not generate the node types.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) Node(javax.jcr.Node) NodeType(javax.jcr.nodetype.NodeType) Resource(org.apache.sling.api.resource.Resource) NodeTypeIterator(javax.jcr.nodetype.NodeTypeIterator) JSONException(org.apache.sling.commons.json.JSONException) RepositoryException(javax.jcr.RepositoryException) PrintWriter(java.io.PrintWriter)

Example 2 with JSONException

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

the class QuicklyInitServlet method doGet.

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Content-Type", " application/json; charset=UTF-8");
    final JSONObject json = new JSONObject();
    try {
        json.put("user", request.getResourceResolver().getUserID());
        json.put("throttle", 200);
        response.getWriter().write(json.toString());
    } catch (JSONException e) {
        response.sendError(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().print("{\"status:\": \"error\"}");
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) JSONException(org.apache.sling.commons.json.JSONException)

Example 3 with JSONException

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

the class DispatcherFlusherServlet method doPost.

@Override
@SuppressWarnings("squid:S3776")
protected final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    final Resource resource = request.getResource();
    final ResourceResolver resourceResolver = request.getResourceResolver();
    final PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
    final Page currentPage = pageManager.getContainingPage(resource);
    final ValueMap properties = resource.getValueMap();
    /* Properties */
    final String[] paths = properties.get("paths", new String[0]);
    final ReplicationActionType replicationActionType = ReplicationActionType.valueOf(properties.get("replicationActionType", ReplicationActionType.ACTIVATE.name()));
    final List<FlushResult> overallResults = new ArrayList<FlushResult>();
    boolean caughtException = false;
    ResourceResolver flushingResourceResolver = null;
    try {
        if (paths.length > 0) {
            if (flushWithAdminResourceResolver) {
                // Use the admin resource resolver for replication to ensure all
                // replication permission checks are OK
                // Make sure to close this resource resolver
                flushingResourceResolver = resourceResolverFactory.getServiceResourceResolver(AUTH_INFO);
            } else {
                // Use the HTTP Request's resource resolver; don't close this resource resolver
                flushingResourceResolver = resourceResolver;
            }
            final Map<Agent, ReplicationResult> results = dispatcherFlusher.flush(flushingResourceResolver, replicationActionType, true, paths);
            for (final Map.Entry<Agent, ReplicationResult> entry : results.entrySet()) {
                final Agent agent = entry.getKey();
                final ReplicationResult result = entry.getValue();
                overallResults.add(new FlushResult(agent, result));
            }
        }
    } catch (ReplicationException e) {
        log.error("Replication exception occurred during Dispatcher Flush request.", e);
        caughtException = true;
    } catch (LoginException e) {
        log.error("Could not obtain an Admin Resource Resolver during Dispatcher Flush request.", e);
        caughtException = true;
    } finally {
        if (flushWithAdminResourceResolver && flushingResourceResolver != null) {
            // Close the admin resource resolver if opened by this servlet
            flushingResourceResolver.close();
        }
    }
    if (request.getRequestPathInfo().getExtension().equals("json")) {
        response.setContentType("application/json");
        JSONWriter writer = new JSONWriter(response.getWriter());
        try {
            writer.object();
            for (final FlushResult result : overallResults) {
                writer.key(result.agentId);
                writer.value(result.success);
            }
            writer.endObject();
        } catch (JSONException e) {
            throw new ServletException("Unable to output JSON data", e);
        }
    } else {
        String suffix;
        if (caughtException) {
            suffix = "replication-error";
        } else {
            suffix = StringUtils.join(overallResults, '/');
        }
        response.sendRedirect(request.getContextPath() + currentPage.getPath() + ".html/" + suffix);
    }
}
Also used : JSONWriter(org.apache.sling.commons.json.io.JSONWriter) Agent(com.day.cq.replication.Agent) ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) ArrayList(java.util.ArrayList) JSONException(org.apache.sling.commons.json.JSONException) Page(com.day.cq.wcm.api.Page) ServletException(javax.servlet.ServletException) ReplicationResult(com.day.cq.replication.ReplicationResult) PageManager(com.day.cq.wcm.api.PageManager) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException) ReplicationException(com.day.cq.replication.ReplicationException) ValueMap(org.apache.sling.api.resource.ValueMap) Map(java.util.Map) ReplicationActionType(com.day.cq.replication.ReplicationActionType)

Example 4 with JSONException

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

the class ChildrenAsPropertyResource method serialize.

/**
 * Serializes all children data as JSON to the resource's propertyName.
 *
 * @throws InvalidDataFormatException
 */
private void serialize() throws InvalidDataFormatException {
    final long start = System.currentTimeMillis();
    final ModifiableValueMap modifiableValueMap = this.resource.adaptTo(ModifiableValueMap.class);
    JSONObject childrenJSON = new JSONObject();
    try {
        // Add the new entries to the JSON
        for (Resource childResource : this.orderedCache) {
            childrenJSON.put(childResource.getName(), this.serializeToJSON(childResource));
        }
        if (childrenJSON.length() > 0) {
            // Persist the JSON back to the Node
            modifiableValueMap.put(this.propertyName, childrenJSON.toString());
        } else {
            // Nothing to persist; delete the property
            modifiableValueMap.remove(this.propertyName);
        }
        log.debug("Persist operation for [ {} ] in [ {} ms ]", this.resource.getPath() + "/" + this.propertyName, System.currentTimeMillis() - start);
    } catch (JSONException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    } catch (NoSuchMethodException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    } catch (IllegalAccessException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    } catch (InvocationTargetException e) {
        throw new InvalidDataFormatException(this.resource, this.propertyName, childrenJSON.toString());
    }
}
Also used : JSONObject(org.apache.sling.commons.json.JSONObject) Resource(org.apache.sling.api.resource.Resource) JSONException(org.apache.sling.commons.json.JSONException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 5 with JSONException

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

the class QrCodeServlet method doGet.

@Override
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    if (externalizer == null) {
        log.warn("Externalizer is not configured. This is required for QR Code servlet to work.");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else if (request.getResource().getValueMap().get(PN_ENABLED, false)) {
        final JSONObject json = new JSONObject();
        final String publishUrl = externalizer.publishLink(request.getResourceResolver(), request.getRequestPathInfo().getSuffix());
        log.debug("Externalized path [ {} ] for QR Code generation to [ {} ]", request.getRequestPathInfo().getSuffix(), publishUrl);
        if (StringUtils.isNotBlank(publishUrl)) {
            try {
                json.put(JSON_KEY_ENABLED, true);
                json.put(JSON_KEY_PUBLISH_URL, publishUrl);
            } catch (JSONException e) {
                log.error("Could not construct the QR Code Servlet JSON response", e);
                throw new ServletException(e);
            }
            response.getWriter().write(json.toString());
            response.getWriter().flush();
        } else {
            log.warn("Externalizer configuration for AEM Publish did not yield a valid URL");
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        log.warn("Externalizer configuration for AEM Publish did not yield a valid URL");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : ServletException(javax.servlet.ServletException) JSONObject(org.apache.sling.commons.json.JSONObject) JSONException(org.apache.sling.commons.json.JSONException)

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