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:servlets.Analysis_servlets.java

private void import_analysis_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {/*from   w  ww .j ava  2  s  .  c o  m*/
        String lockedID = null;
        boolean ROLLBACK_NEEDED = false;
        DAO daoInstance = null;
        Analysis analysis = null;
        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);
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String loggedUser, loggedUserID = null, sessionToken;
            if (cookies != null) {
                loggedUser = cookies.get("loggedUser").getValue();
                sessionToken = cookies.get("sessionToken").getValue();
                loggedUserID = cookies.get("loggedUserID").getValue();
            } else {
                String apicode = requestData.get("apicode").getAsString();
                apicode = new String(Base64.decodeBase64(apicode));

                loggedUser = apicode.split(":")[0];
                sessionToken = apicode.split(":")[1];
            }

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

            if (loggedUserID == null) {
                daoInstance = DAOProvider.getDAOByName("User");
                loggedUserID = ((User) daoInstance.findByID(loggedUser, new Object[] { null, false, true }))
                        .getUserID();
            }

            String experimentID = requestData.get("experiment_id").getAsString();
            String origin = requestData.get("origin").getAsString();

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER EXISTS AND IF EXPERIMENT IS VALID
             * *******************************************************
             */
            daoInstance = DAOProvider.getDAOByName("Experiment");
            Experiment experiment = (Experiment) daoInstance.findByID(experimentID, null);
            if (experiment == null) {
                throw new AccessControlException(experimentID + " is not a valid experiment identifier.");
            } else if (!experiment.isOwner(loggedUserID) && !experiment.isMember(loggedUserID)) {
                throw new AccessControlException("User " + loggedUserID
                        + " is not a valid member of the experiment " + experimentID + ".");
            }

            /**
             * *******************************************************
             * STEP 2 Get the new ID for the ANALYSIS. IF ERROR --> throws
             * SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            daoInstance = DAOProvider.getDAOByName("Analysis");
            lockedID = daoInstance.getNextObjectID(null);
            requestData.add("analysis_id", new JsonPrimitive(lockedID));

            /**
             * *******************************************************
             * STEP 3 Get the ANALYSIS Object by parsing the JSON data. IF
             * ERROR --> throws JsonParseException, GO TO STEP 5b ELSE -->
             * GO TO STEP 4
             * *******************************************************
             */
            analysis = Analysis.parseAnalysisData(origin, loggedUserID, requestData);
            analysis.updateAnalysisID(lockedID);
            analysis.setAssociated_experiment(experimentID);

            /**
             * *******************************************************
             * STEP 4 Add the new ANALYSIS Object in the DATABASE. IF ERROR
             * --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 5
             * *******************************************************
             */
            daoInstance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            daoInstance.insert(analysis);

            /**
             * *******************************************************
             * STEP 4 Add a new message. IF ERROR
             * --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO STEP 5
             * *******************************************************
             */
            Message message = new Message();
            message.setUserID(loggedUserID);
            message.setType("info");
            message.setSender("STATegraEMS notifications");
            message.setTo(loggedUserID);
            message.setSubject("New analysis imported from " + origin);
            message.setContent("A new analysis called \"" + analysis.getAnalysisName()
                    + "\" has been created for experiment " + experimentID
                    + " using an external tool (data imported from " + origin + ").");

            daoInstance = DAOProvider.getDAOByName("Message");
            daoInstance.insert(message);

            /**
             * *******************************************************
             * STEP 5 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO
             * STEP 6
             * *******************************************************
             */
            daoInstance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "import_analysis_handler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
                if (ROLLBACK_NEEDED) {
                    daoInstance.doRollback();
                }
            } else {
                JsonObject obj = new JsonObject();
                obj.add("newID", new JsonPrimitive(lockedID));
                response.getWriter().print(obj.toString());
            }

            /**
             * UNLOCK THE IDS
             */
            if (lockedID != null) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(lockedID);
            }
            /**
             * *******************************************************
             * STEP 6 Close connection.
             * ********************************************************
             */
            if (daoInstance != null) {
                daoInstance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "import_analysis_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

public static String toString(Property prop) {
    try {//from www.  j a v  a2 s  . c o m
        return prop.getString();
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to get string value of property: " + prop, e);
    }
}

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

/**
 * Get a child node relative to the parentNode and create the Wrapper object
 *//*from w w w .  j a va2 s .c om*/
public static <T extends JcrObject> T getJcrObject(Node parentNode, String name, Class<T> type,
        Object... args) {
    try {
        Node n = parentNode.getNode(name);
        return getJcrObject(n, type, args);
    } catch (PathNotFoundException e) {
        return null;
    } 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);
    }
}

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

private void performClientChecks(OAuth2Authentication oAuth2Authentication, ScopePathType requiredScope,
        OrcidMessage orcidMessage, String orcid) {
    OAuth2Request authorizationRequest = oAuth2Authentication.getOAuth2Request();
    // If we have an ORCID in the request, we assume that this is intended
    // as an update
    if (orcidMessage != null && orcidMessage.getOrcidProfile() != null && StringUtils.isNotBlank(orcid)) {

        OrcidIdentifier orcidOb = orcidMessage.getOrcidProfile().getOrcidIdentifier();
        String messageOrcid = orcidOb != null ? orcidOb.getPath() : orcid;
        if (StringUtils.isNotBlank(messageOrcid) && !orcid.equals(messageOrcid)) {
            throw new IllegalArgumentException("The ORCID in the body and the URI do NOT match. Body ORCID: "
                    + messageOrcid + " URI ORCID: " + orcid + " do NOT match.");
        }//from   w  w w. jav a  2 s . c  o m

        profileEntityCacheManager.retrieve(messageOrcid);
        if (!profileEntityManager.existsAndNotClaimedAndBelongsTo(messageOrcid,
                authorizationRequest.getClientId())) {
            throw new AccessControlException(
                    "You cannot update this profile as it has been claimed, or you are not the owner.");
        }
    }
}

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

/**
 * Get or Create a node relative to the Parent Node.
 *///from   w w w. j  ava2 s  .  c om
public static Node getOrCreateNode(Node parentNode, String name, String nodeType) {
    try {
        if (parentNode.hasNode(name)) {
            return parentNode.getNode(name);
        } else {
            return addNode(parentNode, name, nodeType);
        }
    } 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);
    }
}

From source file:servlets.User_servlets.java

private void get_user_details_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w w  w.  java2 s . c  om
        DAO dao_instance = null;
        User user = null;
        try {
            Map<String, Cookie> cookies = this.getCookies(request);
            String loggedUser = cookies.get("loggedUser").getValue();
            String sessionToken = cookies.get("sessionToken").getValue();
            String userID = request.getPathInfo().replaceAll("/", "");

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 3b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 GET USER. IF ERROR --> throws
             * exception if not valid session, GO TO STEP 3b ELSE --> GO TO
             * STEP 2
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("User");
            boolean isEmail = false;
            Object[] params = { null, false, isEmail };
            user = (User) ((User_JDBCDAO) dao_instance).findByID(userID, params);

            if (!loggedUser.equals(user.getEmail()) && !isValidAdminUser(loggedUser)) {
                throw new Exception("User not allowed for this action.");
            }

            if (isValidAdminUser(user.getEmail())) {
                user.setRole("admin");
            }

        } catch (Exception e) {
            ServerErrorManager.handleException(e, User_servlets.class.getName(), "getUserPostHandler",
                    e.getMessage());
        } finally {

            /**
             * *******************************************************
             * STEP 3b CATCH ERROR AND WRITE RESPONSE.
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                response.getWriter().print(user.toJSON());
            }
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, User_servlets.class.getName(), "getUserPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

public static Node addNode(Node parentNode, String name, String nodeType) {
    try {/*from www  .j  a va2  s .c  om*/
        return parentNode.addNode(name, nodeType);
    } 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);
    }
}

From source file:servlets.Samples_servlets.java

/**
 *
 * @param request//  www . j  av  a2  s .c  o m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void add_external_samples_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;
        ArrayList<String> LOCKED_IDS = new ArrayList<String>();
        ArrayList<BioCondition> newSamples = new ArrayList<BioCondition>();

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

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

            /**
             * *******************************************************
             * STEP 2 Get the new ID for the BIOCONDITION. IF ERROR -->
             * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            JsonObject model = requestData.get("model").getAsJsonObject();
            JsonArray samples = requestData.get("samples").getAsJsonArray();

            /**
             * *******************************************************
             * STEP 3 Create new objects for each provided sample id. IF
             * ERROR --> throws JsonParseException, GO TO STEP 6b ELSE -->
             * GO TO STEP
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("BioCondition");
            String newID;
            BioCondition biocondition;
            for (JsonElement sample : samples) {
                newID = dao_instance.getNextObjectID(null);
                LOCKED_IDS.add(newID);
                biocondition = BioCondition.fromJSON(model);
                biocondition.setBioConditionID(newID);
                biocondition.setTitle(sample.getAsJsonObject().get("name").getAsString());
                biocondition.setExternal(true);
                biocondition.setExternalSampleID(sample.getAsJsonObject().get("id").getAsString());
                newSamples.add(biocondition);
            }

            /**
             * *******************************************************
             * STEP 5 Add the new Object in the DATABASE. IF ERROR -->
             * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 6
             * *******************************************************
             */
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            for (BioCondition _biocondition : newSamples) {
                dao_instance.insert(_biocondition);
            }

            /**
             * *******************************************************
             * STEP 6 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 6b ELSE --> GO TO
             * STEP 7
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "add_external_samples_handler", e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 6b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                JsonArray newIDs = new JsonArray();
                for (String locked_id : LOCKED_IDS) {
                    newIDs.add(new JsonPrimitive(locked_id));
                }

                JsonObject obj = new JsonObject();
                obj.add("new_ids", newIDs);
                response.getWriter().print(obj.toString());
            }

            if (LOCKED_IDS.size() > 0) {
                for (String LOCKED_ID : LOCKED_IDS) {
                    BlockedElementsManager.getBlockedElementsManager().unlockID(LOCKED_ID);
                }
            }
            /**
             * *******************************************************
             * STEP 8 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "add_external_samples_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

@SuppressWarnings("unchecked")
public static <T> T asValue(Property prop) {
    // STRING, BOOLEAN, LONG, DOUBLE, PATH, ENTITY
    try {/*from  www.j  a va  2  s.  com*/
        int code = prop.getType();
        if (prop.isMultiple()) {
            List<T> list = new ArrayList<>();
            Value[] values = prop.getValues();
            if (values != null) {
                for (Value value : values) {
                    try {
                        T o = asValue(value, prop.getSession());
                        if (o != null) {
                            list.add(o);
                        }
                    } catch (AccessDeniedException e) {
                        // We are not allowd to see the value (likely a node reference) then
                        // just ignore this value in the result list.
                    }
                }
            }
            if (list.size() > 0) {
                return (T) list;
            } else {
                return (T) Collections.emptyList();
            }
        } else {
            if (code == PropertyType.BOOLEAN) {
                return (T) Boolean.valueOf(prop.getBoolean());
            } else if (code == PropertyType.STRING) {
                return (T) prop.getString();
            } else if (code == PropertyType.LONG) {
                return (T) Long.valueOf(prop.getLong());
            } else if (code == PropertyType.DOUBLE) {
                return (T) Double.valueOf(prop.getDouble());
            } else if (code == PropertyType.PATH) {
                return (T) prop.getPath();
            } else if (code == PropertyType.REFERENCE || code == PropertyType.WEAKREFERENCE) {
                try {
                    return (T) prop.getNode();
                } catch (AccessDeniedException e) {
                    // We are not allowd to see the referenced node so return null;
                    return null;
                }
            } else {
                return (T) asValue(prop.getValue(), prop.getSession());
            }
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to access property type", e);
    }
}

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

/**
 * Get or Create a node relative to the Parent Node and return the Wrapper JcrObject
 *//*from   w  w  w  . j  av a  2  s  . c  om*/
public static <T extends JcrObject> T getOrCreateNode(Node parentNode, String name, String nodeType,
        Class<T> type, Object... constructorArgs) {
    T entity = null;
    try {
        JcrTools tools = new JcrTools();

        //if versionable checkout
        //   if(isVersionable(parentNode)){
        //     JcrVersionUtil.checkout(parentNode);
        //  }
        Node n = tools.findOrCreateChild(parentNode, name, nodeType);
        entity = createJcrObject(n, type, constructorArgs);
        //save ??
        //   JcrVersionUtil.checkinRecursively(n);
        //  if(isVersionable(parentNode)){
        //       JcrVersionUtil.checkin(parentNode);
        //    }
    } 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 entity;
}