Search in sources :

Example 1 with FileTransferException

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

the class HttpClient method processHttpRequest.

/**
     * Perform prepared request and optionally return the response
     * @param httpRequest HttpGet, HttpPost etc
     * @param needResponse do we need the response, if false - then null is returned
     * @return the response from the request as an {@link InputStream} or a {@link String} object
     * @throws FileTransferException
     */
private Object processHttpRequest(HttpUriRequest httpRequest, boolean needResponse, boolean returnAsString) throws FileTransferException {
    HttpEntity responseEntity = null;
    boolean responseNotConsumed = true;
    OutputStream outstream = null;
    String errMsg = "Unable to complete request!";
    String responseAsString = null;
    InputStream responseAsStream = null;
    try {
        // send request
        HttpResponse response = httpClient.execute(httpRequest, httpContext);
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new FileTransferException("Request to '" + httpRequest.getURI() + "' returned " + response.getStatusLine());
        }
        // get the response
        responseEntity = response.getEntity();
        if (!needResponse) {
            responseNotConsumed = true;
        } else {
            if (responseEntity != null) {
                if (!returnAsString) {
                    responseAsStream = responseEntity.getContent();
                } else {
                    int respLengthEstimate = (int) responseEntity.getContentLength();
                    if (respLengthEstimate < 0) {
                        respLengthEstimate = 1024;
                    }
                    outstream = new ByteArrayOutputStream(respLengthEstimate);
                    responseEntity.writeTo(outstream);
                    outstream.flush();
                    responseAsString = outstream.toString();
                }
                responseNotConsumed = false;
            }
        }
    } catch (ClientProtocolException e) {
        log.error(errMsg, e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error(errMsg, e);
        throw new FileTransferException(e);
    } finally {
        if (responseEntity != null && outstream != null) {
            IoUtils.closeStream(outstream);
        }
        if (responseNotConsumed) {
            try {
                // We were not able to properly stream the entity content to the local file system.
                // The next line consumes the entity content closes the underlying stream.
                EntityUtils.consume(responseEntity);
            } catch (IOException e) {
            // we tried our best to release the resources
            }
        }
    }
    log.info("Successfully completed GET request '" + httpRequest.getURI() + "'");
    if (returnAsString) {
        return responseAsString;
    }
    return responseAsStream;
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 2 with FileTransferException

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

the class HttpClient method performUploadFile.

@Override
protected void performUploadFile(String localFile, String remoteDir, String remoteFile) throws FileTransferException {
    checkClientInitialized();
    final String uploadUrl = constructUploadUrl(remoteDir, remoteFile);
    log.info("Uploading " + uploadUrl);
    HttpEntityEnclosingRequestBase uploadMethod;
    Object uploadMethodObject = customProperties.get(HTTP_HTTPS_UPLOAD_METHOD);
    if (uploadMethodObject == null || !uploadMethodObject.toString().equals(HTTP_HTTPS_UPLOAD_METHOD__POST)) {
        uploadMethod = new HttpPut(uploadUrl);
    } else {
        uploadMethod = new HttpPost(uploadUrl);
    }
    String contentType = DEFAULT_HTTP_HTTPS_UPLOAD_CONTENT_TYPE;
    Object contentTypeObject = customProperties.get(HTTP_HTTPS_UPLOAD_CONTENT_TYPE);
    if (contentTypeObject != null) {
        contentType = contentTypeObject.toString();
    }
    FileEntity fileUploadEntity = new FileEntity(new File(localFile), ContentType.parse(contentType));
    uploadMethod.setEntity(fileUploadEntity);
    HttpResponse response = null;
    try {
        // add headers specified by the user
        addRequestHeaders(uploadMethod);
        // upload the file
        response = httpClient.execute(uploadMethod, httpContext);
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode < 200 || responseCode > 206) {
            // 204 No Content - there was a file with same name on same location, we replaced it
            throw new FileTransferException("Uploading '" + uploadUrl + "' returned '" + response.getStatusLine() + "'");
        }
    } catch (ClientProtocolException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error("Unable to upload file!", e);
        throw new FileTransferException(e);
    } finally {
        // the UPLOAD returns response body on error
        if (response != null && response.getEntity() != null) {
            HttpEntity responseEntity = response.getEntity();
            // the underlying stream has been closed
            try {
                EntityUtils.consume(responseEntity);
            } catch (IOException e) {
            // we tried our best to release the resources
            }
        }
    }
    log.info("Successfully uploaded '" + localFile + "' to '" + remoteDir + remoteFile + "', host " + this.hostname);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) FileEntity(org.apache.http.entity.FileEntity) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpPut(org.apache.http.client.methods.HttpPut) ClientProtocolException(org.apache.http.client.ClientProtocolException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) File(java.io.File)

Example 3 with FileTransferException

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

the class HttpClient method performPostRequest.

/**
     * Perform HTTP POST request based on the host and port specified before
     *
     * @param requestedHostRelativeUrl location/query without host and port like: "/my_dir/res?myParam=1"
     * @param needResponse whether caller needs the contents returned from this request
     * @param paramsMap map of parameters to be sent with this POST request
     * @throws FileTransferException
     */
public String performPostRequest(String requestedHostRelativeUrl, boolean needResponse, HashMap<String, String> paramsMap) throws FileTransferException {
    checkClientInitialized();
    final String getUrl = constructGetUrl(requestedHostRelativeUrl);
    log.info("Performing POST request to: " + getUrl);
    HttpPost postMethod = new HttpPost(getUrl);
    addRequestHeaders(postMethod);
    if (paramsMap != null && paramsMap.size() > 0) {
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(paramsMap.size());
        for (Entry<String, String> paramEntry : paramsMap.entrySet()) {
            log.info("Add parameter " + paramEntry.getKey() + " and value: " + paramEntry.getValue());
            parameters.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
        }
        UrlEncodedFormEntity sendEntity = null;
        try {
            sendEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new FileTransferException(ex);
        }
        postMethod.setEntity(sendEntity);
    }
    return (String) processHttpRequest(postMethod, needResponse, true);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 4 with FileTransferException

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

the class HttpClient method addRequestHeaders.

private void addRequestHeaders(HttpRequestBase httpMethod) throws FileTransferException {
    // pass user credentials with the very first headers
    if (preemptiveBasicAuthentication) {
        if (this.username == null) {
            throw new FileTransferException("We cannot set user credentials as the user name is not set");
        }
        try {
            BasicScheme schema = new BasicScheme(Charset.forName("US-ASCII"));
            Header authenticationHeader = schema.authenticate(// here we make 'empty' http request, just so we could authenticate the credentials
            new UsernamePasswordCredentials(this.username, this.userpass), new HttpGet(), httpContext);
            httpMethod.addHeader(authenticationHeader);
        } catch (AuthenticationException ae) {
            throw new FileTransferException("Unable to add Basic Authentication header", ae);
        }
    }
    // Add the rest of the request headers
    for (Header header : requestHeaders) {
        httpMethod.setHeader(header);
    }
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) BasicScheme(org.apache.http.impl.auth.BasicScheme) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpGet(org.apache.http.client.methods.HttpGet) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 5 with FileTransferException

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

the class SftpClient method doConnect.

private void doConnect(String publicKeyAlias) throws FileTransferException {
    // make new SFTP object for every new connection
    disconnect();
    this.jsch = new JSch();
    /* 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 {
        if (username != null) {
            this.session = jsch.getSession(this.username, this.hostname, this.port);
            this.session.setPassword(this.password);
        } else {
            this.jsch.addIdentity(this.keystoreFile, this.publicKeyAlias, this.keystorePassword.getBytes());
            this.session = this.jsch.getSession(this.username, this.hostname, this.port);
        }
        // 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 (JSchException e) {
        throw new FileTransferException("Unable to connect!", e);
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) SshCipher(com.axway.ats.common.filetransfer.SshCipher) SftpListener(com.axway.ats.core.filetransfer.model.ftp.SftpListener) JSch(com.jcraft.jsch.JSch) SftpFileTransferProgressMonitor(com.axway.ats.core.filetransfer.model.ftp.SftpFileTransferProgressMonitor)

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