use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.
the class ZMailbox method uploadAttachments.
/**
* Uploads multiple byte arrays to <tt>FileUploadServlet</tt>.
* @param attachments the attachments. The key to the <tt>Map</tt> is the attachment
* name and the value is the content.
* @return the attachment id
*/
public String uploadAttachments(Map<String, byte[]> attachments, int msTimeout) throws ServiceException {
if (attachments == null || attachments.size() == 0) {
return null;
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (String name : attachments.keySet()) {
byte[] content = attachments.get(name);
String contentType = URLConnection.getFileNameMap().getContentTypeFor(name);
if (contentType != null) {
builder.addBinaryBody(name, content, ContentType.create(contentType), name);
} else {
builder.addBinaryBody(name, content, ContentType.DEFAULT_BINARY, name);
}
}
return uploadAttachments(builder, msTimeout);
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project jmeter by apache.
the class HTTPHC4Impl method setupHttpEntityEnclosingRequestData.
/**
* @param entityEnclosingRequest {@link HttpEntityEnclosingRequestBase}
* @return String body sent if computable
* @throws IOException if sending the data fails due to I/O
*/
protected String setupHttpEntityEnclosingRequestData(HttpEntityEnclosingRequestBase entityEnclosingRequest) 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 (getUseMultipart()) {
if (entityEnclosingRequest.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE).length > 0) {
log.info("Content-Header is set already on the request! Will be replaced by a Multipart-Header. Old headers: {}", Arrays.asList(entityEnclosingRequest.getHeaders(HTTPConstants.HEADER_CONTENT_TYPE)));
entityEnclosingRequest.removeHeaders(HTTPConstants.HEADER_CONTENT_TYPE);
}
// If a content encoding is specified, we use that as the
// encoding of any parameter values
Charset charset;
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();
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;
}
ContentType contentType;
if (arg.getContentType().indexOf(';') >= 0) {
// assume, that the content type contains charset info
// don't add another charset and use parse to cope with the semicolon
contentType = ContentType.parse(arg.getContentType());
} else {
contentType = ContentType.create(arg.getContentType(), charset);
}
StringBody stringBody = new StringBody(arg.getValue(), contentType);
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, ContentType.parse(file.getMimeType()));
multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
}
HttpEntity entity = multipartEntityBuilder.build();
entityEnclosingRequest.setEntity(entity);
writeEntityToSB(postedBody, entity, fileBodies, contentEncoding);
} else {
// not multipart
// Check if the header manager had a content type header
// This allows the user to specify their own content-type for a POST request
Header contentTypeHeader = entityEnclosingRequest.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
// TODO: needs a multiple file upload scenario
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) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
} else if (ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
FileEntity fileRequestEntity = new FileEntity(FileServer.getFileServer().getResolvedFile(file.getPath()), (ContentType) null);
entityEnclosingRequest.setEntity(fileRequestEntity);
// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>");
} else {
// just send all the values as the post body
if (getSendParameterValuesAsPostBody()) {
// TODO: needs a multiple file upload scenario
if (!hasContentTypeHeader) {
HTTPFileArg file = files.length > 0 ? files[0] : null;
if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
} else if (ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.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);
entityEnclosingRequest.setEntity(requestEntity);
postedBody.append(postBody.toString());
} else {
// Set the content type
if (!hasContentTypeHeader && ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
String urlContentEncoding = contentEncoding;
UrlEncodedFormEntity entity = createUrlEncodedFormEntity(urlContentEncoding);
entityEnclosingRequest.setEntity(entity);
writeEntityToSB(postedBody, entity, EMPTY_FILE_BODIES, contentEncoding);
}
}
}
return postedBody.toString();
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project ef-app_android by eurofurence.
the class FursuitsApi method apiV2FursuitsBadgesGet.
/**
* Return all Fursuit Badge Registrations
* * Requires authorization * Requires any of the following roles: **`Developer`**, **`FursuitBadgeSystem`**, **`System`** **Not meant to be consumed by the mobile apps**
* @return List<FursuitBadgeRecord>
*/
public List<FursuitBadgeRecord> apiV2FursuitsBadgesGet() throws TimeoutException, ExecutionException, InterruptedException, ApiException {
Object postBody = null;
// create path and map variables
String path = "/Api/v2/Fursuits/Badges".replaceAll("\\{format\\}", "json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
HttpEntity httpEntity = localVarBuilder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "Bearer" };
try {
String localVarResponse = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if (localVarResponse != null) {
return (List<FursuitBadgeRecord>) ApiInvoker.deserialize(localVarResponse, "array", FursuitBadgeRecord.class);
} else {
return null;
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if (ex.getCause() instanceof VolleyError) {
VolleyError volleyError = (VolleyError) ex.getCause();
if (volleyError.networkResponse != null) {
throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
}
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project ef-app_android by eurofurence.
the class FursuitsApi method apiV2FursuitsCollectingGameFursuitParticpationBadgesByFursuitBadgeIdTokenSafePost.
/**
* * Requires authorization * Requires any of the following roles: **`Attendee`**
* @param fursuitBadgeId
* @param tokenValue
* @return ApiSafeResult
*/
public ApiSafeResult apiV2FursuitsCollectingGameFursuitParticpationBadgesByFursuitBadgeIdTokenSafePost(UUID fursuitBadgeId, String tokenValue) throws TimeoutException, ExecutionException, InterruptedException, ApiException {
Object postBody = tokenValue;
// verify the required parameter 'fursuitBadgeId' is set
if (fursuitBadgeId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'fursuitBadgeId' when calling apiV2FursuitsCollectingGameFursuitParticpationBadgesByFursuitBadgeIdTokenSafePost", new ApiException(400, "Missing the required parameter 'fursuitBadgeId' when calling apiV2FursuitsCollectingGameFursuitParticpationBadgesByFursuitBadgeIdTokenSafePost"));
}
// create path and map variables
String path = "/Api/v2/Fursuits/CollectingGame/FursuitParticpation/Badges/{FursuitBadgeId}/Token:safe".replaceAll("\\{format\\}", "json").replaceAll("\\{" + "FursuitBadgeId" + "\\}", apiInvoker.escapeString(fursuitBadgeId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = { "application/json", "text/json", "application/json-patch+json" };
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
HttpEntity httpEntity = localVarBuilder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "Bearer" };
try {
String localVarResponse = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames);
if (localVarResponse != null) {
return (ApiSafeResult) ApiInvoker.deserialize(localVarResponse, "", ApiSafeResult.class);
} else {
return null;
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if (ex.getCause() instanceof VolleyError) {
VolleyError volleyError = (VolleyError) ex.getCause();
if (volleyError.networkResponse != null) {
throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
}
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
use of org.apache.http.entity.mime.MultipartEntityBuilder in project ef-app_android by eurofurence.
the class FursuitsApi method apiV2FursuitsCollectingGameFursuitParticipationGet.
/**
* * Requires authorization * Requires any of the following roles: **`Attendee`**
* @return List<FursuitParticipationInfo>
*/
public List<FursuitParticipationInfo> apiV2FursuitsCollectingGameFursuitParticipationGet() throws TimeoutException, ExecutionException, InterruptedException, ApiException {
Object postBody = null;
// create path and map variables
String path = "/Api/v2/Fursuits/CollectingGame/FursuitParticipation".replaceAll("\\{format\\}", "json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
HttpEntity httpEntity = localVarBuilder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "Bearer" };
try {
String localVarResponse = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames);
if (localVarResponse != null) {
return (List<FursuitParticipationInfo>) ApiInvoker.deserialize(localVarResponse, "array", FursuitParticipationInfo.class);
} else {
return null;
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if (ex.getCause() instanceof VolleyError) {
VolleyError volleyError = (VolleyError) ex.getCause();
if (volleyError.networkResponse != null) {
throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
}
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
Aggregations