Search in sources :

Example 76 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project ballerina by ballerina-lang.

the class FileSystemService method createErrorResponse.

/**
 * Creates an error response for the given IO Exception.
 *
 * @param ex Thrown Exception
 * @return Error Message
 */
private Response createErrorResponse(Throwable ex) {
    JsonObject entity = new JsonObject();
    String errMsg = ex.getMessage();
    if (ex instanceof AccessDeniedException) {
        errMsg = "Access Denied to " + ex.getMessage();
    } else if (ex instanceof NoSuchFileException) {
        errMsg = "No such file: " + ex.getMessage();
    } else if (ex instanceof FileAlreadyExistsException) {
        errMsg = "File already exists: " + ex.getMessage();
    } else if (ex instanceof NotDirectoryException) {
        errMsg = "Not a directory: " + ex.getMessage();
    } else if (ex instanceof ReadOnlyFileSystemException) {
        errMsg = "Read only: " + ex.getMessage();
    } else if (ex instanceof DirectoryNotEmptyException) {
        errMsg = "Directory not empty: " + ex.getMessage();
    } else if (ex instanceof FileNotFoundException) {
        errMsg = "File not found: " + ex.getMessage();
    }
    entity.addProperty("Error", errMsg);
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(entity).header(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, '*').type(MediaType.APPLICATION_JSON).build();
}
Also used : AccessDeniedException(java.nio.file.AccessDeniedException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) NotDirectoryException(java.nio.file.NotDirectoryException) NoSuchFileException(java.nio.file.NoSuchFileException) FileNotFoundException(java.io.FileNotFoundException) JsonObject(com.google.gson.JsonObject) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) ReadOnlyFileSystemException(java.nio.file.ReadOnlyFileSystemException)

Example 77 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project mycore by MyCoRe-Org.

the class MCRFileSystemProvider method createDirectory.

/* (non-Javadoc)
     * @see java.nio.file.spi.FileSystemProvider#createDirectory(java.nio.file.Path, java.nio.file.attribute.FileAttribute[])
     */
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
    if (attrs.length > 0) {
        throw new UnsupportedOperationException("Setting 'attrs' atomically is unsupported.");
    }
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(dir);
    MCRDirectory rootDirectory;
    if (mcrPath.isAbsolute() && mcrPath.getNameCount() == 0) {
        rootDirectory = MCRDirectory.getDirectory(mcrPath.getOwner());
        if (rootDirectory != null) {
            throw new FileAlreadyExistsException(mcrPath.toString());
        }
        rootDirectory = new MCRDirectory(mcrPath.getOwner());
        return;
    }
    rootDirectory = getRootDirectory(mcrPath);
    MCRPath parentPath = mcrPath.getParent();
    MCRPath absolutePath = getAbsolutePathFromRootComponent(parentPath);
    MCRFilesystemNode childByPath = rootDirectory.getChildByPath(absolutePath.toString());
    if (childByPath == null) {
        throw new NoSuchFileException(parentPath.toString(), dir.getFileName().toString(), "parent directory does not exist");
    }
    if (childByPath instanceof MCRFile) {
        throw new NotDirectoryException(parentPath.toString());
    }
    MCRDirectory parentDir = (MCRDirectory) childByPath;
    String dirName = mcrPath.getFileName().toString();
    if (parentDir.getChild(dirName) != null) {
        throw new FileAlreadyExistsException(mcrPath.toString());
    }
    new MCRDirectory(dirName, parentDir);
}
Also used : MCRFile(org.mycore.datamodel.ifs.MCRFile) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) NotDirectoryException(java.nio.file.NotDirectoryException) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) MCRFilesystemNode(org.mycore.datamodel.ifs.MCRFilesystemNode) NoSuchFileException(java.nio.file.NoSuchFileException) MCRPath(org.mycore.datamodel.niofs.MCRPath)

Example 78 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project mycore by MyCoRe-Org.

the class MCRSwordUtil method extractZipToPath.

public static void extractZipToPath(Path zipFilePath, MCRPath target) throws SwordError, IOException, NoSuchAlgorithmException, URISyntaxException {
    LOGGER.info("Extracting zip: {}", zipFilePath);
    try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFilePath.toUri()), new HashMap<>())) {
        final Path sourcePath = zipfs.getPath("/");
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                final Path relativeSP = sourcePath.relativize(dir);
                // WORKAROUND for bug
                Path targetdir = relativeSP.getNameCount() == 0 ? target : target.resolve(relativeSP);
                try {
                    Files.copy(dir, targetdir);
                } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetdir))
                        throw e;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                MCRSession currentSession = MCRSessionMgr.getCurrentSession();
                LOGGER.info("Extracting: {}", file);
                Path targetFilePath = target.resolve(sourcePath.relativize(file));
                // and before completion we start the transaction to let niofs write the md5 to the table
                try (SeekableByteChannel destinationChannel = Files.newByteChannel(targetFilePath, StandardOpenOption.WRITE, StandardOpenOption.SYNC, StandardOpenOption.CREATE);
                    SeekableByteChannel sourceChannel = Files.newByteChannel(file, StandardOpenOption.READ)) {
                    if (currentSession.isTransactionActive()) {
                        currentSession.commitTransaction();
                    }
                    ByteBuffer buffer = ByteBuffer.allocateDirect(COPY_BUFFER_SIZE);
                    while (sourceChannel.read(buffer) != -1 || buffer.position() > 0) {
                        buffer.flip();
                        destinationChannel.write(buffer);
                        buffer.compact();
                    }
                } finally {
                    if (!currentSession.isTransactionActive()) {
                        currentSession.beginTransaction();
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) URI(java.net.URI) ByteBuffer(java.nio.ByteBuffer) SeekableByteChannel(java.nio.channels.SeekableByteChannel) MCRSession(org.mycore.common.MCRSession) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 79 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project irida by phac-nml.

the class ExceptionHandlerController method handleStorageException.

/**
 * Catch and handle all {@link StorageException}s. Try your best to figure
 * out the root cause of the exception.
 *
 * @param e
 *            the exception that was originally thrown.
 * @param locale
 *            the locale of the request.
 * @return an error message (hopefully) more specific than a general storage
 *         exception.
 */
@ExceptionHandler(StorageException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelMap handleStorageException(final StorageException e, final Locale locale) {
    final ModelMap modelMap = new ModelMap();
    if (e.getCause() instanceof FileAlreadyExistsException) {
        logger.error("General storage exception: File already exists (inconsistent back-end state)", e);
        modelMap.addAttribute("error_message", messageSource.getMessage("project.samples.files.upload.error.filealreadyexistsexception", null, locale));
    } else if (e.getCause() instanceof FileSystemException) {
        final FileSystemException fse = (FileSystemException) e.getCause();
        if (fse.getMessage().contains("No space left on device")) {
            logger.error("General storage exception: No space left on device.", e);
            modelMap.addAttribute("error_message", messageSource.getMessage("project.samples.files.upload.error.nospaceleftondevice", null, locale));
        } else {
            logger.error("General storage exception: Unexpected reason.", e);
            modelMap.addAttribute("error_message", messageSource.getMessage("project.samples.files.upload.error.storageexception", null, locale));
        }
    } else {
        logger.error("General storage exception: Unexpected reason.", e);
        modelMap.addAttribute("error_message", messageSource.getMessage("project.samples.files.upload.error.storageexception", null, locale));
    }
    emailController.sendFilesystemExceptionEmail(notificationAdminEmail, e);
    return modelMap;
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FileSystemException(java.nio.file.FileSystemException) ModelMap(org.springframework.ui.ModelMap) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus)

Example 80 with FileAlreadyExistsException

use of java.nio.file.FileAlreadyExistsException in project azure-gradle-plugins by lenala.

the class AddTask method getTargetFile.

private File getTargetFile(final File packageDir) throws Exception {
    final String functionName = getClassName() + ".java";
    final File targetFile = new File(packageDir, functionName);
    if (targetFile.exists()) {
        throw new FileAlreadyExistsException(format(FILE_EXIST, targetFile.getAbsolutePath()));
    }
    return targetFile;
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) File(java.io.File)

Aggregations

FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)104 Path (java.nio.file.Path)49 IOException (java.io.IOException)44 File (java.io.File)24 NoSuchFileException (java.nio.file.NoSuchFileException)22 Test (org.junit.Test)15 FileNotFoundException (java.io.FileNotFoundException)10 FileSystemException (java.nio.file.FileSystemException)9 AccessDeniedException (java.nio.file.AccessDeniedException)8 DirectoryNotEmptyException (java.nio.file.DirectoryNotEmptyException)8 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)8 NotDirectoryException (java.nio.file.NotDirectoryException)7 AtomicMoveNotSupportedException (java.nio.file.AtomicMoveNotSupportedException)5 CopyOption (java.nio.file.CopyOption)5 FileSystem (java.nio.file.FileSystem)5 FileVisitResult (java.nio.file.FileVisitResult)5 MCRPath (org.mycore.datamodel.niofs.MCRPath)5 FileOutputStream (java.io.FileOutputStream)4 InputStream (java.io.InputStream)4 FileSystemLoopException (java.nio.file.FileSystemLoopException)4