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.Samples_servlets.java

private void send_biocondition_template_document_handler(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    try {//from   ww w.  j  a  v a2 s.  co m

        ArrayList<String> BLOCKED_IDs = new ArrayList<String>();
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;

        try {
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception("Erroneus request.");
            }

            String user_id = "";
            String sessionToken = "";
            File xls_file = null;

            /**
             * *******************************************************
             * STEP 1 Get the request params: read the params and the XLS
             * file. IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE
             * --> GO TO STEP 9
             * *******************************************************
             */
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("text/html");

            //Get the data as a JSON format string
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 100 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 20 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 20 * (int) Math.pow(10, 6);

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setRepository(new File(CACHE_PATH));
            factory.setSizeThreshold(CACHE_SIZE);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if (!item.getName().equals("")) {
                        //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
                        xls_file = new File(CACHE_PATH + "tmp.xls");
                        item.write(xls_file);
                    }
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if ("loggedUser".equals(name)) {
                        user_id = value;
                    } else if ("sessionToken".equals(name)) {
                        sessionToken = value;
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 2 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP AND
             * IF FILE IS CORRECTLY UPDATED. IF ERROR --> throws exception
             * if not valid session, GO TO STEP 6b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            if (!checkAccessPermissions(user_id, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }
            if (xls_file == null) {
                throw new Exception("XLS file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 2 Parse the XLS file and get the information. IF ERROR
             * --> throws Exception, GO TO STEP ? ELSE --> GO TO STEP 3
             * *******************************************************
             */
            Object[] parsingResult = BioCondition_XLS_parser.parseXLSfile(xls_file, user_id);

            ArrayList<BioCondition> biocondition_list = (ArrayList<BioCondition>) parsingResult[0];
            HashMap<String, Batch> batchesTable = (HashMap<String, Batch>) parsingResult[1];
            HashMap<String, Protocol> protocolsTable = (HashMap<String, Protocol>) parsingResult[2];

            /**
             * *******************************************************
             * STEP 3 IF FILE WAS PARSED CORRECTLY ADD THE INFORMATION TO
             * DATABASE. IF ERROR --> throws SQLException, GO TO STEP ? ELSE
             * --> GO TO STEP 4
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("Batch");
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;

            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Batch batch : batchesTable.values()) {
                String batch_id = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(batch_id);
                batch.setBatchID(batch_id);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(batch);
            }

            dao_instance = DAOProvider.getDAOByName("Protocol");
            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Protocol protocol : protocolsTable.values()) {
                String protocolID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(protocolID);
                protocol.setProtocolID(protocolID);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(protocol);
            }

            dao_instance = DAOProvider.getDAOByName("BioCondition");

            for (BioCondition biocondition : biocondition_list) {
                String newID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(newID);
                biocondition.setBioConditionID(newID);
                //THE biocondition ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES
                dao_instance.insert(biocondition);
            }

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

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "send_biocondition_template_document_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) {
                    dao_instance.doRollback();
                }
            } else {
                response.getWriter().print("{success: " + true + "}");
            }

            for (String blocked_id : BLOCKED_IDs) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(blocked_id);
            }

            /**
             * *******************************************************
             * STEP 6 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(),
                "send_xls_creation_document_handler", e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

/**
 * Assuming the specified property is a (WEAK)REFERENCE type, returns whether it is pointing at the specified node ID.
 *///from  w ww . j  a  v  a  2s.  c om
public static boolean isReferencing(Node node, String refProp, String nodeId) {
    try {
        return node.getProperty(refProp).getNode().getIdentifier().equals(nodeId);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to check reference property against node ID: " + nodeId,
                e);
    }
}

From source file:servlets.Analysis_servlets.java

private void update_analysis_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {//  ww  w  .  j a  v  a  2s  .  c om
        ArrayList<String> BLOCKED_IDs = new ArrayList<String>();
        boolean ROLLBACK_NEEDED = false;
        DAO daoInstance1 = null;
        DAO daoInstance2 = 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
             * 6b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            Map<String, Cookie> cookies = this.getCookies(request);
            String loggedUser = cookies.get("loggedUser").getValue();
            String sessionToken = cookies.get("sessionToken").getValue();
            String loggedUserID = cookies.get("loggedUserID").getValue();

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

            /**
             * *******************************************************
             * STEP 3 Get the Object by parsing the JSON data. IF ERROR -->
             * throws JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP
             * 4 *******************************************************
             */
            Analysis analysis = Analysis.fromJSON(requestData.get("analysis_json_data"));

            daoInstance1 = DAOProvider.getDAOByName("Analysis");

            //CHECK IF CURRENT USER IS A VALID OWNER (AVOID HACKING)
            boolean loadRecursive = true;
            Analysis analysisAux = (Analysis) daoInstance1.findByID(analysis.getAnalysisID(),
                    new Object[] { loadRecursive });
            if (!analysisAux.isOwner(loggedUserID) && !loggedUserID.equals("admin")) {
                throw new AccessControlException(
                        "Cannot update selected Analysis. Current user has not privileges over this element.");
            }

            if ("pending".equalsIgnoreCase(analysis.getStatus())) {
                analysis.setStatus("open");
            }

            /**
             * *******************************************************
             * STEP 4 READ ALL STEPS AND CREATE THE LIST OF TASKS.
             * *******************************************************
             */
            ArrayList<Step> to_be_created_steps = new ArrayList<Step>();
            ArrayList<Step> to_be_updated_steps = new ArrayList<Step>();
            ArrayList<String> to_be_deleted_steps = new ArrayList<String>();

            for (Step step : analysis.getNonProcessedData()) {
                if ("new_deleted".equals(step.getStatus())) {
                    continue; //ignore
                } else if ("deleted".equals(step.getStatus()) || "edited_deleted".equals(step.getStatus())) {
                    to_be_deleted_steps.add(step.getStepID()); //DELETES THE STEP
                } else if ("new".equals(step.getStatus())) {
                    to_be_created_steps.add(step); //CREATES THE STEP
                } else {
                    if ("edited".equals(step.getStatus())) {
                        to_be_updated_steps.add(step);
                    }
                }
            }

            for (Step step : analysis.getProcessedData()) {
                if ("new_deleted".equals(step.getStatus())) {
                    continue; //ignore
                } else if ("deleted".equals(step.getStatus()) || "edited_deleted".equals(step.getStatus())) {
                    to_be_deleted_steps.add(step.getStepID()); //DELETES THE STEP
                } else if ("new".equals(step.getStatus())) {
                    to_be_created_steps.add(step); //CREATES THE STEP
                } else {
                    if ("edited".equals(step.getStatus())) {
                        to_be_updated_steps.add(step);
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 5 GET ALL THE IDS FOR THE NEW STEPS AND UPDATE THE
             * INFORMATION
             * *******************************************************
             */
            daoInstance1 = DAOProvider.getDAOByName("Analysis");
            daoInstance2 = DAOProvider.getDAOByName("Step");

            Collections.sort(to_be_created_steps);
            for (Step step : to_be_created_steps) {
                String old_id = step.getStepID();
                String new_id = daoInstance2.getNextObjectID(new Object[] { analysis.getAnalysisID() });
                BLOCKED_IDs.add(new_id);

                step.setStepID(new_id);
                String[] usedData;
                for (Step stepAux : analysis.getNonProcessedData()) {
                    if (stepAux instanceof IntermediateData) {
                        usedData = ((IntermediateData) stepAux).getUsedData();
                        int pos = Arrays.asList(usedData).indexOf(old_id);
                        if (pos != -1) {
                            usedData[pos] = new_id;
                        }
                    }

                }
                for (Step stepAux : analysis.getProcessedData()) {
                    if (stepAux instanceof ProcessedData) {
                        usedData = ((ProcessedData) stepAux).getUsedData();
                        int pos = Arrays.asList(usedData).indexOf(old_id);
                        if (pos != -1) {
                            usedData[pos] = new_id;
                        }
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 5 ADD, UPDATE AND REMOVE THE NPD instances IN DATABASE.
             * Must be in this order because: -- If we change the used data
             * for a specified step adding a to be created step, must be
             * inserted first. -- If we change the used data removing an
             * used step and then we delete this step (the used one), we
             * must update first (because of foreign keys) With this method,
             * when an step is removed, the step_id is lost. Because the
             * "getNextStepID" function is called before removing ADDED
             * steps must be ordered from less to greater step_number
             * <p/>
             * IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO
             * TO STEP 6
             * *******************************************************
             */
            daoInstance1.disableAutocommit();
            ROLLBACK_NEEDED = true;
            daoInstance1.update(analysis);

            /**
             * *******************************************************
             * STEP 6 APPLY THE STEP TASKS IN DATABASE. IF ERROR --> throws
             * SQL Exception, GO TO STEP ? ELSE --> GO TO STEP 8
             * *******************************************************
             */
            ((Step_JDBCDAO) daoInstance2).insert(to_be_created_steps.toArray(new Step[] {}));
            ((Step_JDBCDAO) daoInstance2).remove(to_be_deleted_steps.toArray(new String[] {}));
            ((Step_JDBCDAO) daoInstance2).update(to_be_updated_steps.toArray(new Step[] {}));

            /**
             * *******************************************************
             * STEP 7 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP ? ELSE --> GO TO
             * STEP 8
             * *******************************************************
             */
            daoInstance1.doCommit();
        } catch (Exception e) {
            if (e.getClass().getSimpleName().equals("MySQLIntegrityConstraintViolationException")) {
                ServerErrorManager.handleException(null, null, null,
                        "Unable to update the Analysis information.");
            } else {
                ServerErrorManager.handleException(e, Analysis_servlets.class.getName(),
                        "update_analysis_handler", e.getMessage());
            }
        } finally {
            /**
             * *******************************************************
             * STEP 7b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                for (String BLOCKED_ID : BLOCKED_IDs) {
                    BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID);
                }
                if (ROLLBACK_NEEDED) {
                    daoInstance1.doRollback();
                }
            } else {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                response.getWriter().print(obj.toString());
            }

            for (String BLOCKED_ID : BLOCKED_IDs) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID);
            }

            /**
             * *******************************************************
             * STEP 9 Close connection.
             * ********************************************************
             */
            if (daoInstance1 != null) {
                daoInstance1.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "update_analysis_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:azkaban.webapp.servlet.ProjectManagerServlet.java

private void handleProjectLogsPage(HttpServletRequest req, HttpServletResponse resp, Session session)
        throws ServletException, IOException {
    Page page = newPage(req, resp, session, "azkaban/webapp/servlet/velocity/projectlogpage.vm");
    String projectName = getParam(req, "project");

    User user = session.getUser();/*from ww  w  . ja  v a 2  s  . c  o m*/
    Project project = null;
    try {
        project = projectManager.getProject(projectName);
        if (project == null) {
            page.add("errorMsg", "Project " + projectName + " doesn't exist.");
        } else {
            if (!hasPermission(project, user, Type.READ)) {
                throw new AccessControlException("No permission to view project " + projectName + ".");
            }

            page.add("project", project);
            page.add("admins", Utils.flattenToString(project.getUsersWithPermission(Type.ADMIN), ","));
            Permission perm = this.getPermissionObject(project, user, Type.ADMIN);
            page.add("userpermission", perm);

            boolean adminPerm = perm.isPermissionSet(Type.ADMIN);
            if (adminPerm) {
                page.add("admin", true);
            }
            // Set this so we can display execute buttons only to those who have
            // access.
            if (perm.isPermissionSet(Type.EXECUTE) || adminPerm) {
                page.add("exec", true);
            } else {
                page.add("exec", false);
            }
        }
    } catch (AccessControlException e) {
        page.add("errorMsg", e.getMessage());
    }

    int numBytes = 1024;

    // Really sucks if we do a lot of these because it'll eat up memory fast.
    // But it's expected that this won't be a heavily used thing. If it is,
    // then we'll revisit it to make it more stream friendly.
    StringBuffer buffer = new StringBuffer(numBytes);
    page.add("log", buffer.toString());

    page.render();
}

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

/**
 * Gets the user-defined property names and values for the specified node.
 *
 * @param node the node to be searched//from ww  w  . ja  v a  2s  . co  m
 * @return a map of property names to values
 * @throws IllegalStateException       if a property name is encoded incorrectly
 * @throws MetadataRepositoryException if the metadata repository is unavailable
 */
@Nonnull
public static Map<String, String> getUserProperties(@Nonnull final Node node) {
    // Get node properties
    final PropertyIterator iterator;
    try {
        iterator = node.getProperties();
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to get properties for node: " + node, e);
    }

    // Convert iterator to map
    final String prefix = JcrMetadataAccess.USR_PREFIX + ":";
    final int prefixLength = prefix.length();
    final Map<String, String> properties = new HashMap<>((int) Math.min(iterator.getSize(), Integer.MAX_VALUE));

    while (iterator.hasNext()) {
        final Property property = iterator.nextProperty();
        try {
            if (property.getName().startsWith(prefix)) {
                properties.put(
                        URLDecoder.decode(property.getName().substring(prefixLength), USER_PROPERTY_ENCODING),
                        property.getString());
            }
        } catch (AccessDeniedException e) {
            log.debug("Access denied", e);
            throw new AccessControlException(e.getMessage());
        } catch (RepositoryException e) {
            throw new MetadataRepositoryException(
                    "Failed to access property \"" + property + "\" on node: " + node, e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(
                    "Unsupported encoding for property \"" + property + "\" on node: " + node, e);
        }
    }

    return properties;
}

From source file:servlets.Samples_servlets.java

private void get_all_bioconditions_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*  w  w  w.j a v  a2  s .c om*/
        DAO dao_instance = null;
        ArrayList<Object> bioconditionsList = null;
        try {

            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String loggedUser = requestData.get("loggedUser").getAsString();
            String sessionToken = requestData.get("sessionToken").getAsString();
            /**
             * *******************************************************
             * 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
             * *******************************************************
             */
            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 Get ALL THE ANALYSIS Object from DB. IF ERROR -->
             * throws MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("BioCondition");
            boolean loadRecursive = false;
            if (requestData.has("recursive")) {
                loadRecursive = requestData.get("recursive").getAsBoolean();
            }

            Object[] params = { loadRecursive };
            bioconditionsList = dao_instance.findAll(params);

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "get_all_bioconditions_handler", e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 3b CATCH ERROR. GO TO STEP 4
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                /**
                 * *******************************************************
                 * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4
                 * *******************************************************
                 */
                String bioconditionsJSON = "[";
                for (int i = 0; i < bioconditionsList.size(); i++) {
                    bioconditionsJSON += ((BioCondition) bioconditionsList.get(i)).toJSON()
                            + ((i < bioconditionsList.size() - 1) ? "," : "");
                }
                bioconditionsJSON += "]";

                response.getWriter().print(bioconditionsJSON);
            }
            /**
             * *******************************************************
             * STEP 4 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(), "get_all_bioconditions_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

/**
 * Sets the specified user-defined properties on the specified node.
 *
 * @param node       the target node/*  w w w .  ja  va 2s  .c  o m*/
 * @param fields     the predefined user fields
 * @param properties the map of user-defined property names to values
 * @throws IllegalStateException       if a property name is encoded incorrectly
 * @throws MetadataRepositoryException if the metadata repository is unavailable
 */
public static void setUserProperties(@Nonnull final Node node, @Nonnull final Set<UserFieldDescriptor> fields,
        @Nonnull final Map<String, String> properties) {
    // Verify required properties are not empty
    for (final UserFieldDescriptor field : fields) {
        if (field.isRequired() && StringUtils.isEmpty(properties.get(field.getSystemName()))) {
            throw new MissingUserPropertyException("Missing required property: " + field.getSystemName());
        }
    }

    // Set properties on node
    final Set<String> newProperties = new HashSet<>(properties.size());
    final String prefix = JcrMetadataAccess.USR_PREFIX + ":";

    properties.forEach((key, value) -> {
        try {
            final String name = prefix + URLEncoder.encode(key, USER_PROPERTY_ENCODING);
            newProperties.add(name);
            node.setProperty(name, value);
        } catch (AccessDeniedException e) {
            log.debug("Access denied", e);
            throw new AccessControlException(e.getMessage());
        } catch (RepositoryException e) {
            throw new MetadataRepositoryException(
                    "Failed to set user property \"" + key + "\" on node: " + node, e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e.toString(), e);
        }
    });

    // Get node properties
    final PropertyIterator iterator;
    try {
        iterator = node.getProperties();
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to get properties for node: " + node, e);
    }

    // Remove properties from node
    while (iterator.hasNext()) {
        final Property property = iterator.nextProperty();
        try {
            final String name = property.getName();
            if (name.startsWith(prefix) && !newProperties.contains(name)) {
                property.remove();
            }
        } catch (AccessDeniedException e) {
            log.debug("Access denied", e);
            throw new AccessControlException(e.getMessage());
        } catch (RepositoryException e) {
            throw new MetadataRepositoryException(
                    "Failed to remove property \"" + property + "\" on node: " + node, e);
        }
    }
}

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

/**
 * Copies a property, if present, from the source node to the destination node.
 *
 * @param src  source node/*  w ww  .j a  v a 2s .  co  m*/
 * @param dest destination node
 * @param name the name of the property
 * @return whether the source had a value to copy
 */
public static boolean copyProperty(Node src, Node dest, String name) {
    try {
        if (src.hasProperty(name)) {
            Property prop = src.getProperty(name);

            if (prop.isMultiple()) {
                Value[] values = prop.getValues();
                dest.setProperty(name, values, prop.getType());
            } else {
                Value value = prop.getValue();
                dest.setProperty(name, value, prop.getType());
            }

            return true;
        } else {
            return false;
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(
                "Failed to copy property \"" + name + "\" from node " + src + " to " + dest, e);
    }
}

From source file:azkaban.webapp.servlet.ProjectManagerServlet.java

private void handlePermissionPage(HttpServletRequest req, HttpServletResponse resp, Session session)
        throws ServletException {
    Page page = newPage(req, resp, session, "azkaban/webapp/servlet/velocity/permissionspage.vm");
    String projectName = getParam(req, "project");
    User user = session.getUser();/*from   w w  w.  j  a v  a 2  s  . c  om*/

    Project project = null;
    try {
        project = projectManager.getProject(projectName);
        if (project == null) {
            page.add("errorMsg", "Project " + projectName + " not found.");
        } else {
            if (!hasPermission(project, user, Type.READ)) {
                throw new AccessControlException("No permission to view project " + projectName + ".");
            }

            page.add("project", project);
            page.add("username", user.getUserId());
            page.add("admins", Utils.flattenToString(project.getUsersWithPermission(Type.ADMIN), ","));
            Permission perm = this.getPermissionObject(project, user, Type.ADMIN);
            page.add("userpermission", perm);

            if (perm.isPermissionSet(Type.ADMIN)) {
                page.add("admin", true);
            }

            List<Pair<String, Permission>> userPermission = project.getUserPermissions();
            if (userPermission != null && !userPermission.isEmpty()) {
                page.add("permissions", userPermission);
            }

            List<Pair<String, Permission>> groupPermission = project.getGroupPermissions();
            if (groupPermission != null && !groupPermission.isEmpty()) {
                page.add("groupPermissions", groupPermission);
            }

            Set<String> proxyUsers = project.getProxyUsers();
            if (proxyUsers != null && !proxyUsers.isEmpty()) {
                page.add("proxyUsers", proxyUsers);
            }

            if (hasPermission(project, user, Type.ADMIN)) {
                page.add("isAdmin", true);
            }
        }
    } catch (AccessControlException e) {
        page.add("errorMsg", e.getMessage());
    }

    page.render();
}

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

public static Node getParent(Property prop) {
    try {//from  w  w  w .j a v  a2  s.  c o  m
        return prop.getParent();
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to get the parent node of the property: " + prop, e);
    }
}