List of usage examples for java.security AccessControlException AccessControlException
public AccessControlException(String s)
From source file:org.orcid.core.security.DefaultPermissionChecker.java
private void performPermissionChecks(Authentication authentication, ScopePathType requiredScope, String orcid, OrcidMessage orcidMessage) {/*w w w. j a v a2 s . c om*/ // We can trust that this will return a not-null Authentication object Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); if (authoritiesHasRole(authorities, "ROLE_SYSTEM")) { return; } else if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) { OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication; checkScopes(oAuth2Authentication, requiredScope); performSecurityChecks(oAuth2Authentication, requiredScope, orcidMessage, orcid); } else { throw new AccessControlException( "Cannot access method with authentication type " + authentication != null ? authentication.toString() : ", as it's null!"); } }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java
public static Optional<Property> findProperty(Node node, String name) { try {// w w w . j a v a 2s .c o m if (node.hasProperty(name)) { return Optional.of(node.getProperty(name)); } else { return Optional.empty(); } } catch (AccessDeniedException e) { log.debug("Access denied", e); throw new AccessControlException(e.getMessage()); } catch (RepositoryException e) { throw new MetadataRepositoryException("Failed attempting to locate a property: " + name, e); } }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrUtil.java
public static Iterable<Node> getIterableChildren(Node parent, String name) { @SuppressWarnings("unchecked") Iterable<Node> itr = () -> { try {/*from ww w.ja v a 2 s . co m*/ return name != null ? parent.getNodes(name) : parent.getNodes(); } catch (AccessDeniedException e) { log.debug("Access denied", e); throw new AccessControlException(e.getMessage()); } catch (RepositoryException e) { throw new MetadataRepositoryException("Failed to retrieve the child nodes from: " + parent, e); } }; return itr; }
From source file:servlets.User_servlets.java
private void user_sign_up_handler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w w w. j ava2 s. c o m*/ DAO dao_instance = null; User user = null; boolean ROLLBACK_NEEDED = false; String error = ""; 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 user_id = requestData.get("user_id").getAsString(); String password = requestData.get("password").getAsString(); password = SHA1.getHash(password); dao_instance = DAOProvider.getDAOByName("User"); Object[] params = { null, false, true }; user = (User) ((User_JDBCDAO) dao_instance).findByID(email, params); if (user != null) { throw new AccessControlException("Email already registered."); } user = (User) ((User_JDBCDAO) dao_instance).findByID(user_id, null); if (user != null) { throw new AccessControlException( "There is another user with that name. Try with another name."); } /** * ******************************************************* * STEP 2 Create the new user instance. * ******************************************************* */ user = new User(user_id, email); user.setPassword(password); user.setRandomAPICode(); /** * ******************************************************* * STEP 3 INSERT 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; dao_instance.insert(user); /** * ******************************************************* * 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 (AccessControlException e) { error = e.getMessage(); } 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()); if (ROLLBACK_NEEDED) { dao_instance.doRollback(); } } else { /** * ******************************************************* * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4 * ******************************************************* */ if (error.length() > 0) { JsonObject obj = new JsonObject(); obj.add("success", new JsonPrimitive(false)); obj.add("reason", new JsonPrimitive(error)); response.getWriter().print(obj.toString()); } 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, User_servlets.class.getName(), "userSignUpPostHandler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:org.apache.hadoop.fs.http.server.HttpFSServer.java
/** * Binding to handle GET requests, supported operations are * * @param path the path for operation./*from www .j a v a2 s.co m*/ * @param op the HttpFS operation of the request. * @param params the HttpFS parameters of the request. * * @return the request response. * * @throws IOException thrown if an IO error occurred. Thrown exceptions are * handled by {@link HttpFSExceptionProvider}. * @throws FileSystemAccessException thrown if a FileSystemAccess releated * error occurred. Thrown exceptions are handled by * {@link HttpFSExceptionProvider}. */ @GET @Path("{path:.*}") @Produces({ MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON }) public Response get(@PathParam("path") String path, @QueryParam(OperationParam.NAME) OperationParam op, @Context Parameters params, @Context HttpServletRequest request) throws IOException, FileSystemAccessException { UserGroupInformation user = HttpUserGroupInformation.get(); Response response; path = makeAbsolute(path); MDC.put(HttpFSFileSystem.OP_PARAM, op.value().name()); MDC.put("hostname", request.getRemoteAddr()); switch (op.value()) { case OPEN: { //Invoking the command directly using an unmanaged FileSystem that is // released by the FileSystemReleaseFilter FSOperations.FSOpen command = new FSOperations.FSOpen(path); FileSystem fs = createFileSystem(user); InputStream is = command.execute(fs); Long offset = params.get(OffsetParam.NAME, OffsetParam.class); Long len = params.get(LenParam.NAME, LenParam.class); AUDIT_LOG.info("[{}] offset [{}] len [{}]", new Object[] { path, offset, len }); InputStreamEntity entity = new InputStreamEntity(is, offset, len); response = Response.ok(entity).type(MediaType.APPLICATION_OCTET_STREAM).build(); break; } case GETFILESTATUS: { FSOperations.FSFileStatus command = new FSOperations.FSFileStatus(path); Map json = fsExecute(user, command); AUDIT_LOG.info("[{}]", path); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case LISTSTATUS: { String filter = params.get(FilterParam.NAME, FilterParam.class); FSOperations.FSListStatus command = new FSOperations.FSListStatus(path, filter); Map json = fsExecute(user, command); AUDIT_LOG.info("[{}] filter [{}]", path, (filter != null) ? filter : "-"); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case GETHOMEDIRECTORY: { enforceRootPath(op.value(), path); FSOperations.FSHomeDir command = new FSOperations.FSHomeDir(); JSONObject json = fsExecute(user, command); AUDIT_LOG.info(""); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case INSTRUMENTATION: { enforceRootPath(op.value(), path); Groups groups = HttpFSServerWebApp.get().get(Groups.class); List<String> userGroups = groups.getGroups(user.getShortUserName()); if (!userGroups.contains(HttpFSServerWebApp.get().getAdminGroup())) { throw new AccessControlException("User not in HttpFSServer admin group"); } Instrumentation instrumentation = HttpFSServerWebApp.get().get(Instrumentation.class); Map snapshot = instrumentation.getSnapshot(); response = Response.ok(snapshot).build(); break; } case GETCONTENTSUMMARY: { FSOperations.FSContentSummary command = new FSOperations.FSContentSummary(path); Map json = fsExecute(user, command); AUDIT_LOG.info("[{}]", path); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case GETFILECHECKSUM: { FSOperations.FSFileChecksum command = new FSOperations.FSFileChecksum(path); Map json = fsExecute(user, command); AUDIT_LOG.info("[{}]", path); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case GETFILEBLOCKLOCATIONS: { response = Response.status(Response.Status.BAD_REQUEST).build(); break; } case GETACLSTATUS: { FSOperations.FSAclStatus command = new FSOperations.FSAclStatus(path); Map json = fsExecute(user, command); AUDIT_LOG.info("ACL status for [{}]", path); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case GETXATTRS: { List<String> xattrNames = params.getValues(XAttrNameParam.NAME, XAttrNameParam.class); XAttrCodec encoding = params.get(XAttrEncodingParam.NAME, XAttrEncodingParam.class); FSOperations.FSGetXAttrs command = new FSOperations.FSGetXAttrs(path, xattrNames, encoding); @SuppressWarnings("rawtypes") Map json = fsExecute(user, command); AUDIT_LOG.info("XAttrs for [{}]", path); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } case LISTXATTRS: { FSOperations.FSListXAttrs command = new FSOperations.FSListXAttrs(path); @SuppressWarnings("rawtypes") Map json = fsExecute(user, command); AUDIT_LOG.info("XAttr names for [{}]", path); response = Response.ok(json).type(MediaType.APPLICATION_JSON).build(); break; } default: { throw new IOException(MessageFormat.format("Invalid HTTP GET operation [{0}]", op.value())); } } return response; }
From source file:org.orcid.core.security.DefaultPermissionChecker.java
private void checkScopes(OAuth2Authentication oAuth2Authentication, ScopePathType requiredScope) { OAuth2Request authorizationRequest = oAuth2Authentication.getOAuth2Request(); Set<String> requestedScopes = authorizationRequest.getScope(); if (requiredScope.isUserGrantWriteScope()) { OrcidOAuth2Authentication orcidOauth2Authentication = (OrcidOAuth2Authentication) oAuth2Authentication; String activeToken = orcidOauth2Authentication.getActiveToken(); if (activeToken != null) { OrcidOauth2TokenDetail tokenDetail = orcidOauthTokenDetailService .findNonDisabledByTokenValue(activeToken); if (removeUserGrantWriteScopePastValitity(tokenDetail)) { throw new AccessControlException("Write scopes for this token have expired "); }/*w w w .j a va 2 s .c o m*/ } } if (!hasRequiredScope(requestedScopes, requiredScope)) { throw new AccessControlException("Insufficient or wrong scope " + requestedScopes); } }
From source file:org.netxilia.api.impl.user.AclServiceImpl.java
private void setPermissions(AclObjectType objectType, WorkbookId workbookId, String sheetName, User grantee, Permission... permissions) throws StorageException { // A=object type => sheet // B=username // C=object name => sheet name // D=permissions comma delimited ISheet aclSheet = null;/*from w w w . j a va2s. co m*/ boolean wasSet = AclPrivilegedMode.set(); try { aclSheet = getAclSheet(workbookId); User user = userService.getCurrentUser(); if (user == null) { throw new AccessControlException("No current user"); } if (user.isAdmin()) { return; } Map<String, IGenericValue> row = new HashMap<String, IGenericValue>(); row.put("A", new StringValue(objectType.name())); row.put("B", new StringValue(user.getLogin())); row.put("C", new StringValue(sheetName)); StringBuilder permString = new StringBuilder(); for (Permission perm : permissions) { if (permString.length() > 0) { permString.append(","); } permString.append(perm.name()); } row.put("D", new StringValue(permString.toString())); aclSheet.sendCommand(CellCommands.mapValues(AreaReference.lastRow(0, 3), row)); } catch (NotFoundException e) { // only happens if somebody deleted the sheet right before the filtering throw new StorageException(e); } finally { if (!wasSet) { AclPrivilegedMode.clear(); } } }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java
public static <T> T getProperty(Node node, String name, boolean allowNotFound) { try {/* ww w. j ava 2 s.c o m*/ Property prop = node.getProperty(name); return asValue(prop); } catch (PathNotFoundException e) { if (allowNotFound) { return null; } else { throw new UnknownPropertyException(name, e); } } 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:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java
private Subject performBasicAuth(Subject subject, SubjectCreator subjectCreator, String base64UsernameAndPassword) { String[] credentials = (new String(Base64.decodeBase64(base64UsernameAndPassword.getBytes()))).split(":", 2);/*from w ww.java 2s .c om*/ if (credentials.length == 2) { subject = authenticateUserAndGetSubject(subjectCreator, credentials[0], credentials[1]); } else { //TODO: write a return response indicating failure? throw new AccessControlException("Invalid number of credentials supplied: " + credentials.length); } return subject; }
From source file:servlets.Samples_servlets.java
/** * * @param request//from w ww. j a v a 2 s. com * @param response * @throws ServletException * @throws IOException */ private void add_biocondition_handler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String BLOCKED_ID = null; boolean ROLLBACK_NEEDED = false; DAO dao_instance = 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 * 6b 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 new ID for the BIOCONDITION. IF ERROR --> * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 3 * ******************************************************* */ dao_instance = DAOProvider.getDAOByName("BioCondition"); String newID = dao_instance.getNextObjectID(null); BLOCKED_ID = newID; /** * ******************************************************* * STEP 3 Get the Object by parsing the JSON data. IF ERROR --> * throws JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP * 4 ******************************************************* */ BioCondition biocondition = BioCondition.fromJSON(requestData.get("biocondition_json_data")); /** * ******************************************************* * STEP 4 Set the object and children ID. IF ERROR --> throws * JsonParseException, GO TO STEP 6b ELSE --> GO TO STEP 5 * ******************************************************* */ //TODO: CAMBIAR COMO EN ANALYSIS (CAMBIAR IDs internamente en BioCondition) biocondition.setBioConditionID(newID); if (biocondition.getAssociatedBioreplicates() != null) { ArrayList<Bioreplicate> bioreplicates = new ArrayList<Bioreplicate>(); int nBioReplicate = 1; for (Bioreplicate bioreplicate : biocondition.getAssociatedBioreplicates()) { if (!"new_deleted".equals(bioreplicate.getStatus())) { bioreplicates.add(bioreplicate); if (bioreplicate.getAssociatedAnalyticalReplicates() != null) { ArrayList<AnalyticalReplicate> analyticalReplicates = new ArrayList<AnalyticalReplicate>(); for (AnalyticalReplicate analyticalReplicate : bioreplicate .getAssociatedAnalyticalReplicates()) { if (!"new_deleted".equals(analyticalReplicate.getStatus())) { analyticalReplicates.add(analyticalReplicate); } } bioreplicate.setAssociatedAnalyticalReplicates( analyticalReplicates.toArray(new AnalyticalReplicate[] {})); } bioreplicate.setBioreplicateID(newID, nBioReplicate); nBioReplicate++; } } biocondition.setAssociatedBioreplicates(bioreplicates.toArray(new Bioreplicate[] {})); } /** * ******************************************************* * STEP 5 Add the new Object in the DATABASE. IF ERROR --> * throws SQL Exception, GO TO STEP 6b ELSE --> GO TO STEP 6 * ******************************************************* */ dao_instance.disableAutocommit(); ROLLBACK_NEEDED = true; dao_instance.insert(biocondition); /** * ******************************************************* * STEP 6 COMMIT CHANGES TO DATABASE. throws SQLException IF * ERROR --> throws SQL Exception, GO TO STEP 6b ELSE --> GO TO * STEP 7 * ******************************************************* */ dao_instance.doCommit(); } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "add_biocondition_handler", e.getMessage()); } finally { /** * ******************************************************* * STEP 6b CATCH ERROR, CLEAN CHANGES. throws SQLException * ******************************************************* */ if (ServerErrorManager.errorStatus()) { response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); if (ROLLBACK_NEEDED) { dao_instance.doRollback(); } } else { JsonObject obj = new JsonObject(); obj.add("newID", new JsonPrimitive(BLOCKED_ID)); response.getWriter().print(obj.toString()); } if (BLOCKED_ID != null) { BlockedElementsManager.getBlockedElementsManager().unlockID(BLOCKED_ID); } /** * ******************************************************* * STEP 8 Close connection. * ******************************************************** */ if (dao_instance != null) { dao_instance.closeConnection(); } } //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE } catch (Exception e) { ServerErrorManager.handleException(e, Samples_servlets.class.getName(), "add_biocondition_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }