Search in sources :

Example 26 with FileSystemOperationException

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

the class LocalFileSystemOperations method sendFileToSocketStream.

/**
 * @param file         the file to send
 * @param toFileName   the destination file name
 * @param outputStream the output stream
 * @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 IOException
 */
private void sendFileToSocketStream(File file, String toFileName, OutputStream outputStream, boolean failOnError) throws IOException {
    FileInputStream fis = null;
    try {
        DataOutputStream dos = new DataOutputStream(outputStream);
        if (file.isDirectory()) {
            byte[] dirCreateCommandBytes = DIR_CREATE_SOCKET_COMMAND.getBytes(DEFAULT_CHARSET);
            dos.writeInt(dirCreateCommandBytes.length);
            dos.write(dirCreateCommandBytes);
            byte[] fileNameBytes = toFileName.getBytes(DEFAULT_CHARSET);
            dos.writeInt(fileNameBytes.length);
            dos.write(fileNameBytes);
            dos.flush();
        } else {
            long initialFileSize = file.length();
            long bytesLeftToWrite = initialFileSize;
            byte[] fileCopyCommandBytes = FILE_COPY_SOCKET_COMMAND.getBytes(DEFAULT_CHARSET);
            dos.writeInt(fileCopyCommandBytes.length);
            dos.write(fileCopyCommandBytes);
            byte[] fileNameBytes = toFileName.getBytes(DEFAULT_CHARSET);
            dos.writeInt(fileNameBytes.length);
            dos.write(fileNameBytes);
            dos.writeLong(initialFileSize);
            fis = new FileInputStream(file);
            byte[] buff = new byte[FILE_TRANSFER_BUFFER_SIZE];
            int bytesCount = -1;
            while ((bytesCount = fis.read(buff)) > -1) {
                if (bytesCount <= bytesLeftToWrite) {
                    dos.write(buff, 0, bytesCount);
                    dos.flush();
                    bytesLeftToWrite -= bytesCount;
                } else {
                    if (failOnError) {
                        throw new FileSystemOperationException("The size of file \"" + file.getName() + "\" was increased with " + (bytesCount - bytesLeftToWrite) + " bytes! The initial file size was " + initialFileSize + ". ATS will ignore this error if you set the failOnError flag to false.");
                    }
                    // The file is growing while we are sending it.
                    // We will send only the initial number of bytes, because we already told the recipient side how many bytes to expect.
                    dos.write(buff, 0, (int) bytesLeftToWrite);
                    bytesLeftToWrite = 0;
                    dos.flush();
                    // we have sent as many bytes as we told the recipient, we will not send the remaining bytes
                    break;
                }
            }
            if (bytesLeftToWrite > 0) {
                if (failOnError) {
                    throw new FileSystemOperationException("The size of file \"" + file.getName() + "\" was decreased with " + bytesLeftToWrite + " bytes! The initial file size was " + initialFileSize + ". ATS will ignore this error if you set the failOnError flag to false.");
                }
                // The file is shrinking while we are sending it.
                // We will fill it to the initial size, because we already told the recipient side how many bytes to expect.
                log.warn("File " + file.getPath() + " is getting smaller while copying it. We will append " + bytesLeftToWrite + " zero bytes to reach its initial size of " + initialFileSize + " bytes");
                while (bytesLeftToWrite-- > 0) {
                    dos.write(0);
                }
                dos.flush();
            }
        }
    } finally {
        IoUtils.closeStream(fis);
    }
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) DataOutputStream(java.io.DataOutputStream) FileInputStream(java.io.FileInputStream)

Example 27 with FileSystemOperationException

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

the class LocalFileSystemOperations method getMatchingFiles.

/**
 * Get the files in a folder which match the given {@link FileFilter}
 *
 * @param startLocation   the start location in which to look
 * @param searchFilter    the search filter to apply
 * @param recursiveSearch
 * @return list of matching files
 */
private List<String> getMatchingFiles(File startLocation, FileFilter searchFilter, boolean recursiveSearch) {
    List<String> matchingFiles = new ArrayList<String>();
    File[] files = startLocation.listFiles();
    // listFiles() can return 'null' even when we have no rights to read in the 'startLocaltion' directory
    if (files != null) {
        for (File child : files) {
            if (searchFilter.accept(child)) {
                try {
                    String path = child.getCanonicalPath();
                    if (child.isDirectory()) {
                        // when the path points to a directory, we add file separator character at the end
                        matchingFiles.add(IoUtils.normalizeDirPath(path));
                    } else {
                        matchingFiles.add(path);
                    }
                } catch (IOException ioe) {
                    throw new FileSystemOperationException("Could not get the canonical path of file: " + child.getAbsolutePath(), ioe);
                }
            }
            // if recursion is allowed
            if (recursiveSearch && child.isDirectory()) {
                matchingFiles.addAll(getMatchingFiles(child, searchFilter, recursiveSearch));
            }
        }
    }
    return matchingFiles;
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Example 28 with FileSystemOperationException

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

the class LocalFileSystemOperations method setFileHiddenAttribute.

@Override
public void setFileHiddenAttribute(String sourceFile, boolean hidden) {
    sourceFile = IoUtils.normalizeFilePath(sourceFile, osType);
    checkFileExistence(new File(sourceFile));
    final String errMsg = "Could not " + (hidden ? "set" : "unset") + " the hidden attribute of file '" + sourceFile + "'";
    if (OperatingSystemType.getCurrentOsType().isWindows()) {
        try {
            Path path = Paths.get(sourceFile);
            DosFileAttributes attr;
            attr = Files.readAttributes(path, DosFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            boolean goHidden = attr.isHidden();
            if (!hidden && goHidden) {
                Files.setAttribute(path, "dos:hidden", false, LinkOption.NOFOLLOW_LINKS);
            } else if (hidden && !goHidden) {
                Files.setAttribute(path, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
            }
        } catch (IOException e) {
            throw new FileSystemOperationException(errMsg, e);
        }
    } else if (OperatingSystemType.getCurrentOsType().isUnix()) {
        // a '.' prefix makes the file hidden
        String filePath = IoUtils.getFilePath(sourceFile);
        String fileName = IoUtils.getFileName(sourceFile);
        if (hidden) {
            if (fileName.startsWith(".")) {
                log.warn("File '" + sourceFile + "' is already hidden. No changes are made!");
                return;
            } else {
                fileName = "." + fileName;
            }
        } else {
            if (!fileName.startsWith(".")) {
                log.warn("File '" + sourceFile + "' is already NOT hidden. No changes are made!");
                return;
            } else {
                fileName = fileName.substring(1);
            }
        }
        renameFile(sourceFile, filePath + fileName, false);
    } else {
        throw new FileSystemOperationException(errMsg + ": Unknown OS type");
    }
}
Also used : Path(java.nio.file.Path) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) DosFileAttributes(java.nio.file.attribute.DosFileAttributes) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Example 29 with FileSystemOperationException

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

the class LocalFileSystemOperations method renameFile.

@Override
public void renameFile(String sourceFile, String destinationFile, boolean overwrite) {
    File oldFile = new File(sourceFile);
    File newFile = new File(destinationFile);
    // first check if the file exists
    checkFileExistence(oldFile);
    // required, otherwise we need to notify the client by throwing an exception
    if (newFile.exists()) {
        if (overwrite) {
            if (!newFile.delete()) {
                throw new FileSystemOperationException("Could not delete file '" + destinationFile + "'");
            }
        } else {
            throw new FileSystemOperationException("File '" + destinationFile + "' already exists and overwrite mode is not turned on");
        }
    }
    // rename the file
    if (!oldFile.renameTo(newFile)) {
        throw new FileSystemOperationException("Could not rename file '" + sourceFile + "' to '" + destinationFile + "'");
    }
    log.info("Successfully renamed file '" + sourceFile + "' to '" + destinationFile + "'");
}
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)

Example 30 with FileSystemOperationException

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

the class Test_LocalFileSystemOperationsRealFiles method getFileStats.

private String[] getFileStats(String filename, boolean numericUidAndGid) throws FileSystemOperationException, IOException {
    filename = IoUtils.normalizeFilePath(filename, OperatingSystemType.getCurrentOsType());
    File file = new File(filename);
    String command = file.isDirectory() ? "ls -ld " : "ls -la ";
    if (numericUidAndGid) {
        command = command.trim() + "n ";
    }
    String[] commandTokens = new String[] { "/bin/sh", "-c", command + "'" + filename + "' 2>&1" };
    String[] result = executeExternalProcess(commandTokens);
    String[] lines = result[0].split("\n");
    for (String line : lines) {
        line = line.trim();
        if (line.endsWith(filename) || line.contains(" " + filename + " ")) {
            Matcher m = longListingPattern.matcher(line);
            if (m.matches()) {
                return new String[] { m.group(1), m.group(2), m.group(3) };
            }
        }
    }
    throw new FileSystemOperationException("Could not get statistics for '" + filename + "' file" + "\nby running the following command: " + Arrays.toString(commandTokens) + "\nCould not parse the result form the 'ls' command! Result: \n" + result[0]);
}
Also used : Matcher(java.util.regex.Matcher) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) 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