Search in sources :

Example 26 with FileTransferException

use of com.axway.ats.common.filetransfer.FileTransferException in project ats-framework by Axway.

the class FtpClient method connect.

/**
 * Connect to a remote host using basic authentication
 *
 * @param hostname
 *            the host to connect to
 * @param userName
 *            the user name
 * @param password
 *            the password for the provided user name
 * @throws FileTransferException
 */
@Override
public void connect(String hostname, String userName, String password) throws FileTransferException {
    log.info("Connecting to " + hostname + " on port " + this.port + " using username " + userName + " and password " + password);
    // make new FTP object for every new connection
    disconnect();
    this.ftpConnection = new org.apache.commons.net.ftp.FTPClient();
    /* 
         * When uploading/downloading file with encoding that the server does not, the server will return 452.
         * So we have to either set the control encoding to UTF-8 (or the one that is desired), or if the needed encoding is UTF-8,
         * set the UTF-8 autodetect to true
        */
    String controlEncoding = CoreLibraryConfigurator.getInstance().getFtpControlEncoding();
    boolean autodetectUTF8 = Boolean.valueOf(CoreLibraryConfigurator.getInstance().getFtpAutodetectUTF8());
    if (!StringUtils.isNullOrEmpty(controlEncoding)) {
        this.ftpConnection.setControlEncoding(controlEncoding);
        if (log.isDebugEnabled()) {
            log.debug("Control encoding is set to " + controlEncoding);
        }
    }
    this.ftpConnection.setAutodetectUTF8(autodetectUTF8);
    if (log.isDebugEnabled()) {
        log.debug("Autodetect for UTF-8 is " + ((autodetectUTF8) ? "enabled" : "disabled"));
    }
    if (!"UTF-8".equalsIgnoreCase(controlEncoding) && autodetectUTF8) {
        log.warn("Autodetecting UTF-8 is enabled, but additionaly, the control encoding is set to '" + controlEncoding + "'. UTF-8 will be used.");
    }
    if (this.listener != null) {
        this.listener.setResponses(new ArrayList<String>());
        this.ftpConnection.addProtocolCommandListener(((FtpResponseListener) listener));
    }
    /* if debug mode is true, we log messages from all levels */
    if (isDebugMode()) {
        this.ftpConnection.addProtocolCommandListener(new FtpListener());
    }
    try {
        this.ftpConnection.setConnectTimeout(this.timeout);
        // connect to the host
        this.ftpConnection.connect(hostname, this.port);
        // login to the host
        if (!this.ftpConnection.login(userName, password)) {
            throw new Exception("Invallid username and/or password");
        }
        // enter passive mode
        this.ftpConnection.enterLocalPassiveMode();
        // set transfer mode
        if (this.transferMode == TransferMode.ASCII) {
            if (!this.ftpConnection.setFileType(org.apache.commons.net.ftp.FTPClient.ASCII_FILE_TYPE)) {
                throw new Exception("Unable to set transfer mode to ASCII");
            }
        } else {
            if (!this.ftpConnection.setFileType(org.apache.commons.net.ftp.FTPClient.BINARY_FILE_TYPE)) {
                throw new Exception("Unable to set transfer mode to BINARY");
            }
        }
    } catch (Exception e) {
        String errMessage = "Unable to connect to  " + hostname + " on port " + this.port + " using username " + userName + " and password " + password;
        log.error(errMessage, e);
        throw new FileTransferException(e);
    }
    log.info("Successfully connected to " + hostname + " on port " + this.port + " using username " + userName + " and password " + password);
}
Also used : FtpListener(com.axway.ats.core.filetransfer.model.ftp.FtpListener) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) FtpResponseListener(com.axway.ats.core.filetransfer.model.ftp.FtpResponseListener) IOException(java.io.IOException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException)

Example 27 with FileTransferException

use of com.axway.ats.common.filetransfer.FileTransferException in project ats-framework by Axway.

the class SftpClient method performUploadFile.

@Override
protected void performUploadFile(String localFile, String remoteDir, String remoteFile) throws FileTransferException {
    checkConnected("file upload");
    FileInputStream fis = null;
    try {
        String remoteFileAbsPath = null;
        remoteDir = remoteDir.replace("\\", "/");
        remoteFile = remoteFile.replace("\\", "/");
        if (remoteDir.endsWith("/") && remoteFile.endsWith("/")) {
            remoteFileAbsPath = remoteDir.substring(0, remoteDir.length() - 2) + remoteFile;
        } else if (!remoteDir.endsWith("/") && !remoteFile.endsWith("/")) {
            remoteFileAbsPath = remoteDir + "/" + remoteFile;
        } else {
            remoteFileAbsPath = remoteDir + remoteFile;
        }
        // upload the file
        File file = new File(localFile);
        fis = new FileInputStream(file);
        if (synchronizationSftpTransferListener != null) {
            this.channel.put(fis, remoteFileAbsPath, synchronizationSftpTransferListener);
        } else if (isDebugMode() && debugProgressMonitor != null) {
            debugProgressMonitor.setTransferMetadata(localFile, remoteFileAbsPath, file.length());
            this.channel.put(fis, remoteFileAbsPath, debugProgressMonitor);
        } else {
            this.channel.put(fis, remoteFileAbsPath);
        }
    } catch (SftpException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } catch (FileNotFoundException e) {
        log.error("Unable to find the file that needs to be uploaded!", e);
        throw new FileTransferException(e);
    } finally {
        // close the file input stream
        IoUtils.closeStream(fis, "Unable to close the file stream after successful upload!");
    }
    if (remoteDir != null && !remoteDir.endsWith("/")) {
        remoteDir += "/";
    }
    log.info("Successfully uploaded '" + localFile + "' to '" + remoteDir + remoteFile + "', host " + this.hostname);
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) SftpException(com.jcraft.jsch.SftpException) FileNotFoundException(java.io.FileNotFoundException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 28 with FileTransferException

use of com.axway.ats.common.filetransfer.FileTransferException in project ats-framework by Axway.

the class SftpClient method doConnect.

private void doConnect() throws FileTransferException {
    // make new SFTP object for every new connection
    disconnect();
    /* NOTE: Due to logging being global (static), if one thread enables debug mode, all threads will log messages,
         * and if another thread disables it, logging will be stopped for all threads,
         * until at least one thread enables it again
         */
    if (isDebugMode()) {
        JSch.setLogger(new SftpListener());
        debugProgressMonitor = new SftpFileTransferProgressMonitor();
    } else {
        debugProgressMonitor = null;
    }
    try {
        addHostKeyRepository();
        if (username != null) {
            this.session = jsch.getSession(this.username, this.hostname, this.port);
        }
        this.session.setPassword(this.password);
        if (!StringUtils.isNullOrEmpty(this.keyStoreFile)) {
            byte[] privateKeyContent = getPrivateKeyContent();
            this.jsch.addIdentity("client_prvkey", privateKeyContent, null, null);
        }
        // The internally used client version 'SSH-2.0-JSCH-0.1.54' needs to be changed to 'SSH-2.0-OpenSSH_2.5.3'
        this.session.setClientVersion("SSH-2.0-OpenSSH_2.5.3");
        /**
         * if no trust server certificate or trust store are provided, do not check if hostname is in known hosts *
         */
        if (StringUtils.isNullOrEmpty(this.trustedServerSSLCerfiticateFile) && StringUtils.isNullOrEmpty(this.trustStoreFile)) {
            // skip checking of known hosts and verifying RSA keys
            this.session.setConfig("StrictHostKeyChecking", "no");
        }
        // make keyboard-interactive last authentication method
        this.session.setConfig("PreferredAuthentications", "publickey,password,keyboard-interactive");
        this.session.setTimeout(this.timeout);
        if (this.ciphers != null && this.ciphers.size() > 0) {
            StringBuilder ciphers = new StringBuilder();
            for (SshCipher cipher : this.ciphers) {
                ciphers.append(cipher.getSshAlgorithmName() + ",");
            }
            this.session.setConfig("cipher.c2s", ciphers.toString());
            this.session.setConfig("cipher.s2c", ciphers.toString());
            this.session.setConfig("CheckCiphers", ciphers.toString());
        }
        if (this.listener != null) {
            this.listener.setResponses(new ArrayList<String>());
            JSch.setLogger((com.jcraft.jsch.Logger) this.listener);
        }
        /* 
             * SFTP reference implementation does not support transfer mode.
               Due to that, JSch does not support it either.
               For now setTransferMode() has no effect. It may be left like that,
               implemented to throw new FileTransferException( "Not implemented" )
               or log warning, that SFTP protocol does not support transfer mode change.
            */
        this.session.connect();
        this.channel = (ChannelSftp) this.session.openChannel("sftp");
        this.channel.connect();
    } catch (Exception e) {
        String errMessage = "Unable to connect to  " + hostname + " on port " + this.port + " using username " + username + " and password " + password;
        log.error(errMessage, e);
        throw new FileTransferException(e);
    }
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) SshCipher(com.axway.ats.common.filetransfer.SshCipher) SftpListener(com.axway.ats.core.filetransfer.model.ftp.SftpListener) SftpFileTransferProgressMonitor(com.axway.ats.core.filetransfer.model.ftp.SftpFileTransferProgressMonitor) SftpException(com.jcraft.jsch.SftpException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) JSchException(com.jcraft.jsch.JSchException)

Example 29 with FileTransferException

use of com.axway.ats.common.filetransfer.FileTransferException in project ats-framework by Axway.

the class FtpsClient method executeCommand.

/**
 * Currently not supporting commands requiring opening of data connection
 * @param command the command to run
 * @return String representing the return code
 * @throws FileTransferException
 */
@Override
public String executeCommand(String command) throws FileTransferException {
    log.info("Run '" + command + "'");
    String returnCode = "";
    try {
        returnCode = String.valueOf(this.ftpsConnection.sendCommand(command));
    } catch (IOException e) {
        log.error("Error running command: '" + command + "'", e);
        throw new FileTransferException(e);
    }
    log.info("Return code is '" + returnCode + "'");
    return returnCode;
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) IOException(java.io.IOException)

Example 30 with FileTransferException

use of com.axway.ats.common.filetransfer.FileTransferException in project ats-framework by Axway.

the class FtpsClient method disconnect.

/**
 * Disconnect from the remote host
 *
 * @throws FileTransferException
 */
@Override
public void disconnect() throws FileTransferException {
    if (this.ftpsConnection != null && this.ftpsConnection.isConnected()) {
        try {
            this.ftpsConnection.disconnect();
            this.ftpsConnection = null;
        } catch (IOException e) {
            throw new FileTransferException(e);
        }
    }
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) IOException(java.io.IOException)

Aggregations

FileTransferException (com.axway.ats.common.filetransfer.FileTransferException)36 IOException (java.io.IOException)16 File (java.io.File)11 BaseTest (com.axway.ats.action.BaseTest)7 Test (org.junit.Test)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 FileOutputStream (java.io.FileOutputStream)6 HttpEntity (org.apache.http.HttpEntity)5 HttpResponse (org.apache.http.HttpResponse)5 ClientProtocolException (org.apache.http.client.ClientProtocolException)5 CertificateException (java.security.cert.CertificateException)4 PublicAtsApi (com.axway.ats.common.PublicAtsApi)3 IFileTransferClient (com.axway.ats.core.filetransfer.model.IFileTransferClient)3 SftpException (com.jcraft.jsch.SftpException)3 FileInputStream (java.io.FileInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 OutputStream (java.io.OutputStream)3 HttpGet (org.apache.http.client.methods.HttpGet)3 HttpPost (org.apache.http.client.methods.HttpPost)3 SshCipher (com.axway.ats.common.filetransfer.SshCipher)2