Search in sources :

Example 1 with FileSystemOperationException

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

the class LocalFileSystemOperations method replaceTextInFile.

@Override
public void replaceTextInFile(String fileName, String searchString, String newString, boolean isRegex) {
    BufferedReader inFileReader = null;
    BufferedWriter outFileWriter = null;
    File inputFile = null;
    File outputFile = null;
    try {
        try {
            inputFile = new File(fileName);
            outputFile = new File(fileName + "_" + System.currentTimeMillis() + ".tmp");
            inFileReader = new BufferedReader(new FileReader(inputFile));
            outFileWriter = new BufferedWriter(new FileWriter(outputFile, false));
            String currentLine = inFileReader.readLine();
            while (currentLine != null) {
                if (isRegex) {
                    outFileWriter.write(currentLine.replaceAll(searchString, newString));
                } else {
                    outFileWriter.write(currentLine.replace(searchString, newString));
                }
                outFileWriter.newLine();
                //read a new line
                currentLine = inFileReader.readLine();
            }
            log.info("Successfully replaced all instances of '" + searchString + "' in file '" + fileName + "'");
        } finally {
            IoUtils.closeStream(inFileReader);
            IoUtils.closeStream(outFileWriter);
        }
        //after we are finished, rename the temporary file to the original one
        if (OperatingSystemType.getCurrentOsType().isUnix()) {
            // getting original file permissions before overriding operation
            String permissions = getFilePermissions(inputFile.getCanonicalPath());
            renameFile(outputFile.getCanonicalPath(), fileName, true);
            // restoring file permissions
            setFilePermissions(fileName, permissions);
        } else {
            renameFile(outputFile.getCanonicalPath(), fileName, true);
        }
    } catch (IOException ioe) {
        throw new FileSystemOperationException("Unable to replace text '" + searchString + "' in file '" + fileName + "'", ioe);
    }
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) FileWriter(java.io.FileWriter) BufferedReader(java.io.BufferedReader) ReversedLinesFileReader(org.apache.commons.io.input.ReversedLinesFileReader) FileReader(java.io.FileReader) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) BufferedWriter(java.io.BufferedWriter)

Example 2 with FileSystemOperationException

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

the class LocalFileSystemOperations method getFileStats.

/**
     *
     * @param filename the target file name
     * @return file/directory statistics in format: String[] { permissions (octal format), uid, gid } eg. [ "644", "0", "100" ]
     * @throws FileSystemOperationException
     */
private String[] getFileStats(String filename, boolean numericUidAndGid) throws FileSystemOperationException, IOException {
    filename = IoUtils.normalizeFilePath(filename, osType);
    File file = new File(filename);
    checkFileExistence(file);
    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) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Example 3 with FileSystemOperationException

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

the class FileSystemOperations method copyFileTo.

/**
 * Copies the contents of a file from the local host (Test Executor) to a new file on the atsAgent host
 *
 * @param fromFile the source file to copy
 * @param toFile the destination file name path (not just the directory) to copy to. Absolute path is expected
 */
@PublicAtsApi
public void copyFileTo(@Validate(name = "fromFile", type = ValidationType.STRING_NOT_EMPTY) String fromFile, @Validate(name = "toFile", type = ValidationType.STRING_NOT_EMPTY) String toFile) {
    // validate input parameters
    new Validator().validateMethodParameters(new Object[] { fromFile, toFile });
    try {
        checkIfFileExistsAndIsFile(fromFile);
    } catch (Exception e) {
        throw new FileSystemOperationException("Unable to copy '" + fromFile + "' to '" + toFile + "'", e);
    }
    // execute action
    IFileSystemOperations operations = getOperationsImplementationFor(atsAgent);
    if (operations instanceof LocalFileSystemOperations) {
        ((LocalFileSystemOperations) operations).copyFile(fromFile, toFile, this.failOnError);
        log.info("Successfully copied " + fromFile + " to " + toFile);
    } else {
        RemoteFileSystemOperations rfso = (RemoteFileSystemOperations) operations;
        rfso.setCopyInPassiveMode(copyInPassiveMode);
        rfso.copyFile(fromFile, toFile, this.failOnError);
        log.info("Successfully copied " + fromFile + " from local host to file " + toFile + " on " + atsAgent);
    }
}
Also used : LocalFileSystemOperations(com.axway.ats.core.filesystem.LocalFileSystemOperations) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) IFileSystemOperations(com.axway.ats.core.filesystem.model.IFileSystemOperations) Validator(com.axway.ats.core.validation.Validator) FileNotFoundException(java.io.FileNotFoundException) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 4 with FileSystemOperationException

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

the class RemoteFileSystemOperations method copyDirectoryFrom.

public void copyDirectoryFrom(String fromDirName, String toDirName, boolean isRecursive, boolean failOnError) {
    try {
        int port = localFileSystemOperations.openFileTransferSocket();
        remoteFileSystemOperations.sendDirectoryTo(fromDirName, toDirName, HostUtils.getPublicLocalHostIp(this.atsAgent), port, isRecursive, failOnError);
        localFileSystemOperations.waitForFileTransferCompletion(port);
    } catch (Exception e) {
        String message = new StringBuilder().append("Unable to copy directory ").append(fromDirName).append(" from ").append(this.atsAgent).append(" to ").append(toDirName).append(" on the local host").toString();
        throw new FileSystemOperationException(message, e);
    }
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException)

Example 5 with FileSystemOperationException

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

the class RemoteFileSystemOperations method copyFile.

@Override
public void copyFile(String fromFile, String toFile, boolean failOnError) {
    try {
        // construct toFile final full filepath
        // action is performed to check toFile existence and file type (file/dir)
        toFile = this.remoteFileSystemOperations.constructDestinationFilePath(new File(fromFile).getName(), toFile);
        Integer copyFileStartPort = getCopyFilePortProperty(ActionLibraryConfigurator.getInstance().getCopyFileStartPort());
        Integer copyFileEndPort = getCopyFilePortProperty(ActionLibraryConfigurator.getInstance().getCopyFileEndPort());
        if (copyFileStartPort != null && copyFileStartPort > 0 && copyFileEndPort != null && copyFileEndPort > 0) {
            remoteFileSystemOperations.setCopyFilePortRange(copyFileStartPort, copyFileEndPort);
            localFileSystemOperations.setCopyFilePortRange(copyFileStartPort, copyFileEndPort);
        }
        if (!copyInPassiveMode) {
            int port = remoteFileSystemOperations.openFileTransferSocket();
            localFileSystemOperations.sendFileTo(fromFile, toFile, HostUtils.splitAddressHostAndPort(atsAgent)[0], port, failOnError);
            remoteFileSystemOperations.waitForFileTransferCompletion(port);
        } else {
            int port = localFileSystemOperations.openFileTransferSocketForSending(fromFile, toFile, failOnError);
            remoteFileSystemOperations.sendFileFrom(fromFile, toFile, HostUtils.getPublicLocalHostIp(atsAgent), port, failOnError);
            localFileSystemOperations.waitForFileTransferCompletion(port);
        }
    } catch (Exception e) {
        String message = new StringBuilder().append("Unable to copy file ").append(fromFile).append(" to ").append(toFile).append(" on host ").append(this.atsAgent).toString();
        throw new FileSystemOperationException(message, e);
    }
}
Also used : FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) File(java.io.File) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException)

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