use of org.apache.http.entity.mime.content.StringBody in project scheduling by ow2-proactive.
the class RestSchedulerPushPullFileTest method testIt.
public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception {
File testPushFile = RestFuncTHelper.getDefaultJobXmlfile();
// you can test pushing pulling a big file :
// testPushFile = new File("path_to_a_big_file");
File destFile = new File(new File(spacePath, destPath), testPushFile.getName());
if (destFile.exists()) {
destFile.delete();
}
// PUSHING THE FILE
String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
// either we encode or we test human readable path (with no special character inside)
HttpPost reqPush = new HttpPost(pushfileUrl);
setSessionHeader(reqPush);
// we push a xml job as a simple test
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("fileName", new StringBody(testPushFile.getName()));
multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile), MediaType.APPLICATION_OCTET_STREAM, null));
reqPush.setEntity(multipartEntity);
HttpResponse response = executeUriRequest(reqPush);
System.out.println(response.getStatusLine());
assertHttpStatusOK(response);
Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists());
Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(testPushFile, destFile));
// LISTING THE TARGET DIRECTORY
String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/")));
HttpGet reqPullList = new HttpGet(pullListUrl);
setSessionHeader(reqPullList);
HttpResponse response2 = executeUriRequest(reqPullList);
System.out.println(response2.getStatusLine());
assertHttpStatusOK(response2);
InputStream is = response2.getEntity().getContent();
List<String> lines = IOUtils.readLines(is);
HashSet<String> content = new HashSet<>(lines);
System.out.println(lines);
Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName()));
// PULLING THE FILE
String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8") : destPath.replace("\\", "/") + "/" + testPushFile.getName()));
HttpGet reqPull = new HttpGet(pullfileUrl);
setSessionHeader(reqPull);
HttpResponse response3 = executeUriRequest(reqPull);
System.out.println(response3.getStatusLine());
assertHttpStatusOK(response3);
InputStream is2 = response3.getEntity().getContent();
File answerFile = tmpFolder.newFile();
FileUtils.copyInputStreamToFile(is2, answerFile);
Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(answerFile, testPushFile));
// DELETING THE HIERARCHY
String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length());
String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/")));
HttpDelete reqDelete = new HttpDelete(deleteUrl);
setSessionHeader(reqDelete);
HttpResponse response4 = executeUriRequest(reqDelete);
System.out.println(response4.getStatusLine());
assertHttpStatusOK(response4);
Assert.assertTrue(destFile + " still exist", !destFile.exists());
}
use of org.apache.http.entity.mime.content.StringBody in project Talon-for-Twitter by klinker24.
the class TwitterMultipleImageHelper method uploadPics.
public boolean uploadPics(File[] pics, String text, Twitter twitter) {
JSONObject jsonresponse = new JSONObject();
final String ids_string = getMediaIds(pics, twitter);
if (ids_string == null) {
return false;
}
try {
AccessToken token = twitter.getOAuthAccessToken();
String oauth_token = token.getToken();
String oauth_token_secret = token.getTokenSecret();
// generate authorization header
String get_or_post = "POST";
String oauth_signature_method = "HMAC-SHA1";
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
// any relatively random alphanumeric string will work here
String oauth_nonce = uuid_string;
// get the timestamp
Calendar tempcal = Calendar.getInstance();
// get current time in milliseconds
long ts = tempcal.getTimeInMillis();
// then divide by 1000 to get seconds
String oauth_timestamp = (new Long(ts / 1000)).toString();
// the parameter string must be in alphabetical order, "text" parameter added at end
String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
String twitter_endpoint_host = "api.twitter.com";
String twitter_endpoint_path = "/1.1/statuses/update.json";
String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
HttpProtocolParams.setUseExpectContinue(params, false);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost(twitter_endpoint_host, 443);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, null, null);
SSLSocketFactory ssf = sslcontext.getSocketFactory();
Socket socket = ssf.createSocket();
socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
conn.bind(socket, params);
BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("media_ids", new StringBody(ids_string));
reqEntity.addPart("status", new StringBody(text));
reqEntity.addPart("trim_user", new StringBody("1"));
request2.setEntity(reqEntity);
request2.setParams(params);
request2.addHeader("Authorization", authorization_header_string);
httpexecutor.preProcess(request2, httpproc, context);
HttpResponse response2 = httpexecutor.execute(request2, conn, context);
response2.setParams(params);
httpexecutor.postProcess(response2, httpproc, context);
String responseBody = EntityUtils.toString(response2.getEntity());
System.out.println("response=" + responseBody);
// error checking here. Otherwise, status should be updated.
jsonresponse = new JSONObject(responseBody);
conn.close();
} catch (HttpException he) {
System.out.println(he.getMessage());
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
} catch (NoSuchAlgorithmException nsae) {
System.out.println(nsae.getMessage());
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
} catch (KeyManagementException kme) {
System.out.println(kme.getMessage());
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
} finally {
conn.close();
}
} catch (JSONException jsone) {
jsone.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (Exception e) {
}
return true;
}
use of org.apache.http.entity.mime.content.StringBody in project tutorials by eugenp.
the class HttpClientMultipartLiveTest method givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions.
// tests
@Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
//
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
final HttpEntity entity = builder.build();
//
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
// assertTrue(responseString.contains("Content-Type: multipart/form-data;"));
assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;"));
System.out.println(responseString);
System.out.println("POST Content Type: " + contentTypeInHeader);
}
use of org.apache.http.entity.mime.content.StringBody in project questdb by bluestreak01.
the class HttpTestUtils method upload.
public static int upload(String resource, String url, String schema, StringBuilder response) throws IOException {
HttpPost post = new HttpPost(url);
try (CloseableHttpClient client = HttpClients.createDefault()) {
MultipartEntityBuilder b = MultipartEntityBuilder.create();
if (schema != null) {
b.addPart("schema", new StringBody(schema, ContentType.TEXT_PLAIN));
}
b.addPart("data", new FileBody(resourceFile(resource)));
post.setEntity(b.build());
HttpResponse r = client.execute(post);
if (response != null) {
InputStream is = r.getEntity().getContent();
int n;
while ((n = is.read()) > 0) {
response.append((char) n);
}
is.close();
}
return r.getStatusLine().getStatusCode();
}
}
use of org.apache.http.entity.mime.content.StringBody in project fb-botmill by BotMill.
the class FbBotMillNetworkController method postFormDataMessage.
// TODO: used for attaching files but not working at the moment.
/**
* POSTs a message as a JSON string to Facebook.
*
* @param recipient
* the recipient
* @param type
* the type
* @param file
* the file
*/
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
String pageToken = FbBotMillContext.getInstance().getPageToken();
// If the page token is invalid, returns.
if (!validatePageToken(pageToken)) {
return;
}
// TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);
FileBody filedata = new FileBody(file);
StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA);
StringBody messagePart = new StringBody("{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.STRICT);
builder.addPart("recipient", recipientPart);
builder.addPart("message", messagePart);
// builder.addPart("filedata", filedata);
builder.addBinaryBody("filedata", file);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
// builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
HttpEntity entity = builder.build();
post.setEntity(entity);
// Logs the raw JSON for debug purposes.
BufferedReader br;
// post.addHeader("Content-Type", "multipart/form-data");
try {
// br = new BufferedReader(new InputStreamReader(
// ())));
Header[] allHeaders = post.getAllHeaders();
for (Header h : allHeaders) {
logger.debug("Header {} -> {}", h.getName(), h.getValue());
}
// String output = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
// postInternal(post);
}
Aggregations