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

private void delete_user_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from w  ww  .ja  va  2s . c  o m
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = 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
             * 4b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            if (!checkAccessPermissions(request.getParameter("loggedUser"),
                    request.getParameter("sessionToken"))) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            if (!"admin".equals(request.getParameter("loggedUser"))) {
                throw new AccessControlException(
                        request.getParameter("loggedUser") + " is no allowed for this operation.");
            }

            String user_id = request.getParameter("user_id");

            if (UserSessionManager.getUserSessionManager().isLoggedUser(user_id)) {
                throw new Exception("Unable to remove User " + user_id
                        + ". Reason: The user is currently logged in the application.");
            }

            /**
             * *******************************************************
             * STEP 3 UPDATE IN DATABASE. IF ERROR --> throws exception if
             * not valid session, GO TO STEP 4b ELSE --> GO TO STEP 4
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("User");
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            new User_JDBCDAO().remove(user_id);

            /**
             * *******************************************************
             * STEP 4 COMMIT CHANGES IN DB. IF ERROR --> throws exception if
             * not valid session, GO TO STEP 4b ELSE --> GO TO STEP 5
             * *******************************************************
             */
            dao_instance.doCommit();

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

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                response.getWriter().print("{success: " + true + "}");
            }
            /**
             * *******************************************************
             * 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, User_servlets.class.getName(), "removeUserPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:servlets.Analysis_servlets.java

private void export_analysis_handler(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    try {//from  ww  w .  j a v  a 2  s  .  c o  m
        DAO dao_instance = null;
        Analysis analysis = null;
        String tmpFile = "";
        Path tmpDir = null;

        try {
            String format = request.getParameter("format");
            if (format == null) {
                format = "json";
            }

            Map<String, Cookie> cookies = this.getCookies(request);

            String loggedUser, sessionToken;
            loggedUser = cookies.get("loggedUser").getValue();
            sessionToken = cookies.get("sessionToken").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 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 = request.getParameter("analysis_id");
            analysis = (Analysis) dao_instance.findByID(analysis_id, params);

            tmpDir = Files.createTempDirectory(null);
            tmpFile = analysis.export(tmpDir.toString(), format,
                    this.getServletContext().getRealPath("/data/templates"));

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Analysis_servlets.class.getName(), "export_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 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, Analysis_servlets.class.getName(), "export_analysis_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.ClientRMService.java

@SuppressWarnings("unchecked")
@Override//from   w w w  . j a  v  a 2  s  . c om
public FailApplicationAttemptResponse failApplicationAttempt(FailApplicationAttemptRequest request)
        throws YarnException {

    ApplicationAttemptId attemptId = request.getApplicationAttemptId();
    ApplicationId applicationId = attemptId.getApplicationId();

    UserGroupInformation callerUGI;
    try {
        callerUGI = UserGroupInformation.getCurrentUser();
    } catch (IOException ie) {
        LOG.info("Error getting UGI ", ie);
        RMAuditLogger.logFailure("UNKNOWN", AuditConstants.FAIL_ATTEMPT_REQUEST, "UNKNOWN", "ClientRMService",
                "Error getting UGI", applicationId, attemptId);
        throw RPCUtil.getRemoteException(ie);
    }

    RMApp application = this.rmContext.getRMApps().get(applicationId);
    if (application == null) {
        RMAuditLogger.logFailure(callerUGI.getUserName(), AuditConstants.FAIL_ATTEMPT_REQUEST, "UNKNOWN",
                "ClientRMService", "Trying to fail an attempt of an absent application", applicationId,
                attemptId);
        throw new ApplicationNotFoundException(
                "Trying to fail an attempt " + attemptId + " of an absent application " + applicationId);
    }

    RMAppAttempt appAttempt = application.getAppAttempts().get(attemptId);
    if (appAttempt == null) {
        throw new ApplicationAttemptNotFoundException(
                "ApplicationAttempt with id '" + attemptId + "' doesn't exist in RM.");
    }

    if (!checkAccess(callerUGI, application.getUser(), ApplicationAccessType.MODIFY_APP, application)) {
        RMAuditLogger.logFailure(callerUGI.getShortUserName(), AuditConstants.FAIL_ATTEMPT_REQUEST,
                "User doesn't have permissions to " + ApplicationAccessType.MODIFY_APP.toString(),
                "ClientRMService", AuditConstants.UNAUTHORIZED_USER, applicationId);
        throw RPCUtil.getRemoteException(
                new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation "
                        + ApplicationAccessType.MODIFY_APP.name() + " on " + applicationId));
    }

    FailApplicationAttemptResponse response = recordFactory
            .newRecordInstance(FailApplicationAttemptResponse.class);

    if (!ACTIVE_APP_STATES.contains(application.getState())) {
        if (COMPLETED_APP_STATES.contains(application.getState())) {
            RMAuditLogger.logSuccess(callerUGI.getShortUserName(), AuditConstants.FAIL_ATTEMPT_REQUEST,
                    "ClientRMService", applicationId);
            return response;
        }
    }

    this.rmContext.getDispatcher().getEventHandler()
            .handle(new RMAppAttemptEvent(attemptId, RMAppAttemptEventType.FAIL, "Attempt failed by user."));

    RMAuditLogger.logSuccess(callerUGI.getShortUserName(), AuditConstants.FAIL_ATTEMPT_REQUEST,
            "ClientRMService", applicationId, attemptId);

    return response;
}

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

public static Value createValue(Session session, Object value, boolean weakRef) {
    try {/*from   ww w .  ja  v a  2  s .c  o m*/
        ValueFactory factory = session.getValueFactory();
        if (value == null) {
            throw new IllegalArgumentException("Cannot create a value from null");
        } else if (value instanceof Enum) {
            return factory.createValue(((Enum) value).name());
        } else if (value instanceof JcrObject) {
            return factory.createValue(((JcrObject) value).getNode(), weakRef);
            //                return factory.createValue(((JcrObject) value).getNode().getIdentifier(), weakRef ? PropertyType.WEAKREFERENCE : PropertyType.REFERENCE);
        } else if (value instanceof Value) {
            return (Value) value;
        } else if (value instanceof Node) {
            //                return factory.createValue((Node) value, weakRef);
            return factory.createValue(((Node) value).getIdentifier(),
                    weakRef ? PropertyType.WEAKREFERENCE : PropertyType.REFERENCE);
        } else if (value instanceof Binary) {
            return factory.createValue((Binary) value);
        } else if (value instanceof Calendar) {
            return factory.createValue((Calendar) value);
        } else if (value instanceof DateTime) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(((DateTime) value).toDate());
            return factory.createValue(cal);
        } else if (value instanceof Date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime((Date) value);
            return factory.createValue(cal);
        } else if (value instanceof BigDecimal) {
            return factory.createValue((BigDecimal) value);
        } else if (value instanceof Long) {
            return factory.createValue(((Long) value).longValue());
        } else if (value instanceof Double) {
            return factory.createValue((Double) value);
        } else if (value instanceof Boolean) {
            return factory.createValue((Boolean) value);
        } else if (value instanceof InputStream) {
            return factory.createValue((InputStream) value);
            //        } else if (value instanceof Collection) {
            //            String[] list = new String[((Collection<Object>) value).size()];
            //            int pos = 0;
            //            for (Object cal : (Collection<Object>) value) {
            //                list[pos] = cal.toString();
            //                pos += 1;
            //            }
            //            return factory.createValue(list);
        } else {
            return factory.createValue(value.toString());
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to create value frpm: " + value, e);
    }
}

From source file:org.apache.hadoop.hive.shims.Hadoop23Shims.java

/**
 * If there is an AccessException buried somewhere in the chain of failures, wrap the original
 * exception in an AccessException. Othewise just return the original exception.
 *//*from   w w  w  .ja va  2  s  .co  m*/
private static Exception wrapAccessException(Exception err) {
    final int maxDepth = 20;
    Throwable curErr = err;
    for (int idx = 0; curErr != null && idx < maxDepth; ++idx) {
        // fs.permission.AccessControlException removed by HADOOP-11356, but Hive users on older
        // Hadoop versions may still see this exception .. have to reference by name.
        if (curErr instanceof org.apache.hadoop.security.AccessControlException || curErr.getClass().getName()
                .equals("org.apache.hadoop.fs.permission.AccessControlException")) {
            Exception newErr = new AccessControlException(curErr.getMessage());
            newErr.initCause(err);
            return newErr;
        }
        curErr = curErr.getCause();
    }
    return err;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.ClientRMService.java

@SuppressWarnings("unchecked")
@Override/*from   w  w w  .  ja  v a2  s . c  om*/
public KillApplicationResponse forceKillApplication(KillApplicationRequest request) throws YarnException {

    ApplicationId applicationId = request.getApplicationId();
    CallerContext callerContext = CallerContext.getCurrent();

    UserGroupInformation callerUGI;
    try {
        callerUGI = UserGroupInformation.getCurrentUser();
    } catch (IOException ie) {
        LOG.info("Error getting UGI ", ie);
        RMAuditLogger.logFailure("UNKNOWN", AuditConstants.KILL_APP_REQUEST, "UNKNOWN", "ClientRMService",
                "Error getting UGI", applicationId, callerContext);
        throw RPCUtil.getRemoteException(ie);
    }

    RMApp application = this.rmContext.getRMApps().get(applicationId);
    if (application == null) {
        RMAuditLogger.logFailure(callerUGI.getUserName(), AuditConstants.KILL_APP_REQUEST, "UNKNOWN",
                "ClientRMService", "Trying to kill an absent application", applicationId, callerContext);
        throw new ApplicationNotFoundException("Trying to kill an absent" + " application " + applicationId);
    }

    if (!checkAccess(callerUGI, application.getUser(), ApplicationAccessType.MODIFY_APP, application)) {
        RMAuditLogger.logFailure(callerUGI.getShortUserName(), AuditConstants.KILL_APP_REQUEST,
                "User doesn't have permissions to " + ApplicationAccessType.MODIFY_APP.toString(),
                "ClientRMService", AuditConstants.UNAUTHORIZED_USER, applicationId, callerContext);
        throw RPCUtil.getRemoteException(
                new AccessControlException("User " + callerUGI.getShortUserName() + " cannot perform operation "
                        + ApplicationAccessType.MODIFY_APP.name() + " on " + applicationId));
    }

    if (application.isAppFinalStateStored()) {
        return KillApplicationResponse.newInstance(true);
    }

    StringBuilder message = new StringBuilder();
    message.append("Application ").append(applicationId).append(" was killed by user ")
            .append(callerUGI.getShortUserName());

    InetAddress remoteAddress = Server.getRemoteIp();
    if (null != remoteAddress) {
        message.append(" at ").append(remoteAddress.getHostAddress());
    }

    String diagnostics = org.apache.commons.lang.StringUtils.trimToNull(request.getDiagnostics());
    if (diagnostics != null) {
        message.append(" with diagnostic message: ");
        message.append(diagnostics);
    }

    this.rmContext.getDispatcher().getEventHandler()
            .handle(new RMAppKillByClientEvent(applicationId, message.toString(), callerUGI, remoteAddress));

    // For UnmanagedAMs, return true so they don't retry
    return KillApplicationResponse.newInstance(application.getApplicationSubmissionContext().getUnmanagedAM());
}

From source file:servlets.File_servlets.java

private void delete_file_handler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {// ww  w.  j a  va  2  s .  co  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 delete 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 delete 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"));
            }

            tmpDir = Files.createTempDirectory(null);
            String[] files = new String[] { fileName };
            FileManager.getFileManager(DATA_LOCATION).removeFiles(files,
                    experiment.getDataDirectoryInformation());

        } catch (Exception e) {
            ServerErrorManager.handleException(e, File_servlets.class.getName(), "delete_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 {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                response.getWriter().print(obj.toString());
            }
            /**
             * *******************************************************
             * 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(), "delete_file_handler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

/**
 * Check if an app has access to a target bean.
 *
 * @param aAppName The app name//  w  w  w. j  a  v  a  2  s .  c o  m
 * @param aBeanPath The bean path
 */
public void checkWhiteListedBean(String aAppName, String aBeanPath) {
    Iterator<String> lIt = mSettings.getAppWhiteListedBeans(aAppName).iterator();
    while (lIt.hasNext()) {
        String lWLB = lIt.next();
        // basic checks
        if (lWLB.equals(aBeanPath) || lWLB.equals("*:*")) {
            return;
        }

        // complex checks
        String[] lParts = aBeanPath.split(":");
        String lNS = lParts[0];

        if ("".equals(lNS) && lWLB.equals("*:*")) {
            return;
        }
        if (lWLB.equals(lNS + ":*")) {
            return;
        }
    }

    throw new AccessControlException(
            "The '" + aBeanPath + "' bean access " + "is not allowed in '" + aAppName + "' app!");
}

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

public static Value asValue(ValueFactory factory, Object obj) {
    // STRING, BOOLEAN, LONG, DOUBLE, PATH, ENTITY
    try {// w w w  .  j  av  a 2s .co m
        switch (getJCRPropertyType(obj)) {
        case PropertyType.STRING:
            return factory.createValue((String) obj);
        case PropertyType.BOOLEAN:
            return factory.createValue((Boolean) obj);
        case PropertyType.DATE:
            return factory.createValue((Calendar) obj);
        case PropertyType.LONG:
            return obj instanceof Long ? factory.createValue(((Long) obj).longValue())
                    : factory.createValue(((Integer) obj).longValue());
        case PropertyType.DOUBLE:
            return obj instanceof Double ? factory.createValue((Double) obj)
                    : factory.createValue(((Float) obj).doubleValue());
        case PropertyType.BINARY:
            return factory.createValue((InputStream) obj);
        case PropertyType.REFERENCE:
            return factory.createValue((Node) obj);
        default:
            return (obj != null ? factory.createValue(obj.toString()) : factory.createValue(StringUtils.EMPTY));
        }
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Invalid value format", e);
    }
}

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.
 *//*  w w w  .ja va2  s.co m*/
public static boolean isReferencing(Node node, String refProp, Node targetNode) {
    try {
        return node.getProperty(refProp).getNode().isSame(targetNode);
    } 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: " + node, e);
    }
}