List of usage examples for java.nio.file AccessDeniedException AccessDeniedException
public AccessDeniedException(String file)
From source file:com.github.fge.ftpfs.io.commonsnetimpl.CommonsNetFtpAgent.java
@Override protected InputStream openInputStream(final String file) throws IOException { try {//ww w. j a va 2s .co m ftpClient.setFileType(FTP.ASCII_FILE_TYPE); final FTPFile[] files = ftpClient.listFiles(file); if (files.length == 0) throw new AccessDeniedException(file); if (files.length > 1) throw new IOException(file + " is a directory"); if (files[0].isDirectory()) throw new AccessDeniedException(file); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); final InputStream ret = ftpClient.retrieveFileStream(file); if (ret == null) throw new IOException("cannot open stream to file (server " + "reply " + ftpClient.getReplyCode()); return ret; } catch (FTPConnectionClosedException e) { status = Status.DEAD; throw new IOException("service unavailable", e); } }
From source file:com.github.fge.ftpfs.io.commonsnetimpl.CommonsNetFtpAgent.java
private static void handleFailedDirectoryList(final String dir, final FTPFile file) throws FileSystemException { throw file.isDirectory() ? new AccessDeniedException(dir) : new NotDirectoryException(dir); }
From source file:at.beris.virtualfile.client.sftp.SftpClient.java
private void handleSftpException(SftpException e) throws IOException { if (e.id == ChannelSftp.SSH_FX_PERMISSION_DENIED) throw new AccessDeniedException(e.getMessage()); else if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) throw new NoSuchFileException(e.getMessage()); else/*from w w w . j a v a 2s . c o m*/ throw new IOException(e); }
From source file:me.hqm.plugindev.wget.WGCommand.java
/** * Download a URL (jar or zip) to a file * * @param url Valid URL/*from w w w. ja va2s . co m*/ * @return Success or failure */ private boolean download(URL url) { // The plugin folder path String path = plugin.getDataFolder().getParentFile().getPath(); // Wrap everything in a try/catch try { // Get the filename from the url String fileName = fileName(url); // Create a new input stream and output file InputStream in = url.openStream(); File outFile = new File(path + "/" + fileName); // If the file already exists, delete it if (outFile.exists()) { outFile.delete(); } // Create the output stream and download the file FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(in, out); // Close the streams in.close(); out.close(); // If downloaded file is a zip file... if (fileName.endsWith(".zip")) { // Declare a new input stream outside of a try/catch ZipInputStream zis = null; try { // Define the input stream zis = new ZipInputStream(new FileInputStream(outFile)); // Decalre a zip entry for the while loop ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { // Make a new file object for the entry File entryFile = new File(path, entry.getName()); // If it is a directory and doesn't already exist, create the new directory if (entry.isDirectory()) { if (!entryFile.exists()) { entryFile.mkdirs(); } } else { // Make sure all folders exist if (entryFile.getParentFile() != null && !entryFile.getParentFile().exists()) { entryFile.getParentFile().mkdirs(); } // Create file on disk if (!entryFile.exists() && !entryFile.createNewFile()) { // Access denied, let the console know throw new AccessDeniedException(entryFile.getPath()); } // Write data to file from zip. OutputStream os = null; try { os = new FileOutputStream(entryFile); IOUtils.copy(zis, os); } finally { // Silently close the output stream IOUtils.closeQuietly(os); } } } } finally { // Always close streams IOUtils.closeQuietly(zis); } // Delete the zip file outFile.delete(); } // Return success return true; } catch (NullPointerException | IOException oops) { getLogger().severe("---------- WGET BEGIN -----------"); getLogger().severe("An error occurred during a file download/extraction:"); oops.printStackTrace(); getLogger().severe("----------- WGET END ------------"); } // The download failed, report failure return false; }
From source file:dsfixgui.FileIO.DSFixFileController.java
/** *Writes a string to a text file/*from ww w. j a va 2s . c o m*/ * * @param filePath * the path of the file to be read, including the filename * @param text * the String to be written to the file; can be more than one line. * @param overwrite * determines whether the user wants to overwrite the write file if it * already exists. If true, pre-existing file will be overwritten * @throws IIOException * if the write file already exists and the user allowed overwriting, but * the file could not be overwritten * @throws AccessDeniedException * if the write file already exists but the user didn't allow overwriting * @throws IOException * if an error occurs initializing the BufferedWriter */ public static void writeTextFile(String filePath, String text, boolean overwrite) throws IIOException, IOException, AccessDeniedException { //The file to be written File writeFile = new File(filePath); if (writeFile.exists() && overwrite) { //If file exists, try to delete it if (!writeFile.delete()) { //If file cannot be deleted, throw OIOException throw new IIOException("Could not delete pre-existing file: " + filePath); } } else if (writeFile.exists() && !overwrite) { //If file exists but is not allowed to be overwritten, throw AccessDeniedException throw new AccessDeniedException(writeFile.getPath()); } //Format each linebreak to be displayed correctly in a text file String formattedText = text.replaceAll("\n", String.format("%n")); //Initialize BufferedWriter to write string to file BufferedWriter fileWriter = new BufferedWriter(new FileWriter(writeFile)); //Write the file Scanner scanner = new Scanner(formattedText); while (scanner.hasNextLine()) { fileWriter.write(scanner.nextLine()); fileWriter.newLine(); } fileWriter.close(); }
From source file:com.epam.catgenome.manager.FileManager.java
/** * Returns contents of a directory, specified by path, to browse NGS files * * @param path a path to directory to browse * @return {@link List} of {@link FsDirectory}s, and {@link FsFile}, representing subdirectories and files * @throws IOException//from w w w .jav a 2 s . co m */ public List<AbstractFsItem> loadDirectoryContents(String path) throws IOException { if (!filesBrowsingAllowed) { throw new AccessDeniedException("Server file system browsing is not allowed"); } List<File> parentDirs = new ArrayList<>(); if (path == null) { if ("/".equals(ngsDataRootPath)) { parentDirs = Arrays.asList(File.listRoots()); } else { parentDirs.add(new File(ngsDataRootPath)); } } else { parentDirs.add(new File(path)); } Assert.isTrue(parentDirs.stream().allMatch(File::exists), "Specified path does not exist: " + path); Assert.isTrue(parentDirs.stream().allMatch(File::isDirectory), "Specified path is not a directory: " + path); List<AbstractFsItem> items = new ArrayList<>(); boolean accessDenied = false; String fileName = ""; String otherFileName = ""; for (File parentDir : parentDirs) { if (parentDir.listFiles() == null) { continue; } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(parentDir.toPath())) { for (Path child : dirStream) { try { File childFile = child.toFile(); if (childFile.isDirectory()) { FsDirectory directory = new FsDirectory(); directory.setPath(childFile.getAbsolutePath()); if (childFile.canRead()) { directory.setFileCount(countChildrenFiles(child)); } items.add(directory); } else { addFsFile(items, childFile); } } catch (AccessDeniedException e) { LOGGER.error("Access denied:", e); accessDenied = true; fileName = e.getFile(); otherFileName = e.getOtherFile(); } } if (items.isEmpty() && accessDenied) { throw new AccessDeniedException(fileName, otherFileName, "Access denied"); } } } return items; }
From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java
void checkAccess(CryptoPath cleartextPath, AccessMode... modes) throws IOException { if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class)) { Set<PosixFilePermission> permissions = readAttributes(cleartextPath, PosixFileAttributes.class) .permissions();// w ww. ja va 2 s . c o m boolean accessGranted = true; for (AccessMode accessMode : modes) { switch (accessMode) { case READ: accessGranted &= permissions.contains(PosixFilePermission.OWNER_READ); break; case WRITE: accessGranted &= permissions.contains(PosixFilePermission.OWNER_WRITE); break; case EXECUTE: accessGranted &= permissions.contains(PosixFilePermission.OWNER_EXECUTE); break; default: throw new UnsupportedOperationException("AccessMode " + accessMode + " not supported."); } } if (!accessGranted) { throw new AccessDeniedException(cleartextPath.toString()); } } else if (fileStore.supportsFileAttributeView(DosFileAttributeView.class)) { DosFileAttributes attrs = readAttributes(cleartextPath, DosFileAttributes.class); if (ArrayUtils.contains(modes, AccessMode.WRITE) && attrs.isReadOnly()) { throw new AccessDeniedException(cleartextPath.toString(), null, "read only file"); } } else { // read attributes to check for file existence / throws IOException if file does not exist readAttributes(cleartextPath, BasicFileAttributes.class); } }
From source file:org.kitodo.filemanagement.locking.LockManagement.java
private static GrantedAccess tryCast(LockResult lockingResult) throws AccessDeniedException { if (!(lockingResult instanceof GrantedAccess)) { throw new AccessDeniedException(UNSUITABLE_LOCKING_RESULT + Objects.toString(lockingResult)); }/*from w ww. j a v a2s .c o m*/ return (GrantedAccess) lockingResult; }
From source file:org.kitodo.filemanagement.locking.LockManagement.java
/** * Checks if a user is allowed to open a read channel on the file. If the * user is authorized to read the file, the method silently returns and * nothing happens. If not, an {@code AccessDeniedException} is thrown with * a meaningful justification. However, if the user code previously * submitted a request for appropriate permissions and verified that the * answer was positive, then this case should never happen. * * <p>/*from w ww . j a v a 2s .c o m*/ * In case the user gets read access due to an immutable read lock, this * method returns the URI to the temporary copy of the main file. The * subsequent file access process must therefore open the read channel to * this temporary copy, not to the main file. * * @param lockingResult * which user requests the write channel * @param uri * for which file the channel is requested * @param write * if true, also check for permission to write, else read only * @return the URI to use. This is the same one that was passed, except for * the immutable read lock, where it is the URI of the immutable * read copy. * @throws AccessDeniedException * if the user does not have sufficient authorization * @throws ProtocolException * if the file had to be first read in again, but this step was * skipped on the protocol. This error can occur with the * UPGRADE_WRITE_ONCE lock because its protocol form requires * that the file must first be read in again and the input * stream must be closed after the lock has been upgraded. */ public URI checkPermission(LockResult lockingResult, URI uri, boolean write) throws AccessDeniedException, ProtocolException { GrantedAccess permissions = tryCast(lockingResult); logger.trace("{} wants to open a {} channel to {}.", permissions.getUser(), write ? "writing" : "reading", uri); try { GrantedPermissions granted = grantedPermissions.get(uri); if (Objects.isNull(granted)) { throw new AccessDeniedException(permissions.getUser() + " claims to have a privilege to " + uri + " he does not have at all. Whatever he did, it was wrong."); } granted.checkAuthorization(permissions.getUser(), permissions.getLock(uri), write); } catch (AccessDeniedException e) { logger.trace("{} is not allowed to open a {} channel to {}. The reason is: {}", permissions.getUser(), write ? "writing" : "reading", uri, e.getMessage()); throw e; } AbstractLock lock = permissions.getLock(uri); if (lock instanceof ImmutableReadLock) { uri = ((ImmutableReadLock) lock).getImmutableReadCopyURI(); } logger.trace("{} is allowed to open a {} channel to {}.", permissions.getUser(), write ? "writing" : "reading", uri); return uri; }
From source file:org.yes.cart.remote.service.impl.RemoteDownloadServiceImpl.java
/** * {@inheritDoc}/* w w w . j a va 2s . com*/ */ public byte[] download(final String fileName) throws IOException { final String exportRoot = this.exportDirectorService.getExportDirectory(); final File fileToDownload; if (fileName.startsWith("/")) { boolean allowed = false; for (final String path : this.allowedPaths) { if (fileName.startsWith(path)) { allowed = true; break; } } if (!allowed && !fileName.startsWith(exportRoot)) { LOG.warn("Attempted to download file from {} ... access denied", fileName); throw new AccessDeniedException("Downloading files from specified location is prohibited"); } fileToDownload = new File(fileName); } else { fileToDownload = new File(exportRoot + File.separator + fileName); } if (fileToDownload.exists()) { if (fileToDownload.getName().endsWith(".zip")) { // Zip's just download return FileUtils.readFileToByteArray(fileToDownload); } else { // Non zip's, zip first final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ZipOutputStream zos = new ZipOutputStream(baos); final InputStream is = new BufferedInputStream(new FileInputStream(fileToDownload)); byte[] buff = new byte[1024]; final ZipEntry entry = new ZipEntry(fileToDownload.getName()); zos.putNextEntry(entry); int len; while ((len = is.read(buff)) > 0) { zos.write(buff, 0, len); } is.close(); zos.closeEntry(); zos.close(); return baos.toByteArray(); } } throw new IOException("File " + fileToDownload.getAbsolutePath() + " not found"); }