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:controllers.base.SareTransactionalAction.java

public static <T extends PersistentObject> T fetchResource(Context ctx, UUID id, Class<T> clazz,
        boolean bypassAccessibility) {
    Validate.notNull(clazz);/*from   www . j  a v  a2 s  .c  om*/

    Logger.info(LoggedAction.getLogEntry(ctx,
            String.format("attempting to fetch resource: %s of type: %s", id, clazz.getName())));

    T object = null;
    try {
        byte[] uuid = UuidUtils.toBytes(id);
        object = em().find(clazz, uuid);

        if (object != null && (!SessionedAction.isOwnerOf(object)
                || (!bypassAccessibility && object instanceof UserInaccessibleModel))) {
            throw new AccessControlException(UuidUtils.normalize(id));
        }
    } catch (EntityNotFoundException e) {
        object = null;
    }

    if (object == null) {
        throw new EntityNotFoundException(UuidUtils.normalize(id));
    }

    Logger.info(LoggedAction.getLogEntry(ctx,
            String.format("found resource: %s of type: %s", id, clazz.getName())));
    return object;
}

From source file:org.apache.hadoop.fs.DefaultFileAccess.java

public static void checkFileAccess(FileSystem fs, FileStatus stat, FsAction action, String user,
        List<String> groups) throws IOException, AccessControlException {

    if (groups == null) {
        groups = emptyGroups;/*from  ww  w .  java2 s  .c  o  m*/
    }

    String superGroupName = getSuperGroupName(fs.getConf());
    if (userBelongsToSuperGroup(superGroupName, groups)) {
        LOG.info("User \"" + user + "\" belongs to super-group \"" + superGroupName + "\". "
                + "Permission granted for action: " + action + ".");
        return;
    }

    final FsPermission dirPerms = stat.getPermission();
    final String grp = stat.getGroup();

    if (user.equals(stat.getOwner())) {
        if (dirPerms.getUserAction().implies(action)) {
            return;
        }
    } else if (groups.contains(grp)) {
        if (dirPerms.getGroupAction().implies(action)) {
            return;
        }
    } else if (dirPerms.getOtherAction().implies(action)) {
        return;
    }
    throw new AccessControlException(
            "action " + action + " not permitted on path " + stat.getPath() + " for user " + user);
}

From source file:org.simalliance.openmobileapi.service.security.AccessControlApplet.java

public byte[] readAPKACRecord(byte[] hashApkCert) throws AccessControlException, CardException {
    CommandApdu apdu = mReadAPKACRecord.clone();
    apdu.setData(hashApkCert);//from w ww  .  jav  a2 s.  c  o  m
    ResponseApdu response = send(apdu);
    if (response.getSW1SW2() == 0x6984) {
        throw new AccessControlException("referenced ACL contains invalid data");
    }
    response.checkStatus(new int[] { 0x9000, 0x6A83 }, "READ APK AC RECORD");
    return response.getData();
}

From source file:org.apache.syncope.client.lib.RestClientExceptionMapper.java

@Override
public Exception fromResponse(final Response response) {
    int statusCode = response.getStatus();
    String message = response.getHeaderString(RESTHeaders.ERROR_INFO);

    Exception ex;/* w  w w  . j a v a  2s  .com*/
    SyncopeClientCompositeException scce = checkSyncopeClientCompositeException(response);
    if (scce != null) {
        // 1. Check for client (possibly composite) exception in HTTP header
        ex = scce.getExceptions().size() == 1 ? scce.getExceptions().iterator().next() : scce;
    } else if (statusCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
        // 2. Map SC_UNAUTHORIZED
        ex = new AccessControlException(
                StringUtils.isBlank(message) ? "Remote unauthorized exception" : message);
    } else if (statusCode == Response.Status.FORBIDDEN.getStatusCode()) {
        // 3. Map SC_FORBIDDEN
        ex = new ForbiddenException(StringUtils.isBlank(message) ? "Remote forbidden exception" : message);
    } else if (statusCode == Response.Status.BAD_REQUEST.getStatusCode()) {
        // 4. Map SC_BAD_REQUEST
        ex = StringUtils.isBlank(message) ? new BadRequestException() : new BadRequestException(message);
    } else {
        // 5. All other codes are mapped to runtime exception with HTTP code information
        ex = new WebServiceException(String.format("Remote exception with status code: %s",
                Response.Status.fromStatusCode(statusCode).name()));
    }
    LOG.error("Exception thrown", ex);
    return ex;
}

From source file:uk.ac.sanger.cgp.wwdocker.Config.java

public static void protectedFileCheck(String filename) throws AccessControlException, IOException {
    Path path = Paths.get(filename);
    Set<PosixFilePermission> permset = Files.getPosixFilePermissions(path);
    Iterator perm = permset.iterator();
    while (perm.hasNext()) {
        PosixFilePermission p = (PosixFilePermission) perm.next();
        if (p.equals(PosixFilePermission.GROUP_READ) || p.equals(PosixFilePermission.OTHERS_READ)) {
            throw new AccessControlException(
                    "Your configuration file (which contains passwords) is readable to others:\n" + "\tFile: "
                            + filename.toString() + "\tPerm: " + PosixFilePermissions.toString(permset));
        }/*from  w  w  w  .j av  a2s .com*/
    }
}

From source file:org.apache.syncope.client.rest.RestClientExceptionMapper.java

@Override
public Exception fromResponse(final Response response) {
    final int statusCode = response.getStatus();
    Exception ex;/* ww  w  . j  a v  a  2 s  .  co  m*/

    // 1. Check for client (possibly composite) exception in HTTP header
    SyncopeClientCompositeException scce = checkSyncopeClientCompositeException(response);
    if (scce != null) {
        if (scce.getExceptions().size() == 1) {
            ex = scce.getExceptions().iterator().next();
        } else {
            ex = scce;
        }
    } // 2. Map SC_UNAUTHORIZED
    else if (statusCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
        ex = new AccessControlException("Remote unauthorized exception");
    } // 3. Map SC_BAD_REQUEST
    else if (statusCode == Response.Status.BAD_REQUEST.getStatusCode()) {
        ex = new BadRequestException();
    } // 4. All other codes are mapped to runtime exception with HTTP code information
    else {
        ex = new WebServiceException(String.format("Remote exception with status code: %s",
                Response.Status.fromStatusCode(statusCode).name()));
    }
    LOG.error("Exception thrown by REST methods: " + ex.getMessage(), ex);
    return ex;
}

From source file:com.jpeterson.littles3.bo.Resource.java

/**
 * Determines if the <code>principal</code> can "read" the resource. The
 * meaning of "read" depends on the particular implementation of the
 * resource.//from  www.  j  ava 2  s .  co m
 * 
 * @param grantee
 *            The entity to check and see if they can "read" the resource.
 *            This is typically the authenticated principal requesting to
 *            read the resource.
 * @throws AccessControlException
 *             Thrown if the <code>principal</code> can not "read" the
 *             resource.
 */
public void canRead(Grantee grantee) throws AccessControlException {
    if (acp == null) {
        throw new AccessControlException("Access Control Policy is null, therefore, no grants");
    }

    Permission permission = new ResourcePermission(grantee, ResourcePermission.ACTION_READ);
    acp.checkPermission(permission);
}

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

/**
 * Creates a path out of the arguments appropriate for JCR.
 *
 * @param parent   the parent node on whose path will be appended the additional elements
 * @param elements the remaining elements to form the path
 * @return a path string//w  w w  .  j a  v  a  2s.c  om
 */
public static Path path(Node parent, String... elements) {
    try {
        return JcrPath.get(parent.getPath(), elements);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Unable to get the path of the node: " + parent, e);
    }
}

From source file:org.eclipse.skalli.view.internal.filter.ProjectPermitsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    // retrieve userId and project instance from previous filters in chain
    String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID);
    Project project = (Project) request.getAttribute(Consts.ATTRIBUTE_PROJECT);
    boolean isAnonymousUser = BooleanUtils
            .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_ANONYMOUS_USER));
    boolean isProjectAdmin = BooleanUtils
            .toBoolean((Boolean) request.getAttribute(Consts.ATTRIBUTE_PROJECTADMIN));

    String servletPath = httpRequest.getServletPath();
    String pathInfo = httpRequest.getPathInfo();

    if (servletPath.startsWith(Consts.URL_PROJECTS)) {
        // handle access to project detail page
        if (project != null && !Permits.hasProjectPermit(Permit.ALLOW, Permit.ACTION_GET, project)) {
            AccessControlException e = new AccessControlException(MessageFormat.format(
                    "User ''{0}'' is not authorized to view project ''{1}''", userId, project.getProjectId()));
            FilterUtil.handleACException(httpRequest, response, e);
            return;
        }/*from   w  w  w. j  ava2 s  . c  o m*/
        // handle URL starting with /projects
        String actionValue = request.getParameter(Consts.PARAM_ACTION);
        if (project != null && Consts.PARAM_VALUE_EDIT.equals(actionValue)) {
            // handle /projects/{projectId}?action=edit
            if (!isProjectAdmin) {
                AccessControlException e = new AccessControlException(
                        MessageFormat.format("User ''{0}'' is not authorized to edit project ''{1}''", userId,
                                project.getProjectId()));
                FilterUtil.handleACException(httpRequest, response, e);
                return;
            }
        } else if (project == null && StringUtils.isNotBlank(pathInfo)) {
            // handle /projects/{projectId} with unknown projectId => project creation dialog
            if (isAnonymousUser) {
                AccessControlException e = new AccessControlException(
                        "Anonymous users are not authorized to create new projects");
                FilterUtil.handleACException(httpRequest, response, e);
                return;
            }
        }
    } else {
        // handle all other URLs not starting with /projects
        if (isAnonymousUser) {
            AccessControlException e = new AccessControlException(
                    "Anonymous users are not authorized to view this page");
            FilterUtil.handleACException(request, response, e);
            return;
        }
        if (StringUtils.isNotBlank(pathInfo)) {
            if (project == null) {
                FilterException e = new FilterException(MessageFormat
                        .format("No project instance available although servlet path is {0}.", servletPath));
                FilterUtil.handleException(request, response, e);
                return;
            } else if (!isProjectAdmin) {
                AccessControlException e = new AccessControlException(
                        "User is not authorized to view this page");
                FilterUtil.handleACException(request, response, e);
                return;
            }
        }
    }

    // proceed along the chain
    chain.doFilter(request, response);
}

From source file:org.openmrs.module.openhmis.cashier.api.impl.BillServiceImpl.java

/**
 * Saves the bill to the database, creating a new bill or updating an existing one.
 * @param bill The bill to be saved.//from  ww w  . java 2 s .c om
 * @return The saved bill.
 * @should Generate a new receipt number if one has not been defined.
 * @should Not generate a receipt number if one has already been defined.
 * @should Throw APIException if receipt number cannot be generated.
 */
@Override
@Authorized({ PrivilegeConstants.MANAGE_BILLS })
@Transactional
public Bill save(Bill bill) {
    if (bill == null) {
        throw new NullPointerException("The bill must be defined.");
    }

    /* Check for refund.
     * A refund is given when the total of the bill's line items is negative.
     */
    if (bill.getTotal().compareTo(BigDecimal.ZERO) < 0
            && !Context.hasPrivilege(PrivilegeConstants.REFUND_MONEY)) {
        throw new AccessControlException("Access denied to give a refund.");
    }
    IReceiptNumberGenerator generator = ReceiptNumberGeneratorFactory.getGenerator();
    if (generator == null) {
        LOG.warn(
                "No receipt number generator has been defined.  Bills will not be given a receipt number until one is"
                        + " defined.");
    } else {
        if (StringUtils.isEmpty(bill.getReceiptNumber())) {
            bill.setReceiptNumber(generator.generateNumber(bill));
        }
    }

    return super.save(bill);
}