Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.apache.camel.component.file.remote;
 
 import java.io.File;
 import java.util.List;
 
 
 
 import static org.apache.camel.util.ObjectHelper.isNotEmpty;

SFTP remote file operations
 
 public class SftpOperations implements RemoteFileOperations<ChannelSftp.LsEntry> {
     private static final transient Logger LOG = LoggerFactory.getLogger(SftpOperations.class);
     private static final Pattern UP_DIR_PATTERN = Pattern.compile("/[^/]+");
     private SftpEndpoint endpoint;
     private ChannelSftp channel;
     private Session session;

    
Extended user info which supports interactive keyboard mode, by entering the password.
 
     public interface ExtendedUserInfo extends UserInfoUIKeyboardInteractive {
     }
 
     public void setEndpoint(GenericFileEndpoint<ChannelSftp.LsEntryendpoint) {
         this. = (SftpEndpointendpoint;
     }
 
     public boolean connect(RemoteFileConfiguration configurationthrows GenericFileOperationFailedException {
         if (isConnected()) {
             // already connected
             return true;
         }
 
         boolean connected = false;
         int attempt = 0;
 
         while (!connected) {
             try {
                 if (.isTraceEnabled() && attempt > 0) {
                     .trace("Reconnect attempt #{} connecting to + {}"attemptconfiguration.remoteServerInformation());
                 }
 
                 if ( == null || !.isConnected()) {
                     if ( == null || !.isConnected()) {
                         .trace("Session isn't connected, trying to recreate and connect.");
                          = createSession(configuration);
                         if (.getConfiguration().getConnectTimeout() > 0) {
                             .trace("Connecting use connectTimeout: " + .getConfiguration().getConnectTimeout() + " ...");
                             .connect(.getConfiguration().getConnectTimeout());
                         } else {
                            .trace("Connecting ...");
                            .connect();
                        }
                    }
                    .trace("Channel isn't connected, trying to recreate and connect.");
                     = (ChannelSftp.openChannel("sftp");
                    if (.getConfiguration().getConnectTimeout() > 0) {
                        .trace("Connecting use connectTimeout: " + .getConfiguration().getConnectTimeout() + " ...");
                        .connect(.getConfiguration().getConnectTimeout());
                    } else {
                        .trace("Connecting ...");
                        .connect();
                    }
                    .info("Connected to " + configuration.remoteServerInformation());
                }
                // yes we could connect
                connected = true;
            } 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 = new GenericFileOperationFailedException("Cannot connect to " + configuration.remoteServerInformation(), e);
                .trace("Cannot connect due: {}"failed.getMessage());
                attempt++;
                if (attempt > .getMaximumReconnectAttempts()) {
                    throw failed;
                }
                if (.getReconnectDelay() > 0) {
                    try {
                        Thread.sleep(.getReconnectDelay());
                    } catch (InterruptedException ie) {
                        // we could potentially also be interrupted during sleep
                        Thread.currentThread().interrupt();
                        throw new GenericFileOperationFailedException("Interrupted during sleeping"ie);
                    }
                }
            }
        }
        return true;
    }
    protected Session createSession(final RemoteFileConfiguration configurationthrows JSchException {
        final JSch jsch = new JSch();
        JSch.setLogger(new JSchLogger());
        SftpConfiguration sftpConfig = (SftpConfigurationconfiguration;
        if (isNotEmpty(sftpConfig.getCiphers())) {
            .debug("Using ciphers: {}"sftpConfig.getCiphers());
            Hashtable<StringStringciphers = new Hashtable<StringString>();
            ciphers.put("cipher.s2c"sftpConfig.getCiphers());
            ciphers.put("cipher.c2s"sftpConfig.getCiphers());
            JSch.setConfig(ciphers);
        }
        
        if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
            .debug("Using private keyfile: {}"sftpConfig.getPrivateKeyFile());
            if (isNotEmpty(sftpConfig.getPrivateKeyFilePassphrase())) {
                jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyFilePassphrase());
            } else {
                jsch.addIdentity(sftpConfig.getPrivateKeyFile());
            }
        }
        if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
            .debug("Using knownhosts file: {}"sftpConfig.getKnownHostsFile());
            jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
        }
        final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());
        if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
            .debug("Using StrickHostKeyChecking: {}"sftpConfig.getStrictHostKeyChecking());
            session.setConfig("StrictHostKeyChecking"sftpConfig.getStrictHostKeyChecking());
        }
        
        session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
        session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());
        // compression
        if (sftpConfig.getCompression() > 0) {
            .debug("Using compression: {}"sftpConfig.getCompression());
            session.setConfig("compression.s2c""zlib@openssh.com, zlib, none");
            session.setConfig("compression.c2s""zlib@openssh.com, zlib, none");
            session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
        }
        // set user information
        session.setUserInfo(new ExtendedUserInfo() {
            public String getPassphrase() {
                return null;
            }
            public String getPassword() {
                return configuration.getPassword();
            }
            public boolean promptPassword(String s) {
                return true;
            }
            public boolean promptPassphrase(String s) {
                return true;
            }
            public boolean promptYesNo(String s) {
                .warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
                // Return 'false' indicating modification of the hosts file is disabled.
                return false;
            }
            public void showMessage(String s) {
                .trace("Message received from Server: " + s);
            }
            public String[] promptKeyboardInteractive(String destinationString name,
                                                      String instructionString[] promptboolean[] echo) {
                return new String[]{configuration.getPassword()};
            }
        });
        return session;
    }
    private static final class JSchLogger implements com.jcraft.jsch.Logger {
        public boolean isEnabled(int level) {
            switch (level) {
            case :
                // use ERROR as FATAL
                return .isErrorEnabled();
            case :
                return .isErrorEnabled();
            case :
                return .isWarnEnabled();
            case :
                return .isInfoEnabled();
            default:
                return .isDebugEnabled();
            }
        }
        public void log(int levelString message) {
            switch (level) {
            case :
                // use ERROR as FATAL
                .error("JSCH -> " + message);
                break;
            case :
                .error("JSCH -> " + message);
                break;
            case :
                .warn("JSCH -> " + message);
                break;
            case :
                .info("JSCH -> " + message);
                break;
            default:
                .debug("JSCH -> " + message);
                break;
            }
        }
    }
    public boolean isConnected() throws GenericFileOperationFailedException {
        return  != null && .isConnected() &&  != null && .isConnected();
    }
    public void disconnect() throws GenericFileOperationFailedException {
        if ( != null && .isConnected()) {
            .disconnect();
        }
        if ( != null && .isConnected()) {
            .disconnect();
        }
    }
    public boolean deleteFile(String namethrows GenericFileOperationFailedException {
        .debug("Deleting file: {}"name);
        try {
            .rm(name);
            return true;
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot delete file: " + namee);
        }
    }
    public boolean renameFile(String fromString tothrows GenericFileOperationFailedException {
        .debug("Renaming file: {} to: {}"fromto);
        try {
            .rename(fromto);
            return true;
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot rename file from: " + from + " to: " + toe);
        }
    }
    public boolean buildDirectory(String directoryboolean absolutethrows GenericFileOperationFailedException {
        // must normalize directory first
        directory = .getConfiguration().normalizePath(directory);
        .trace("buildDirectory({},{})"directoryabsolute);
        // ignore absolute as all dirs are relative with FTP
        boolean success = false;
        String originalDirectory = getCurrentDirectory();
        try {
            // maybe the full directory already exists
            try {
                .cd(directory);
                success = true;
            } catch (SftpException e) {
                // ignore, we could not change directory so try to create it instead
            }
            if (!success) {
                .debug("Trying to build remote directory: {}"directory);
                try {
                    .mkdir(directory);
                    success = true;
                } catch (SftpException e) {
                    // we are here if the server side doesn't create intermediate folders
                    // so create the folder one by one
                    success = buildDirectoryChunks(directory);
                }
            }
        } catch (IOException e) {
            throw new GenericFileOperationFailedException("Cannot build directory: " + directorye);
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot build directory: " + directorye);
        } finally {
            // change back to original directory
            if (originalDirectory != null) {
                changeCurrentDirectory(originalDirectory);
            }
        }
        return success;
    }
    private boolean buildDirectoryChunks(String dirNamethrows IOExceptionSftpException {
        final StringBuilder sb = new StringBuilder(dirName.length());
        final String[] dirs = dirName.split("/|\\\\");
        boolean success = false;
        for (String dir : dirs) {
            sb.append(dir).append('/');
            // must normalize the directory name
            String directory = .getConfiguration().normalizePath(sb.toString());
            // do not try to build root folder (/ or \)
            if (!(directory.equals("/") || directory.equals("\\"))) {
                try {
                    .trace("Trying to build remote directory by chunk: {}"directory);
                    .mkdir(directory);
                    success = true;
                } catch (SftpException e) {
                    // ignore keep trying to create the rest of the path
                }
            }
        }
        return success;
    }
        .trace("getCurrentDirectory()");
        try {
            String answer = .pwd();
            .trace("Current dir: {}"answer);
            return answer;
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot get current directory"e);
        }
    }
        .trace("changeCurrentDirectory({})"path);
        if (ObjectHelper.isEmpty(path)) {
            return;
        }
        // must compact path so SFTP server can traverse correctly, make use of the '/'
        // separator because JSch expects this as the file separator even on Windows
        String before = path;
        char separatorChar = '/';
        path = FileUtil.compactPath(pathseparatorChar);
        if (.isTraceEnabled()) {
            .trace("Compacted path: {} -> {} using separator: {}"new Object[]{beforepathseparatorChar});
        }
        // not stepwise should change directory in one operation
        if (!.getConfiguration().isStepwise()) {
            doChangeDirectory(path);
            return;
        }
        if (getCurrentDirectory().startsWith(path)) {
            // use relative path
            String p = getCurrentDirectory().substring(path.length());
            if (p.length() == 0) {
                return;
            }
            // the first character must be '/' and hence removed
            path = .matcher(p).replaceAll("/..").substring(1);
        }
        // if it starts with the root path then a little special handling for that
        if (FileUtil.hasLeadingSeparator(path)) {
            // change to root path
            doChangeDirectory(path.substring(0, 1));
            path = path.substring(1);
        }
        // split into multiple dirs
        final String[] dirs = path.split("/|\\\\");
        if (dirs == null || dirs.length == 0) {
            // path was just a relative single path
            doChangeDirectory(path);
            return;
        }
        // there are multiple dirs so do this in chunks
        for (String dir : dirs) {
            doChangeDirectory(dir);
        }
    }
    private void doChangeDirectory(String path) {
        if (path == null || ".".equals(path) || ObjectHelper.isEmpty(path)) {
            return;
        }
        .trace("Changing directory: {}"path);
        try {
            .cd(path);
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot change directory to: " + pathe);
        }
    }
        .trace("changeToParentDirectory()");
        String current = getCurrentDirectory();
        String parent = FileUtil.compactPath(current + "/..");
        // must start with absolute
        if (!parent.startsWith("/")) {
            parent = "/" + parent;
        }
        changeCurrentDirectory(parent);
    }
        return listFiles(".");
    }
        .trace("listFiles({})"path);
        if (ObjectHelper.isEmpty(path)) {
            // list current directory if file path is not given
            path = ".";
        }
        try {
            final List<ChannelSftp.LsEntrylist = new ArrayList<ChannelSftp.LsEntry>();
            @SuppressWarnings("rawtypes")
            Vector files = .ls(path);
            // can return either null or an empty list depending on FTP servers
            if (files != null) {
                for (Object file : files) {
                    list.add((ChannelSftp.LsEntryfile);
                }
            }
            return list;
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot list directory: " + pathe);
        }
    }
    public boolean retrieveFile(String nameExchange exchangethrows GenericFileOperationFailedException {
        .trace("retrieveFile({})"name);
        if (ObjectHelper.isNotEmpty(.getLocalWorkDirectory())) {
            // local work directory is configured so we should store file content as files in this local directory
            return retrieveFileToFileInLocalWorkDirectory(nameexchange);
        } else {
            // store file content directory as stream on the body
            return retrieveFileToStreamInBody(nameexchange);
        }
    }
    
    @Override
        
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new GenericFileOperationFailedException(e.getMessage(), e);
            }
        }
    }
    @SuppressWarnings("unchecked")
    private boolean retrieveFileToStreamInBody(String nameExchange exchangethrows GenericFileOperationFailedException {
        OutputStream os = null;
        String currentDir = null;
        try {
            GenericFile<ChannelSftp.LsEntrytarget =
                    (GenericFile<ChannelSftp.LsEntry>) exchange.getProperty(.);
            ObjectHelper.notNull(target"Exchange should have the " + . + " set");
            
            String remoteName = name;
            if (.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);
            }
            // use input stream which works with Apache SSHD used for testing
            InputStream is = .get(remoteName);
            
            if (.getConfiguration().isStreamDownload()) {
                target.setBody(is);
                exchange.getIn().setHeader(.is);
            } else {
                os = new ByteArrayOutputStream();
                target.setBody(os);
                IOHelper.copyAndCloseInput(isos);
            }
            return true;
        } catch (IOException e) {
            throw new GenericFileOperationFailedException("Cannot retrieve file: " + namee);
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot retrieve file: " + namee);
        } finally {
            IOHelper.close(os"retrieve: " + name);
            // change back to current directory if we changed directory
            if (currentDir != null) {
                changeCurrentDirectory(currentDir);
            }
        }
    }
    @SuppressWarnings("unchecked")
    private boolean retrieveFileToFileInLocalWorkDirectory(String nameExchange exchangethrows GenericFileOperationFailedException {
        File temp;
        File local = new File(.getLocalWorkDirectory());
        OutputStream os;
        GenericFile<ChannelSftp.LsEntryfile =
                (GenericFile<ChannelSftp.LsEntry>) exchange.getProperty(.);
        ObjectHelper.notNull(file"Exchange should have the " + . + " set");
        try {
            // use relative filename in local work directory
            String relativeName = file.getRelativeFilePath();
            temp = new File(localrelativeName + ".inprogress");
            local = new File(localrelativeName);
            // create directory to local work file
            local.mkdirs();
            // delete any existing files
            if (temp.exists()) {
                if (!FileUtil.deleteFile(temp)) {
                    throw new GenericFileOperationFailedException("Cannot delete existing local work file: " + temp);
                }
            }
            if (local.exists()) {
                if (!FileUtil.deleteFile(local)) {
                    throw new GenericFileOperationFailedException("Cannot delete existing local work file: " + local);
                }
            }
            // create new temp local work file
            if (!temp.createNewFile()) {
                throw new GenericFileOperationFailedException("Cannot create new local work file: " + temp);
            }
            // store content as a file in the local work directory in the temp handle
            os = new FileOutputStream(temp);
            // set header with the path to the local work file
            exchange.getIn().setHeader(.local.getPath());
        } catch (Exception e) {
            throw new GenericFileOperationFailedException("Cannot create new local work file: " + local);
        }
        String currentDir = null;
        try {
            // store the java.io.File handle as the body
            file.setBody(local);
            String remoteName = name;
            if (.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);
            }
            .get(remoteNameos);
        } catch (SftpException e) {
            .trace("Error occurred during retrieving file: {} to local directory. Deleting local work file: {}"nametemp);
            // failed to retrieve the file so we need to close streams and delete in progress file
            // must close stream before deleting file
            IOHelper.close(os"retrieve: " + name);
            boolean deleted = FileUtil.deleteFile(temp);
            if (!deleted) {
                .warn("Error occurred during retrieving file: " + name + " to local directory. Cannot delete local work file: " + temp);
            }
            throw new GenericFileOperationFailedException("Cannot retrieve file: " + namee);
        } finally {
            IOHelper.close(os"retrieve: " + name);
            // change back to current directory if we changed directory
            if (currentDir != null) {
                changeCurrentDirectory(currentDir);
            }
        }
        .debug("Retrieve file to local work file result: true");
        // operation went okay so rename temp to local after we have retrieved the data
        .trace("Renaming local in progress file from: {} to: {}"templocal);
        try {
            if (!FileUtil.renameFile(templocalfalse)) {
                throw new GenericFileOperationFailedException("Cannot rename local work file from: " + temp + " to: " + local);
            }
        } catch (IOException e) {
            throw new GenericFileOperationFailedException("Cannot rename local work file from: " + temp + " to: " + locale);
        }
        return true;
    }
    public boolean storeFile(String nameExchange exchangethrows GenericFileOperationFailedException {
        // must normalize name first
        name = .getConfiguration().normalizePath(name);
        .trace("storeFile({})"name);
        boolean answer = false;
        String currentDir = null;
        String path = FileUtil.onlyPath(name);
        String targetName = name;
        try {
            if (path != null && .getConfiguration().isStepwise()) {
                // must remember current dir so we stay in that directory after the write
                currentDir = getCurrentDirectory();
                // change to path of name
                changeCurrentDirectory(path);
                // the target name should be without path, as we have changed directory
                targetName = FileUtil.stripPath(name);
            }
            // store the file
            answer = doStoreFile(nametargetNameexchange);
        } finally {
            // change back to current directory if we changed directory
            if (currentDir != null) {
                changeCurrentDirectory(currentDir);
            }
        }
        return answer;
    }
    private boolean doStoreFile(String nameString targetNameExchange exchangethrows GenericFileOperationFailedException {
        .trace("doStoreFile({})"targetName);
        // if an existing file already exists what should we do?
        if (.getFileExist() == .
                || .getFileExist() == .
                || .getFileExist() == .) {
            boolean existFile = existsFile(targetName);
            if (existFile && .getFileExist() == .) {
                // ignore but indicate that the file was written
                .trace("An existing file already exists: {}. Ignore and do not override it."name);
                return true;
            } else if (existFile && .getFileExist() == .) {
                throw new GenericFileOperationFailedException("File already exist: " + name + ". Cannot write new file.");
            } else if (existFile && .getFileExist() == .) {
                // move any existing file first
                doMoveExistingFile(nametargetName);
            }
        }
        InputStream is = null;
        if (exchange.getIn().getBody() == null) {
            // Do an explicit test for a null body and decide what to do
            if (.isAllowNullBody()) {
                .trace("Writing empty file.");
                is = new ByteArrayInputStream(new byte[]{});
            } else {
                throw new GenericFileOperationFailedException("Cannot write null body to file: " + name);
            }
        }
        try {
            if (is == null) {
                is = exchange.getIn().getMandatoryBody(InputStream.class);
            }
            final StopWatch watch = new StopWatch();
            .debug("About to store file: {} using stream: {}"targetNameis);
            if (.getFileExist() == .) {
                .trace("Client appendFile: {}"targetName);
                .put(istargetName.);
            } else {
                .trace("Client storeFile: {}"targetName);
                // override is default
                .put(istargetName);
            }
            watch.stop();
            if (.isDebugEnabled()) {
                .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 = .getConfiguration().getChmod();
            if (ObjectHelper.isNotEmpty(mode)) {
                // parse to int using 8bit mode
                int permissions = Integer.parseInt(mode, 8);
                .trace("Setting chmod: {} on file: "modetargetName);
                .chmod(permissionstargetName);
            }
            return true;
        
        } catch (SftpException e) {
            throw new GenericFileOperationFailedException("Cannot store file: " + namee);
        } catch (InvalidPayloadException e) {
            throw new GenericFileOperationFailedException("Cannot store file: " + namee);
        } finally {
            IOHelper.close(is"store: " + name);
        }
    }

    
Moves any existing file due fileExists=Move is in use.
    private void doMoveExistingFile(String nameString targetNamethrows 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 = .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(.targetName);
        dummy.getIn().setHeader(.onlyName);
        dummy.getIn().setHeader(.parent);
        String to = .getMoveExisting().evaluate(dummyString.class);
        // we only support relative paths for the ftp component, so strip any leading paths
        to = FileUtil.stripLeadingSeparator(to);
        // normalize accordingly to configuration
        to = .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(dirfalse);
        }
        // deal if there already exists a file
        if (existsFile(to)) {
            if (.isEagerDeleteTargetFile()) {
                .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);
            }
        }
        .trace("Moving existing file: {} to: {}"nameto);
        if (!renameFile(targetNameto)) {
            throw new GenericFileOperationFailedException("Cannot rename file from: " + name + " to: " + to);
        }
    }
    public boolean existsFile(String namethrows GenericFileOperationFailedException {
        .trace("existsFile({})"name);
        if (.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 = .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.LsEntryfile;
                String existing = entry.getFilename();
                .trace("Existing file: {}, target file: {}"existingname);
                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 (. == e.id) {
                return false;
            }
            // otherwise its a more serious error so rethrow
            throw new GenericFileOperationFailedException(e.getMessage(), e);
        }
    }
    protected boolean fastExistsFile(String namethrows GenericFileOperationFailedException {
        .trace("fastExistsFile({})"name);
        try {
            @SuppressWarnings("rawtypes")
            Vector files = .ls(name);
            if (files == null) {
                return false;
            }
            return files.size() >= 1;
        } catch (SftpException e) {
            // or an exception can be thrown with id 2 which means file does not exists
            if (. == e.id) {
                return false;
            }
            // otherwise its a more serious error so rethrow
            throw new GenericFileOperationFailedException(e.getMessage(), e);
        }
    }
    public boolean sendNoop() throws GenericFileOperationFailedException {
        // is not implemented
        return true;
    }
    public boolean sendSiteCommand(String commandthrows GenericFileOperationFailedException {
        // is not implemented
        return true;
    }
New to GrepCode? Check out our FAQ X