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 add_new_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from   w w  w . jav  a 2  s .  c om
        DAO daoInstance;
        File uploadedFile;
        Experiment experiment;
        String parent_dir;
        String file_name;

        try {

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

            /**
             * *******************************************************
             * 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;
            if (cookies != null) {
                loggedUser = cookies.get("loggedUser").getValue();
                sessionToken = cookies.get("sessionToken").getValue();
                loggedUserID = cookies.get("loggedUserID").getValue();
            } else {
                String apicode = request.getParameter("apicode");
                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();
            }

            /**
             * *******************************************************
             * 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();
            }

            parent_dir = "";
            if (request.getParameter("parent_dir") != null) {
                parent_dir = request.getParameter("parent_dir");
            }

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

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

            /**
             * *******************************************************
             * STEP 4 Read the uploaded file and store in a temporal dir.
             * *******************************************************
             */
            FileItem tmpUploadedFile = null;
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 500 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 600 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 500 * (int) Math.pow(10, 6); //TODO: READ FROM SETTINGS

            // 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("")) {
                        tmpUploadedFile = item;
                    }
                }
            }

            if (tmpUploadedFile == null) {
                throw new Exception("The file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 5 SAVE THE FILE IN THE SERVER.
             * *******************************************************
             */
            //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
            Path tmpDir = Files.createTempDirectory(null);
            file_name = (file_name.isEmpty() ? tmpUploadedFile.getName() : file_name);
            uploadedFile = new File(tmpDir.toString(), file_name);

            try {
                tmpUploadedFile.write(uploadedFile);

                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"));
                }

                FileManager.getFileManager(DATA_LOCATION).saveFiles(new File[] { uploadedFile },
                        experiment.getDataDirectoryInformation(), parent_dir);
            } catch (IOException e) {
                // Directory creation failed
                throw new Exception(
                        "Unable to save the uploded file. Please check if the Tomcat user has read/write permissions over the data application directory.");
            } finally {
                tmpUploadedFile.delete();
                uploadedFile.delete();
                Files.delete(tmpDir);
            }
        } catch (Exception e) {
            ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_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));
                response.getWriter().print(obj.toString());
            }
        }
    } catch (Exception e) {
        ServerErrorManager.handleException(e, File_servlets.class.getName(), "add_new_file_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

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

public static Long getLong(Node node, String name) {
    try {//w w w. j  a va2 s.  co m
        Property prop = node.getProperty(name);
        return prop.getLong();
    } 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 access property: " + name, e);
    }
}

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

public static Node getNode(Session session, String absPath) {
    try {/*  ww  w.  j ava 2s  . co  m*/
        if (absPath.startsWith("/")) {
            return session.getNode(absPath);
        } else {
            return session.getRootNode().getNode(absPath);
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to retrieve the Node at the path: " + absPath, e);
    }
}

From source file:servlets.User_servlets.java

private void user_sign_in_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  w  w  w  .j  a  v  a 2  s.  c om
        DAO dao_instance = null;
        User user = null;
        try {
            /**
             * *******************************************************
             * STEP 1 Check if the user exists in the DB. IF ERROR -->
             * throws MySQL exception, GO TO STEP 2b throws
             * NoSuchAlgorithmException, GO TO STEP 2b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String email = requestData.get("email").getAsString();
            String password = requestData.get("password").getAsString();
            password = SHA1.getHash(password);

            boolean isEmail = true;
            boolean last_experiment = true;
            Object[] params = { password, last_experiment, isEmail };
            dao_instance = DAOProvider.getDAOByName("User");

            user = (User) ((User_JDBCDAO) dao_instance).findByID(email, params);
            /**
             * *******************************************************
             * STEP 2 Check if user exists. IF NOT --> throws Exception, GO
             * TO STEP 2b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            if (user == null) {
                throw new AccessControlException("User not found. Please check the username and password.");
            }

            user.setSessionToken(UserSessionManager.getUserSessionManager().registerNewUser(email));

        } catch (Exception e) {
            ServerErrorManager.handleException(e, User_servlets.class.getName(), "userLoginPostHandler",
                    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
                 * *******************************************************
                 */
                response.setStatus(200);
                response.getWriter().print(user.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, User_servlets.class.getName(), "userLoginPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:org.apache.falcon.service.ProxyUserService.java

private String normalizeHostname(String name) {
    try {/* w ww .j  ava  2s .  c om*/
        InetAddress address = InetAddress.getByName(name);
        return address.getCanonicalHostName();
    } catch (IOException ex) {
        throw new AccessControlException(
                MessageFormat.format("Could not resolve host [{0}], [{1}]", name, ex.getMessage()));
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.common.JcrObject.java

public void setProperty(String name, Object value) {
    try {/*  w  w w  .j  av  a  2  s .c  om*/
        JcrPropertyUtil.setProperty(this.node, name, value);
    } catch (AccessControlException e) {
        // Re-throw with possibly a better message
        throw new AccessControlException("You do not have the permission to set property \"" + name + "\"");
    }
}

From source file:com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions.java

@Override
public void checkPermission(Set<Action> actions) {
    for (Action action : actions) {
        Node current = getNode();
        for (Action parent : action.getHierarchy()) {
            if (!JcrUtil.hasNode(current, parent.getSystemName())) {
                throw new AccessControlException("Not authorized to perform the action: " + action.getTitle());
            }/*from   ww  w .  j a  v  a  2 s .c om*/

            current = JcrUtil.getNode(current, parent.getSystemName());
        }
    }
}

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

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

    long timeBeginnProcessing = System.currentTimeMillis();

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String pathInfo = httpRequest.getPathInfo();
    String requestURL = httpRequest.getRequestURL().toString();

    // servletUrl = schema://host:port/contextPath/servletPath
    String servletURL = StringUtils.removeEnd(requestURL, pathInfo);
    request.setAttribute(Consts.ATTRIBUTE_SERVLET_URL, servletURL);

    // baseUrl = schema://host:port/contextPath
    String baseURL = StringUtils.removeEnd(servletURL, httpRequest.getServletPath());
    request.setAttribute(Consts.ATTRIBUTE_BASE_URL, baseURL);

    // webLocator = schema://host:port
    String webLocator = StringUtils.removeEnd(requestURL, httpRequest.getRequestURI());
    request.setAttribute(Consts.ATTRIBUTE_WEBLOCATOR, webLocator);

    String paramProjectId = request.getParameter(Consts.PARAM_ID);

    // determine the project from the URL
    Project project = null;/* w  w  w  . j  ava  2 s  .c  o  m*/
    ProjectService projectService = ((ProjectService) EntityServices.getByEntityClass(Project.class));

    // first check if project can be deduced from pathInfo
    if (StringUtils.isNotBlank(pathInfo)) {
        if (pathInfo.startsWith(FilterUtil.PATH_SEPARATOR)) {
            pathInfo = pathInfo.replaceFirst(FilterUtil.PATH_SEPARATOR, StringUtils.EMPTY);
        }
        if (pathInfo.contains(FilterUtil.PATH_SEPARATOR)) {
            pathInfo = pathInfo.substring(0, pathInfo.indexOf(FilterUtil.PATH_SEPARATOR));
        }
        project = projectService.getProjectByProjectId(pathInfo);

        // project not found by name, search by UUID
        if (project == null && UUIDUtils.isUUID(pathInfo)) {
            UUID uuid = UUIDUtils.asUUID(pathInfo);
            project = projectService.getByUUID(uuid);
            // project not found by UUID, search for deleted project by UUID
            if (project == null) {
                project = projectService.getDeletedProject(uuid);
            }
        }

        if (project == null) {
            request.setAttribute(Consts.ATTRIBUTE_WINDOWNAME, httpRequest.getPathInfo());
        }
    }

    // project not found by pathInfo, check if project is provided via URL parameter
    if (project == null && StringUtils.isNotBlank(paramProjectId)) {
        project = projectService.getProjectByProjectId(paramProjectId);
        if (project == null) {
            // currently we don't support a scenario where projects are passed via UUID
            FilterUtil.handleException(request, response,
                    new FilterException(String.format("Invalid project identifier '%s' specified in query '%s'",
                            paramProjectId, Consts.PARAM_ID)));
            return;
        }
    }

    if (project != null) {
        request.setAttribute(Consts.ATTRIBUTE_PROJECT, project);
        request.setAttribute(Consts.ATTRIBUTE_PROJECTID, project.getProjectId());
        request.setAttribute(Consts.ATTRIBUTE_PROJECTUUID, project.getUuid().toString());
    } else {
        // do nothing if project is null since this filter runs during
        // creation of projects and displaying of search results, too
    }

    // login and ensure that the user is allowed to access
    PermitService permitService = Services.getRequiredService(PermitService.class);
    String userId = permitService.login(httpRequest, project);
    User user = null;
    boolean isAnonymousUser = StringUtils.isBlank(userId);
    if (isAnonymousUser && rejectAnonymousUsers) {
        FilterUtil.handleACException(httpRequest, response,
                new AccessControlException("Forbidden for anonymous users"));
        return;
    }
    if (!isAnonymousUser) {
        request.setAttribute(Consts.ATTRIBUTE_USERID, userId);
        String userDisplayName = userId;
        user = UserServices.getUser(userId);
        if (user != null) {
            userDisplayName = user.getDisplayName();
            request.setAttribute(Consts.ATTRIBUTE_USER, user);
        }
        request.setAttribute(Consts.ATTRIBUTE_USER_DISPLAY_NAME, userDisplayName);
    }

    boolean isProjectAdmin = !isAnonymousUser && project != null
            && (GroupUtils.isAdministrator(userId) || Permits.isAllowed(Permit.ACTION_PUT, project));
    boolean isProjectAdminInParentChain = !isAnonymousUser && project != null
            && ProjectUtils.isProjectAdminInParentChain(userId, project);

    request.setAttribute(Consts.ATTRIBUTE_ANONYMOUS_USER, isAnonymousUser);
    request.setAttribute(Consts.ATTRIBUTE_PROJECTADMIN, isProjectAdmin);
    request.setAttribute(Consts.ATTRIBUTE_PARENTPROJECTADMIN, isProjectAdminInParentChain);

    // track the access
    Statistics statistics = Statistics.getDefault();
    if (user != null) {
        statistics.trackUser(userId, user.getDepartment(), user.getLocation());
    } else if (StringUtils.isNotBlank(userId)) {
        statistics.trackUser(userId, null, null);
    }

    String referer = httpRequest.getHeader("Referer"); //$NON-NLS-1$
    if (StringUtils.isBlank(referer)) {
        referer = request.getParameter("referer"); //$NON-NLS-1$
    }

    if (StringUtils.isNotBlank(referer)) {
        statistics.trackReferer(userId, referer);
    }

    String requestLine = MessageFormat.format("{0} {1}", //$NON-NLS-1$
            httpRequest.getMethod(), httpRequest.getRequestURI());
    if (project != null) {
        requestLine = MessageFormat.format("{0} /projects/{1}", //$NON-NLS-1$
                httpRequest.getMethod(), project.getProjectId());
    }
    statistics.trackUsage(userId, requestLine, referer);

    String browser = httpRequest.getHeader("User-Agent"); //$NON-NLS-1$
    if (StringUtils.isNotBlank(browser)) {
        statistics.trackBrowser(userId, browser);
    }

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

    // track the overall response time
    long responseTime = System.currentTimeMillis() - timeBeginnProcessing;
    statistics.trackResponseTime(userId, requestLine, responseTime);
    LOG.info(MessageFormat.format("{0}: responseTime={1} milliseconds)", requestLine,
            Long.toString(responseTime)));
}

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

public static Node getNode(Node parentNode, String name) {
    try {/*from ww w.  j a  v  a2 s  . c  o  m*/
        return parentNode.getNode(name);
    } 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.fcrepo.auth.oauth.api.TokenEndpoint.java

/**
 * @param oauthRequest/*  ww  w.j  a  v  a  2s  .c  o m*/
 * @return An answer to whether or not this request matches up with an
 *         authorization code issued at the {@link AuthzEndpoint}
 * @throws RepositoryException
 */
private boolean isValidAuthCode(final OAuthTokenRequest oauthRequest) throws RepositoryException {
    final String client = oauthRequest.getClientId();
    LOGGER.debug("Request has authorization client: {}", client);
    final String code = oauthRequest.getCode();
    final Set<String> scopes = oauthRequest.getScopes();
    final Session session = sessions.getSession(OAUTH_WORKSPACE);
    try {
        final Node authCodeNode = session.getNode("/authorization-codes/" + code);
        LOGGER.debug("Found authorization code node stored: {}", authCodeNode.getPath());
        // if the client is right
        if (authCodeNode.getProperty(CLIENT_PROPERTY).getString().equals(client)) {
            // final Set<String> storedScopes =
            // newHashSet(map(authCodeNode
            // .getProperty(SCOPES_PROPERTY).getValues(),
            // value2string));
            // and if there is at least one scope in common
            // if (intersection(storedScopes, scopes).size() > 0) {
            return true;
            // }
        }
    } catch (final PathNotFoundException e) {
        // this wasn't a code we stored
        return false;
    } finally {
        session.logout();
    }
    throw new AccessControlException(
            "Could not establish validity or invalidity of authorization code! Code:" + code);
}