Example usage for java.security AccessControlException AccessControlException

List of usage examples for java.security AccessControlException AccessControlException

Introduction

In this page you can find the example usage for java.security AccessControlException AccessControlException.

Prototype

public AccessControlException(String s) 

Source Link

Document

Constructs an AccessControlException with the specified, detailed message.

Usage

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrUtil.java

public static <T extends JcrObject> List<T> getChildrenMatchingNodeType(Node parentNode, String childNodeType,
        Class<T> type, Object... args) {

    try {/*w  w w  .jav a  2s  .c om*/
        String query = "SELECT child.* from [" + parentNode.getPrimaryNodeType() + "] as parent inner join ["
                + childNodeType + "] as child ON ISCHILDNODE(child,parent) WHERE parent.[mode:id]  = '"
                + parentNode.getIdentifier() + "'";
        return JcrQueryUtil.find(parentNode.getSession(), query, type, args);

    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Unable to find Children matching type " + childNodeType, e);
    }

}

From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java

@Test
public void systemPropertiesSecurityManager() {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClass(TestBean.class);
    bd.getPropertyValues().add("country", "#{systemProperties.country}");
    ac.registerBeanDefinition("tb", bd);

    SecurityManager oldSecurityManager = System.getSecurityManager();
    try {//ww w  .  ja v  a  2s  .  c  o m
        System.setProperty("country", "NL");

        SecurityManager securityManager = new SecurityManager() {
            @Override
            public void checkPropertiesAccess() {
                throw new AccessControlException("Not Allowed");
            }

            @Override
            public void checkPermission(Permission perm) {
                // allow everything else
            }
        };
        System.setSecurityManager(securityManager);
        ac.refresh();

        TestBean tb = ac.getBean("tb", TestBean.class);
        assertEquals("NL", tb.getCountry());

    } finally {
        System.setSecurityManager(oldSecurityManager);
        System.getProperties().remove("country");
    }
}

From source file:com.cloudera.hoop.Hoop.java

/**
 * Binding to handle all GET requests, supported operations are
 * {@link GetOpParam.Values}.//from  w  w w .j av  a  2s.c om
 * <p/>
 * The {@link GetOpParam.Values#INSTRUMENTATION} operation is available only
 * to users that are in Hoop's admin group (see {@link HoopServer}. It returns
 * Hoop instrumentation data. The specified path must be '/'.
 *
 * @param user principal making the request.
 * @param path path for the GET request.
 * @param op GET operation, default value is {@link GetOpParam.Values#DATA}.
 * @param offset of the  file being fetch, used only with
 * {@link GetOpParam.Values#DATA} operations.
 * @param len amounts of bytes, used only with {@link GetOpParam.Values#DATA}
 * operations.
 * @param filter Glob filter, default value is none. Used only if the
 * operation is {@link GetOpParam.Values#LIST}
 * @param doAs user being impersonated, defualt value is none. It can be used
 * only if the current user is a Hoop proxyuser.
 * @return the request response.
 * @throws IOException thrown if an IO error occurred. Thrown exceptions are
 * handled by {@link HoopExceptionProvider}.
 * @throws HadoopException thrwon if a Hadoop releated error occurred. Thrown
 * exceptions are handled by {@link HoopExceptionProvider}.
 */
@GET
@Path("{path:.*}")
@Produces({ MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON })
public Response get(@Context Principal user, @PathParam("path") @DefaultValue("") FsPathParam path,
        @QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT) GetOpParam op,
        @QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT) OffsetParam offset,
        @QueryParam(LenParam.NAME) @DefaultValue(LenParam.DEFAULT) LenParam len,
        @QueryParam(FilterParam.NAME) @DefaultValue(FilterParam.DEFAULT) FilterParam filter,
        @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) DoAsParam doAs)
        throws IOException, HadoopException {
    Response response = null;
    path.makeAbsolute();
    MDC.put("op", op.value().name());
    switch (op.value()) {
    case DATA: {
        //Invoking the command directly using an unmanaged FileSystem that is released by the
        //FileSystemReleaseFilter
        FSOpen command = new FSOpen(path.value());
        FileSystem fs = createFileSystem(user, doAs.value());
        InputStream is = command.execute(fs);
        AUDIT_LOG.info("[{}] offset [{}] len [{}]", new Object[] { path, offset, len });
        InputStreamEntity entity = new InputStreamEntity(is, offset.value(), len.value());
        response = Response.ok(entity).type(MediaType.APPLICATION_OCTET_STREAM).build();
        break;
    }
    case STATUS: {
        FSFileStatus command = new FSFileStatus(path.value());
        Map json = fsExecute(user, doAs.value(), command);
        AUDIT_LOG.info("[{}]", path);
        response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
        break;
    }
    case LIST: {
        FSListStatus command = new FSListStatus(path.value(), filter.value());
        JSONArray json = fsExecute(user, doAs.value(), command);
        if (filter.value() == null) {
            AUDIT_LOG.info("[{}]", path);
        } else {
            AUDIT_LOG.info("[{}] filter [{}]", path, filter.value());
        }
        response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
        break;
    }
    case HOMEDIR: {
        FSHomeDir command = new FSHomeDir();
        JSONObject json = fsExecute(user, doAs.value(), command);
        AUDIT_LOG.info("");
        response = Response.ok(json).type(MediaType.APPLICATION_JSON).build();
        break;
    }
    case INSTRUMENTATION: {
        if (!path.value().equals("/")) {
            throw new UnsupportedOperationException(
                    MessageFormat.format("Invalid path for {0}={1}, must be '/'", GetOpParam.NAME,
                            GetOpParam.Values.INSTRUMENTATION));
        }
        Groups groups = HoopServer.get().get(Groups.class);
        List<String> userGroups = groups.getGroups(user.getName());
        if (!userGroups.contains(HoopServer.get().getAdminGroup())) {
            throw new AccessControlException("User not in Hoop admin group");
        }
        Instrumentation instrumentation = HoopServer.get().get(Instrumentation.class);
        Map snapshot = instrumentation.getSnapshot();
        response = Response.ok(snapshot).build();
        break;
    }
    }
    return response;
}

From source file:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java

private Subject authenticateUserAndGetSubject(SubjectCreator subjectCreator, String username, String password) {
    SubjectAuthenticationResult authResult = subjectCreator.authenticate(username, password);
    if (authResult.getStatus() != AuthenticationStatus.SUCCESS) {
        //TODO: write a return response indicating failure?
        throw new AccessControlException("Incorrect username or password");
    }//from www .  java2 s  . c  om
    Subject subject = authResult.getSubject();
    return subject;
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

public static Map<String, Object> getProperties(Node node) {
    try {/*from ww w . j  a v a2s  . c  o  m*/
        Map<String, Object> propMap = new HashMap<>();
        PropertyIterator itr = node.getProperties();

        while (itr.hasNext()) {
            try {
                Property prop = (Property) itr.next();
                Object value = asValue(prop);
                propMap.put(prop.getName(), value);
            } catch (AccessDeniedException e) {
                log.debug("Access denied - skipping property", e);
            }
        }

        return propMap;
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to access properties", e);
    }
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

private <T> T doExecute(HttpUriRequest request, boolean retry, Function<HttpEntity, T> function) {
    LOGGER.debug("Calling URL: {} [{}]", request.getURI(), request.getMethod());

    // disable XSRF check:
    if (!request.containsHeader("X-Atlassian-Token")) {
        request.addHeader("X-Atlassian-Token", "nocheck");
    }//from   w  ww.ja  v a  2 s.c  o m

    HttpResponse response;
    try {
        response = httpClient.execute(request, httpClientContext);
    } catch (IOException e) {
        if (Thread.interrupted()) {
            LOGGER.trace("Could not call URL: {}", request.getURI(), e);
            throw new InterruptedError();
        } else {
            throw new IllegalStateException("Could not call URL: " + request.getURI(), e);
        }
    }

    LOGGER.debug("Response received ({})", response.getStatusLine().toString().trim());

    HttpEntity entity = response.getEntity();
    try {
        if (Thread.interrupted()) {
            throw new InterruptedError();
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (isSuccess(statusCode)) {
            T result;
            try {
                result = function.apply(entity, Hint.none());
            } catch (NotAuthenticatedException e) {
                if (retry) {
                    resetAuthentication();
                    setCredentials();
                    return doExecute(request, false, function);
                } else {
                    throw e.getCause();
                }
            } catch (RuntimeException e) {
                if (Thread.interrupted()) {
                    LOGGER.trace("Could not call URL: {}", request.getURI(), e);
                    throw new InterruptedError();
                } else {
                    throw e;
                }
            }

            if (Thread.interrupted()) {
                throw new InterruptedError();
            }

            return result;
        } else {
            if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                resetAuthentication();
                if (retry) {
                    setCredentials();
                    return doExecute(request, false, function);
                } else {
                    String error = readErrorResponse(request.getURI(), entity);
                    LOGGER.debug("Unauthorized [401]: {}", error);
                    throw new AccessControlException("Unauthorized [401]: " + request.getURI());
                }
            } else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) {
                resetAuthentication();
                checkAccountLocked(response);
                if (retry) {
                    setCredentials();
                    return doExecute(request, false, function);
                } else {
                    throw new AccessControlException("Forbidden [403]: " + request.getURI());
                }
            } else {
                String status = response.getStatusLine().toString().trim();
                String message;
                if (entity == null) {
                    message = status;
                } else {
                    String error = readErrorResponse(request.getURI(), entity);
                    message = status + (error.isEmpty() ? "" : ": " + error);
                }

                if (Thread.interrupted()) {
                    throw new InterruptedError();
                }

                if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
                    throw new NoSuchElementException(message);
                } else {
                    throw new IllegalStateException(message);
                }
            }
        }
    } finally {
        EntityUtils.consumeQuietly(entity);
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions.java

private boolean togglePermission(Action action, Principal principal, boolean enable) {
    boolean isAdminAction = isAdminAction(action);
    boolean result = true;

    if (isAdminAction) {
        if (enable) {
            // If this actions is a permission management action then grant this principal admin privileges to the whole tree.
            result = JcrAccessControlUtil.addRecursivePermissions(getNode(), JcrAllowableAction.NODE_TYPE,
                    principal, ADMIN_PRIVILEGES);
        } else {/* www.j a  v  a 2  s.  co m*/
            // Remove admin privileges but keep grant privileges if needed
            isAdminAction = getEnabledActions(principal).stream().allMatch(action::equals); // has non-admin action remaining?
            final String[] privileges = isAdminAction ? ADMIN_PRIVILEGES
                    : ArrayUtils.removeElements(ADMIN_PRIVILEGES, GRANT_PRIVILEGES);
            result = JcrAccessControlUtil.removeRecursivePermissions(getNode(), JcrAllowableAction.NODE_TYPE,
                    principal, privileges);
        }
    }
    if (!isAdminAction) {
        result &= findActionNode(action).map(node -> {
            if (enable) {
                return JcrAccessControlUtil.addHierarchyPermissions(node, principal, this.node,
                        GRANT_PRIVILEGES);
            } else {
                return JcrAccessControlUtil.removeRecursivePermissions(node, JcrAllowableAction.NODE_TYPE,
                        principal, GRANT_PRIVILEGES);
            }
        }).orElseThrow(() -> new AccessControlException(
                "Not authorized to " + (enable ? "enable" : "disable") + " the action: " + action));
    }

    return result;
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrUtil.java

public static <T extends JcrObject> T toJcrObject(Node node, String nodeType,
        JcrObjectTypeResolver<T> typeResolver, Object... args) {
    try {//from  w w  w  .  j  a  v a 2s. c om
        if (nodeType == null || node.isNodeType(nodeType)) {
            T entity = constructNodeObject(node, typeResolver.resolve(node), args);
            return entity;
        } else {
            throw new MetadataRepositoryException("Unable to instanciate object of node type: " + nodeType);
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Unable to instanciate object from node: " + node, e);
    }
}

From source file:org.apache.jackrabbit.jcr2spi.SessionImpl.java

/**
 * @see javax.jcr.Session#checkPermission(String, String)
 *///from w ww  . j a  v  a  2s . com
public void checkPermission(String absPath, String actions) throws AccessControlException, RepositoryException {
    if (!hasPermission(absPath, actions)) {
        throw new AccessControlException(
                "Access control violation: path = " + absPath + ", actions = " + actions);
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

public static Node setProperties(Session session, Node entNode, Map<String, Object> props) {
    ValueFactory factory;//from   w  w w  .ja v a  2s .c om
    try {
        factory = session.getValueFactory();

        if (props != null) {
            //                JcrVersionUtil.ensureCheckoutNode(entNode);
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                if (entry.getValue() instanceof JcrExtensiblePropertyCollection) {
                    JcrExtensiblePropertyCollection propertyCollection = ((JcrExtensiblePropertyCollection) entry
                            .getValue());
                    propertyCollection.getCollectionType();
                    Value[] values = new Value[propertyCollection.getCollection().size()];
                    int i = 0;
                    for (Object o : propertyCollection.getCollection()) {
                        boolean weak = false;
                        if (propertyCollection.getCollectionType() == PropertyType.WEAKREFERENCE) {
                            weak = true;
                        }
                        Value value = createValue(session, o, weak);
                        values[i] = value;
                        i++;
                    }
                    entNode.setProperty(entry.getKey(), values);
                } else {
                    Value value = asValue(factory, entry.getValue());
                    entNode.setProperty(entry.getKey(), value);
                }
            }
        }

        return entNode;
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to set properties", e);
    }
}