Java Code Examples for com.jcraft.jsch.ChannelSftp.LsEntry#getFilename()

The following examples show how to use com.jcraft.jsch.ChannelSftp.LsEntry#getFilename() . 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: SFTPUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
/**  
 * 删除文件夹-sftp协议.如果文件夹有内容,则会抛出异常.  
 * @param path 文件夹路径  
 * @throws SftpException   SftpException
 */   
public void deleteDir(String path) throws SftpException {   
    @SuppressWarnings("unchecked")   
    Vector<LsEntry> vector = client.ls(path);   
    if (vector.size() == 1) { // 文件,直接删除   
        client.rm(path);   
    } else if (vector.size() == 2) { // 空文件夹,直接删除   
        client.rmdir(path);   
    } else {   
        String fileName = "";   
        // 删除文件夹下所有文件   
        for (LsEntry en : vector) {   
            fileName = en.getFilename();   
            if (".".equals(fileName) || "..".equals(fileName)) {   
                continue;   
            } else {   
            	deleteDir(path + "/" + fileName);   
            }   
        }   
        // 删除文件夹   
        client.rmdir(path);   
    }   
}
 
Example 2
Source File: SFTPTransfer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private FileInfo newFileInfo(final LsEntry entry, String path) {
    if (entry == null) {
        return null;
    }
    final File newFullPath = new File(path, entry.getFilename());
    final String newFullForwardPath = newFullPath.getPath().replace("\\", "/");

    String perms = entry.getAttrs().getPermissionsString();
    if (perms.length() > 9) {
        perms = perms.substring(perms.length() - 9);
    }

    FileInfo.Builder builder = new FileInfo.Builder()
        .filename(entry.getFilename())
        .fullPathFileName(newFullForwardPath)
        .directory(entry.getAttrs().isDir())
        .size(entry.getAttrs().getSize())
        .lastModifiedTime(entry.getAttrs().getMTime() * 1000L)
        .permissions(perms)
        .owner(Integer.toString(entry.getAttrs().getUId()))
        .group(Integer.toString(entry.getAttrs().getGId()));
    return builder.build();
}
 
Example 3
Source File: SFTPImportJob.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected void doTransferDirectory(ChannelSftp channel, IPath remotePath, SftpATTRS remoteAttributes, File localFile) throws SftpException, IOException {
	//create the local folder on import
	localFile.mkdirs();
	@SuppressWarnings("unchecked")
	Vector<LsEntry> remoteChildren = channel.ls(remotePath.toString());
	addTaskTotal(remoteChildren.size());

	//visit remote children
	for (LsEntry remoteChild : remoteChildren) {
		String childName = remoteChild.getFilename();
		if (shouldSkip(childName)) {
			taskItemLoaded();
			continue;
		}
		File localChild = new File(localFile, childName);
		if (remoteChild.getAttrs().isDir()) {
			doTransferDirectory(channel, remotePath.append(childName), remoteChild.getAttrs(), localChild);
		} else {
			doTransferFile(channel, remotePath.append(childName), remoteChild.getAttrs(), localChild);
		}
		taskItemLoaded();
	}
	synchronizeTimestamp(remoteAttributes, localFile);
}
 
Example 4
Source File: SFTPUtil.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
private List<FileBean> _buildFiles(Vector ls,String dir) throws Exception {  
    if (ls != null && ls.size() >= 0) {  
        List<FileBean> list = new ArrayList<FileBean>();
        for (int i = 0; i < ls.size(); i++) {  
            LsEntry f = (LsEntry) ls.get(i);  
            String nm = f.getFilename();  
            
            if (nm.equals(".") || nm.equals(".."))  
                continue;  
            SftpATTRS attr = f.getAttrs();  
            FileBean fileBean=new FileBean();
            if (attr.isDir()) {  
                fileBean.setDir(true);
            } else {  
                fileBean.setDir(false);
            }  
            fileBean.setAttrs(attr);
            fileBean.setFilePath(dir);
            fileBean.setFileName(nm);
            list.add(fileBean);  
        }  
        return list;  
    }  
    return null;  
}
 
Example 5
Source File: SFTPFileSystem.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
DirectoryStream<Path> newDirectoryStream(final SFTPPath path, Filter<? super Path> filter) throws IOException {
    try (Channel channel = channelPool.get()) {
        List<LsEntry> entries = channel.listFiles(path.path());
        boolean isDirectory = false;
        for (Iterator<LsEntry> i = entries.iterator(); i.hasNext(); ) {
            LsEntry entry = i.next();
            String filename = entry.getFilename();
            if (CURRENT_DIR.equals(filename)) {
                isDirectory = true;
                i.remove();
            } else if (PARENT_DIR.equals(filename)) {
                i.remove();
            }
        }

        if (!isDirectory) {
            // https://github.com/robtimus/sftp-fs/issues/4: don't fail immediately but check the attributes
            // Follow links to ensure the directory attribute can be read correctly
            SftpATTRS attributes = channel.readAttributes(path.path(), true);
            if (!attributes.isDir()) {
                throw new NotDirectoryException(path.path());
            }
        }
        return new SFTPPathDirectoryStream(path, entries, filter);
    }
}
 
Example 6
Source File: SftpUtil.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
private void handleMergeFile(String pathFolder, List<IMergeUnit> mergeunits, LsEntry file)
		throws MergeUnitException, SftpException, SftpUtilException {
	String fileName = file.getFilename();
	String attributes = file.getLongname();
	String path = pathFolder + fileName;

	LOGGER.fine(() -> String.format("Getting file fileName=%s, path=%s, attributes=%s", fileName, path, //$NON-NLS-1$
			attributes));
	try (InputStream is = sftpChannel.get(path)) {

		IMergeUnit mergeunit = null;
		if (fileName.endsWith(Configuration.EXTENSION_PLAINMERGE_FILE)
				|| fileName.endsWith(Configuration.SVN_EXTENSION_FILE)
				|| fileName.endsWith(Configuration.SVN_PACKAGE_MERGE_EXTENSION_FILE)) {
			LOGGER.fine(() -> String.format("Parsing SVN merge file %s.", path)); //$NON-NLS-1$
			mergeunit = SVNMergeUnitFactory.createMergeUnitFromPlainMergeFile(configuration, path, fileName,
					is);
		} else if (fileName.endsWith(Configuration.GIT_EXTENSION_FILE)) {
			LOGGER.fine(() -> String.format("Parsing GIT merge file %s.", path)); //$NON-NLS-1$
			mergeunit = GITMergeUnitFactory.create(configuration, Paths.get(path), is);
		} else {
			LOGGER.info(() -> String.format("Skipping file fileName=%s, path=%s, attributes=%s", //$NON-NLS-1$
					fileName, path, attributes));
			return;
		}
		mergeunits.add(mergeunit);
	} catch (IOException e) {
		String message = String.format("Caught exception while parsing merge unit from path=[%s].", path); //$NON-NLS-1$
		throw LogUtil.throwing(new SftpUtilException(message, e));
	}
}
 
Example 7
Source File: JschSftpClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private FileEntry getFileEntry( LsEntry lsEntry, String parentPath ) {

        FileEntry fileEntry = new FileEntry(lsEntry.getFilename(),
                                            IoUtils.normalizeUnixDir(parentPath) + lsEntry.getFilename(),
                                            lsEntry.getAttrs().isDir());
        fileEntry.setSize(lsEntry.getAttrs().getSize());
        fileEntry.setParentPath(parentPath);
        fileEntry.setLastModificationTime(lsEntry.getAttrs().getMTime());
        return fileEntry;
    }
 
Example 8
Source File: SftpConnection.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
private JFTPFile toFtpFile(LsEntry lsEntry, String filePath) throws SftpException {

        String name = lsEntry.getFilename();
        long fileSize = lsEntry.getAttrs().getSize();
        String fullPath = String.format("%s%s%s", filePath, "/", lsEntry.getFilename());
        //   String fullPath = channel.realpath(filePath); //为何不用这个
        int mTime = lsEntry.getAttrs().getMTime();
        boolean directory = lsEntry.getAttrs().isDir();

        return new JFTPFile(name, fileSize, fullPath, (long) mTime * MILLIS, directory);
    }
 
Example 9
Source File: SFTPConnection.java    From davos with MIT License 5 votes vote down vote up
private FTPFile toFtpFile(LsEntry lsEntry, String filePath) throws SftpException {

        String name = lsEntry.getFilename();
        long fileSize = lsEntry.getAttrs().getSize();
        int mTime = lsEntry.getAttrs().getMTime();
        boolean directory = lsEntry.getAttrs().isDir();

        return new FTPFile(name, fileSize, filePath, (long) mTime * 1000, directory);
    }
 
Example 10
Source File: SFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Info info(LsEntry file, String name, URI parent, URI self) {
	if (file == null) {
		return null;
	}
	try {
		return new SFTPInfo(file, (name != null) ? name : file.getFilename(), parent, self);
	} catch (IOException ex) {
		return null;
	}
}
 
Example 11
Source File: PooledSFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Info info(LsEntry file, String name, URI parent, URI self) {
	if (file == null) {
		return null;
	}
	try {
		return new SFTPInfo(file, (name != null) ? name : file.getFilename(), parent, self);
	} catch (IOException ex) {
		return null;
	}
}
 
Example 12
Source File: SftpSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@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: WcardPattern.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Gets files from fileName that can contain wildcards or returns original name.
 * @param url
 * @return
 */
private List<String> getSftpNames(URL url) {
	// result list
	List<String> mfiles = new ArrayList<String>();
	
	// if no wildcard found, return original name
	if (!hasWildcard(url)) {
		mfiles.add(url.toString());
		return mfiles;
	}

	URL originalURL = url;
	Pair<String, String> parts = FileUtils.extractProxyString(url.toString());
	try {
		url = FileUtils.getFileURL(parent, parts.getFirst());
	} catch (MalformedURLException ex) {
		
	}
	String proxyString = parts.getSecond();
	Proxy proxy = null;
	UserInfo proxyCredentials = null;
	if (proxyString != null) {
		proxy = FileUtils.getProxy(proxyString);
		try {
			String userInfo = new URI(proxyString).getUserInfo();
			if (userInfo != null) {
				proxyCredentials = new UserInfo(userInfo);
			}
		} catch (URISyntaxException use) {
		}
	}

	// get files
	SFTPConnection sftpConnection = null;
	try {
		// list files
		sftpConnection = (SFTPConnection) ((proxy != null) ? url.openConnection(proxy) : url.openConnection());
		sftpConnection.setProxyCredentials(proxyCredentials);
		Vector<?> v = sftpConnection.ls(url.getFile());				// note: too long operation
		for (Object lsItem: v) {
			LsEntry lsEntry = (LsEntry) lsItem;
			if (lsEntry.getAttrs().isDir()) {
				continue; // CLO-9619
			}
			String resolverdFileNameWithoutPath = lsEntry.getFilename();
			
			// replace file name
			String urlPath = url.getFile();

			// find last / or \ or set index to the start position
			// create new filepath
			int lastIndex = urlPath.lastIndexOf('/')+1;
			if (lastIndex <= 0) lastIndex = urlPath.lastIndexOf('\\')+1;
			String newUrlPath = urlPath.substring(0, lastIndex) + resolverdFileNameWithoutPath;
			
			// add new resolved url string
			mfiles.add(originalURL.toString().replace(urlPath, newUrlPath));
		}
	} catch (Throwable e) {
		// return original name
		logger.debug("SFTP wildcard resolution failed", e);
		mfiles.add(url.toString());
	}
	
	return mfiles;
}