use of org.apache.http.entity.mime.MultipartEntityBuilder in project ats-framework by Axway.
the class AtsDbLoggerUtilities method attachFileToCurrentTest.
/**
* Attach a local file to the current test case in the Test Explorer DB.
* </br>The file must not be bigger than 10MB
*
* @param fileLocation the absolute path to the file
* @param testExplorerContextName the name of the web application, e.g. "TestExplorer" or "TestExplorer-3.11.0" etc.
* @param testExplorerPort the port of the web application, e.g. 8080
* @return TRUE if the operation was successful and false if not. A warning will be logged on failure.
*/
@PublicAtsApi
public boolean attachFileToCurrentTest(String fileLocation, String testExplorerContextName, int testExplorerPort) {
ERR_MSG_PREFIX = ERR_MSG_PREFIX.replace("{FILE}", fileLocation);
if (!checkFileExist(fileLocation)) {
return false;
}
if (!checkFileSizeIsNotTooLarge(fileLocation)) {
return false;
}
ActiveDbAppender dbAppender = ActiveDbAppender.getCurrentInstance();
if (dbAppender == null) {
logger.warn(ERR_MSG_PREFIX + "Perhaps the database logging is turned off");
return false;
}
final int runId = dbAppender.getRunId();
final int suiteId = dbAppender.getSuiteId();
final int testcaseId = dbAppender.getTestCaseId();
if (runId < 1 || suiteId < 1 || testcaseId < 1) {
logger.warn(ERR_MSG_PREFIX + "Perhaps the database logging is turned off or you are trying to log while a testcase is not yet started");
return false;
}
final String database = dbAppender.getDatabase();
final String host = dbAppender.getHost();
final String URL = "http://" + host + ":" + testExplorerPort + "/" + testExplorerContextName + "/UploadServlet";
URL url = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(URL);
url = post.getURI().toURL();
if (!isURLConnetionAvailable(url)) {
return false;
}
logger.debug("POSTing " + fileLocation + " on " + URL);
File file = new File(fileLocation);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, fileLocation);
builder.addTextBody("dbName", database);
builder.addTextBody("runId", Integer.toString(runId));
builder.addTextBody("suiteId", Integer.toString(suiteId));
builder.addTextBody("testcaseId", Integer.toString(testcaseId));
HttpEntity entity = builder.build();
post.setEntity(entity);
checkPostExecutedSuccessfully(client.execute(post), fileLocation);
} catch (FileNotFoundException fnfe) {
logger.warn(ERR_MSG_PREFIX + "it does not exist on the local file system", fnfe);
return false;
} catch (ClientProtocolException cpe) {
logger.warn(ERR_MSG_PREFIX + "Upload to \"" + url + "\" failed", cpe);
return false;
} catch (ConnectException ce) {
logger.warn(ERR_MSG_PREFIX + "Upload to \"" + url + "\" failed", ce);
return false;
} catch (IOException ioe) {
logger.warn(ERR_MSG_PREFIX + "Upload to \"" + url + "\" failed", ioe);
return false;
}
logger.info("Successfully attached \"" + fileLocation + "\" to the current Test Explorer testcase");
return true;
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project perun by CESNET.
the class RTMessagesManagerBlImpl method prepareDataAndGetHttpRequest.
private HttpUriRequest prepareDataAndGetHttpRequest(PerunSession sess, int voId, String queue, String requestor, String subject, String text) throws InternalErrorException {
//Ticket from this part is already evidet like 'new'
String id = "ticket/new";
//If there is no requestor, it is uknown requestor
if (requestor == null || requestor.isEmpty()) {
requestor = "unknown";
}
//If queue is null, try to check if exist value in attribute rtVoQueue, if not, use default
if (queue == null || queue.isEmpty()) {
Vo vo = null;
if (voId != 0) {
try {
vo = perunBl.getVosManagerBl().getVoById(sess, voId);
} catch (VoNotExistsException ex) {
throw new InternalErrorException("VoId with Id=" + voId + " not exists.", ex);
}
Attribute voQueue = null;
try {
voQueue = perunBl.getAttributesManagerBl().getAttribute(sess, vo, AttributesManager.NS_VO_ATTR_DEF + ":RTVoQueue");
} catch (AttributeNotExistsException ex) {
throw new InternalErrorException("Attribute RTVoQueue not exists.", ex);
} catch (WrongAttributeAssignmentException ex) {
throw new InternalErrorException(ex);
}
if (voQueue.getValue() != null) {
queue = (String) voQueue.getValue();
} else
queue = rtDefaultQueue;
} else
queue = rtDefaultQueue;
}
//If subject is null or empty, use Unspecified instead
if (subject == null || subject.isEmpty())
subject = "(No subject)";
//Text can be null so if it is, put empty string
if (text == null)
text = "";
//Prepare credentials
String username = BeansUtils.getCoreConfig().getRtServiceuserUsername();
String password = BeansUtils.getCoreConfig().getRtServiceuserPassword();
//Prepare content of message
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
try {
entityBuilder.addPart("Content-Type", new StringBody("application/x-www-form-urlencoded", ContentType.create("text/plain", Consts.UTF_8)));
entityBuilder.addPart("charset", new StringBody("utf-8", ContentType.create("text/plain", Consts.UTF_8)));
entityBuilder.addPart("Connection", new StringBody("Close", ContentType.create("text/plain", Consts.UTF_8)));
StringBody content = new StringBody("id: " + id + '\n' + "Queue: " + queue + '\n' + "Requestor: " + requestor + '\n' + "Subject: " + subject + '\n' + "Text: " + text, ContentType.create("text/plain", Consts.UTF_8));
entityBuilder.addPart("content", content);
} catch (Exception e) {
throw new RuntimeException(e);
}
//Test rtURL for null
if (rtURL == null || rtURL.length() == 0)
throw new InternalErrorException("rtURL is not prepared and is null in the moment of posting.");
// prepare post request
HttpPost post = new HttpPost(rtURL);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
post.addHeader(BasicScheme.authenticate(credentials, "utf-8", false));
post.setEntity(entityBuilder.build());
return post;
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project perun by CESNET.
the class MUStrategy method getHttpRequest.
@Override
public HttpUriRequest getHttpRequest(String uco, int yearSince, int yearTill, PublicationSystem ps) {
//prepare request body
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
try {
entityBuilder.addPart("typ", new StringBody("xml", ContentType.create("text/plain", Consts.UTF_8)));
entityBuilder.addPart("kodovani", new StringBody("utf-8", ContentType.create("text/plain", Consts.UTF_8)));
entityBuilder.addPart("keyfile", new ByteArrayBody(buildRequestKeyfile(Integer.parseInt(uco), yearSince, yearTill).getBytes(), "template.xml"));
} catch (Exception e) {
throw new RuntimeException(e);
}
//prepare post request
HttpPost post = new HttpPost(ps.getUrl());
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(ps.getUsername(), ps.getPassword());
//cred, enc, proxy
post.addHeader(BasicScheme.authenticate(credentials, "utf-8", false));
post.setEntity(entityBuilder.build());
return post;
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project jmeter by apache.
the class HTTPHC4Impl method sendPostData.
// TODO needs cleaning up
/**
*
* @param post {@link HttpPost}
* @return String posted body if computable
* @throws IOException if sending the data fails due to I/O
*/
protected String sendPostData(HttpPost post) throws IOException {
// Buffer to hold the post body, except file content
StringBuilder postedBody = new StringBuilder(1000);
HTTPFileArg[] files = getHTTPFiles();
final String contentEncoding = getContentEncodingOrNull();
final boolean haveContentEncoding = contentEncoding != null;
// application/x-www-form-urlencoded post request
if (getUseMultipartForPost()) {
// If a content encoding is specified, we use that as the
// encoding of any parameter values
Charset charset = null;
if (haveContentEncoding) {
charset = Charset.forName(contentEncoding);
} else {
charset = MIME.DEFAULT_CHARSET;
}
if (log.isDebugEnabled()) {
log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}", getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
}
// Write the request to our own stream
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
if (getDoBrowserCompatibleMultipart()) {
multipartEntityBuilder.setLaxMode();
} else {
multipartEntityBuilder.setStrictMode();
}
// Add any parameters
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
multipartEntityBuilder.addPart(formPart);
}
// Add any files
// Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
for (int i = 0; i < files.length; i++) {
HTTPFileArg file = files[i];
File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
}
HttpEntity entity = multipartEntityBuilder.build();
post.setEntity(entity);
if (entity.isRepeatable()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (ViewableFileBody fileBody : fileBodies) {
fileBody.hideFileData = true;
}
entity.writeTo(bos);
for (ViewableFileBody fileBody : fileBodies) {
fileBody.hideFileData = false;
}
bos.flush();
// We get the posted bytes using the encoding used to create it
postedBody.append(bos.toString(// $NON-NLS-1$ this is the default used by HttpClient
contentEncoding == null ? // $NON-NLS-1$ this is the default used by HttpClient
"US-ASCII" : contentEncoding));
bos.close();
} else {
// $NON-NLS-1$
postedBody.append("<Multipart was not repeatable, cannot view what was sent>");
}
// // Set the content type TODO - needed?
// String multiPartContentType = multiPart.getContentType().getValue();
// post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);
} else {
// not multipart
// Check if the header manager had a content type header
// This allows the user to specify his own content-type for a POST request
Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
// TODO: needs a multiple file upload scenerio
if (!hasArguments() && getSendFileAsPostBody()) {
// If getSendFileAsPostBody returned true, it's sure that file is not null
HTTPFileArg file = files[0];
if (!hasContentTypeHeader) {
// Allow the mimetype of the file to control the content type
if (file.getMimeType() != null && file.getMimeType().length() > 0) {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
} else {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
// TODO is null correct?
FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);
post.setEntity(fileRequestEntity);
// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>");
} else {
// the post body will be encoded in the specified content encoding
if (haveContentEncoding) {
post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
}
// just send all the values as the post body
if (getSendParameterValuesAsPostBody()) {
// TODO: needs a multiple file upload scenerio
if (!hasContentTypeHeader) {
HTTPFileArg file = files.length > 0 ? files[0] : null;
if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
} else {
// TODO - is this the correct default?
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
// Just append all the parameter values, and use that as the post body
StringBuilder postBody = new StringBuilder();
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (haveContentEncoding) {
postBody.append(arg.getEncodedValue(contentEncoding));
} else {
postBody.append(arg.getEncodedValue());
}
}
// Let StringEntity perform the encoding
StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
post.setEntity(requestEntity);
postedBody.append(postBody.toString());
} else {
// Set the content type
if (!hasContentTypeHeader) {
post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
// Add the parameters
PropertyIterator args = getArguments().iterator();
List<NameValuePair> nvps = new ArrayList<>();
String urlContentEncoding = contentEncoding;
if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
// Use the default encoding for urls
urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
}
while (args.hasNext()) {
HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
// The HTTPClient always urlencodes both name and value,
// so if the argument is already encoded, we have to decode
// it before adding it to the post request
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
String parameterValue = arg.getValue();
if (!arg.isAlwaysEncoded()) {
// The value is already encoded by the user
// Must decode the value now, so that when the
// httpclient encodes it, we end up with the same value
// as the user had entered.
parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
}
// Add the parameter, httpclient will urlencode it
nvps.add(new BasicNameValuePair(parameterName, parameterValue));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
post.setEntity(entity);
if (entity.isRepeatable()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
post.getEntity().writeTo(bos);
bos.flush();
// We get the posted bytes using the encoding used to create it
postedBody.append(bos.toString(contentEncoding != null ? contentEncoding : SampleResult.DEFAULT_HTTP_ENCODING));
bos.close();
} else {
postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
}
}
}
}
return postedBody.toString();
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project android by JetBrains.
the class GoogleCrash method newMultipartEntityBuilderWithKv.
@NotNull
private static MultipartEntityBuilder newMultipartEntityBuilderWithKv(@NotNull Map<String, String> kv) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
kv.forEach(builder::addTextBody);
return builder;
}
Aggregations