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.feedmgr.sla.DefaultServiceLevelAgreementService.java

/**
 * get a SLA and convert it to the editable SLA form object
 *//*from   ww  w  . j a v a 2 s.  c o  m*/
@Override
public ServiceLevelAgreementGroup getServiceLevelAgreementAsFormObject(String slaId) {

    com.thinkbiganalytics.metadata.rest.model.sla.FeedServiceLevelAgreement systemSla = findFeedServiceLevelAgreementAsAdmin(
            slaId, true);

    if (systemSla != null) {

        return metadataAccess.read(() -> {
            //read it in as the current user
            FeedServiceLevelAgreement agreement = feedSlaProvider.findAgreement(slaProvider.resolve(slaId));
            //ensure the feed count match
            if (agreement.getFeeds().size() != systemSla.getFeeds().size()) {
                throw new AccessControlException("Unable to access the SLA " + agreement.getName()
                        + ".  You dont have proper access to one or more of the feeds associated with this SLA");
            }
            if (agreement != null) {
                com.thinkbiganalytics.metadata.rest.model.sla.FeedServiceLevelAgreement modelSla = serviceLevelAgreementTransform
                        .toModel(agreement, true);
                ServiceLevelAgreementMetricTransformerHelper transformer = new ServiceLevelAgreementMetricTransformerHelper();
                ServiceLevelAgreementGroup serviceLevelAgreementGroup = transformer
                        .toServiceLevelAgreementGroup(modelSla);
                feedManagerFeedService.applyFeedSelectOptions(ServiceLevelAgreementMetricTransformer.instance()
                        .findPropertiesForRulesetMatchingRenderTypes(serviceLevelAgreementGroup.getRules(),
                                new String[] { PolicyPropertyTypes.PROPERTY_TYPE.feedChips.name(),
                                        PolicyPropertyTypes.PROPERTY_TYPE.feedSelect.name(),
                                        PolicyPropertyTypes.PROPERTY_TYPE.currentFeed.name() }));
                serviceLevelAgreementGroup.setCanEdit(modelSla.isCanEdit());
                return serviceLevelAgreementGroup;
            }
            return null;

        });
    } else {
        return null;
    }
}

From source file:org.exoplatform.services.cms.templates.impl.TemplateServiceImpl.java

/**
 * {@inheritDoc}/*from  ww w .java  2  s.c om*/
 */
public String getTemplatePathByUser(boolean isDialog, String nodeTypeName, String userName) throws Exception {
    if (IdentityConstants.ANONIM.equals(userName) || DynamicIdentity.DYNAMIC.equals(userName)
            || userName == null) {
        return getTemplatePathByAnonymous(isDialog, nodeTypeName);
    }
    Node templateHomeNode = (Node) getSession(WCMCoreUtils.getSystemSessionProvider())
            .getItem(cmsTemplatesBasePath_);
    String type = DIALOGS;
    if (!isDialog)
        type = VIEWS;
    Node nodeTypeNode = templateHomeNode.getNode(nodeTypeName);
    NodeIterator templateIter = nodeTypeNode.getNode(type).getNodes();
    while (templateIter.hasNext()) {
        Node node = templateIter.nextNode();
        String roles = getTemplateRoles(node);
        if (hasPermission(userName, roles, identityRegistry_)) {
            String templatePath = node.getPath();
            return templatePath;
        }
    }
    throw new AccessControlException("You don't have permission to access any template");
}

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

public static boolean hasProperty(Node node, String propName) {
    try {/*from ww  w .  ja  v  a  2 s.  co  m*/
        return node.hasProperty(propName);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to test for property", e);
    }
}

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

private static void checkAccountLocked(HttpResponse response) {
    Header header = response.getLastHeader("X-Authentication-Denied-Reason");
    if (header != null) {
        String info = Objects.toString(header.getValue(), "").trim();
        throw new AccessControlException(
                "Your account seems to be locked" + (info.isEmpty() ? "" : ": " + info));
    }// w  ww .j  a v a2  s.co m
}

From source file:servlets.File_servlets.java

/**
 * This function sends a file to an external application (e.g. a Galaxy
 * server)./*ww  w .j a v a  2  s .com*/
 *
 * @param request
 * @param response
 * @throws IOException
 */
private void send_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        DAO daoInstance = null;
        String errors = "";
        try {

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 5b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            Map<String, Cookie> cookies = this.getCookies(request);

            String loggedUser, loggedUserID = null, sessionToken;
            loggedUser = cookies.get("loggedUser").getValue();
            sessionToken = cookies.get("sessionToken").getValue();
            loggedUserID = cookies.get("loggedUserID").getValue();

            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 Get the Experiment Object from DB. IF ERROR --> throws
             * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            ArrayList<String> files = new ArrayList<String>();
            Iterator<JsonElement> it = requestData.get("files").getAsJsonArray().iterator();
            while (it.hasNext()) {
                files.add(it.next().getAsString());
            }

            String source_id = requestData.get("source_id").getAsString();
            daoInstance = DAOProvider.getDAOByName("ExternalSource");
            ExternalSource externalSource = (ExternalSource) daoInstance.findByID(source_id, null);

            //CONFIGURE THE DESTINATION SETTINGS
            HashMap<String, String> destination_settings = new HashMap<String, String>();
            destination_settings.put("type", externalSource.getType());
            destination_settings.put("host", externalSource.getUrl());

            if (requestData.get("credentials") != null
                    && !"".equals(requestData.get("credentials").getAsString())) {
                String credentials = requestData.get("credentials").getAsString();
                credentials = new String(Base64.decodeBase64(credentials));
                destination_settings.put("user", credentials.split(":")[0]);
                destination_settings.put("pass",
                        (credentials.split(":").length > 1 ? credentials.split(":")[1] : ""));
            } else {
                String apikey = requestData.get("apikey").getAsString();
                destination_settings.put("apikey", apikey);
            }

            String experiment_id;
            if (request.getParameter("experiment_id") != null) {
                experiment_id = requestData.get("experiment_id").getAsString();
            } else {
                experiment_id = cookies.get("currentExperimentID").getValue();
            }

            /**
             * *******************************************************
             * STEP 3 Check that the user is a valid owner for the
             * experiment.
             * *******************************************************
             */
            daoInstance = DAOProvider.getDAOByName("Experiment");
            Experiment experiment = (Experiment) daoInstance.findByID(experiment_id, null);

            if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID)
                    && !loggedUserID.equals("admin")) {
                throw new AccessControlException(
                        "Cannot get files for selected study. Current user is not a valid member for study "
                                + experiment_id + ".");
            }

            /**
             * *******************************************************
             * STEP 3 SEND THE FILES IN THE SERVER. IF ERROR --> throws
             * exception if not valid session, GO TO STEP 6b ELSE --> GO TO
             * STEP 3
             * *******************************************************
             */
            for (String file_path : files) {
                try {
                    FileManager.getFileManager(DATA_LOCATION).sendFile(file_path,
                            experiment.getDataDirectoryInformation(), destination_settings);
                } catch (Exception e) {
                    errors += "Failed while sending file " + file_path + "\n";
                }
            }

        } catch (Exception e) {
            ServerErrorManager.handleException(e, File_servlets.class.getName(), "send_file_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                obj.add("errors", new JsonPrimitive(errors));
                response.getWriter().print(obj.toString());
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, File_servlets.class.getName(), "send_file_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:org.hippoecm.repository.jackrabbit.SessionImplHelper.java

/**
 * Before this method the JackRabbiit Session.checkPermission is called.
 * That function checks the validity of absPath and the default JCR permissions:
 * read, remove, add_node and set_property. So we don't have to check for those
 * things again here.//w w  w. ja v a 2s . c  o m
 * @param absPath
 * @param actions
 * @throws AccessControlException
 * @throws RepositoryException
 */
public void checkPermission(String absPath, String actions) throws AccessControlException, RepositoryException {
    AccessControlManager acMgr = session.getAccessControlManager();

    // build the set of actions to be checked
    HashSet<Privilege> privileges = new HashSet<Privilege>();
    for (String action : actions.split(",")) {
        privileges.add(acMgr.privilegeFromName(action));
    }
    privileges.removeAll(jcrPrivileges);
    if (privileges.size() > 0) {
        if (!acMgr.hasPrivileges(absPath, privileges.toArray(new Privilege[privileges.size()]))) {
            throw new AccessControlException("Privileges '" + actions + "' denied for " + absPath);
        }
    }
}

From source file:org.apache.hadoop.hive.ql.security.authorization.StorageBasedAuthorizationProvider.java

private static AccessControlException accessControlException(Exception e) {
    AccessControlException ace = new AccessControlException(e.getMessage());
    ace.initCause(e);/*from   w  ww.  j  a  v a  2s.c om*/
    return ace;
}

From source file:org.orcid.core.security.DefaultPermissionChecker.java

private void performUserChecks(OAuth2Authentication oAuth2Authentication, ScopePathType requiredScope,
        OrcidMessage orcidMessage, String orcid) {
    ProfileEntity principal = (ProfileEntity) oAuth2Authentication.getPrincipal();
    String userOrcid = principal.getId();
    if (orcidMessage != null && orcidMessage.getOrcidProfile() != null
            && orcidMessage.getOrcidProfile().getOrcidIdentifier() != null && StringUtils.isNotBlank(orcid)) {
        String messageOrcid = orcidMessage.getOrcidProfile().getOrcidIdentifier().getPath();
        // First check that this is a valid call. If these don't match then
        // the request is invalid
        if (!messageOrcid.equals(orcid)) {
            throw new IllegalArgumentException("The ORCID in the body and the URI do not match. Body ORCID: "
                    + messageOrcid + " URI ORCID: " + orcid + " do NOT match.");
        }// w  ww .  jav a  2s .  c om
    }
    // Is this the owner making the call? If it is, then let 'em on
    // through
    if (userOrcid.equals(orcid)) {
        return;
    } else {
        // Have they been granted permission?
        if (profileEntityManager.hasBeenGivenPermissionTo(orcid, userOrcid)) {
            // TODO: We will need to parse both incoming and existing to
            // make sure they're not trying to
            // update private information.
            return;
        } else if (profileDao.isProfileDeprecated(orcid)) {
            ProfileEntity entity = profileEntityCacheManager.retrieve(orcid);
            Map<String, String> params = new HashMap<String, String>();
            StringBuffer primary = new StringBuffer(baseUrl).append("/")
                    .append(entity.getPrimaryRecord().getId());
            params.put(OrcidDeprecatedException.ORCID, primary.toString());
            if (entity.getDeprecatedDate() != null) {
                XMLGregorianCalendar calendar = DateUtils
                        .convertToXMLGregorianCalendar(entity.getDeprecatedDate());
                params.put(OrcidDeprecatedException.DEPRECATED_DATE, calendar.toString());
            }
            throw new OrcidDeprecatedException(params);
        }
    }
    throw new AccessControlException("You do not have the required permissions.");
}

From source file:servlets.User_servlets.java

private void validate_session_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from www  .  ja v a 2s  . c  om
        /**
         * *******************************************************
         * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF ERROR
         * --> throws exception if not valid session, GO TO STEP 4b ELSE -->
         * *******************************************************
         */
        if (!checkAccessPermissions(request.getParameter("loggedUser"), request.getParameter("sessionToken"))) {
            throw new AccessControlException("Your session is invalid. User or session token not allowed.");
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, User_servlets.class.getName(), "removeUserPostHandler",
                e.getMessage());
    } finally {
        /**
         * *******************************************************
         * STEP 4b CATCH ERROR, CLEAN CHANGES. throws SQLException
         * *******************************************************
         */
        if (ServerErrorManager.errorStatus()) {
            response.setStatus(400);
            response.getWriter().print(ServerErrorManager.getErrorResponse());
        } else {
            response.getWriter().print("{success: " + true + "}");
        }
    }
}

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

/**
 * get All Child nodes under a parentNode and create the wrapped JCRObject the second argument, name, can be null to get all the nodes under the parent
 *//*  w w  w.j  a v a  2  s  .  com*/
public static <T extends JcrObject> List<T> getJcrObjects(Node parentNode, String name, NodeType nodeType,
        JcrObjectTypeResolver<T> typeResolver, Object... args) {
    List<T> list = new ArrayList<>();
    try {
        javax.jcr.NodeIterator nodeItr = null;
        if (StringUtils.isBlank(name)) {
            nodeItr = parentNode.getNodes();
        } else {
            nodeItr = parentNode.getNodes(name);
        }
        if (nodeItr != null) {
            while (nodeItr.hasNext()) {
                Node n = nodeItr.nextNode();

                if (nodeType == null || n.isNodeType(nodeType.getName())) {
                    T entity = constructNodeObject(n, typeResolver.resolve(n), args);
                    list.add(entity);
                }
            }
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to retrieve the Node named" + name, e);
    }
    return list;
}