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;
}
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);
}
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);
}
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);
}
}
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);
}
}
Aggregations