Search in sources :

Example 6 with ResourceNotFoundException

use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.

the class UpdateUserServlet method updateUser.

/* (non-Javadoc)
     * @see org.apache.sling.jackrabbit.usermanager.UpdateUser#updateUser(javax.jcr.Session, java.lang.String, java.util.Map, java.util.List)
     */
public User updateUser(Session jcrSession, String name, Map<String, ?> properties, List<Modification> changes) throws RepositoryException {
    User user;
    UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
    Authorizable authorizable = userManager.getAuthorizable(name);
    if (authorizable instanceof User) {
        user = (User) authorizable;
    } else {
        throw new ResourceNotFoundException("User to update could not be determined");
    }
    Collection<RequestProperty> reqProperties = collectContent(properties);
    try {
        // cleanup any old content (@Delete parameters)
        processDeletes(user, reqProperties, changes);
        // write content from form
        writeContent(jcrSession, user, reqProperties, changes);
        //SLING-2072 set the user as enabled or disabled if the request
        // has supplied the relevant properties
        String disabledParam = convertToString(properties.get(":disabled"));
        if ("true".equalsIgnoreCase(disabledParam)) {
            //set the user as disabled
            String disabledReason = convertToString(properties.get(":disabledReason"));
            if (disabledReason == null) {
                disabledReason = "";
            }
            user.disable(disabledReason);
        } else if ("false".equalsIgnoreCase(disabledParam)) {
            //re-enable a disabled user
            user.disable(null);
        }
    } catch (RepositoryException re) {
        throw new RepositoryException("Failed to update user.", re);
    }
    return user;
}
Also used : UpdateUser(org.apache.sling.jackrabbit.usermanager.UpdateUser) User(org.apache.jackrabbit.api.security.user.User) RequestProperty(org.apache.sling.servlets.post.impl.helper.RequestProperty) UserManager(org.apache.jackrabbit.api.security.user.UserManager) Authorizable(org.apache.jackrabbit.api.security.user.Authorizable) RepositoryException(javax.jcr.RepositoryException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Example 7 with ResourceNotFoundException

use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.

the class AbstractGetAclServlet method internalGetAcl.

@SuppressWarnings("unchecked")
protected JsonObject internalGetAcl(Session jcrSession, String resourcePath) throws RepositoryException {
    if (jcrSession == null) {
        throw new RepositoryException("JCR Session not found");
    }
    Item item = jcrSession.getItem(resourcePath);
    if (item != null) {
        resourcePath = item.getPath();
    } else {
        throw new ResourceNotFoundException("Resource is not a JCR Node");
    }
    // Calculate a map of privileges to all the aggregate privileges it is contained in.
    // Use for fast lookup during the mergePrivilegeSets calls below.
    AccessControlManager accessControlManager = AccessControlUtil.getAccessControlManager(jcrSession);
    Map<Privilege, Set<Privilege>> privilegeToAncestorMap = new HashMap<Privilege, Set<Privilege>>();
    Privilege[] supportedPrivileges = accessControlManager.getSupportedPrivileges(item.getPath());
    for (Privilege privilege : supportedPrivileges) {
        if (privilege.isAggregate()) {
            Privilege[] ap = privilege.getAggregatePrivileges();
            for (Privilege privilege2 : ap) {
                Set<Privilege> set = privilegeToAncestorMap.get(privilege2);
                if (set == null) {
                    set = new HashSet<Privilege>();
                    privilegeToAncestorMap.put(privilege2, set);
                }
                set.add(privilege);
            }
        }
    }
    AccessControlEntry[] declaredAccessControlEntries = getAccessControlEntries(jcrSession, resourcePath);
    Map<String, Map<String, Object>> aclMap = new LinkedHashMap<String, Map<String, Object>>();
    int sequence = 0;
    for (AccessControlEntry ace : declaredAccessControlEntries) {
        Principal principal = ace.getPrincipal();
        Map<String, Object> map = aclMap.get(principal.getName());
        if (map == null) {
            map = new LinkedHashMap<String, Object>();
            aclMap.put(principal.getName(), map);
            map.put("order", sequence++);
        }
    }
    //evaluate these in reverse order so the most entries with highest specificity are last
    for (int i = declaredAccessControlEntries.length - 1; i >= 0; i--) {
        AccessControlEntry ace = declaredAccessControlEntries[i];
        Principal principal = ace.getPrincipal();
        Map<String, Object> map = aclMap.get(principal.getName());
        Set<Privilege> grantedSet = (Set<Privilege>) map.get("granted");
        if (grantedSet == null) {
            grantedSet = new LinkedHashSet<Privilege>();
            map.put("granted", grantedSet);
        }
        Set<Privilege> deniedSet = (Set<Privilege>) map.get("denied");
        if (deniedSet == null) {
            deniedSet = new LinkedHashSet<Privilege>();
            map.put("denied", deniedSet);
        }
        boolean allow = AccessControlUtil.isAllow(ace);
        if (allow) {
            Privilege[] privileges = ace.getPrivileges();
            for (Privilege privilege : privileges) {
                mergePrivilegeSets(privilege, privilegeToAncestorMap, grantedSet, deniedSet);
            }
        } else {
            Privilege[] privileges = ace.getPrivileges();
            for (Privilege privilege : privileges) {
                mergePrivilegeSets(privilege, privilegeToAncestorMap, deniedSet, grantedSet);
            }
        }
    }
    List<JsonObject> aclList = new ArrayList<>();
    Set<Entry<String, Map<String, Object>>> entrySet = aclMap.entrySet();
    for (Entry<String, Map<String, Object>> entry : entrySet) {
        String principalName = entry.getKey();
        Map<String, Object> value = entry.getValue();
        JsonObjectBuilder aceObject = Json.createObjectBuilder();
        aceObject.add("principal", principalName);
        Set<Privilege> grantedSet = (Set<Privilege>) value.get("granted");
        if (grantedSet != null && !grantedSet.isEmpty()) {
            JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
            for (Privilege v : grantedSet) {
                arrayBuilder.add(v.getName());
            }
            aceObject.add("granted", arrayBuilder);
        }
        Set<Privilege> deniedSet = (Set<Privilege>) value.get("denied");
        if (deniedSet != null && !deniedSet.isEmpty()) {
            JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
            for (Privilege v : deniedSet) {
                arrayBuilder.add(v.getName());
            }
            aceObject.add("denied", arrayBuilder);
        }
        aceObject.add("order", (Integer) value.get("order"));
        aclList.add(aceObject.build());
    }
    JsonObjectBuilder jsonAclMap = Json.createObjectBuilder();
    for (Map.Entry<String, Map<String, Object>> entry : aclMap.entrySet()) {
        JsonObjectBuilder builder = Json.createObjectBuilder();
        for (Map.Entry<String, Object> inner : entry.getValue().entrySet()) {
            addTo(builder, inner.getKey(), inner.getValue());
        }
        jsonAclMap.add(entry.getKey(), builder);
    }
    for (JsonObject jsonObj : aclList) {
        jsonAclMap.add(jsonObj.getString("principal"), jsonObj);
    }
    return jsonAclMap.build();
}
Also used : AccessControlManager(javax.jcr.security.AccessControlManager) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) JsonObject(javax.json.JsonObject) LinkedHashMap(java.util.LinkedHashMap) Item(javax.jcr.Item) AccessControlEntry(javax.jcr.security.AccessControlEntry) Entry(java.util.Map.Entry) JsonArrayBuilder(javax.json.JsonArrayBuilder) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) JsonObjectBuilder(javax.json.JsonObjectBuilder) AccessControlEntry(javax.jcr.security.AccessControlEntry) RepositoryException(javax.jcr.RepositoryException) JsonObject(javax.json.JsonObject) Privilege(javax.jcr.security.Privilege) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Principal(java.security.Principal)

Example 8 with ResourceNotFoundException

use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.

the class DefaultGetServlet method doGet.

/**
     * @throws ResourceNotFoundException if the resource of the request is a non
     *             existing resource.
     */
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    // cannot handle the request for missing resources
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        throw new ResourceNotFoundException(request.getResource().getPath(), "No resource found");
    }
    Servlet rendererServlet;
    String ext = request.getRequestPathInfo().getExtension();
    if (ext == null) {
        rendererServlet = streamerServlet;
    } else {
        rendererServlet = rendererMap.get(ext);
    }
    // fail if we should not just stream or we cannot support the ext.
    if (rendererServlet == null) {
        request.getRequestProgressTracker().log("No renderer for extension " + ext);
        // do nothing (but log an error message)
        if (response.isCommitted() || request.getAttribute(SlingConstants.ATTR_REQUEST_SERVLET) != null) {
            logger.error("No renderer for extension {}, cannot render resource {}", ext, request.getResource());
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
        return;
    }
    request.getRequestProgressTracker().log("Using " + rendererServlet.getClass().getName() + " to render for extension=" + ext);
    rendererServlet.service(request, response);
}
Also used : JsonRendererServlet(org.apache.sling.servlets.get.impl.helpers.JsonRendererServlet) StreamRendererServlet(org.apache.sling.servlets.get.impl.helpers.StreamRendererServlet) HtmlRendererServlet(org.apache.sling.servlets.get.impl.helpers.HtmlRendererServlet) Servlet(javax.servlet.Servlet) PlainTextRendererServlet(org.apache.sling.servlets.get.impl.helpers.PlainTextRendererServlet) SlingSafeMethodsServlet(org.apache.sling.api.servlets.SlingSafeMethodsServlet) XMLRendererServlet(org.apache.sling.servlets.get.impl.helpers.XMLRendererServlet) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Example 9 with ResourceNotFoundException

use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.

the class JsonRendererServlet method doGet.

@Override
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws IOException {
    // Access and check our data
    final Resource r = req.getResource();
    if (ResourceUtil.isNonExistingResource(r)) {
        throw new ResourceNotFoundException("No data to render.");
    }
    int maxRecursionLevels = 0;
    try {
        maxRecursionLevels = getMaxRecursionLevel(req);
    } catch (IllegalArgumentException iae) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
        return;
    }
    resp.setContentType(req.getResponseContentType());
    resp.setCharacterEncoding("UTF-8");
    // We check the tree to see if the nr of nodes isn't bigger than the allowed nr.
    boolean allowDump = true;
    int allowedLevel = 0;
    final boolean tidy = isTidy(req);
    final boolean harray = hasSelector(req, HARRAY);
    ResourceTraversor traversor = null;
    try {
        traversor = new ResourceTraversor(maxRecursionLevels, maximumResults, r);
        allowedLevel = traversor.collectResources();
        if (allowedLevel != -1) {
            allowDump = false;
        }
    } catch (final Exception e) {
        reportException(e);
    }
    try {
        // Dump the resource if we can
        if (allowDump) {
            if (tidy || harray) {
                final JsonRenderer.Options opt = renderer.options().withIndent(tidy ? INDENT_SPACES : 0).withArraysForChildren(harray);
                resp.getWriter().write(renderer.prettyPrint(traversor.getJSONObject(), opt));
            } else {
                // If no rendering options, use the plain toString() method, for
                // backwards compatibility. Output might be slightly different
                // with prettyPrint and no options
                Json.createGenerator(resp.getWriter()).write(traversor.getJSONObject()).close();
            }
        } else {
            // We are not allowed to do the dump.
            // Send a 300
            String tidyUrl = (tidy) ? "tidy." : "";
            resp.setStatus(HttpServletResponse.SC_MULTIPLE_CHOICES);
            JsonGenerator writer = Json.createGenerator(resp.getWriter());
            writer.writeStartArray();
            while (allowedLevel >= 0) {
                writer.write(r.getResourceMetadata().getResolutionPath() + "." + tidyUrl + allowedLevel + ".json");
                allowedLevel--;
            }
            writer.writeEnd();
            writer.close();
        }
    } catch (Exception je) {
        reportException(je);
    }
}
Also used : Resource(org.apache.sling.api.resource.Resource) ResourceTraversor(org.apache.sling.servlets.get.impl.util.ResourceTraversor) JsonGenerator(javax.json.stream.JsonGenerator) JsonRenderer(org.apache.sling.servlets.get.impl.util.JsonRenderer) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) SlingException(org.apache.sling.api.SlingException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Example 10 with ResourceNotFoundException

use of org.apache.sling.api.resource.ResourceNotFoundException in project sling by apache.

the class SlingPostServlet method doPost.

@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException {
    final VersioningConfiguration localVersioningConfig = createRequestVersioningConfiguration(request);
    request.setAttribute(VersioningConfiguration.class.getName(), localVersioningConfig);
    // prepare the response
    final PostResponse htmlResponse = createPostResponse(request);
    htmlResponse.setReferer(request.getHeader("referer"));
    final PostOperation operation = getSlingPostOperation(request);
    if (operation == null) {
        htmlResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid operation specified for POST request");
    } else {
        request.getRequestProgressTracker().log("Calling PostOperation: {0}", operation.getClass().getName());
        final SlingPostProcessor[] processors = this.cachedPostProcessors;
        try {
            operation.run(request, htmlResponse, processors);
        } catch (ResourceNotFoundException rnfe) {
            htmlResponse.setStatus(HttpServletResponse.SC_NOT_FOUND, rnfe.getMessage());
        } catch (final Exception exception) {
            log.warn("Exception while handling POST " + request.getResource().getPath() + " with " + operation.getClass().getName(), exception);
            htmlResponse.setError(exception);
        }
    }
    // check for redirect URL if processing succeeded
    if (htmlResponse.isSuccessful()) {
        if (redirectIfNeeded(request, htmlResponse, response)) {
            return;
        }
    }
    // create a html response and send if unsuccessful or no redirect
    htmlResponse.send(response, isSetStatus(request));
}
Also used : SlingPostProcessor(org.apache.sling.servlets.post.SlingPostProcessor) VersioningConfiguration(org.apache.sling.servlets.post.VersioningConfiguration) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) PostOperation(org.apache.sling.servlets.post.PostOperation) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) PostResponse(org.apache.sling.servlets.post.PostResponse)

Aggregations

ResourceNotFoundException (org.apache.sling.api.resource.ResourceNotFoundException)22 RepositoryException (javax.jcr.RepositoryException)10 Resource (org.apache.sling.api.resource.Resource)10 Authorizable (org.apache.jackrabbit.api.security.user.Authorizable)6 UserManager (org.apache.jackrabbit.api.security.user.UserManager)5 ArrayList (java.util.ArrayList)4 Session (javax.jcr.Session)4 Group (org.apache.jackrabbit.api.security.user.Group)4 User (org.apache.jackrabbit.api.security.user.User)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Item (javax.jcr.Item)3 ServletException (javax.servlet.ServletException)3 InputStream (java.io.InputStream)2 PrintWriter (java.io.PrintWriter)2 Principal (java.security.Principal)2 LinkedHashMap (java.util.LinkedHashMap)2 Entry (java.util.Map.Entry)2