com.jcraft.jsch.SftpException Java Examples

The following examples show how to use com.jcraft.jsch.SftpException. 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: SFTPConnection.java    From davos with MIT License 6 votes vote down vote up
@Override
public void download(FTPFile file, String localFilePath) {

    String path = FileUtils.ensureTrailingSlash(file.getPath()) + file.getName();
    String cleanLocalPath = FileUtils.ensureTrailingSlash(localFilePath);
    
    LOGGER.debug("Download. Remote path: {}", path);
    LOGGER.debug("Download. Local path: {}", cleanLocalPath);

    try {

        if (file.isDirectory())
            downloadDirectoryAndContents(file, cleanLocalPath, path);
        else
            doGet(path, cleanLocalPath);

    } catch (SftpException e) {
        throw new DownloadFailedException("Unable to download file " + path, e);
    }
}
 
Example #2
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testMoveReplaceFile() throws IOException {
    addDirectory("/foo");
    addDirectory("/foo/bar");
    addFile("/baz");

    CopyOption[] options = {};
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.move(createPath("/baz"), createPath("/foo/bar"), options));
    assertEquals("/baz", exception.getFile());
    assertEquals("/foo/bar", exception.getOtherFile());

    verify(getExceptionFactory()).createMoveException(eq("/baz"), eq("/foo/bar"), any(SftpException.class));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isDirectory(getPath("/foo/bar")));
    assertTrue(Files.isRegularFile(getPath("/baz")));
}
 
Example #3
Source File: SftpRemoteFileSystem.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
public boolean exists(String filename) throws FileSystemException {
    // we have to be connected
    if (channel == null) {
        throw new FileSystemException("Not yet connected to SFTP server");
    }

    // easiest way to check if a file already exists is to do a file stat
    // this method will error out if the remote file does not exist!
    try {
        SftpATTRS attrs = channel.stat(filename);
        // if we get here, then file exists
        return true;
    } catch (SftpException e) {
        // map "no file" message to return correct result
        if (e.getMessage().toLowerCase().indexOf("no such file") >= 0) {
            return false;
        }
        // otherwise, this means an underlying error occurred
        throw new FileSystemException("Underlying error with SFTP session while checking if file exists", e);
    }
}
 
Example #4
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopySFTPFailure() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");

    // failure: target parent does not exist

    CopyOption[] options = {};
    NoSuchFileException exception = assertThrows(NoSuchFileException.class,
            () -> fileSystem.copy(createPath("/foo/bar"), createPath("/baz/bar"), options));
    assertEquals("/baz/bar", exception.getFile());

    verify(getExceptionFactory()).createNewOutputStreamException(eq("/baz/bar"), any(SftpException.class), anyCollection());
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
    assertFalse(Files.exists(getPath("/baz")));
    assertFalse(Files.exists(getPath("/baz/bar")));
}
 
Example #5
Source File: SftpClient.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized int getPermissions(String path) throws RemoteException {
    int permissions = -1;
    try {
        sftpLogger.info("LIST " + path); // NOI18N
        sftpLogger.info(NbBundle.getMessage(SftpClient.class, "LOG_DirListing"));

        ChannelSftp.LsEntry file = getFile(path);
        if (file != null) {
            permissions = file.getAttrs().getPermissions();
        }

        sftpLogger.info(NbBundle.getMessage(SftpClient.class, "LOG_DirectorySendOk"));
    } catch (SftpException ex) {
        LOGGER.log(Level.FINE, "Error while getting permissions for " + path, ex);
    }
    return permissions;
}
 
Example #6
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 #7
Source File: SftpSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatInfo createStatInfo(String dirName, String baseName, SftpATTRS attrs, ChannelSftp cftp) throws SftpException {
    String linkTarget = null;
    if (attrs.isLink()) {
        String path = dirName + '/' + baseName;
        RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("readlink", path); // NOI18N
        try {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "performing readlink {0}", path);
            }
            linkTarget = cftp.readlink(path);
        } finally {
            RemoteStatistics.stopChannelActivity(activityID);
        }
    }
    Date lastModified = new Date(attrs.getMTime() * 1000L);
    StatInfo result = new FileInfoProvider.StatInfo(baseName, attrs.getUId(), attrs.getGId(), attrs.getSize(),
            attrs.isDir(), attrs.isLink(), linkTarget, attrs.getPermissions(), lastModified);
    return result;
}
 
Example #8
Source File: SFTPUtil.java    From bestconf with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: SftpLightWeightFileSystem.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(Path path) throws IOException {
  ChannelSftp channel = null;
  try {
    channel = this.fsHelper.getSftpChannel();
    if (getFileStatus(path).isDirectory()) {
      channel.rmdir(HadoopUtils.toUriPath(path));
    } else {
      channel.rm(HadoopUtils.toUriPath(path));
    }
  } catch (SftpException e) {
    throw new IOException(e);
  } finally {
    safeDisconnect(channel);
  }
  return true;
}
 
Example #10
Source File: SftpConnection.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * Upload a single file to the sFTP server.未支持断点续传
 *
 * @param localFilePath       Path of the file on local computer
 * @param remoteDirectoryPath path of directory where the file will be stored
 * @return true if the file was uploaded successfully, false otherwise
 * @throws IOException if any network or IO error occurred.
 */
@Override
public void uploadFile(String localFilePath, String remoteDirectoryPath, boolean logProcess) throws FtpException {

    if (!Paths.get(localFilePath).toFile().exists()) {
        throw new FtpException("Unable to upload file, file does not exist :  " + localFilePath);
    }

    if (!existsDirectory(remoteDirectoryPath))
        createDirectory(remoteDirectoryPath);

    try {
        channel.put(localFilePath, remoteDirectoryPath);
    } catch (SftpException e) {
        e.printStackTrace();
        throw new FtpException("Unable to upload file :  " + localFilePath);
    }

    logger.info("upload file succeed : " + localFilePath);
}
 
Example #11
Source File: SftpConnection.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
     * Determines whether a directory exists or not
     * 如果是文件,也会抛出异常,返回 false
     *
     * @param remoteDirectoryPath
     * @return true if exists, false otherwise
     * @throws IOException thrown if any I/O error occurred.
     */
    @Override
    public boolean existsDirectory(String remoteDirectoryPath) {

        try {
            // System.out.println(channel.realpath(remoteFilePath));
            SftpATTRS attrs = channel.stat(remoteDirectoryPath);
            return attrs.isDir();
        } catch (SftpException e) {
            // e.printStackTrace();
            return false;
        }


//        String originalWorkingDirectory = getWorkingDirectory();
//        try {
//            changeDirectory(remoteDirectoryPath);
//        } catch (FtpException e) {
//            //文件夹不存在,会抛出异常。
//            return false;
//        }
//        //恢复 ftpClient 当前工作目录属性
//        changeDirectory(originalWorkingDirectory);
//        return true;
    }
 
Example #12
Source File: SftpExecutorTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testPopulateErrorStreamOnSftpError() throws Exception
{
    ChannelSftp channel = mock(ChannelSftp.class);
    SftpException sftpException = new SftpException(0, "error");
    doThrow(sftpException).when(channel).pwd();
    ServerConfiguration serverConfiguration = new ServerConfiguration();
    serverConfiguration.setAgentForwarding(true);
    SftpOutput sftpOutput = sftpExecutor.executeCommand(serverConfiguration, new Commands("pwd"), channel);
    assertEquals("", sftpOutput.getResult());
    InOrder ordered = inOrder(channel, softAssert);
    ordered.verify(channel).setAgentForwarding(serverConfiguration.isAgentForwarding());
    ordered.verify(channel).connect();
    ordered.verify(channel).pwd();
    ordered.verify(softAssert).recordFailedAssertion("SFTP command error", sftpException);
    ordered.verifyNoMoreInteractions();
}
 
Example #13
Source File: SftpFileUtil.java    From Leo with Apache License 2.0 6 votes vote down vote up
/**
    * 删除服务器上的文件
    * @param filepath
    * @return boolean
    */
   public  boolean delFile(String filepath) {
	boolean flag=false;
	ChannelSftp channel=getChannel();
	try {
		channel.rm(filepath);
		log.info("删除文件"+filepath+"成功");
		flag=true;
	} catch (SftpException e) {
		log.error("删除文件"+filepath+"失败");
		log.error(e.getMessage());
	}finally {
			//channel.quit();
          
       }
	
	return flag;
}
 
Example #14
Source File: SFTPTransfer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteFile(final String path, final String remoteFileName) throws IOException {
    final String fullPath = (path == null) ? remoteFileName : (path.endsWith("/")) ? path + remoteFileName : path + "/" + remoteFileName;
    try {
        sftp.rm(fullPath);
    } catch (final SftpException e) {
        switch (e.id) {
            case ChannelSftp.SSH_FX_NO_SUCH_FILE:
                throw new FileNotFoundException("Could not find file " + remoteFileName + " to remove from remote SFTP Server");
            case ChannelSftp.SSH_FX_PERMISSION_DENIED:
                throw new PermissionDeniedException("Insufficient permissions to delete file " + remoteFileName + " from remote SFTP Server", e);
            default:
                throw new IOException("Failed to delete remote file " + fullPath, e);
        }
    }
}
 
Example #15
Source File: SftpCommandTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "PMD.ReplaceVectorWithList", "PMD.UseArrayListInsteadOfVector" })
void shouldExecuteLsCommand() throws IOException, SftpException
{
    ChannelSftp channel = mock(ChannelSftp.class);
    String path = "/dir-to-list";
    LsEntry lsEntry1 = mock(LsEntry.class);
    when(lsEntry1.getFilename()).thenReturn("file1.txt");
    LsEntry lsEntry2 = mock(LsEntry.class);
    when(lsEntry2.getFilename()).thenReturn("file2.story");
    Vector<LsEntry> ls = new Vector<>();
    ls.add(lsEntry1);
    ls.add(lsEntry2);
    when(channel.ls(path)).thenReturn(ls);
    String result = SftpCommand.LS.execute(channel, path);
    assertEquals("file1.txt,file2.story", result);
}
 
Example #16
Source File: SFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void delete(ChannelSftp channel, Info info, DeleteParameters params) throws IOException, SftpException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	URI uri = info.getURI();
	if (info.isDirectory()) {
		if (params.isRecursive()) {
			List<Info> children = list(uri, channel, LIST_NONRECURSIVE);
			for (Info child: children) {
				delete(channel, child, params);
			}
			channel.rmdir(getPath(uri));
		} else {
			throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.cannot_remove_directory"), uri)); //$NON-NLS-1$
		}
	} else {
		channel.rm(getPath(uri));
	}
}
 
Example #17
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyReplaceNonEmptyDirAllowed() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");
    addFile("/baz");

    CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING };
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.copy(createPath("/baz"), createPath("/foo"), options));
    assertEquals("/foo", exception.getFile());

    verify(getExceptionFactory()).createDeleteException(eq("/foo"), any(SftpException.class), eq(true));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
    assertTrue(Files.isRegularFile(getPath("/baz")));
}
 
Example #18
Source File: CommandDelegatorMethods.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #19
Source File: PooledSFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void delete(ChannelSftp channel, Info info, DeleteParameters params) throws IOException, SftpException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	URI uri = info.getURI();
	if (info.isDirectory()) {
		if (params.isRecursive()) {
			List<Info> children = list(uri, channel, LIST_NONRECURSIVE);
			for (Info child: children) {
				delete(channel, child, params);
			}
			channel.rmdir(getPath(uri));
		} else {
			throw new IOException(MessageFormat.format(FileOperationMessages.getString("IOperationHandler.cannot_remove_directory"), uri)); //$NON-NLS-1$
		}
	} else {
		channel.rm(getPath(uri));
	}
}
 
Example #20
Source File: SFTPClient.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated use {@link #get(FileObject, String)}
 * @param localFilePath
 * @param remoteFile
 * @throws KettleJobException
 */
@Deprecated
public void get( String localFilePath, String remoteFile ) throws KettleJobException {
  int mode = ChannelSftp.OVERWRITE;
  try {
    c.get( remoteFile, localFilePath, null, mode );
  } catch ( SftpException e ) {
    throw new KettleJobException( e );
  }
}
 
Example #21
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetOwnerNonExisting() {
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.setOwner(createPath("/foo/bar"), new SimpleUserPrincipal("1")));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory()).createSetOwnerException(eq("/foo/bar"), any(SftpException.class));
}
 
Example #22
Source File: SFTPConnection.java    From davos with MIT License 5 votes vote down vote up
@Override
public String currentDirectory() {

    try {
        String pwd = channel.pwd();
        LOGGER.debug("{}", pwd);
        return pwd;
    } catch (SftpException e) {
        throw new FileListingException("Unable to print the working directory", e);
    }
}
 
Example #23
Source File: SftpLightWeightFileSystem.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public void setWorkingDirectory(Path path) {
  ChannelSftp channelSftp = null;
  try {
    channelSftp = this.fsHelper.getSftpChannel();
    channelSftp.lcd(HadoopUtils.toUriPath(path));

  } catch (SftpException e) {
    throw new RuntimeException("Failed to set working directory", e);
  } finally {
    safeDisconnect(channelSftp);
  }
}
 
Example #24
Source File: SftpClient.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized boolean retrieveFile(String remote, OutputStream local) throws RemoteException {
    try {
        sftpLogger.info("RETR " + remote); // NOI18N

        sftpClient.get(remote, local);

        sftpLogger.info(NbBundle.getMessage(SftpClient.class, "LOG_FileSendOk"));
        return true;
    } catch (SftpException ex) {
        LOGGER.log(Level.FINE, "Error while retrieving file " + remote, ex);
        sftpLogger.error(ex.getLocalizedMessage());
        throw new RemoteException(NbBundle.getMessage(SftpClient.class, "MSG_CannotStoreFile", remote), ex);
    }
}
 
Example #25
Source File: SftpFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an input stream to read the file content from. The input stream is starting at the given position in the
 * file.
 */
InputStream getInputStream(final long filePointer) throws IOException {
    final ChannelSftp channel = getAbstractFileSystem().getChannel();
    // Using InputStream directly from the channel
    // is much faster than the memory method.
    try {
        return new SftpInputStream(channel, channel.get(getName().getPathDecoded(), null, filePointer));
    } catch (final SftpException e) {
        getAbstractFileSystem().putChannel(channel);
        throw new FileSystemException(e);
    }
}
 
Example #26
Source File: SFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public List<Info> list(SingleCloverURI parent, ListParameters params)
		throws IOException {
	URI parentUri = parent.toURI();
	SFTPSession session = null;
	try {
		session = connect(parentUri);
		return list(parentUri, session.channel, params);
	} catch (SftpException ex) {
		throw new IOException(ex);
	} finally {
		disconnectQuietly(session);
	}
}
 
Example #27
Source File: SftpClient.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized String printWorkingDirectory() throws RemoteException {
    try {
        sftpLogger.info("PWD"); // NOI18N

        String pwd = sftpClient.pwd();

        sftpLogger.info(pwd);
        return pwd;
    } catch (SftpException ex) {
        LOGGER.log(Level.FINE, "Error while pwd", ex);
        sftpLogger.error(ex.getLocalizedMessage());
        throw new RemoteException(NbBundle.getMessage(SftpClient.class, "MSG_CannotPwd", configuration.getHost()), ex);
    }
}
 
Example #28
Source File: FTPUtil.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * download Via SFTP
 * <p>
 *     文件下载失败时,该方法会自动登出服务器并释放SFTP连接,然后抛出RuntimeException
 * </p>
 * @param hostname  SFTP地址
 * @param port      SFTP端口(通常为22)
 * @param username  SFTP登录用户
 * @param password  SFTP登录密码
 * @param remoteURL 保存在SFTP上的含完整路径和后缀的完整文件名
 */
public static InputStream downloadViaSFTP(String hostname, int port, String username, String password, String remoteURL){
    if(!loginViaSFTP(hostname, port, username, password, DEFAULT_SFTP_TIMEOUT)){
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "SFTP服务器登录失败");
    }
    try{
        return channelSftpMap.get().get(FilenameUtils.separatorsToUnix(remoteURL));
    }catch(SftpException e){
        logoutViaSFTP();
        throw new SeedException(CodeEnum.SYSTEM_BUSY.getCode(), "从SFTP服务器["+hostname+"]下载文件["+remoteURL+"]失败", e);
    }
}
 
Example #29
Source File: SFTPUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static SFTPConnection connectSftp(final SFTPConfiguration conf) throws JSchException, SftpException, IOException {
    final JSch jsch = new JSch();
    final Session session = SFTPUtils.createSession(conf, jsch);
    final ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
    sftp.connect();
    return new SFTPConnection(session, sftp);
}
 
Example #30
Source File: SftpCommandTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void shouldExecuteCdCommand() throws IOException, SftpException
{
    ChannelSftp channel = mock(ChannelSftp.class);
    String path = "/path";
    String result = SftpCommand.CD.execute(channel, path);
    assertNull(result);
    verify(channel).cd(path);
}