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

The following examples show how to use com.jcraft.jsch.ChannelSftp#get() . 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: SFTPTransfer.java    From localization_nifi with Apache License 2.0 10 votes vote down vote up
@Override
public InputStream getInputStream(final String remoteFileName, final FlowFile flowFile) throws IOException {
    final ChannelSftp sftp = getChannel(flowFile);
    try {
        return sftp.get(remoteFileName);
    } catch (final SftpException e) {
        switch (e.id) {
            case ChannelSftp.SSH_FX_NO_SUCH_FILE:
                throw new FileNotFoundException("Could not find file " + remoteFileName + " on remote SFTP Server");
            case ChannelSftp.SSH_FX_PERMISSION_DENIED:
                throw new PermissionDeniedException("Insufficient permissions to read file " + remoteFileName + " from remote SFTP Server", e);
            default:
                throw new IOException("Failed to obtain file content for " + remoteFileName, e);
        }
    }
}
 
Example 2
Source File: SftpSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void work() throws IOException, CancellationException, JSchException, SftpException, ExecutionException, InterruptedException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "{0} started", getTraceName());
    }
    ChannelSftp cftp = getChannel();
    RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("download", srcFileName); // NOI18N
    try {
        cftp.get(srcFileName, dstFileName);
    } catch (SftpException e) {
        if (MiscUtils.mightBrokeSftpChannel(e)) {
            cftp.quit();
        }
        throw decorateSftpException(e, srcFileName);
    } finally {
        releaseChannel(cftp);
        RemoteStatistics.stopChannelActivity(activityID, new File(dstFileName).length());
    }
}
 
Example 3
Source File: SSHShell.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Downloads the content of a file from the remote host as a String.
 *
 * @param fileName the name of the file for which the content will be downloaded
 * @param fromPath the path of the file for which the content will be downloaded
 * @param isUserHomeBased true if the path of the file is relative to the user's home directory
 * @return the content of the file
 * @throws Exception exception thrown
 */
public String download(String fileName, String fromPath, boolean isUserHomeBased) throws Exception {
    ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp");
    channel.connect();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    BufferedOutputStream buff = new BufferedOutputStream(outputStream);
    String absolutePath = isUserHomeBased ? channel.getHome() + "/" + fromPath : fromPath;
    channel.cd(absolutePath);
    channel.get(fileName, buff);

    channel.disconnect();

    return outputStream.toString();
}
 
Example 4
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 5
Source File: SftpFileUtil.java    From Leo with Apache License 2.0 6 votes vote down vote up
/**
     * 下载指定的文档内容,保存到指定位置,返回文件内容
     * @param filepath
     * @param savepath
     * @return  String
     */
    public  String getFile(String filepath,String savepath) {
 		String strtmp=null;
    	InputStream  input;
 		ChannelSftp channel=getChannel();
 		try {
 			input=channel.get(filepath);
 			strtmp=FileUtil.readInputStreamToString(input, "UTF-8");
 			if (null!=savepath && savepath.length()>0) {
 				FileUtil.writeString(strtmp, savepath, "UTF-8");
			}
// 			log.info("从文件"+filepath+"获取信息成功");
 		} catch (SftpException e) {
 			log.error("从文件"+filepath+"获取信息失败");
 			log.error(e.getMessage());
 		}finally {
// 			channel.quit();
        }
 		
 		return strtmp;		
 	
 	}
 
Example 6
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 抓遠端檔案然後存到本機 , 單筆
 * 
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param remoteFile
 * @param localFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void get(String user, String password, String addr, int port, 
		String remoteFile, String localFile) throws JSchException, SftpException, Exception {
			
	Session session = getSession(user, password, addr, port);
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	logger.info("get remote file: " + remoteFile + " write to:" + localFile );	
	try {
		sftpChannel.get(remoteFile, localFile);
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();			
	}
	File f=new File(localFile);
	if (!f.exists()) {
		f=null;
		logger.error("get remote file:"+remoteFile + " fail!");
		throw new Exception("get remote file:"+remoteFile + " fail!");
	}
	f=null;
	logger.info("success write:" + localFile);
}
 
Example 7
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 抓遠端檔案然後存到本機 , 多筆
 * 
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param remoteFile
 * @param localFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void get(String user, String password, String addr, int port, 
		List<String> remoteFile, List<String> localFile) throws JSchException, SftpException, Exception {
			
	Session session = getSession(user, password, addr, port);	
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (int i=0; i<remoteFile.size(); i++) {
			String rf=remoteFile.get(i);
			String lf=localFile.get(i);
			logger.info("get remote file: " + rf + " write to:" + lf );
			sftpChannel.get(rf, lf);
			File f=new File(lf);
			if (!f.exists()) {
				f=null;
				logger.error("get remote file:"+rf + " fail!");
				throw new Exception("get remote file:"+rf + " fail!");
			}
			f=null;
			logger.info("success write:" + lf);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}
}
 
Example 8
Source File: SFTPRepository.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
public InputStream openStream(SFTPResource resource) throws IOException {
    ChannelSftp c = getSftpChannel(resource.getName());
    try {
        String path = getPath(resource.getName());
        return c.get(path);
    } catch (SftpException | URISyntaxException e) {
        throw new IOException("impossible to open stream for " + resource + " on "
                + getHost() + (e.getMessage() != null ? ": " + e.getMessage() : ""), e);
    }
}
 
Example 9
Source File: SFTPRepository.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
public void get(String source, File destination) throws IOException {
    fireTransferInitiated(getResource(source), TransferEvent.REQUEST_GET);
    ChannelSftp c = getSftpChannel(source);
    try {
        String path = getPath(source);
        c.get(path, destination.getAbsolutePath(), new MyProgressMonitor());
    } catch (SftpException | URISyntaxException e) {
        throw new IOException("impossible to get " + source + " on " + getHost()
                + (e.getMessage() != null ? ": " + e.getMessage() : ""), e);
    }
}
 
Example 10
Source File: CommandDelegatorMethods.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method downloads a single file
 * @param channelSftp
 * @param remoteFilePath remote file (not directory) path
 * @param localDirPath
 * @throws SftpException
 */
private void downloadSingleFile(ChannelSftp channelSftp, String remoteFilePath,
		String localDirPath, String user) throws SftpException {
	new File(localDirPath).mkdirs();
	changeOwnership(localDirPath, user);
	channelSftp.get(remoteFilePath, localDirPath + File.separator + Paths.get(remoteFilePath).getFileName().toString());
	changeOwnership(localDirPath + File.separator + Paths.get(remoteFilePath).getFileName().toString(), user);
}
 
Example 11
Source File: SftpLightWeightFileSystem.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public FSDataInputStream open(Path path, int bufferSize) throws IOException {
  SftpGetMonitor monitor = new SftpGetMonitor();
  try {
    ChannelSftp channelSftp = this.fsHelper.getSftpChannel();
    InputStream is = channelSftp.get(HadoopUtils.toUriPath(path), monitor);
    return new FSDataInputStream(new BufferedFSInputStream(new SftpFsHelper.SftpFsFileInputStream(is, channelSftp), bufferSize));
  } catch (SftpException e) {
    throw new IOException(e);
  }
}
 
Example 12
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a get SftpCommand and returns an input stream to the file
 * @param cmd is the command to execute
 * @param sftp is the channel to execute the command on
 * @throws SftpException
 */
@Override
public InputStream getFileStream(String file) throws FileBasedHelperException {
  SftpGetMonitor monitor = new SftpGetMonitor();
  try {
    ChannelSftp channel = getSftpChannel();
    return new SftpFsFileInputStream(channel.get(file, monitor), channel);
  } catch (SftpException e) {
    throw new FileBasedHelperException("Cannot download file " + file + " due to " + e.getMessage(), e);
  }
}
 
Example 13
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
    channelSftp.get(remoteFile, localDir + "jschFile.txt");
    channelSftp.exit();
}
 
Example 14
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 15
Source File: SftpFileObject.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an input stream to read the file content from.
 */
@SuppressWarnings("resource")
@Override
protected InputStream doGetInputStream(final int bufferSize) throws Exception {
    // VFS-113: avoid npe
    synchronized (getAbstractFileSystem()) {
        final ChannelSftp channel = getAbstractFileSystem().getChannel();
        try {
            // return channel.get(getName().getPath());
            // hmmm - using the in memory method is soooo much faster ...

            // TODO - Don't read the entire file into memory. Use the
            // stream-based methods on ChannelSftp once they work properly

            /*
             * final ByteArrayOutputStream outstr = new ByteArrayOutputStream(); channel.get(relPath, outstr);
             * outstr.close(); return new ByteArrayInputStream(outstr.toByteArray());
             */

            InputStream inputStream;
            try {
                // VFS-210: sftp allows to gather an input stream even from a directory and will
                // fail on first read. So we need to check the type anyway
                if (!getType().hasContent()) {
                    throw new FileSystemException("vfs.provider/read-not-file.error", getName());
                }

                inputStream = channel.get(relPath);
            } catch (final SftpException e) {
                if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
                    throw new FileNotFoundException(getName());
                }

                throw new FileSystemException(e);
            }

            return new SftpInputStream(channel, inputStream, bufferSize);

        } finally {
            // getAbstractFileSystem().putChannel(channel);
        }
    }
}
 
Example 16
Source File: SFTPUtils.java    From axelor-open-suite with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Returns an {@link InputStream} corresponding to given {@code absoluteFilePath} in remote
 * server.
 */
public static InputStream get(ChannelSftp channel, String absoluteFilePath) throws SftpException {
  return channel.get(absoluteFilePath);
}