Search in sources :

Example 91 with MultipartEntityBuilder

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

the class TestFileUpload method testAdminUploadWithCsrfInHeader.

@Test
public void testAdminUploadWithCsrfInHeader() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    HttpPost post = new HttpPost(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("localhost");
    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(FILE_NAME, "some file content".getBytes(), ContentType.create(contentType), FILE_NAME);
    HttpEntity httpEntity = builder.build();
    post.setEntity(httpEntity);
    HttpClient client = clientBuilder.build();
    post.addHeader(Constants.CSRF_TOKEN, csrfToken);
    HttpResponse httpResponse = HttpClientUtil.executeMethod(client, post);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = EntityUtils.toString(httpResponse.getEntity());
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
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) Element(com.zimbra.common.soap.Element) 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) ServiceException(com.zimbra.common.service.ServiceException) HttpClient(org.apache.http.client.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Example 92 with MultipartEntityBuilder

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

the class TestFileUpload method testMissingCsrfAdminUpload.

@Test
public void testMissingCsrfAdminUpload() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    HttpPost post = new HttpPost(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("localhost");
    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(FILE_NAME, "some file content".getBytes(), ContentType.create(contentType), FILE_NAME);
    HttpEntity httpEntity = builder.build();
    post.setEntity(httpEntity);
    HttpClient client = clientBuilder.build();
    HttpResponse httpResponse = HttpClientUtil.executeMethod(client, post);
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = EntityUtils.toString(httpResponse.getEntity());
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
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) Element(com.zimbra.common.soap.Element) 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) ServiceException(com.zimbra.common.service.ServiceException) HttpClient(org.apache.http.client.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Example 93 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project ats-framework by Axway.

the class HttpClient method constructRequestBody.

private void constructRequestBody() {
    // we have work to do here only when using multipart body
    if (requestBodyParts.size() > 0) {
        try {
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            for (HttpBodyPart part : requestBodyParts) {
                entityBuilder.addPart(part.getName(), part.constructContentBody());
            }
            requestBody = entityBuilder.build();
        } catch (Exception e) {
            throw new HttpException("Exception trying to create a multipart message.", e);
        }
    }
}
Also used : MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) URISyntaxException(java.net.URISyntaxException) GeneralSecurityException(java.security.GeneralSecurityException) ClientProtocolException(org.apache.http.client.ClientProtocolException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 94 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project vft-capture by videofirst.

the class DefaultUploadService method getHttpPost.

/**
 * Prepare HTTP Post upload call
 */
private HttpPost getHttpPost(Capture capture) {
    // Get capture file and data file
    File videoFile = validateExists(capture.getVideoFile());
    File dataFile = validateExists(capture.getDataFile());
    HttpPost httpPost = new HttpPost(uploadConfig.getUrl());
    uploadConfig.getHeaders().entrySet().stream().forEach(e -> httpPost.setHeader(e.getKey(), e.getValue()));
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody(PARAM_VIDEO, videoFile, ContentType.DEFAULT_BINARY, videoFile.getName());
    builder.addBinaryBody(PARAM_DATA, dataFile, ContentType.DEFAULT_BINARY, dataFile.getName());
    HttpEntity multipart = builder.build();
    ProgressListener pListener = new VideoUploadProgressListener(captureDao, capture, DAO_UPDATE_INTERVAL_MILLIS);
    httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
    return httpPost;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) ProgressListener(io.videofirst.capture.http.ProgressListener) File(java.io.File) ProgressEntityWrapper(io.videofirst.capture.http.ProgressEntityWrapper)

Example 95 with MultipartEntityBuilder

use of org.apache.http.entity.mime.MultipartEntityBuilder in project vft-capture by videofirst.

the class MockUploadController method main.

/**
 * Manually hit an end-point.
 */
public static void main(String[] args) throws IOException {
    String dir = "src/test/resources/videos/acme/moon-rocket/ui/bob-feature/dave-scenario/2018-02-15_12-14-02_n3jwzb/";
    File videoFile = new File(dir + "2018-02-15_12-14-02_n3jwzb.avi");
    File dataFile = new File(dir + "2018-02-15_12-14-02_n3jwzb.json");
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:1357/mock-upload");
    httpPost.setHeader("Authorization", "Basic dGVzdDpwYXNzd29yZA==");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("video", videoFile, ContentType.DEFAULT_BINARY, videoFile.getName());
    builder.addBinaryBody("data", dataFile, ContentType.DEFAULT_BINARY, dataFile.getName());
    HttpEntity multipart = builder.build();
    ProgressListener pListener = (transferredBytes, totalBytes) -> System.out.println("transferredBytes [ " + transferredBytes + " ] , totalBytes [ " + totalBytes + " ] ");
    httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
    System.out.println("Posting");
    CloseableHttpResponse response = client.execute(httpPost);
    System.out.println(response.getStatusLine().getStatusCode());
    client.close();
    System.out.println("Done");
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) PostMapping(org.springframework.web.bind.annotation.PostMapping) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestParam(org.springframework.web.bind.annotation.RequestParam) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) RequiredArgsConstructor(lombok.RequiredArgsConstructor) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) IOException(java.io.IOException) Profile(org.springframework.context.annotation.Profile) RestController(org.springframework.web.bind.annotation.RestController) File(java.io.File) ProgressEntityWrapper(io.videofirst.capture.http.ProgressEntityWrapper) ProgressListener(io.videofirst.capture.http.ProgressListener) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) HttpClients(org.apache.http.impl.client.HttpClients) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) ProgressListener(io.videofirst.capture.http.ProgressListener) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) ProgressEntityWrapper(io.videofirst.capture.http.ProgressEntityWrapper)

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