Java 我无法使sftp继续下载…在这段时间内下载了0kb的文件…我使用了VFS2。

Java 我无法使sftp继续下载…在这段时间内下载了0kb的文件…我使用了VFS2。,java,Java,我无法使SFtp连续下载…0 Kb文件正在下载之间..我使用了VFS2。虽然在windows中也会发生同样的情况,但一旦我刷新文件夹,文件就会被填满……但在Ubuntu中不会……有人能帮我解决这个问题吗。。 包com.softwareag.webmastersperformer.common.model import java.io.File; import java.io.IOException; import java.util.ArrayList; impo

我无法使SFtp连续下载…0 Kb文件正在下载之间..我使用了VFS2。虽然在windows中也会发生同样的情况,但一旦我刷新文件夹,文件就会被填满……但在Ubuntu中不会……有人能帮我解决这个问题吗。。 包com.softwareag.webmastersperformer.common.model

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Map;

    import org.apache.commons.vfs2.FileObject;
    import org.apache.commons.vfs2.FileSystemException;
    import org.apache.commons.vfs2.FileSystemOptions;
    import org.apache.commons.vfs2.Selectors;
    import org.apache.commons.vfs2.impl.StandardFileSystemManager;
    import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlTransient;
    import javax.xml.bind.annotation.XmlType;
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelSftp;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    import com.jcraft.jsch.SftpException;
    import com.softwareag.webmastersperformer.common.exception.ActionExecutionFailedException;
    import com.softwareag.webmastersperformer.common.exception.InvalidDataException;

    /**
    * This class extends from AbstractAction by providing specific implementation
    * for SFTP action type.
    * @author : YEJ
    */
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(propOrder = {
        "fileTransferMethod", "serverHostName", "serverSFTPPort",
        "serverRelativePath", "fileName", "localFilePath", "basicSettings",
        "advancedSettings"
    })
    public class SftpAction implements IAction {
        private String fileTransferMethod;

        private String serverHostName;

        private int serverSFTPPort;

        private String serverRelativePath;

        private String fileName;

        private String localFilePath;

        @XmlJavaTypeAdapter(GenericMapAdapter.class)
        private Map<String, Object> basicSettings;

        @XmlJavaTypeAdapter(GenericMapAdapter.class)
        private Map<String, Object> advancedSettings;

        @XmlTransient
        private ActionBean parent;

        @XmlTransient
        private static final Logger LOG = LoggerFactory.getLogger(SftpAction.class
            .getName());

        @XmlTransient
        private FileObject localFile;

        @XmlTransient
        private FileObject remoteFile;

        @XmlTransient
        private static StandardFileSystemManager manager;

        @XmlTransient
        private int i = 0;

        // Initializing file manager. This manager object is made one per class as
        // we
        // cannot have more than one instance of this class instance.
        static {
            try {
                manager = new StandardFileSystemManager();
                manager.init();
            } catch (FileSystemException ex) {
                // Need to log this properly
                ex.printStackTrace();
            }
        }

        /**
         * Constructor.
         */
        public SftpAction() {
            super();
            this.fileTransferMethod = "put";
            this.serverHostName = "";
            this.serverSFTPPort = 0;
            this.serverRelativePath = "";
            this.fileName = "";
            this.localFilePath = "";
        }

        /**
         * Constructor.
         * @param parent : ActionBean
         * @param fileTransferMethod : File transfer method [put/get]
         * @param serverHostName : server host name
         * @param serverSFTPPort : server SFTP port
         * @param localFilePath : local file path
         * @throws InvalidDataException : file transfer method is not given
         */
        // CHECKSTYLE:OFF
        public SftpAction(final ActionBean parent, final String fileTransferMethod,
            final String serverHostName, final int serverSFTPPort,
            final String serverRelativeFtpPath, final String fileName,
            final String localFilePath, final Map<String, Object> basicSettings)
            throws InvalidDataException {
            // CHECKSTYLE:ON
            if (fileTransferMethod == null
                || fileTransferMethod.trim().length() == 0) {
                throw new InvalidDataException(
                    "File transfer method cannot be null or empty");
            }

            System.out.println("================================================SFTPACTION() " + serverHostName);
            this.setParent(parent);
            this.setFileTransferMethod(fileTransferMethod);
            this.setServerHostName(serverHostName);
            this.setServerSFTPPort(serverSFTPPort);
            this.setServerRelativePath(serverRelativeFtpPath);
            this.setFileName(fileName);
            this.setLocalFilePath(localFilePath);
            this.setBasicSettings(basicSettings);

            this.createClient();
        }

        /**
         * Create a client.
         * @throws InvalidDataException : InvalidDataException
         */
        public final void createClient() throws InvalidDataException {
            try {
                if (fileTransferMethod.equalsIgnoreCase("put")) {
                    final File file = new File(this.localFilePath + File.separator
                        + this.fileName);
                    if (!file.exists()) {
                        throw new RuntimeException("Error: Local file "
                            + file.getAbsolutePath() + " not found");
                    }

                    try {
                        // Put : Create local file object
                        localFile = manager.resolveFile(file.getAbsolutePath());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    // Get : Create remote file object
    //                remoteFile = manager.resolveFile(
    //                    createConnectionString(
    //                        (this.serverHostName + ":" + this.serverSFTPPort), this
    //                            .getBasicSettings().get(Constants.USERNAME)
    //                            .toString(),
    //                        this.getBasicSettings().get(Constants.PASSWORD)
    //                            .toString(), (this.serverRelativePath
    //                            + File.separator + this.fileName)),
    //                    createDefaultOptions());
                    remoteFile = manager.resolveFile(
                        createConnectionString(
                            "10.60.24.218:9876", "perfuser", "manage", ("1MB.txt")),
                        createDefaultOptions());
                }
            } catch (FileSystemException ex) {
                ex.printStackTrace();
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final boolean execute() throws ActionExecutionFailedException {
            if (getFileTransferMethod().equalsIgnoreCase("put")) {
                this.put();
            } else {
                this.get();
            }

            return true;
        }

        // Method to upload a file in Remote server
        public void put() {
            try {
                // Create remote file object
                remoteFile = manager
                    .resolveFile(
                        createConnectionString(
                            (this.serverHostName + ":" + this.serverSFTPPort), this
                                .getBasicSettings().get(Constants.USERNAME)
                                .toString(),
                            this.getBasicSettings().get(Constants.PASSWORD)
                                .toString(), (this.serverRelativePath + "/"
                                + this.fileName + "_" + i++)),
                        createDefaultOptions());

                // Copy local file to sftp server
                remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }


        // Download file function:
        public void get() {
            try {
                String downloadFilePath = this.localFilePath + File.separator
                    + this.fileName + "_" + i++;

                // Create local file object
                localFile = manager.resolveFile(downloadFilePath);

                // Copy local file to sftp server
                localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final ActionBean getParent() {
            return this.parent;
        }

        /**
         * @return the fileTransferMethod
         */
        public final String getFileTransferMethod() {
            return this.fileTransferMethod;
        }

        /**
         * @return the serverHostName
         */
        public final String getServerHostName() {
            return this.serverHostName;
        }

        public final int getServerSFTPPort() {
            return this.serverSFTPPort;
        }

        /**
         * @return the localFilePath
         */
        public final String getLocalFilePath() {
            return this.localFilePath;
        }

        /**
         * @return the local file name
         */
        public final String getFileName() {
            return this.fileName;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final String getActionName() {
            return this.parent.getActionName();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final String getActionDescription() {
            return this.parent.getDescription();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final ActionType getActionType() {
            return this.parent.getActionType();
        }

        @Override
        public final Map<String, Object> getBasicSettings() {
            return this.basicSettings;
        }

        @Override
        public final Map<String, Object> getAdvancedSettings() {
            return this.advancedSettings;
        }

        @Override
        public final Map<String, ArrayList<String>> getParameterisedData() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public final String getPayloadData() throws IOException {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public final RequestResponseHolder getRequestResponse()
            throws ActionExecutionFailedException {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void addParameter(final String parameterName,
            final ArrayList<String> parameterValues) {
            // TODO Auto-generated method stub

        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final void setParent(final ActionBean action)
            throws InvalidDataException {
            if (null == action) {
                throw new InvalidDataException(
                    "Invalid Parent. ActionBean cannot be null");
            }
            this.parent = action;
        }

        /**
         * @param fileTransferMethod : file transfer method to set
         * @throws InvalidDataException if file transfer method is null or empty
         */
        public final void setFileTransferMethod(final String fileTransferMethod)
            throws InvalidDataException {
            this.fileTransferMethod = fileTransferMethod;
        }

        /**
         * @param serverURL : the server URL to set
         * @throws InvalidDataException if server URL is null or empty
         */
        public final void setServerHostName(String serverURL)
            throws InvalidDataException {
            serverURL = "10.60.24.218:9876";
            if (serverURL == null || serverURL.trim().length() == 0) {
                throw new InvalidDataException("Server URL cannot be null or empty");
            }
            this.serverHostName = serverURL;
        }

        public final void setServerSFTPPort(final int serverSFTPPort) {
            this.serverSFTPPort = serverSFTPPort;
        }

        /**
         * @param localFilePath : local file path to set
         * @throws InvalidDataException if local file null or empty
         */
        public final void setLocalFilePath(final String localFilePath)
            throws InvalidDataException {
            if (localFilePath == null || localFilePath.trim().length() == 0
            /* || !(new File(localFilePath).exists()) */) {
                throw new InvalidDataException(
                    "Local file path cannot be null or empty or invalid");
            }

            this.localFilePath = localFilePath;
        }

        @Override
        public final void setBasicSettings(final Map<String, Object> basicSettings)
            throws InvalidDataException {
            this.basicSettings = basicSettings;
        }

        @Override
        public final void setAdvancedSettings(
            final Map<String, Object> advancedSettings) {
            this.advancedSettings = advancedSettings;
        }

        @Override
        public void setPayload(final String payload) throws InvalidDataException {
            // TODO Auto-generated method stub

        }

        @Override
        public void modifyURL(final String newHost, final int newPort)
            throws InvalidDataException {
            // TODO Auto-generated method stub

        }

        /**
         * This method is used to set the new file name from the parameter file for
         * each action.
         * @param newFileName : new file name
         */
        public final void setFileName(final String newFileName) {
            this.fileName = newFileName;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final SftpAction copyAction() {
            /*
             * Cloning the action Note: Cloned action will not contain parameterized
             * map
             */
            SftpAction clonedAction = null;
            try {
                clonedAction = new SftpAction();
                clonedAction.setParent(this.getParent());
                clonedAction.setFileTransferMethod(this.getFileTransferMethod());
                clonedAction.setServerHostName(this.getServerHostName());
                clonedAction.setServerSFTPPort(this.getServerSFTPPort());
                clonedAction.setServerRelativePath(this.getServerRelativePath());
                clonedAction.setFileName(this.getFileName());
                clonedAction.setLocalFilePath(this.getLocalFilePath());
                clonedAction.setBasicSettings(this.getBasicSettings());
            } catch (InvalidDataException e) {
                e.printStackTrace();
                LOG.error(e.getMessage());
            }
            return clonedAction;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void stopExecution() {
            // nothing to do
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public final void shutdown() {
            if (this.manager != null) {
                this.manager.close();
            }
        }

        public String getServerRelativePath() {
            return serverRelativePath;
        }

        public void setServerRelativePath(String serverRelativePath) {
            this.serverRelativePath = serverRelativePath;
        }

        // Establishing connection
        private String createConnectionString(String hostName, String username,
            String password, String remoteFilePath) {
            return "sftp://" + username + ":" + password + "@" + hostName + "/"
                + remoteFilePath;
        }

        // Method to setup default SFTP config:
        private FileSystemOptions createDefaultOptions() throws FileSystemException {
            // Create SFTP options
            FileSystemOptions opts = new FileSystemOptions();

            // SSH Key checking
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
                opts, "no");

            // Root directory set to user home
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);

            // Timeout is count by Milliseconds
            SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

            return opts;
        }
    }
导入java.io.File;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.Map;
导入org.apache.commons.vfs2.FileObject;
导入org.apache.commons.vfs2.FileSystemException;
导入org.apache.commons.vfs2.FileSystemOptions;
导入org.apache.commons.vfs2.Selectors;
导入org.apache.commons.vfs2.impl.StandardFileSystemManager;
导入org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
导入javax.xml.bind.annotation.XmlAccessType;
导入javax.xml.bind.annotation.XmlAccessorType;
导入javax.xml.bind.annotation.XmlRootElement;
导入javax.xml.bind.annotation.XmlTransient;
导入javax.xml.bind.annotation.XmlType;
导入javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
导入com.jcraft.jsch.Channel;
导入com.jcraft.jsch.ChannelSftp;
导入com.jcraft.jsch.jsch;
导入com.jcraft.jsch.JSchException;
导入com.jcraft.jsch.Session;
导入com.jcraft.jsch.SftpException;
导入com.softwareag.webmastersperformer.common.exception.ActionExecutionFailedException;
导入com.softwareag.webmastersperformer.common.exception.InvalidDataException;
/**
*这个类通过提供特定的实现从AbstractAction扩展而来
*对于SFTP操作类型。
*@作者:YEJ
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(比例器={
“fileTransferMethod”、“serverHostName”、“ServerSFtport”,
“服务器相对路径”、“文件名”、“本地文件路径”、“基本设置”,
“高级设置”
})
公共类SFTPATION实现IAction{
私有字符串文件传输方法;
私有字符串服务器主机名;
私有int服务器支持;
私有字符串serverRelativePath;
私有字符串文件名;
私有字符串localFilePath;
@XmlJavaTypeAdapter(GenericMapAdapter.class)
私有地图基础设置;
@XmlJavaTypeAdapter(GenericMapAdapter.class)
私人地图设置;
@XmlTransient
私人行动豆父母;
@XmlTransient
私有静态最终记录器日志=LoggerFactory.getLogger(SftpAction.class
.getName());
@XmlTransient
私有文件对象本地文件;
@XmlTransient
私有文件对象远程文件;
@XmlTransient
私有静态标准文件系统管理器;
@XmlTransient
私有整数i=0;
//正在初始化文件管理器。此管理器对象根据需要为每个类创建一个
//我们
//此类实例不能有多个实例。
静止的{
试一试{
manager=新的标准文件系统管理器();
manager.init();
}捕获(FileSystemException ex){
//需要正确地记录这个
例如printStackTrace();
}
}
/**
*构造器。
*/
公共事务委员会(){
超级();
this.fileTransferMethod=“put”;
this.serverHostName=“”;
this.serverSFTPPort=0;
this.serverRelativePath=“”;
this.fileName=“”;
this.localFilePath=“”;
}
/**
*构造器。
*@param-parent:ActionBean
*@param fileTransferMethod:文件传输方法[put/get]
*@param serverHostName:服务器主机名
*@param serverSFTPPort:服务器SFTP端口
*@param localFilePath:本地文件路径
*@Trows InvalidDataException:未提供文件传输方法
*/
//检查样式:关闭
公共SftpAction(最终ActionBean父级、最终字符串fileTransferMethod、,
最终字符串serverHostName,最终int serversftport,
最终字符串ServerRelativeFTPath,最终字符串文件名,
最终字符串localFilePath,最终映射基本设置)
抛出InvalidDataException{
//CHECKSTYLE:ON
如果(fileTransferMethod==null
||fileTransferMethod.trim().length()=0){
抛出新的InvalidDataException(
“文件传输方法不能为null或空”);
}
System.out.println(“========================================================================sftpackation()”+服务器主机名);
这个.setParent(parent);
此.setFileTransferMethod(fileTransferMethod);
此.setServerHostName(服务器主机名);
此.setServerSFtport(ServerSFtport);
此.setServerRelativePath(ServerRelativeFTPath);
此.setFileName(文件名);
this.setLocalFilePath(localFilePath);
这是一个基本设置(basicSettings);
这个.createClient();
}
/**
*创建一个客户端。
*@InvalidDataException:InvalidDataException
*/
public final void createClient()引发InvalidDataException{
试一试{
if(fileTransferMethod.equalsIgnoreCase(“put”)){
最终文件=新文件(this.localFilePath+File.separator
+此文件名为“.fileName”);
如果(!file.exists()){
抛出新运行时异常(“错误:本地文件”
+getAbsolutePath()+“未找到”);
}
试一试{