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

private void get_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from   w w  w .j  a  va 2s  . c o m*/
        DAO dao_instance = null;
        String tmpFile = "";
        Path tmpDir = null;
        try {
            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();

            /**
             * *******************************************************
             * 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 the Experiment Object from DB. IF ERROR --> throws
             * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            String experiment_id;
            if (request.getParameter("experiment_id") != null) {
                experiment_id = request.getParameter("experiment_id");
            } else {
                experiment_id = cookies.get("currentExperimentID").getValue();
            }

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

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

            String fileName;
            if (request.getParameter("filename") != null) {
                fileName = request.getParameter("filename");
            } else {
                throw new FileNotFoundException("Cannot get selected file. File not found in server.");
            }

            if (request.getParameter("credentials") != null) {
                byte[] decoded = Base64.decodeBase64(request.getParameter("credentials"));
                String[] credentials = new String(decoded).split(":", 2);
                experiment.setDataDirectoryUser(credentials[0]);
                experiment.setDataDirectoryPass(credentials[1]);
            } else if (request.getParameter("apikey") != null) {
                experiment.setDataDirectoryApiKey(request.getParameter("apikey"));
            }

            fileName = fileName.replaceAll(" ", "%20");

            tmpDir = Files.createTempDirectory(null);
            tmpFile = FileManager.getFileManager(DATA_LOCATION).getFile(fileName,
                    experiment.getDataDirectoryInformation(), tmpDir.toString());

        } catch (Exception e) {
            ServerErrorManager.handleException(e, File_servlets.class.getName(), "get_file_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
                 * *******************************************************
                 */
                // reads input file from an absolute path
                File downloadFile = new File(tmpFile);
                try {
                    FileInputStream inStream = new FileInputStream(downloadFile);
                    // gets MIME type of the file
                    String mimeType = getServletContext().getMimeType(tmpFile);
                    if (mimeType == null) {
                        // set to binary type if MIME mapping not found
                        mimeType = "application/octet-stream";
                    }
                    response.setContentType(mimeType);
                    response.setHeader("Content-Disposition", "filename=\"" + downloadFile.getName() + "\"");

                    // obtains response's output stream
                    OutputStream outStream = response.getOutputStream();

                    byte[] buffer = new byte[4096];
                    int bytesRead = -1;

                    while ((bytesRead = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, bytesRead);
                    }

                    inStream.close();
                    outStream.close();
                } catch (Exception ex) {
                } finally {
                    if (downloadFile.exists()) {
                        downloadFile.delete();
                    }
                    if (tmpDir != null) {
                        Files.delete(tmpDir);
                    }
                }
            }
            /**
             * *******************************************************
             * 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, File_servlets.class.getName(), "get_file_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:servlets.Analysis_servlets.java

private void get_analysis_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from   w  w w.j  a va2  s  . com
        DAO dao_instance = null;
        Analysis analysis = 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 THE ANALYSIS Object from DB. IF ERROR --> throws
             * MySQL exception, GO TO STEP 3b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("Analysis");
            boolean loadRecursive = true;
            Object[] params = { loadRecursive };
            String analysis_id = requestData.get("analysis_id").getAsString();
            analysis = (Analysis) dao_instance.findByID(analysis_id, params);

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "get_analysis_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 SUCCESS RESPONSE. GO TO STEP 4
                 * *******************************************************
                 */
                response.getWriter().print(analysis.toJSON());
            }
            /**
             * *******************************************************
             * 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, Analysis_servlets.class.getName(), "get_analysis_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

/**
 * Creates an object set from the nodes of a same-name sibling property
 *///from  w  w  w  . ja  va 2s . co m
public static <T extends JcrObject> Set<T> getPropertyObjectSet(Node parentNode, String property,
        Class<T> objClass, Object... args) {
    try {
        Set<T> set = new HashSet<>();
        NodeIterator itr = parentNode.getNodes(property);
        while (itr.hasNext()) {
            Node objNode = (Node) itr.next();
            T obj = constructNodeObject(objNode, objClass, args);
            set.add(obj);
        }
        return set;
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(
                "Failed to create set of child objects from property: " + property, e);
    }
}

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

public static boolean removeAllFromSetProperty(Node node, String name) {
    try {//from  w w  w .ja  v  a2 s .  c o  m
        //            JcrVersionUtil.ensureCheckoutNode(node);
        if (node == null) {
            throw new IllegalArgumentException("Cannot remove a property from a null-node!");
        }
        if (name == null) {
            throw new IllegalArgumentException("Cannot remove a property without a provided name");
        }

        Set<Value> values = new HashSet<>();
        node.setProperty(name, (Value[]) values.stream().toArray(size -> new Value[size]));
        return true;

    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to remove set property: " + name, e);
    }
}

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

public static NodeType getNodeType(Session session, String typeName) {
    try {/*ww  w .ja  v  a  2  s . c  o  m*/
        return session.getWorkspace().getNodeTypeManager().getNodeType(typeName);
    } catch (NoSuchNodeTypeException e) {
        throw new MetadataRepositoryException("No node type exits named: " + typeName, e);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to retrieve node type named: " + typeName, e);
    }
}

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

public static Node copy(Session session, String srcPath, String destPath) {
    try {/*from ww  w .  java2 s.c  o  m*/
        session.getWorkspace().copy(srcPath, destPath);
        return session.getNode(destPath);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(
                "Failed to copy source path: " + srcPath + " to destination path: " + destPath, e);
    }
}

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

public static Node copy(Node srcNode, Node destNode) {
    try {// ww w.  j  a v  a 2  s  .c  o m
        Session sess = srcNode.getSession();
        return copy(sess, srcNode.getPath(), destNode.getPath());
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(
                "Failed to copy source node: " + srcNode + " to destination node: " + destNode, e);
    }
}

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

public static boolean removeFromSetProperty(Node node, String name, Object value, boolean weakRef) {
    try {//from  w  w  w  . j  av  a  2s . com
        //            JcrVersionUtil.ensureCheckoutNode(node);

        if (node == null) {
            throw new IllegalArgumentException("Cannot remove a property from a null-node!");
        }
        if (name == null) {
            throw new IllegalArgumentException("Cannot remove a property without a provided name");
        }

        Set<Value> values = new HashSet<>();

        if (node.hasProperty(name)) {
            values = Arrays.stream(node.getProperty(name).getValues()).collect(Collectors.toSet());
        } else {
            values = new HashSet<>();
        }

        Value existingVal = createValue(node.getSession(), value,
                values.stream().anyMatch(v -> v.getType() == PropertyType.WEAKREFERENCE));
        boolean result = values.remove(existingVal);
        node.setProperty(name, (Value[]) values.stream().toArray(size -> new Value[size]));
        return result;
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to remove from set property: " + name + "->" + value, e);
    }
}

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

public static Node copy(Node srcNode, String destPath) {
    try {/*  w  ww .jav  a 2s.c  o m*/
        Session sess = srcNode.getSession();
        return copy(sess, srcNode.getPath(), destPath);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(
                "Failed to copy source node: " + srcNode + " to destination path: " + destPath, e);
    }
}

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

public static <T> Set<T> getSetProperty(Node node, String name) {
    try {/*from   www  . j a v a2  s  .  com*/
        if (node == null) {
            throw new IllegalArgumentException("Cannot set a property on a null-node!");
        }
        if (name == null) {
            throw new IllegalArgumentException("Cannot set a property without a provided name");
        }

        if (node.hasProperty(name)) {
            Set<T> result = new HashSet<T>((Collection<T>) getProperty(node, name));
            return result;
        } else {
            return Collections.emptySet();
        }
    } catch (ClassCastException e) {
        throw new MetadataRepositoryException("Wrong property data type for set", e);
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to get set property: " + name, e);
    }
}