Search in sources :

Example 86 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 87 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.

the class ZMailbox method uploadAttachments.

/* ------------------------------------------------- */
/**
 * Uploads files to <tt>FileUploadServlet</tt>.
 * @return the attachment id
 */
public String uploadAttachments(File[] files, int msTimeout) throws ServiceException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(file.getName());
        if (contentType != null) {
            builder.addBinaryBody("upfile", file, ContentType.create(contentType, "UTF-8"), file.getName());
        } else {
            builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName());
        }
    }
    return uploadAttachments(builder, msTimeout);
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) File(java.io.File)

Example 88 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.

the class LmcSendMsgRequest method postAttachment.

/*
    * Post the attachment represented by File f and return the attachment ID
    */
public String postAttachment(String uploadURL, LmcSession session, File f, // cookie domain e.g. ".example.zimbra.com"
String domain, int msTimeout) throws LmcSoapClientException, IOException, HttpException {
    String aid = null;
    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcSendMsgRequest.postAttachment session=null");
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpPost post = new HttpPost(uploadURL);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        BasicCookieStore initialState = new BasicCookieStore();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            BasicClientCookie cookie = new BasicClientCookie(ck.getKey(), ck.getValue());
            cookie.setDomain(domain);
            cookie.setPath("/");
            cookie.setSecure(false);
            cookie.setExpiryDate(null);
            initialState.addCookie(cookie);
        }
        clientBuilder.setDefaultCookieStore(initialState);
        RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
        clientBuilder.setDefaultRequestConfig(reqConfig);
    }
    SocketConfig config = SocketConfig.custom().setSoTimeout(msTimeout).build();
    clientBuilder.setDefaultSocketConfig(config);
    int statusCode = -1;
    try {
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName());
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("upfile", f, ContentType.create(contentType, "UTF-8"), f.getName());
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpClient client = clientBuilder.build();
        HttpResponse httpResponse = HttpClientUtil.executeMethod(client, post);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        // parse the response
        if (statusCode == 200) {
            // paw through the returned HTML and get the attachment id
            String response = EntityUtils.toString(httpResponse.getEntity());
            // System.out.println("response is\n" + response);
            int lastQuote = response.lastIndexOf("'");
            int firstQuote = response.indexOf("','") + 3;
            if (lastQuote == -1 || firstQuote == -1)
                throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response);
            aid = response.substring(firstQuote, lastQuote);
        } else {
            throw new LmcSoapClientException("Attachment post failed, status=" + statusCode);
        }
    } catch (IOException | HttpException e) {
        System.err.println("Attachment post failed");
        e.printStackTrace();
        throw e;
    } finally {
        post.releaseConnection();
    }
    return aid;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) SocketConfig(org.apache.http.config.SocketConfig) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) IOException(java.io.IOException) ZAuthToken(com.zimbra.common.auth.ZAuthToken) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.http.HttpException) Map(java.util.Map)

Example 89 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.

the class TestDeployZimlet method adminUpload.

public String adminUpload(String authToken, String fileName, String filePath) throws Exception {
    HttpPost post = new HttpPost(ADMIN_UPLOAD_URL);
    String contentType = "application/x-msdownload";
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    BasicCookieStore state = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie(ZimbraCookie.authTokenCookieName(true), authToken);
    cookie.setDomain(localServer.getServiceHostname());
    cookie.setPath("/");
    cookie.setSecure(false);
    state.addCookie(cookie);
    clientBuilder.setDefaultCookieStore(state);
    RequestConfig reqConfig = RequestConfig.copy(ZimbraHttpConnectionManager.getInternalHttpConnMgr().getZimbraConnMgrParams().getReqConfig()).setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    clientBuilder.setDefaultRequestConfig(reqConfig);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody(fileName, new File(filePath), ContentType.create(contentType), fileName);
    HttpEntity httpEntity = builder.build();
    post.setEntity(httpEntity);
    HttpClient client = clientBuilder.build();
    HttpResponse response = HttpClientUtil.executeMethod(client, post);
    int statusCode = response.getStatusLine().getStatusCode();
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = EntityUtils.toString(response.getEntity());
    assertNotNull("Response should not be empty", resp);
    ZimbraLog.test.debug("Upload response " + resp);
    String[] responseParts = resp.split(",", 3);
    String aid = null;
    if (responseParts.length == 3) {
        aid = responseParts[2].trim();
        if (aid.startsWith("'") || aid.startsWith("\"")) {
            aid = aid.substring(1);
        }
        if (aid.endsWith("'") || aid.endsWith("\"")) {
            aid = aid.substring(0, aid.length() - 1);
        }
    }
    return aid;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpClient(org.apache.http.client.HttpClient) File(java.io.File)

Example 90 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project zm-mailbox by Zimbra.

the class TestFileUpload method postAndVerify.

private String postAndVerify(ZMailbox mbox, URI uri, boolean clearCookies, String requestId, String attContent) throws IOException, HttpException {
    HttpClientBuilder clientBuilder = mbox.getHttpClientBuilder(uri);
    // if (clearCookies) {
    // clientBuilder.
    // }
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart(FormBodyPartBuilder.create().addField("requestId", requestId).build());
    if (attContent != null) {
        builder.addBinaryBody("test.txt", attContent.getBytes());
    }
    HttpPost post = new HttpPost(uri.toString());
    HttpEntity httpEntity = builder.build();
    post.setEntity(httpEntity);
    HttpClient client = clientBuilder.build();
    HttpResponse httpResponse = HttpClientUtil.executeMethod(client, post);
    int status = httpResponse.getStatusLine().getStatusCode();
    Assert.assertEquals(200, status);
    String contentType = getHeaderValue(post, "Content-Type");
    Assert.assertTrue(contentType, contentType.startsWith("text/html"));
    String content = EntityUtils.toString(httpResponse.getEntity());
    post.releaseConnection();
    return content;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Aggregations

MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)213 HttpEntity (org.apache.http.HttpEntity)161 ArrayList (java.util.ArrayList)126 HashMap (java.util.HashMap)122 VolleyError (com.android.volley.VolleyError)120 ApiException (io.swagger.client.ApiException)120 Pair (io.swagger.client.Pair)120 ExecutionException (java.util.concurrent.ExecutionException)61 TimeoutException (java.util.concurrent.TimeoutException)61 Response (com.android.volley.Response)60 HttpPost (org.apache.http.client.methods.HttpPost)59 List (java.util.List)40 File (java.io.File)37 HttpResponse (org.apache.http.HttpResponse)33 IOException (java.io.IOException)26 Test (org.junit.Test)25 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)17 ApiSafeResultCollectTokenResponse (io.swagger.client.model.ApiSafeResultCollectTokenResponse)16 CollectTokenResponse (io.swagger.client.model.CollectTokenResponse)15 StringBody (org.apache.http.entity.mime.content.StringBody)15