String localdir = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator"); SftpClient sftp = getSftpClient(host, port,username, password); sftp.cd(fileLocation); sftp.lcd(localdir); @SuppressWarnings("rawtypes") List listinbox = sftp.ls(); for (Iterator<?> it = listinbox.iterator(); it.hasNext();) { file = (SftpFile) it.next(); try { SSH_LOG.info("Downloading the file: " + outputFileName); sftp.get(outputFileName, outputFileName); SSH_LOG.info("Download completed");
/** * Put file to remote host. * * @param host the hostname of the client * @param port the port number the user want to use for connection * @param username the username required for authentication * @param password the password required for authentication * @param localfilePath the localfile path where the file is situated * @param remotePath the remote path where the file is going to be put * @param fileName the file name you want to put * @throws IOException Signals that an I/O exception has occurred. */ @SuppressWarnings("unchecked") public static void putFileToRemoteHost(String host, int port,String username,String password, String localfilePath,String remotePath,String fileName)throws IOException { SftpClient sftp = getSftpClient(host,port, username, password); sftp.lcd(localfilePath); sftp.cd(remotePath); sftp.put(fileName); List<SftpFile> dirContents = sftp.ls(remotePath); Iterator<SftpFile> it = dirContents.iterator(); while(it.hasNext()){ if(it.next().getFilename().equals(fileName)){ SSH_LOG.info("The file " + fileName + " was tranferred successfully to " + remotePath); return; } } SSH_LOG.error("The file " + fileName + " was not tranferred to " + remotePath); }
/***********************************************************************/ public static void sftpUpload(FTPConfig config, File file, String remoteFileName) throws IOException { SshClient ssh = new SshClient(); SftpClient sftp = sshLogin(config, ssh); sftp.mkdirs(remoteFileName.substring(0, remoteFileName.lastIndexOf("/"))); sftp.put(new FileInputStream(file), remoteFileName); sftp.quit(); ssh.disconnect(); } /************************************************************************/
/** * Gets the file from remote host. * * @param host the hostname of the client * @param port the port number the user want to use for connection * @param username the username required for authentication * @param password the password required for authentication * @param remoteFilePath remotePath the remote path from where the file is going to be get * @param localfilePath the local file path where the file is going to be put * @param fileName the name of the file you want to transfer * @return the file from the remote host * @throws IOException Signals that an I/O exception has occurred. */ public static void getFileFromRemoteHost(String host, int port,String username,String password, String remoteFilePath,String localPath,String fileName) throws IOException { SftpClient sftp = getSftpClient(host, port,username, password); sftp.cd(remoteFilePath); sftp.lcd(localPath); sftp.get(fileName); File f = new File(localPath+System.getProperty("file.separator")+fileName); if (!f.exists()){ SSH_LOG.error("The file " + fileName + " was not tranferred to " + localPath); } else{ SSH_LOG.info("The file " + fileName + " was tranferred successfully to " + localPath); } }
/************************************************************************/ public static File sftpDownload(FTPConfig config, File file, String remoteFileName) throws IOException { SshClient ssh = new SshClient(); SftpClient sftp = sshLogin(config, ssh); sftp.get(remoteFileName, new FileOutputStream(file)); sftp.quit(); ssh.disconnect(); return file; } /***********************************************************************/
/** * Create directory on remote server. * * @param operationName * The remote directory creation is not available for all operation. * @throws IOException * if any IO problem occur while sending file or connecting to server */ public void createRemoteDirectoryIfNeeded(final String operationName) throws IOException { final String directory = this.info.getDirectory(); if (this.info.isCreateFolder() && !StringHelper.isNullOrEmpty(directory) && ((SFTPConstants.MPUT.equalsIgnoreCase(operationName)) || SFTPConstants.PUT.equalsIgnoreCase(operationName))) { // write operation : create all necessary folders try { this.client.cd(directory); } catch (final FileNotFoundException e) { // In principle, this exception occurs when the remote directory does not exist. this.client.mkdirs(directory); } } }
/** * List the content of the directory specified in the SFTPConfigurationInfo * used to build an instance of this object. Only the file are returned, * directories are ignored, because this is not relevant since this * component does not allow the user to swich from a directory to another. * * @return the list of the files found in the "working directory" specified * the SFTPConnectionInfo object which configures this connection * @throws IOException * if any IO problem occur while sending file or connecting to * server */ public List<String> list() throws IOException { // The list used to store the result of the ls operation final List<String> fileList = new ArrayList<String>(); List<SftpFile> sftpFiles = client.ls(); for (SftpFile file : sftpFiles) { if (file.isFile()) { if (logger.isLoggable(Level.FINE)) { logger.fine("file : " + file.getFilename()); } fileList.add(file.getFilename()); } } return fileList; }
@Override public void destroyObject(final PooledObject<WrappedSftpClient> pooledClient) throws Exception { final WrappedSftpClient client = pooledClient.getObject(); if (client != null) { final SftpClient activeSftpClient = client.getActiveSftpClient(); if (this.logger.isLoggable(Level.FINEST)) { this.logger.finest( "Log out user and disconnect ssh session : [" + this.connectionConfiguration.toString() + "]"); } if (activeSftpClient != null && !activeSftpClient.isClosed()) { activeSftpClient.quit(); } if (client.isConnected()) { client.disconnect(); } } }
client.get(remoteFile.getFilename(), out); out.flush(); final ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
@Override public boolean validateObject(final PooledObject<WrappedSftpClient> pooledClient) { this.logger.finest("Validate instance of SFTPClient"); final WrappedSftpClient client = pooledClient.getObject(); if (client == null) { return false; } try { final SftpClient activeSftpClient = client.getActiveSftpClient(); if (activeSftpClient != null && !activeSftpClient.isClosed() && client.isConnected()) { this.logger.finest("SFTPClient is connected"); return true; } } catch (final IOException e) { this.logger.log(Level.WARNING, "An error occurs validating pooled connection. Error skiped", e); } return false; } }
/*** * * @param filePattern * @throws IOException */ @SuppressWarnings("unchecked") public void del(String filePattern) throws IOException { final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromWildCard(filePattern); final List<SftpFile> fileContainedWithinWorkingDir = client.ls(); // Retrieve the files that match the given name for (SftpFile file : fileContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { file.delete(); break; } } }
/** * The sftp-client MUST be connected. This method DOES NOT close the * sftp-client * * @param remoteFile * @param client * a sftpclient, MUST be CONNECTED * @return the retrieved file, as a datahandler * @throws IOException * the file is not found or FTP access problem */ private DataHandler getAsDataHandler(SftpFile remoteFile, SftpClient client) throws IOException { DataHandler result; this.logger.info("start receiving file " + remoteFile.getFilename() + " from SFTP server"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(remoteFile .getAttributes().getSize().intValue()); client.get(remoteFile.getFilename(), outputStream); outputStream.flush(); logger.finest(remoteFile.getFilename() + " file received from SFTP server"); final ByteArrayDataSource datasource = new ByteArrayDataSource(outputStream.toByteArray(), FileTypeMap.getDefaultFileTypeMap().getContentType(remoteFile.getFilename())); outputStream.close(); datasource.setName(remoteFile.getFilename()); result = new DataHandler(datasource); logger.finest(remoteFile.getFilename() + " set as DataHandler"); return result; }
/** * Retrieve the specified files from the SSH server. * * @param fileFilterList * the list of files to get from the SFTP server * @return fhe files specified in the list * @throws IOException * if any IO problem occur while sending file or connecting to server */ @SuppressWarnings("unchecked") public Map<String, DataHandler> mGet(final List<String> fileFilterList) throws IOException { // Holds the result of the MGET operation final Map<String, DataHandler> dataHandlers = new HashMap<String, DataHandler>(); // Performs the MGET operation // Construct the fileFilters to match files read from the FTP // directory final List<FilenameFilter> filterList = new LinkedList<>(); for (final String string : fileFilterList) { filterList.add(FileNamePatternUtil.buildFileNameFilterFromWildCard(string)); } final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromFilters(filterList); final List<SftpFile> filesContainedWithinWorkingDir = client.ls(); for (SftpFile file : filesContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { dataHandlers.put(file.getFilename(), this.getAsDataHandler(file, client)); } } return dataHandlers; }
/** * Retrieve the file given by its filename on the SFTP server. * * @param filePattern * name of the file to get from the SFTP server * @return the retrieved file, streamed * @throws IOException * if any IO problem occur while sending file or connecting to * server */ @SuppressWarnings("unchecked") public Document get(final String filePattern) throws IOException { final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromWildCard(filePattern); // Holds the result of the GET operation Document result = null; final List<SftpFile> fileContainedWithinWorkingDir = client.ls(); for (SftpFile file : fileContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { result = this.getAsDocument(file, client); break; } } // If the file doen't exist if (result == null) { throw new IOException("Can not find the specified resource"); } return result; }
/** * Retrieve the file given by its filename on the SFTP server. * * @param filePattern * name of the file to get from the SFTP server * @return the retrieved file * @throws IOException * if any IO problem occur while sending file or connecting to * server */ @SuppressWarnings("unchecked") public DataHandler getAsAttachment(final String filePattern) throws IOException { final FilenameFilter filter = FileNamePatternUtil.buildFileNameFilterFromWildCard(filePattern); // Holds the result of the GET operation DataHandler retrievedFile = null; // Retrieve all the files from the current directory List<SftpFile> fileContainedWithinWorkingDir = client.ls(); // Retrieve the files that match the given name for (SftpFile file : fileContainedWithinWorkingDir) { if ((file.isFile() && file.canRead()) && filter.accept(null, file.getFilename())) { retrievedFile = this.getAsDataHandler(file, client); break; } } // If the file doen't exist if (retrievedFile == null) { throw new IOException("File not found"); } return retrievedFile; }