use of org.apache.http.entity.mime.content.StringBody in project sling by apache.
the class SlingClient method createNode.
/** Create a node at specified path, with optional properties
* @param path Used in POST request to Sling server
* @param properties If not null, properties are added to the created node
* @return The actual path of the node that was created
*/
public String createNode(String path, Map<String, Object> properties) throws UnsupportedEncodingException, IOException {
String actualPath = null;
final MultipartEntity entity = new MultipartEntity();
// Add Sling POST options
entity.addPart(":redirect", new StringBody("*"));
entity.addPart(":displayExtension", new StringBody(""));
// Add user properties
if (properties != null) {
for (Map.Entry<String, Object> e : properties.entrySet()) {
entity.addPart(e.getKey(), new StringBody(e.getValue().toString()));
}
}
final HttpResponse response = executor.execute(builder.buildPostRequest(path).withEntity(entity).withCredentials(username, password)).assertStatus(302).getResponse();
final Header location = response.getFirstHeader(LOCATION_HEADER);
assertNotNull("Expecting " + LOCATION_HEADER + " in response", location);
actualPath = locationToPath(location.getValue());
return actualPath;
}
use of org.apache.http.entity.mime.content.StringBody in project vorto by eclipse.
the class DefaultModelPublisher method publish.
@Override
public ModelId publish(ModelType type, String content) throws ModelPublishException {
String uploadModelsUrl = String.format("%s/rest/secure", getRequestContext().getBaseUrl());
HttpPost query = new HttpPost(uploadModelsUrl);
HttpEntity entity = MultipartEntityBuilder.create().addPart("fileName", new StringBody("vortomodel" + type.getExtension(), ContentType.DEFAULT_TEXT)).addPart("fileDescription", new StringBody("", ContentType.DEFAULT_TEXT)).addPart("file", new ByteArrayBody(content.getBytes(), ContentType.APPLICATION_OCTET_STREAM, "vortomodel" + type.getExtension())).build();
query.setEntity(entity);
try {
CompletableFuture<UploadModelResponse> response = execute(query, new TypeToken<UploadModelResponse>() {
}.getType());
List<UploadModelResult> result = response.get().getObj();
if (response.get().getIsSuccess()) {
String checkinModelUrl = String.format("%s/rest/secure/%s", getRequestContext().getBaseUrl(), result.get(0).getHandleId());
HttpPut checkInModel = new HttpPut(checkinModelUrl);
CompletableFuture<ModelId> checkedInResult = execute(checkInModel, new TypeToken<ModelId>() {
}.getType());
return (ModelId) checkedInResult.get();
} else {
throw new ModelPublishException(result.get(0));
}
} catch (Throwable ex) {
if (!(ex instanceof ModelPublishException)) {
throw new RuntimeException(ex);
} else {
throw ((ModelPublishException) ex);
}
}
}
use of org.apache.http.entity.mime.content.StringBody in project iNaturalistAndroid by inaturalist.
the class INaturalistService method request.
private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated, boolean useJWTToken, boolean allowAnonymousJWTToken) throws AuthenticationException {
DefaultHttpClient client = new DefaultHttpClient();
// Handle redirects (301/302) for all HTTP methods (including POST)
client.setRedirectHandler(new DefaultRedirectHandler() {
@Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
boolean isRedirect = super.isRedirectRequested(response, context);
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return isRedirect;
}
});
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getUserAgent(mApp));
// Log.d(TAG, String.format("%s (%b - %s): %s", method, authenticated,
// authenticated ? mCredentials : "<null>",
// url));
HttpRequestBase request;
Log.d(TAG, String.format("URL: %s - %s (%s)", method, url, (params != null ? params.toString() : "null")));
if (method.equalsIgnoreCase("post")) {
request = new HttpPost(url);
} else if (method.equalsIgnoreCase("delete")) {
request = new HttpDelete(url);
} else if (method.equalsIgnoreCase("put")) {
request = new HttpPut(url);
} else {
request = new HttpGet(url);
}
// POST params
if (jsonContent != null) {
// JSON body content
request.setHeader("Content-type", "application/json");
StringEntity entity = null;
try {
entity = new StringEntity(jsonContent.toString(), HTTP.UTF_8);
} catch (UnsupportedEncodingException exc) {
exc.printStackTrace();
}
if (method.equalsIgnoreCase("put")) {
((HttpPut) request).setEntity(entity);
} else {
((HttpPost) request).setEntity(entity);
}
} else if (params != null) {
// "Standard" multipart encoding
Charset utf8Charset = Charset.forName("UTF-8");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int i = 0; i < params.size(); i++) {
if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file") || params.get(i).getName().equalsIgnoreCase("user[icon]")) {
// If the key equals to "image", we use FileBody to transfer the data
String value = params.get(i).getValue();
if (value != null)
entity.addPart(params.get(i).getName(), new FileBody(new File(value)));
} else {
// Normal string data
try {
entity.addPart(params.get(i).getName(), new StringBody(params.get(i).getValue(), utf8Charset));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "failed to add " + params.get(i).getName() + " to entity for a " + method + " request: " + e);
}
}
}
if (method.equalsIgnoreCase("put")) {
((HttpPut) request).setEntity(entity);
} else {
((HttpPost) request).setEntity(entity);
}
}
if (url.startsWith(API_HOST) && (mCredentials != null)) {
// For the node API, if we're logged in, *always* use JWT authentication
authenticated = true;
useJWTToken = true;
}
if (authenticated) {
if (useJWTToken && allowAnonymousJWTToken && (mCredentials == null)) {
// User not logged in, but allow using anonymous JWT
request.setHeader("Authorization", getAnonymousJWTToken());
} else {
ensureCredentials();
if (useJWTToken) {
// Use JSON Web Token for this request
request.setHeader("Authorization", getJWTToken());
} else if (mLoginType == LoginType.PASSWORD) {
// Old-style password authentication
request.setHeader("Authorization", "Basic " + mCredentials);
} else {
// OAuth2 token (Facebook/G+/etc)
request.setHeader("Authorization", "Bearer " + mCredentials);
}
}
}
try {
mResponseErrors = null;
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String content = entity != null ? EntityUtils.toString(entity) : null;
Log.d(TAG, String.format("RESP: %s", content));
JSONArray json = null;
mLastStatusCode = response.getStatusLine().getStatusCode();
switch(response.getStatusLine().getStatusCode()) {
// switch (response.getStatusCode()) {
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
// Validation error - still need to return response
Log.e(TAG, response.getStatusLine().toString());
case HttpStatus.SC_OK:
try {
json = new JSONArray(content);
} catch (JSONException e) {
Log.d(TAG, "Failed to create JSONArray, JSONException: " + e.toString());
try {
JSONObject jo = new JSONObject(content);
json = new JSONArray();
json.put(jo);
} catch (JSONException e2) {
Log.d(TAG, "Failed to create JSONObject, JSONException: " + e2.toString());
}
}
mResponseHeaders = response.getAllHeaders();
try {
if ((json != null) && (json.length() > 0)) {
JSONObject result = json.getJSONObject(0);
if (result.has("errors")) {
// Error response
Log.e(TAG, "Got an error response: " + result.get("errors").toString());
mResponseErrors = result.getJSONArray("errors");
return null;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if ((content != null) && (content.length() == 0)) {
// In case it's just non content (but OK HTTP status code) - so there's no error
json = new JSONArray();
}
return json;
case HttpStatus.SC_UNAUTHORIZED:
throw new AuthenticationException();
case HttpStatus.SC_GONE:
Log.e(TAG, "GONE: " + response.getStatusLine().toString());
// or post them as new observations
default:
Log.e(TAG, response.getStatusLine().toString());
}
} catch (IOException e) {
// request.abort();
Log.w(TAG, "Error for URL " + url, e);
}
return null;
}
use of org.apache.http.entity.mime.content.StringBody in project briefcase by opendatakit.
the class AggregateUtils method uploadFilesToServer.
public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u, String distinguishedFileTagName, File file, List<File> files, DocumentDescription description, SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) {
boolean allSuccessful = true;
formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true);
EventBus.publish(new FormStatusEvent(formToTransfer));
// handles case where there are no media files
boolean first = true;
int lastJ = 0;
int j = 0;
while (j < files.size() || first) {
lastJ = j;
first = false;
if (terminationFuture.isCancelled()) {
formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true);
EventBus.publish(new FormStatusEvent(formToTransfer));
return false;
}
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
long byteCount = 0L;
// mime post
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// add the submission file first...
FileBody fb = new FileBody(file, ContentType.TEXT_XML);
builder.addPart(distinguishedFileTagName, fb);
log.info("added " + distinguishedFileTagName + ": " + file.getName());
byteCount += file.length();
for (; j < files.size(); j++) {
File f = files.get(j);
log.info("Trying file {}", f);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, ContentType.TEXT_XML);
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, ContentType.create("image/jpeg"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, ContentType.create("audio/3gpp"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, ContentType.create("video/3gpp"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, ContentType.create("video/mp4"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, ContentType.create("text/csv"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added csv file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, ContentType.create("application/vnd.ms-excel"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.info("added xls file " + f.getName());
} else {
fb = new FileBody(f, ContentType.create("application/octet-stream"));
builder.addPart(f.getName(), fb);
byteCount += f.length();
log.warn("added unrecognized file (application/octet-stream)");
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) {
// more than 100 attachments or the next file would exceed the 10MB threshold...
log.info("Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8")));
builder.addPart("*isIncomplete*", sb);
} catch (Exception e) {
log.error("impossible condition", e);
throw new IllegalStateException("never happens");
}
// advance over the last attachment added...
++j;
break;
}
}
}
httppost.setEntity(builder.build());
int[] validStatusList = { 201 };
try {
if (j != files.size()) {
formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size() + " media attachments", true);
} else if (j == 0) {
formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " with no media attachments", true);
} else {
formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and " + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true);
}
EventBus.publish(new FormStatusEvent(formToTransfer));
httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action);
} catch (XmlDocumentFetchException e) {
allSuccessful = false;
log.error("upload failed", e);
formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false);
EventBus.publish(new FormStatusEvent(formToTransfer));
if (description.isCancelled())
return false;
}
}
return allSuccessful;
}
use of org.apache.http.entity.mime.content.StringBody 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) {
// 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;
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;
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(StandardCharsets.UTF_8.toString(), 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;
}
Aggregations