Search in sources :

Example 16 with GenericFileOperationFailedException

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

the class FtpOperations method connect.

public boolean connect(RemoteFileConfiguration configuration) throws GenericFileOperationFailedException {
    log.trace("Connecting using FTPClient: {}", client);
    String host = configuration.getHost();
    int port = configuration.getPort();
    String username = configuration.getUsername();
    String account = ((FtpConfiguration) configuration).getAccount();
    if (clientConfig != null) {
        log.trace("Configuring FTPClient with config: {}", clientConfig);
        client.configure(clientConfig);
    }
    if (log.isTraceEnabled()) {
        log.trace("Connecting to {} using connection timeout: {}", configuration.remoteServerInformation(), client.getConnectTimeout());
    }
    boolean connected = false;
    int attempt = 0;
    while (!connected) {
        try {
            if (log.isTraceEnabled() && attempt > 0) {
                log.trace("Reconnect attempt #{} connecting to {}", attempt, configuration.remoteServerInformation());
            }
            client.connect(host, port);
            // must check reply code if we are connected
            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                // yes we could connect
                connected = true;
            } else {
                // throw an exception to force the retry logic in the catch exception block
                throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), "Server refused connection");
            }
        } catch (Exception e) {
            // check if we are interrupted so we can break out
            if (Thread.currentThread().isInterrupted()) {
                throw new GenericFileOperationFailedException("Interrupted during connecting", new InterruptedException("Interrupted during connecting"));
            }
            GenericFileOperationFailedException failed;
            if (e instanceof GenericFileOperationFailedException) {
                failed = (GenericFileOperationFailedException) e;
            } else {
                failed = new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
            }
            log.trace("Cannot connect due: {}", failed.getMessage());
            attempt++;
            if (attempt > endpoint.getMaximumReconnectAttempts()) {
                throw failed;
            }
            if (endpoint.getReconnectDelay() > 0) {
                try {
                    Thread.sleep(endpoint.getReconnectDelay());
                } catch (InterruptedException ie) {
                    // we could potentially also be interrupted during sleep
                    Thread.currentThread().interrupt();
                    throw new GenericFileOperationFailedException("Interrupted during sleeping", ie);
                }
            }
        }
    }
    // must enter passive mode directly after connect
    if (configuration.isPassiveMode()) {
        log.trace("Using passive mode connections");
        client.enterLocalPassiveMode();
    }
    // must set soTimeout after connect
    if (endpoint instanceof FtpEndpoint) {
        FtpEndpoint<?> ftpEndpoint = (FtpEndpoint<?>) endpoint;
        if (ftpEndpoint.getSoTimeout() > 0) {
            log.trace("Using SoTimeout={}", ftpEndpoint.getSoTimeout());
            try {
                client.setSoTimeout(ftpEndpoint.getSoTimeout());
            } catch (IOException e) {
                throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
            }
        }
    }
    try {
        boolean login;
        if (username != null) {
            if (account != null) {
                log.trace("Attempting to login user: {} using password: ******** and account: {}", new Object[] { username, account });
                login = client.login(username, configuration.getPassword(), account);
            } else {
                log.trace("Attempting to login user: {} using password: ********", username);
                login = client.login(username, configuration.getPassword());
            }
        } else {
            if (account != null) {
                // not sure if it makes sense to login anonymous with account?
                log.trace("Attempting to login anonymous using account: {}", account);
                login = client.login("anonymous", "", account);
            } else {
                log.trace("Attempting to login anonymous");
                login = client.login("anonymous", "");
            }
        }
        log.trace("User {} logged in: {}", username != null ? username : "anonymous", login);
        if (!login) {
            // store replyString, because disconnect() will reset it
            String replyString = client.getReplyString();
            int replyCode = client.getReplyCode();
            // disconnect to prevent connection leaks
            client.disconnect();
            throw new GenericFileOperationFailedException(replyCode, replyString);
        }
        client.setFileType(configuration.isBinary() ? FTP.BINARY_FILE_TYPE : FTP.ASCII_FILE_TYPE);
    } catch (IOException e) {
        throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
    }
    // site commands
    if (endpoint.getConfiguration().getSiteCommand() != null) {
        // commands can be separated using new line
        Iterator<?> it = ObjectHelper.createIterator(endpoint.getConfiguration().getSiteCommand(), "\n");
        while (it.hasNext()) {
            Object next = it.next();
            String command = endpoint.getCamelContext().getTypeConverter().convertTo(String.class, next);
            log.trace("Site command to send: {}", command);
            if (command != null) {
                boolean result = sendSiteCommand(command);
                if (!result) {
                    throw new GenericFileOperationFailedException("Site command: " + command + " returned false");
                }
            }
        }
    }
    return true;
}
Also used : GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) IOException(java.io.IOException) GenericFileEndpoint(org.apache.camel.component.file.GenericFileEndpoint) GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) IOException(java.io.IOException) InvalidPayloadException(org.apache.camel.InvalidPayloadException)

Example 17 with GenericFileOperationFailedException

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

the class FtpOperations method retrieveFileToStreamInBody.

@SuppressWarnings("unchecked")
private boolean retrieveFileToStreamInBody(String name, Exchange exchange) throws GenericFileOperationFailedException {
    boolean result;
    try {
        GenericFile<FTPFile> target = (GenericFile<FTPFile>) exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE);
        ObjectHelper.notNull(target, "Exchange should have the " + FileComponent.FILE_EXCHANGE_FILE + " set");
        String remoteName = name;
        String currentDir = null;
        if (endpoint.getConfiguration().isStepwise()) {
            // remember current directory
            currentDir = getCurrentDirectory();
            // change directory to path where the file is to be retrieved
            // (must do this as some FTP servers cannot retrieve using absolute path)
            String path = FileUtil.onlyPath(name);
            if (path != null) {
                changeCurrentDirectory(path);
            }
            // remote name is now only the file name as we just changed directory
            remoteName = FileUtil.stripPath(name);
        }
        log.trace("Client retrieveFile: {}", remoteName);
        if (endpoint.getConfiguration().isStreamDownload()) {
            InputStream is = client.retrieveFileStream(remoteName);
            target.setBody(is);
            exchange.getIn().setHeader(RemoteFileComponent.REMOTE_FILE_INPUT_STREAM, is);
            result = true;
        } else {
            // read the entire file into memory in the byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            result = client.retrieveFile(remoteName, bos);
            // close the stream after done
            IOHelper.close(bos);
            target.setBody(bos.toByteArray());
        }
        // store client reply information after the operation
        exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE, client.getReplyCode());
        exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING, client.getReplyString());
        // change back to current directory
        if (endpoint.getConfiguration().isStepwise()) {
            changeCurrentDirectory(currentDir);
        }
    } catch (IOException e) {
        throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
    }
    return result;
}
Also used : GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) FTPFile(org.apache.commons.net.ftp.FTPFile) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) GenericFile(org.apache.camel.component.file.GenericFile)

Example 18 with GenericFileOperationFailedException

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

the class FtpOperations 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);
            boolean result;
            try {
                result = client.deleteFile(to);
                if (!result) {
                    throw new GenericFileOperationFailedException("Cannot delete file: " + to);
                }
            } catch (IOException e) {
                throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), "Cannot delete file: " + to, e);
            }
        } 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) IOException(java.io.IOException)

Example 19 with GenericFileOperationFailedException

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

the class FtpOperations method getCurrentDirectory.

public String getCurrentDirectory() throws GenericFileOperationFailedException {
    log.trace("getCurrentDirectory()");
    try {
        String answer = client.printWorkingDirectory();
        log.trace("Current dir: {}", answer);
        return answer;
    } catch (IOException e) {
        throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
    }
}
Also used : GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) IOException(java.io.IOException)

Example 20 with GenericFileOperationFailedException

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

the class FtpOperations method existsFile.

public 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);
    String onlyName = FileUtil.stripPath(name);
    try {
        String[] names;
        if (directory != null) {
            names = client.listNames(directory);
        } else {
            names = client.listNames();
        }
        // can return either null or an empty list depending on FTP servers
        if (names == null) {
            return false;
        }
        for (String existing : names) {
            log.trace("Existing file: {}, target file: {}", existing, name);
            existing = FileUtil.stripPath(existing);
            if (existing != null && existing.equals(onlyName)) {
                return true;
            }
        }
        return false;
    } catch (IOException e) {
        throw new GenericFileOperationFailedException(client.getReplyCode(), client.getReplyString(), e.getMessage(), e);
    }
}
Also used : GenericFileOperationFailedException(org.apache.camel.component.file.GenericFileOperationFailedException) IOException(java.io.IOException)

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