Search in sources :

Example 31 with MultipartEntityBuilder

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);
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder)

Example 32 with MultipartEntityBuilder

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();
}
Also used : FileEntity(org.apache.http.entity.FileEntity) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) JMeterProperty(org.apache.jmeter.testelement.property.JMeterProperty) ContentType(org.apache.http.entity.ContentType) HttpEntity(org.apache.http.HttpEntity) Charset(java.nio.charset.Charset) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HTTPFileArg(org.apache.jmeter.protocol.http.util.HTTPFileArg) FormBodyPart(org.apache.http.entity.mime.FormBodyPart) StringEntity(org.apache.http.entity.StringEntity) HTTPArgument(org.apache.jmeter.protocol.http.util.HTTPArgument) Header(org.apache.http.Header) BufferedHeader(org.apache.http.message.BufferedHeader) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Example 33 with MultipartEntityBuilder

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: **&#x60;Developer&#x60;**, **&#x60;FursuitBadgeSystem&#x60;**, **&#x60;System&#x60;**  **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;
    }
}
Also used : FursuitBadgeRecord(io.swagger.client.model.FursuitBadgeRecord) VolleyError(com.android.volley.VolleyError) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) Pair(io.swagger.client.Pair) ApiException(io.swagger.client.ApiException) TimeoutException(java.util.concurrent.TimeoutException)

Example 34 with MultipartEntityBuilder

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: **&#x60;Attendee&#x60;**
 * @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;
    }
}
Also used : VolleyError(com.android.volley.VolleyError) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ApiSafeResult(io.swagger.client.model.ApiSafeResult) ExecutionException(java.util.concurrent.ExecutionException) ApiException(io.swagger.client.ApiException) Pair(io.swagger.client.Pair) TimeoutException(java.util.concurrent.TimeoutException)

Example 35 with MultipartEntityBuilder

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: **&#x60;Attendee&#x60;**
 * @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;
    }
}
Also used : VolleyError(com.android.volley.VolleyError) FursuitParticipationInfo(io.swagger.client.model.FursuitParticipationInfo) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) Pair(io.swagger.client.Pair) ApiException(io.swagger.client.ApiException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)227 HttpEntity (org.apache.http.HttpEntity)166 ArrayList (java.util.ArrayList)126 HashMap (java.util.HashMap)123 VolleyError (com.android.volley.VolleyError)120 ApiException (io.swagger.client.ApiException)120 Pair (io.swagger.client.Pair)120 HttpPost (org.apache.http.client.methods.HttpPost)68 ExecutionException (java.util.concurrent.ExecutionException)61 TimeoutException (java.util.concurrent.TimeoutException)61 Response (com.android.volley.Response)60 File (java.io.File)40 List (java.util.List)40 HttpResponse (org.apache.http.HttpResponse)37 IOException (java.io.IOException)31 Test (org.junit.Test)26 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)22 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)22 StringBody (org.apache.http.entity.mime.content.StringBody)18 ApiSafeResultCollectTokenResponse (io.swagger.client.model.ApiSafeResultCollectTokenResponse)16