Search in sources :

Example 46 with FileSystemOperationException

use of com.axway.ats.common.filesystem.FileSystemOperationException in project ats-framework by Axway.

the class LocalFileSystemOperations method copyFile.

@SuppressWarnings("resource")
@Override
public void copyFile(String sourceFile, String destinationFile, boolean failOnError) {
    File inputFile = new File(sourceFile);
    checkFileExistence(inputFile);
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        // Create channel on the source
        srcChannel = new FileInputStream(sourceFile).getChannel();
        // Create channel on the destination
        dstChannel = new FileOutputStream(destinationFile).getChannel();
        // Copy file contents from source to destination
        dstChannel.truncate(0);
        if (log.isDebugEnabled()) {
            log.debug("Copying file '" + sourceFile + "' of " + srcChannel.size() + "bytes to '" + destinationFile + "'");
        }
        /* Copy the file in chunks.
             * If we provide the whole file at once, the copy process does not start or does not
             * copy the whole file on some systems when the file is a very large one - usually
             * bigger than 2 GBs
             */
        // 16 MB chunks
        final long CHUNK = 16 * 1024 * 1024;
        for (long pos = 0; pos < srcChannel.size(); ) {
            pos += dstChannel.transferFrom(srcChannel, pos, CHUNK);
        }
        if (srcChannel.size() != dstChannel.size()) {
            throw new FileSystemOperationException("Size of the destination file \"" + destinationFile + "\" and the source file \"" + sourceFile + "\" mismatch!");
        }
        if (osType.isUnix()) {
            // set the original file permission to the new file
            setFilePermissions(destinationFile, getFilePermissions(sourceFile));
        }
    } catch (IOException e) {
        throw new FileSystemOperationException("Unable to copy file '" + sourceFile + "' to '" + destinationFile + "'", e);
    } finally {
        // Close the channels
        IoUtils.closeStream(srcChannel, "Unable to close input channel while copying file '" + sourceFile + "' to '" + destinationFile + "'");
        IoUtils.closeStream(dstChannel, "Unable to close destination channel while copying file '" + sourceFile + "' to '" + destinationFile + "'");
    }
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) FileChannel(java.nio.channels.FileChannel) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 47 with FileSystemOperationException

use of com.axway.ats.common.filesystem.FileSystemOperationException in project ats-framework by Axway.

the class LocalFileSystemOperations method setFilePermissions.

@Override
public void setFilePermissions(String sourceFile, String permissions) {
    sourceFile = IoUtils.normalizeFilePath(sourceFile, osType);
    File file = new File(sourceFile);
    checkFileExistence(file);
    checkAttributeOsSupport(FileAttributes.PERMISSIONS);
    try {
        Files.setPosixFilePermissions(new File(sourceFile).getCanonicalFile().toPath(), getPosixFilePermission(Integer.parseInt(permissions, 8)));
    } catch (IOException ioe) {
        throw new FileSystemOperationException("Could not update permissions for file '" + sourceFile + "'", ioe);
    }
    log.info("Successfully set permissions of file '" + sourceFile + "' to " + permissions);
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Example 48 with FileSystemOperationException

use of com.axway.ats.common.filesystem.FileSystemOperationException in project ats-framework by Axway.

the class LocalFileSystemOperations method executeExternalProcess.

private String[] executeExternalProcess(String[] command) {
    String stdOut = "";
    String stdErr = "";
    String exitCode = "";
    try {
        // start the external process
        Process process = Runtime.getRuntime().exec(command);
        // read the external process output streams
        // reading both streams helps releasing OS resources
        stdOut = IoUtils.streamToString(process.getInputStream()).trim();
        stdErr = IoUtils.streamToString(process.getErrorStream()).trim();
        // process.getOutputStream().close();
        exitCode = String.valueOf(process.waitFor());
    } catch (Exception e) {
        StringBuilder err = new StringBuilder();
        err.append("Error executing command '");
        err.append(Arrays.toString(command));
        err.append("'");
        if (!StringUtils.isNullOrEmpty(stdOut)) {
            err.append("\nSTD OUT: ");
            err.append(stdOut);
        }
        if (!StringUtils.isNullOrEmpty(stdErr)) {
            err.append("\nSTD ERR: ");
            err.append(stdErr);
        }
        if (!StringUtils.isNullOrEmpty(exitCode)) {
            err.append("\nexit code: ");
            err.append(exitCode);
        }
        throw new FileSystemOperationException(err.toString(), e);
    }
    return new String[] { stdOut, stdErr, exitCode };
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) AttributeNotSupportedException(com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) FileDoesNotExistException(com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 49 with FileSystemOperationException

use of com.axway.ats.common.filesystem.FileSystemOperationException in project ats-framework by Axway.

the class LocalFileSystemOperations method deleteRecursively.

/**
 * If the parameter is a file it is deleted. Otherwise if it is a directory then it's contents
 * are first deleted (if any exist) and then the directory itself is deleted.
 *
 * @param file the target file
 * @throws FileSystemOperationException
 */
private void deleteRecursively(File file) {
    if (file.isDirectory()) {
        DirectoryStream<Path> dirStream = null;
        try {
            dirStream = Files.newDirectoryStream(file.toPath());
            Iterator<Path> it = dirStream.iterator();
            while (it.hasNext()) {
                Path path = it.next();
                deleteRecursively(path.toFile());
            }
        } catch (Exception e) {
            throw new FileSystemOperationException("Could not purge contents of directory '" + file.getAbsolutePath() + "'", e);
        } finally {
            IoUtils.closeStream(dirStream);
        }
    }
    if (!file.delete()) {
        throw new FileSystemOperationException("Unable to delete " + file);
    }
}
Also used : Path(java.nio.file.Path) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) AttributeNotSupportedException(com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) FileDoesNotExistException(com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 50 with FileSystemOperationException

use of com.axway.ats.common.filesystem.FileSystemOperationException in project ats-framework by Axway.

the class LocalFileSystemOperations method copyDirectoryInternal.

/**
 * Copy directory
 *
 * @param from        source directory to copy from.
 * @param to          directory destination.
 * @param filter      array of names not to copy.
 * @param isRecursive should sub directories be copied too
 * @param failOnError set to true if you want to be thrown an exception,
 *                    if there is still a process writing in the file that is being copied
 * @throws FileSystemOperationException
 */
private void copyDirectoryInternal(File from, File to, String[] filter, boolean isRecursive, boolean failOnError) {
    if (from == null || !from.exists() || !from.isDirectory()) {
        return;
    }
    if (!to.exists()) {
        if (!to.mkdirs()) {
            throw new FileSystemOperationException("Could not create target directory " + to.getAbsolutePath());
        }
    }
    if (osType.isUnix()) {
        // set the original file permission to the new file
        setFilePermissions(to.getAbsolutePath(), getFilePermissions(from.getAbsolutePath()));
    }
    String[] list = from.list();
    // Some JVMs return null for File.list() when the directory is empty.
    if (list != null) {
        boolean skipThisFile = false;
        for (int i = 0; i < list.length; i++) {
            skipThisFile = false;
            String fileName = list[i];
            if (filter != null) {
                for (int j = 0; j < filter.length; j++) {
                    if (fileName.equals(filter[j])) {
                        skipThisFile = true;
                        break;
                    }
                }
            }
            if (!skipThisFile) {
                File entry = new File(from, fileName);
                if (entry.isDirectory()) {
                    if (isRecursive) {
                        copyDirectoryInternal(entry, new File(to, fileName), filter, isRecursive, failOnError);
                    }
                // else - skip
                } else {
                    copyFile(entry.getAbsolutePath(), to.getAbsolutePath() + "/" + fileName, failOnError);
                }
            }
        }
    }
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Aggregations

FileSystemOperationException (com.axway.ats.common.filesystem.FileSystemOperationException)58 IOException (java.io.IOException)32 File (java.io.File)31 RandomAccessFile (java.io.RandomAccessFile)29 ZipFile (org.apache.commons.compress.archivers.zip.ZipFile)29 FileDoesNotExistException (com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException)16 FileNotFoundException (java.io.FileNotFoundException)16 SocketTimeoutException (java.net.SocketTimeoutException)14 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 AttributeNotSupportedException (com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException)13 EOFException (java.io.EOFException)13 OverlappingFileLockException (java.nio.channels.OverlappingFileLockException)13 FileOutputStream (java.io.FileOutputStream)10 FileInputStream (java.io.FileInputStream)9 BufferedOutputStream (java.io.BufferedOutputStream)8 DataOutputStream (java.io.DataOutputStream)8 BaseTest (com.axway.ats.action.BaseTest)7 LocalFileSystemOperations (com.axway.ats.core.filesystem.LocalFileSystemOperations)7 Test (org.junit.Test)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7