Java Code Examples for com.jcraft.jsch.ChannelSftp#ls()
The following examples show how to use
com.jcraft.jsch.ChannelSftp#ls() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SFTPRepository.java From ant-ivy with Apache License 2.0 | 9 votes |
@SuppressWarnings("unchecked") public List<String> list(String parent) throws IOException { try { ChannelSftp c = getSftpChannel(parent); String path = getPath(parent); Collection<LsEntry> r = c.ls(path); if (r != null) { if (!path.endsWith("/")) { path = parent + "/"; } List<String> result = new ArrayList<>(); for (LsEntry entry : r) { if (".".equals(entry.getFilename()) || "..".equals(entry.getFilename())) { continue; } result.add(path + entry.getFilename()); } return result; } } catch (SftpException | URISyntaxException e) { throw new IOException("Failed to return a listing for '" + parent + "'", e); } return null; }
Example 2
Source File: SshFileController.java From Jpom with MIT License | 8 votes |
/** * 删除文件或者文件夹 * * @param channel channel * @param path 文件路径 * @throws SftpException SftpException */ private void deleteFile(ChannelSftp channel, String path) throws SftpException { Vector<ChannelSftp.LsEntry> vector = channel.ls(path); if (null == vector) { return; } int size = vector.size(); if (size == 1) { // 文件,直接删除 channel.rm(path); } else if (size == 2) { // 空文件夹,直接删除 channel.rmdir(path); } else { // 删除文件夹下所有文件 String fileName; for (ChannelSftp.LsEntry en : vector) { fileName = en.getFilename(); if (!".".equals(fileName) && !"..".equals(fileName)) { deleteFile(channel, path + "/" + fileName); } } channel.rmdir(path); } }
Example 3
Source File: SFTPTransfer.java From localization_nifi with Apache License 2.0 | 7 votes |
@Override @SuppressWarnings("unchecked") public FileInfo getRemoteFileInfo(final FlowFile flowFile, final String path, String filename) throws IOException { final ChannelSftp sftp = getChannel(flowFile); final String fullPath; if (path == null) { fullPath = filename; int slashpos = filename.lastIndexOf('/'); if (slashpos >= 0 && !filename.endsWith("/")) { filename = filename.substring(slashpos + 1); } } else { fullPath = path + "/" + filename; } final Vector<LsEntry> vector; try { vector = sftp.ls(fullPath); } catch (final SftpException e) { // ls throws exception if filename is not present if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) { return null; } else { throw new IOException("Failed to obtain file listing for " + fullPath, e); } } LsEntry matchingEntry = null; for (final LsEntry entry : vector) { if (entry.getFilename().equalsIgnoreCase(filename)) { matchingEntry = entry; break; } } return newFileInfo(matchingEntry, path); }
Example 4
Source File: SFTPUtil.java From bestconf with Apache License 2.0 | 6 votes |
public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{ File file = new File(uploadFile); if(file.exists()){ try { Vector content = sftp.ls(directory); if(content == null){ sftp.mkdir(directory); System.out.println("mkdir:" + directory); } } catch (SftpException e) { sftp.mkdir(directory); } sftp.cd(directory); System.out.println("directory: " + directory); if(file.isFile()){ InputStream ins = new FileInputStream(file); sftp.put(ins, new String(file.getName().getBytes(),"UTF-8")); }else{ File[] files = file.listFiles(); for (File file2 : files) { String dir = file2.getAbsolutePath(); if(file2.isDirectory()){ String str = dir.substring(dir.lastIndexOf(file2.separator)); directory = directory + str; } System.out.println("directory is :" + directory); upload(directory,dir,sftp); } } } }
Example 5
Source File: SFtpClientUtils.java From bamboobsc with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public static Vector<LsEntry> getRemoteFileList(String user, String password, String addr, int port, String cwd) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Vector<LsEntry> lsVec=null; Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; try { lsVec=(Vector<LsEntry>)sftpChannel.ls(cwd); //sftpChannel.lpwd() } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } return lsVec; }
Example 6
Source File: CommandDelegatorMethods.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * This method downloads whole directory recursively * @param channelSftp * @param remotePath remote directory (not file) path * @param localPath * @throws SftpException */ private void downloadDirectory(ChannelSftp channelSftp, String remotePath, String localPath, String user) throws SftpException { @SuppressWarnings("unchecked") Vector<ChannelSftp.LsEntry> childs = channelSftp.ls(remotePath); changeOwnership(localPath, user); for (ChannelSftp.LsEntry child : childs) { if (child.getAttrs().isDir()) { if (CURRENT_DIR.equals(child.getFilename()) || PARENT_DIR.equals(child.getFilename())) { continue; } new File(localPath + File.separator + child.getFilename()).mkdirs(); changeOwnership(localPath + File.separator + child.getFilename(), user); downloadDirectory(channelSftp, remotePath + File.separator + child.getFilename() + File.separator, localPath + File.separator + child.getFilename(),user); } else { channelSftp.get(remotePath + File.separator + child.getFilename(), localPath + File.separator + child.getFilename()); changeOwnership(localPath + File.separator + child.getFilename(), user); } } }
Example 7
Source File: SFTPUtils.java From axelor-open-suite with GNU Affero General Public License v3.0 | 5 votes |
/** Returns a list of all files in given directory {@code dir}. */ @SuppressWarnings("unchecked") public static List<LsEntry> getFiles(ChannelSftp channel, String dir) throws SftpException { List<LsEntry> files = new ArrayList<>((Vector<LsEntry>) channel.ls(dir)); files.sort( Comparator.comparing((LsEntry file) -> file.getAttrs().getMTime()) .thenComparing(LsEntry::getFilename)); return files; }
Example 8
Source File: SFTPOperationHandler.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
private List<Info> list(URI parentUri, ChannelSftp channel, ListParameters params) throws IOException, SftpException { if (Thread.currentThread().isInterrupted()) { throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$ } Info rootInfo = info(parentUri, channel); if (rootInfo == null) { throw new FileNotFoundException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.file_not_found"), parentUri.toString())); //$NON-NLS-1$ } if (parentUri.toString().endsWith(URIUtils.PATH_SEPARATOR) && !rootInfo.isDirectory()) { throw new FileNotFoundException(format(FileOperationMessages.getString("IOperationHandler.not_a_directory"), parentUri)); //$NON-NLS-1$ } if (!rootInfo.isDirectory()) { return Arrays.asList(rootInfo); } else { @SuppressWarnings("unchecked") Vector<LsEntry> files = channel.ls(getPath(parentUri)); List<Info> result = new ArrayList<Info>(files.size()); for (LsEntry file: files) { if ((file != null) && !file.getFilename().equals(URIUtils.CURRENT_DIR_NAME) && !file.getFilename().equals(URIUtils.PARENT_DIR_NAME)) { Info child = info(file, null, parentUri, null); result.add(child); if (params.isRecursive() && file.getAttrs().isDir()) { result.addAll(list(child.getURI(), channel, params)); } } } return result; } }
Example 9
Source File: PooledSFTPOperationHandler.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
private List<Info> list(URI parentUri, ChannelSftp channel, ListParameters params) throws IOException, SftpException { if (Thread.currentThread().isInterrupted()) { throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$ } Info rootInfo = info(parentUri, channel); if (rootInfo == null) { throw new FileNotFoundException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.file_not_found"), parentUri.toString())); //$NON-NLS-1$ } if (parentUri.toString().endsWith(URIUtils.PATH_SEPARATOR) && !rootInfo.isDirectory()) { throw new FileNotFoundException(format(FileOperationMessages.getString("IOperationHandler.not_a_directory"), parentUri)); //$NON-NLS-1$ } if (!rootInfo.isDirectory()) { return Arrays.asList(rootInfo); } else { @SuppressWarnings("unchecked") Vector<LsEntry> files = channel.ls(getPath(parentUri)); List<Info> result = new ArrayList<Info>(files.size()); for (LsEntry file: files) { if ((file != null) && !file.getFilename().equals(URIUtils.CURRENT_DIR_NAME) && !file.getFilename().equals(URIUtils.PARENT_DIR_NAME)) { Info child = info(file, null, parentUri, null); result.add(child); if (params.isRecursive() && file.getAttrs().isDir()) { result.addAll(list(child.getURI(), channel, params)); } } } return result; } }
Example 10
Source File: SftpFsHelper.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Override public List<String> ls(String path) throws FileBasedHelperException { try { List<String> list = new ArrayList<>(); ChannelSftp channel = getSftpChannel(); Vector<LsEntry> vector = channel.ls(path); for (LsEntry entry : vector) { list.add(entry.getFilename()); } channel.disconnect(); return list; } catch (SftpException e) { throw new FileBasedHelperException("Cannot execute ls command on sftp connection", e); } }
Example 11
Source File: SftpUtils.java From secure-data-service with Apache License 2.0 | 5 votes |
public static void landFile(File fileToLand, UploadProperties properties) throws Exception { JSch jsch = new JSch(); String host = properties.getSftpServer(); String user = properties.getUser(); String password = properties.getPassword(); int port = properties.getPort(); Session session = jsch.getSession(user, host, port); session.setOutputStream(System.out); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(TIMEOUT); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp c = (ChannelSftp) channel; // delete any existing file with the target filename, so that rename will work @SuppressWarnings("unchecked") Vector<LsEntry> files = c.ls("."); for (LsEntry file : files) { if (FINAL_REMOTE_FILENAME.equals(file.getFilename())) { c.rm(FINAL_REMOTE_FILENAME); } } // transmit file, using temp remote name, so ingestion won't process file until complete c.put(new FileInputStream(fileToLand), TEMP_REMOTE_FILENAME, ChannelSftp.OVERWRITE); // rename remote file so ingestion can begin c.rename(TEMP_REMOTE_FILENAME, FINAL_REMOTE_FILENAME); c.disconnect(); channel.disconnect(); session.disconnect(); }
Example 12
Source File: SftpSupport.java From netbeans with Apache License 2.0 | 4 votes |
@Override @SuppressWarnings("unchecked") public StatInfo[] call() throws IOException, CancellationException, JSchException, ExecutionException, InterruptedException, SftpException { if (!path.startsWith("/")) { //NOI18N throw new FileNotFoundException("Path is not absolute: " + path); //NOI18N } List<StatInfo> result = null; SftpException exception = null; if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} started", getTraceName()); } String threadName = Thread.currentThread().getName(); Thread.currentThread().setName(PREFIX + ": " + getTraceName()); // NOI18N int attempt = 1; try { for (; attempt <= LS_RETRY_COUNT; attempt++) { ChannelSftp cftp = getChannel(); RemoteStatistics.ActivityID lsLoadID = RemoteStatistics.startChannelActivity("lsload", path); // NOI18N try { List<LsEntry> entries = (List<LsEntry>) cftp.ls(path); result = new ArrayList<>(Math.max(1, entries.size() - 2)); for (LsEntry entry : entries) { String name = entry.getFilename(); if (!".".equals(name) && !"..".equals(name)) { //NOI18N SftpATTRS attrs = entry.getAttrs(); //if (!(attrs.isDir() || attrs.isLink())) { // if ( (attrs.getPermissions() & S_IFMT) != S_IFREG) { // // skip not regular files // continue; // } //} result.add(createStatInfo(path, name, attrs, cftp)); } } exception = null; break; } catch (SftpException e) { exception = e; if (e.id == SftpIOException.SSH_FX_FAILURE) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} - exception while attempt {1}", new Object[]{getTraceName(), attempt}); } if (MiscUtils.mightBrokeSftpChannel(e)) { cftp.quit(); } } else { // re-try in case of failure only // otherwise consider this exception as unrecoverable break; } } finally { RemoteStatistics.stopChannelActivity(lsLoadID); releaseChannel(cftp); } } } finally { Thread.currentThread().setName(threadName); } if (exception != null) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} failed", getTraceName()); } throw decorateSftpException(exception, path); } if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "{0} finished in {1} attempt(s)", new Object[]{getTraceName(), attempt}); } return result == null ? new StatInfo[0] : result.toArray(new StatInfo[result.size()]); }
Example 13
Source File: CommandDelegatorMethods.java From jumbune with GNU Lesser General Public License v3.0 | 2 votes |
/** * Checks if the remote file path provided is a directory or a file. * @param channelSftp * @param remotePath * @return * @throws SftpException */ @SuppressWarnings("unchecked") private boolean isDirectory(ChannelSftp channelSftp, String remotePath) throws SftpException { Vector<ChannelSftp.LsEntry> childs = channelSftp.ls(remotePath); return childs.size() == 1 ? false : true; }