public void prepareErrorList(){ errors.put(new Exception(), Integer.MIN_VALUE); errors.put(new NullPointerException(), 10); errors.put(new NoSuchFileException("The file could not be found. Sorry for the inconvience"), 20); errors.put(new IllegalStateException(), 30); errors.put(new FileNotFoundException(), 200); errors.put(new AccessDeniedException("The account "+System.getProperty("user.name")+"\nhas not the privileges to do this action."), 40); errors.put(new ArrayIndexOutOfBoundsException(), 50); errors.put(new UnsupportedOperationException(), 60); errors.put(new IOException(), 70); errors.put(new MalformedURLException(), 80); errors.put(new IllegalArgumentException(), 90); desc.put(10,"NullPointerException - w którymś momencie w kodzie została napotkana wartość null."); desc.put(30,"The value or component has tried to gain illegal state."); desc.put(200, "The given file hasn't been found, asure that you gave\nan absolute path and the file exists!"); desc.put(50, "The index is out of range; it means that the method tried to access the index which is\n" + "not in that array."); desc.put(60, "Requested operation is not supported at the moment."); desc.put(70, "The problem was occured while operating on Input/Output streams."); desc.put(90, "The argument given was illegal."); desc.put(80, "Given URL is malformed, check\nthat you have write a proper URL address"); }
public void testFileSystemExceptions() throws IOException { for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"), new NoSuchFileException("a", "b", "c"), new NotDirectoryException("a"), new DirectoryNotEmptyException("a"), new AtomicMoveNotSupportedException("a", "b", "c"), new FileAlreadyExistsException("a", "b", "c"), new AccessDeniedException("a", "b", "c"), new FileSystemLoopException("a"))) { FileSystemException serialize = serialize(ex); assertEquals(serialize.getClass(), ex.getClass()); assertEquals("a", serialize.getFile()); if (serialize.getClass() == NotDirectoryException.class || serialize.getClass() == FileSystemLoopException.class || serialize.getClass() == DirectoryNotEmptyException.class) { assertNull(serialize.getOtherFile()); assertNull(serialize.getReason()); } else { assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile()); assertEquals(serialize.getClass().toString(), "c", serialize.getReason()); } } }
@Override public FileContentStream getContentStream(FileHandle handle, String path, String mimeType) { final File file = getFile(handle, path); File parent = file.getParentFile(); while( parent != null ) { if( parent.getName().toUpperCase().equals(SECURE_FOLDER) ) { throw Throwables.propagate(new com.tle.exceptions.AccessDeniedException( CurrentLocale.get(KEY_PFX+"error.protectedresource"))); } parent = parent.getParentFile(); } return getContentStream(file, mimeType); }
public static void main(String[] args) throws Throwable { try (FileChannel ch = FileChannel.open(BLK_PATH, READ); RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) { long size1 = ch.size(); long size2 = file.length(); if (size1 != size2) { throw new RuntimeException("size differs when retrieved" + " in different ways: " + size1 + " != " + size2); } System.out.println("OK"); } catch (NoSuchFileException nsfe) { System.err.println("File " + BLK_FNAME + " not found." + " Skipping test"); } catch (AccessDeniedException ade) { System.err.println("Access to " + BLK_FNAME + " is denied." + " Run test as root."); } }
/** * Check whether the current process can create a directory at the specified path. This is useful * for providing immediate feedback to an end user that a path they have selected or typed may not * be suitable before attempting to create the directory; e.g. in a tooltip. * * @param path tentative location for directory * @throws AccessDeniedException if a directory in the path is not writable * @throws NotDirectoryException if a segment of the path is a file */ public static void verifyDirectoryCreatable(Path path) throws AccessDeniedException, NotDirectoryException { for (Path segment = path; segment != null; segment = segment.getParent()) { if (Files.exists(segment)) { if (Files.isDirectory(segment)) { // Can't create a directory if the bottom most currently existing directory in // the path is not writable. if (!Files.isWritable(segment)) { throw new AccessDeniedException(segment + " is not writable"); } } else { // Can't create a directory if a non-directory file already exists with that name // somewhere in the path. throw new NotDirectoryException(segment + " is a file"); } break; } } }
private <T> T throwException(String segmentName, Exception e) throws StreamSegmentException { if (e instanceof NoSuchFileException || e instanceof FileNotFoundException) { throw new StreamSegmentNotExistsException(segmentName); } if (e instanceof FileAlreadyExistsException) { throw new StreamSegmentExistsException(segmentName); } if (e instanceof IndexOutOfBoundsException) { throw new IllegalArgumentException(e.getMessage()); } if (e instanceof AccessControlException || e instanceof AccessDeniedException || e instanceof NonWritableChannelException) { throw new StreamSegmentSealedException(segmentName, e); } throw Lombok.sneakyThrow(e); }
@Test public void testCreateBucketAccessErrors() throws IOException { GcsOptions pipelineOptions = gcsOptionsWithTestCredential(); GcsUtil gcsUtil = pipelineOptions.getGcsUtil(); Storage mockStorage = Mockito.mock(Storage.class); gcsUtil.setStorageClient(mockStorage); Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class); Storage.Buckets.Insert mockStorageInsert = Mockito.mock(Storage.Buckets.Insert.class); BackOff mockBackOff = BackOffAdapter.toGcpBackOff(FluentBackoff.DEFAULT.backoff()); GoogleJsonResponseException expectedException = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Waves hand mysteriously", "These aren't the buckets you're looking for"); when(mockStorage.buckets()).thenReturn(mockStorageObjects); when(mockStorageObjects.insert( any(String.class), any(Bucket.class))).thenReturn(mockStorageInsert); when(mockStorageInsert.execute()) .thenThrow(expectedException); thrown.expect(AccessDeniedException.class); gcsUtil.createBucket("a", new Bucket(), mockBackOff, new FastNanoClockAndSleeper()); }
/** * Create the directory returned by {@link #getPath()} if it does not yet exist. * * @throws IOException * in case the directory cannot be created or exists and is not a directory or * cannot be accessed */ protected void prepareStorageDirectory() throws IOException { File file = new File(getPath()); if (!file.exists()) { if (!file.mkdirs()) { throw new IOException("cannot create directory " + file.getAbsolutePath()); } } if (!file.isDirectory()) { throw new FileNotFoundException("Defined storage directory isn't a directory: " + file.getAbsolutePath()); } else { if (!file.canRead() || !file.canWrite()) { throw new AccessDeniedException(file.getAbsolutePath()); } LOGGER.debug("Prepared storage directory: {}", file.getAbsolutePath()); } }
@Override public boolean rename(final Path src, final Path dst) throws IOException { final File srcFile = pathToFile(src); final File dstFile = pathToFile(dst); final File dstParent = dstFile.getParentFile(); // Files.move fails if the destination directory doesn't exist //noinspection ResultOfMethodCallIgnored -- we don't care if the directory existed or was created dstParent.mkdirs(); try { Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING); return true; } catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) { // catch the errors that are regular "move failed" exceptions and return false return false; } }
public void addStatusNote(UUID reservationId,Integer statusCode,NoteModel noteModel) throws Exception{ String projectGroupCode = SecurityContextUtil.getUserProjectGroup(); List<MatchStatus> statusHistory = repositoryFactory.getMatchStatusRepository().findByReservationIdAndStatus(reservationId,statusCode); if(statusHistory.isEmpty()) throw new AccessDeniedException("Access denide"); StatusNotesEntity note = new StatusNotesEntity(); note.setNotes(noteModel.getNote()); note.setStatusId(statusHistory.get(0).getId()); note.setDateCreated(LocalDateTime.now()); note.setDateUpdated(LocalDateTime.now()); note.setProjectGroupCode(projectGroupCode); note.setUserId(SecurityContextUtil.getUserAccount().getAccountId()); note.setClientId(statusHistory.get(0).getClientId()); note.setClientDedupId(statusHistory.get(0).getClientDedupId()); repositoryFactory.getStatusNotesRepository().save(note); }
@ApiOperation( value = "Get specific acquisition request of file transfer with given id", notes = "Privilege level: Consumer of this endpoint must be a member of organization based on valid access token" ) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK",response = RequestDTO.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Can't access this organization."), @ApiResponse(code = 500, message = "Internal server error, see logs for details.") }) @RequestMapping(value = "/{id}", method = GET) @ResponseBody public RequestDTO getRequest(@PathVariable String id, HttpServletRequest context) throws AccessDeniedException { LOGGER.debug("get({})", id); Request request = requestStore.get(id).orElseThrow(NoSuchElementException::new); RequestDTO toReturn = request.toDto(); permissionVerifier.throwForbiddenWhenNotAuthorized(context, toReturn); return toReturn; }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 5L; Long enrolmentId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/enrolments/{enrolmentId}/enrolmentsubjects/{id}", enrolmentId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long enrolmentId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/enrolments/{enrolmentId}/statuses/{id}", enrolmentId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long enrolmentId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/enrolments/{enrolmentId}/benefits/{id}", enrolmentId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long publicActivityId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/publicactivities/{publicActivityId}/awards/{id}", publicActivityId, id)); verify(facade).getResource(id); }
void delete(EphemeralFsPath path) throws IOException { synchronized(fsLock) { ResolvedPath resolvedPath = ResolvedPath.resolve(path, true); if(resolvedPath.hasTarget()) { INode iNode = resolvedPath.getTarget(); if(iNode.isDir() && !iNode.isEmpty()) { throw new DirectoryNotEmptyException(path.toString()); } } if(!resolvedPath.didResolve()) { throw new NoSuchFileException(path.toString()); } if(getSettings().isWindows() && resolvedPath.getResolvedProperties().getDosIsReadOnly()) { throw new AccessDeniedException(path.toString()); } resolvedPath.getParent().remove(resolvedPath.getPath().getFileName()); } }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long specOfferId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/specoffers/{specOfferId}/waves/{id}", specOfferId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long personId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/persons/{personId}/pensions/{id}", personId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long personId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/persons/{personId}/contacts/{id}", personId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long personId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/persons/{personId}/educations/{id}", personId, id)); verify(facade).getResource(id); }
@Test(expected = AccessDeniedException.class) public void testGetResourceWithAccessDeniedException() throws Exception { // Given Long id = 1L; Long personId = 2L; // When doThrow(AccessDeniedException.class).when(facade) .getResource(anyLong()); // Then mockMvc.perform(get("/persons/{personId}/languages/{id}", personId, id)); verify(facade).getResource(id); }
@IgnoreUnless(FsType.WINDOWS) @Test public void testDirMoveAlreadyExistsAtomicWindows() throws Exception { Path sourceDir = Files.createDirectory(root.resolve("sourceDir")); Files.createFile(sourceDir.resolve("aFile")); Path targetDir = Files.createDirectory(root.resolve("targetDir")); try { Files.move(sourceDir, targetDir, StandardCopyOption.ATOMIC_MOVE); fail(); } catch(AccessDeniedException e) { //pass } assertTrue(Files.exists(sourceDir.resolve("aFile"))); assertFalse(Files.exists(targetDir.resolve("aFile"))); }
@Get("json") public String doGet() throws GatewayDriverException, DatapointInvalidValueTypeException, UnknownHostException, DatapointReadonlyAccessTypeException, UnsupportedDataTypeException, DatapointWriteonlyAccessTypeException, KNXLinkClosedException, KNXTimeoutException, InterruptedException, AccessDeniedException { RestletServer.configureRestForm(getResponse()); AuthService.CheckAuthorization(getRequest().getResourceRef().getQueryAsForm()); final String gwAddress = getRequest().getAttributes().get("gateway_address").toString(); final IGatewayDriver gateway = config.findGateway(gwAddress); if (gateway == null) return toJSON(new ServiceResourceErrorException("Gateway not found.")); gateway.connect(); List<String> result = gateway.scanNetworkRouters(); gateway.disconnect(); return toJSON(result); }
/** * @param path path of the file to open * @param openOptions file open options * @return file handle used to identify and close open files. * @throws AccessDeniedException Thrown if the requested openOptions are not supported * @throws IOException */ protected long open(Path path, Set<OpenOption> openOptions) throws AccessDeniedException, IOException { if (openOptions.contains(StandardOpenOption.WRITE)) { throw new AccessDeniedException(path.toString(), null, "Unsupported open options: WRITE"); } else { return openFiles.open(path, StandardOpenOption.READ); } }
private static long estimateSize(Directory directory) throws IOException { long estimatedSize = 0; String[] files = directory.listAll(); for (String file : files) { try { estimatedSize += directory.fileLength(file); } catch (NoSuchFileException | FileNotFoundException | AccessDeniedException e) { // ignore, the file is not there no more; on Windows, if one thread concurrently deletes a file while // calling Files.size, you can also sometimes hit AccessDeniedException } } return estimatedSize; }
@Test (expected = AccessDeniedException.class) public void throwIfDestinationNotWritable() throws IOException { byte[] sourceContent = new byte[] { 100 }; Path source = createFileInTempDir("source", sourceContent); Path dest = createFileInTempDir("dest"); boolean isReadOnly = dest.toFile().setReadOnly(); assertTrue(isReadOnly); FileOps.filter(source, dest, (in, out) -> {}); }
@Override public BackgroundException map(final IOException e) { final StringBuilder buffer = new StringBuilder(); this.append(buffer, e.getMessage()); if(e instanceof AccessDeniedException) { return new LocalAccessDeniedException(buffer.toString(), e); } if(e instanceof FileAlreadyExistsException) { return new LocalAccessDeniedException(buffer.toString(), e); } if(e instanceof NoSuchFileException) { return new NotfoundException(buffer.toString(), e); } return this.wrap(e, buffer); }
protected final int translateOrThrow(Exception exception) { return ExceptionTranslator.<Integer, Exception> of(exception) // .translate(AccessDeniedException.class, e -> -ErrorCodes.EPERM()) // .translate(NoSuchFileException.class, e -> -ErrorCodes.ENOENT()) // .translate(NotDirectoryException.class, e -> -ErrorCodes.ENOTDIR()) // .translate(NotLinkException.class, e -> -ErrorCodes.EINVAL()) // .translate(UnsupportedOperationException.class, e -> -ErrorCodes.ENOSYS()) // .translate(IOException.class, e -> { logger.warn("", e); // Unmapped IOException, log warning return -ErrorCodes.EIO(); }).get(); }
protected void testAllErrors(Try.CheckedConsumer<ExpectedResult, Exception> sut) throws Exception { List<ExpectedResult> list = list( // exp(new NoSuchFileException(null), -ErrorCodes.ENOENT()), // exp(new AccessDeniedException(null), -ErrorCodes.EPERM()), // exp(new NotDirectoryException(null), -ErrorCodes.ENOTDIR()), // exp(new NotLinkException(null), -ErrorCodes.EINVAL()), // exp(new UnsupportedOperationException(), -ErrorCodes.ENOSYS()), // exp(new IOException(), -ErrorCodes.EIO())); // list.forEach(expected -> Try.runWithCatch(() -> sut.accept(expected), Exception.class).get()); }
@Test public void testJmxAttributeValidationExceptionList2() throws Exception { List<JmxAttribute> attributeNames = new ArrayList<>(); attributeNames.add(new JmxAttribute("att1")); attributeNames.add(new JmxAttribute("att2")); attributeNames.add(new JmxAttribute("att3")); JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException( "exception str", new AccessDeniedException(""), attributeNames); assertEquals(jmxAttributeValidationException.getAttributeNames(), attributeNames); }
@Test public void testJmxAttributeValidationExceptionJmxElement() throws Exception { JmxAttribute attributeName = new JmxAttribute("attr_name"); JmxAttributeValidationException jmxAttributeValidationException = new JmxAttributeValidationException( "exception str", new AccessDeniedException(""), attributeName); assertEquals(jmxAttributeValidationException.getAttributeNames(), Arrays.asList(attributeName)); }
/** * <p> * This first invokes {@link #readInternalAclFileAttributes()} * to determine file existence, which throws a {@link FileNotFoundException} if the file doesn't exist. * Access to the file is then checked by first retrieving the * {@link CloudHostConfiguration#getUserGroupLookupService() user service} and if it is * of has the mixin interface {@link UserGroupLookupService} then it will get the * {@link CloudHostConfiguration#getCloudHostSecurityManager() cloud host security manager} and invoke * {@link CloudHostSecurityManager#checkAccessAllowed(CloudAclEntrySet, UserPrincipal, Set)} to work out * if the permissions are valid. * </p> * <p> * If no {@link UserGroupLookupService} exists or the lookup returns <em>null</em> then the * {@link AnonymousUserPrincipal#INSTANCE} is used. * </p> * <p> * If no {@link CloudHostSecurityManager} is available then access will just be allowed as no access * check is possible. * </p> * @throws SecurityException If access is not allowed */ public CloudAclFileAttributes checkAccess(Set<AclEntryPermission> checkPermissions) throws IOException { // Throws FileNotFoundException CloudAclFileAttributes readAttributes = readInternalAclFileAttributes(); // Read the config CloudHostConfiguration cloudHostConfiguration = path.getFileSystem().getCloudHostConfiguration(); // Get the security manager CloudHostSecurityManager cloudHostSecurityManager = cloudHostConfiguration.getCloudHostSecurityManager(); if (cloudHostSecurityManager == null) { // No security manager, no access LOG.info("No {} found in cloud host configuration {}, default action is to allow all access", CloudHostSecurityManager.class, cloudHostConfiguration); return readAttributes; } // Try to get the current user UserPrincipal currentUser = null; UserGroupLookupService<?> userGroupLookupService = cloudHostConfiguration.getUserGroupLookupService(); if (userGroupLookupService != null) { currentUser = ((UserGroupLookupService<?>)userGroupLookupService).getCurrentUser(); } // Default to anonymous if (currentUser == null) { currentUser = AnonymousUserPrincipal.INSTANCE; } // Check for access against the ACL's if (!cloudHostSecurityManager.checkAccessAllowed(readAttributes.getAclSet(), currentUser, checkPermissions)) { LOG.debug("Permission doesn't allow access for '{}': {}", path.toString(), checkPermissions); throw new AccessDeniedException(path.toString(), null, "Permission doesn't allow access"); } return readAttributes; }
@Test public void testCheckAccessForADirectoryWithAnAnonymousUserWillThrowAAccessDeniedExceptionIfTheSecurityManagerDoesNotAllowAccess() throws IOException { CloudHostSecurityManager securityManager = context.mock(CloudHostSecurityManager.class); EnumSet<AclEntryPermission> perms = EnumSet.of(AclEntryPermission.ADD_FILE); context.checking(new Expectations() {{ allowing(config).getUserGroupLookupService(); will(returnValue(null)); allowing(config).getCloudHostSecurityManager(); will(returnValue(securityManager)); allowing(blobStore).directoryExists(TEST_CONTAINER, TEST_PATH); will(returnValue(true)); exactly(1).of(securityManager).checkAccessAllowed(with(any(CloudAclEntrySet.class)), with(equal(AnonymousUserPrincipal.INSTANCE)), with(equal(perms))); will(returnValue(false)); }}); try { view.checkAccess(perms); Assert.fail("Did not expect to have access"); } catch (AccessDeniedException e) { // OK } }