Search in sources :

Example 1 with GenericFileOperationFailedException

use of org.apache.camel.component.file.GenericFileOperationFailedException in project camel by apache.

the class SftpOperations method listFiles.

public synchronized List<ChannelSftp.LsEntry> listFiles(String path) throws GenericFileOperationFailedException {
    LOG.trace("listFiles({})", path);
    if (ObjectHelper.isEmpty(path)) {
        // list current directory if file path is not given
        path = ".";
    }
    try {
        final List<ChannelSftp.LsEntry> list = new ArrayList<ChannelSftp.LsEntry>();
        @SuppressWarnings("rawtypes") Vector files = channel.ls(path);
        // can return either null or an empty list depending on FTP servers
        if (files != null) {
            for (Object file : files) {
                list.add((ChannelSftp.LsEntry) file);
            }
        }
        return list;
    } catch (SftpException e) {
        throw new GenericFileOperationFailedException("Cannot list directory: " + path, e);
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) SftpException(com.jcraft.jsch.SftpException) ArrayList(java.util.ArrayList) Vector(java.util.Vector)

Example 2 with GenericFileOperationFailedException

use of org.apache.camel.component.file.GenericFileOperationFailedException in project camel by apache.

the class SftpOperations method doMoveExistingFile.

/**
     * Moves any existing file due fileExists=Move is in use.
     */
private void doMoveExistingFile(String name, String targetName) throws GenericFileOperationFailedException {
    // need to evaluate using a dummy and simulate the file first, to have access to all the file attributes
    // create a dummy exchange as Exchange is needed for expression evaluation
    // we support only the following 3 tokens.
    Exchange dummy = endpoint.createExchange();
    // we only support relative paths for the ftp component, so dont provide any parent
    String parent = null;
    String onlyName = FileUtil.stripPath(targetName);
    dummy.getIn().setHeader(Exchange.FILE_NAME, targetName);
    dummy.getIn().setHeader(Exchange.FILE_NAME_ONLY, onlyName);
    dummy.getIn().setHeader(Exchange.FILE_PARENT, parent);
    String to = endpoint.getMoveExisting().evaluate(dummy, String.class);
    // we only support relative paths for the ftp component, so strip any leading paths
    to = FileUtil.stripLeadingSeparator(to);
    // normalize accordingly to configuration
    to = endpoint.getConfiguration().normalizePath(to);
    if (ObjectHelper.isEmpty(to)) {
        throw new GenericFileOperationFailedException("moveExisting evaluated as empty String, cannot move existing file: " + name);
    }
    // do we have a sub directory
    String dir = FileUtil.onlyPath(to);
    if (dir != null) {
        // ensure directory exists
        buildDirectory(dir, false);
    }
    // deal if there already exists a file
    if (existsFile(to)) {
        if (endpoint.isEagerDeleteTargetFile()) {
            LOG.trace("Deleting existing file: {}", to);
            deleteFile(to);
        } else {
            throw new GenericFileOperationFailedException("Cannot moved existing file from: " + name + " to: " + to + " as there already exists a file: " + to);
        }
    }
    LOG.trace("Moving existing file: {} to: {}", name, to);
    if (!renameFile(targetName, to)) {
        throw new GenericFileOperationFailedException("Cannot rename file from: " + name + " to: " + to);
    }
}
Also used : Exchange(org.apache.camel.Exchange) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException)

Example 3 with GenericFileOperationFailedException

use of org.apache.camel.component.file.GenericFileOperationFailedException in project camel by apache.

the class SftpOperations method doStoreFile.

private boolean doStoreFile(String name, String targetName, Exchange exchange) throws GenericFileOperationFailedException {
    LOG.trace("doStoreFile({})", targetName);
    // if an existing file already exists what should we do?
    if (endpoint.getFileExist() == GenericFileExist.Ignore || endpoint.getFileExist() == GenericFileExist.Fail || endpoint.getFileExist() == GenericFileExist.Move) {
        boolean existFile = existsFile(targetName);
        if (existFile && endpoint.getFileExist() == GenericFileExist.Ignore) {
            // ignore but indicate that the file was written
            LOG.trace("An existing file already exists: {}. Ignore and do not override it.", name);
            return true;
        } else if (existFile && endpoint.getFileExist() == GenericFileExist.Fail) {
            throw new GenericFileOperationFailedException("File already exist: " + name + ". Cannot write new file.");
        } else if (existFile && endpoint.getFileExist() == GenericFileExist.Move) {
            // move any existing file first
            doMoveExistingFile(name, targetName);
        }
    }
    InputStream is = null;
    if (exchange.getIn().getBody() == null) {
        // Do an explicit test for a null body and decide what to do
        if (endpoint.isAllowNullBody()) {
            LOG.trace("Writing empty file.");
            is = new ByteArrayInputStream(new byte[] {});
        } else {
            throw new GenericFileOperationFailedException("Cannot write null body to file: " + name);
        }
    }
    try {
        if (is == null) {
            String charset = endpoint.getCharset();
            if (charset != null) {
                // charset configured so we must convert to the desired
                // charset so we can write with encoding
                is = new ByteArrayInputStream(exchange.getIn().getMandatoryBody(String.class).getBytes(charset));
                LOG.trace("Using InputStream {} with charset {}.", is, charset);
            } else {
                is = exchange.getIn().getMandatoryBody(InputStream.class);
            }
        }
        final StopWatch watch = new StopWatch();
        LOG.debug("About to store file: {} using stream: {}", targetName, is);
        if (endpoint.getFileExist() == GenericFileExist.Append) {
            LOG.trace("Client appendFile: {}", targetName);
            channel.put(is, targetName, ChannelSftp.APPEND);
        } else {
            LOG.trace("Client storeFile: {}", targetName);
            // override is default
            channel.put(is, targetName);
        }
        watch.stop();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Took {} ({} millis) to store file: {} and FTP client returned: true", new Object[] { TimeUtils.printDuration(watch.taken()), watch.taken(), targetName });
        }
        // after storing file, we may set chmod on the file
        String mode = endpoint.getConfiguration().getChmod();
        if (ObjectHelper.isNotEmpty(mode)) {
            // parse to int using 8bit mode
            int permissions = Integer.parseInt(mode, 8);
            LOG.trace("Setting chmod: {} on file: {}", mode, targetName);
            channel.chmod(permissions, targetName);
        }
        return true;
    } catch (SftpException e) {
        throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
    } catch (InvalidPayloadException e) {
        throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
    } catch (UnsupportedEncodingException e) {
        throw new GenericFileOperationFailedException("Cannot store file: " + name, e);
    } finally {
        IOHelper.close(is, "store: " + name, LOG);
    }
}
Also used : GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SftpException(com.jcraft.jsch.SftpException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidPayloadException(org.apache.camel.InvalidPayloadException) GenericFileEndpoint(org.apache.camel.component.file.GenericFileEndpoint) StopWatch(org.apache.camel.util.StopWatch)

Example 4 with GenericFileOperationFailedException

use of org.apache.camel.component.file.GenericFileOperationFailedException in project camel by apache.

the class SftpOperations method getCurrentDirectory.

public synchronized String getCurrentDirectory() throws GenericFileOperationFailedException {
    LOG.trace("getCurrentDirectory()");
    try {
        String answer = channel.pwd();
        LOG.trace("Current dir: {}", answer);
        return answer;
    } catch (SftpException e) {
        throw new GenericFileOperationFailedException("Cannot get current directory", e);
    }
}
Also used : GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) SftpException(com.jcraft.jsch.SftpException)

Example 5 with GenericFileOperationFailedException

use of org.apache.camel.component.file.GenericFileOperationFailedException in project camel by apache.

the class SftpOperations method existsFile.

public synchronized boolean existsFile(String name) throws GenericFileOperationFailedException {
    LOG.trace("existsFile({})", name);
    if (endpoint.isFastExistsCheck()) {
        return fastExistsFile(name);
    }
    // check whether a file already exists
    String directory = FileUtil.onlyPath(name);
    if (directory == null) {
        // assume current dir if no path could be extracted
        directory = ".";
    }
    String onlyName = FileUtil.stripPath(name);
    try {
        @SuppressWarnings("rawtypes") Vector files = channel.ls(directory);
        // can return either null or an empty list depending on FTP servers
        if (files == null) {
            return false;
        }
        for (Object file : files) {
            ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) file;
            String existing = entry.getFilename();
            LOG.trace("Existing file: {}, target file: {}", existing, name);
            existing = FileUtil.stripPath(existing);
            if (existing != null && existing.equals(onlyName)) {
                return true;
            }
        }
        return false;
    } catch (SftpException e) {
        // or an exception can be thrown with id 2 which means file does not exists
        if (ChannelSftp.SSH_FX_NO_SUCH_FILE == e.id) {
            return false;
        }
        // otherwise its a more serious error so rethrow
        throw new GenericFileOperationFailedException(e.getMessage(), e);
    }
}
Also used : ChannelSftp(com.jcraft.jsch.ChannelSftp) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) SftpException(com.jcraft.jsch.SftpException) Vector(java.util.Vector)

Aggregations

GenericFileOperationFailedException (org.apache.camel.component.file.GenericFileOperationFailedException)39 IOException (java.io.IOException)22 SftpException (com.jcraft.jsch.SftpException)10 File (java.io.File)8 InvalidPayloadException (org.apache.camel.InvalidPayloadException)7 GenericFile (org.apache.camel.component.file.GenericFile)7 Test (org.junit.Test)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 Exchange (org.apache.camel.Exchange)6 GenericFileEndpoint (org.apache.camel.component.file.GenericFileEndpoint)5 ChannelSftp (com.jcraft.jsch.ChannelSftp)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 FTPFile (org.apache.commons.net.ftp.FTPFile)4 JSchException (com.jcraft.jsch.JSchException)3 FileOutputStream (java.io.FileOutputStream)3 OutputStream (java.io.OutputStream)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 ArrayList (java.util.ArrayList)3 StopWatch (org.apache.camel.util.StopWatch)3