Example usage for org.apache.http.entity.mime MultipartEntityBuilder create

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntityBuilder create.

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:edu.si.services.sidora.rest.batch.BatchServiceTest.java

@Test
public void newBatchRequest_addResourceObjects_Test() throws Exception {

    String resourceListXML = FileUtils
            .readFileToString(new File("src/test/resources/test-data/batch-test-files/audio/audioFiles.xml"));

    String expectedHTTPResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
            + "<Batch>\n" + "    <ParentPID>" + parentPid + "</ParentPID>\n" + "    <CorrelationID>"
            + correlationId + "</CorrelationID>\n" + "</Batch>\n";

    BatchRequestResponse expectedCamelResponseBody = new BatchRequestResponse();
    expectedCamelResponseBody.setParentPID(parentPid);
    expectedCamelResponseBody.setCorrelationId(correlationId);

    MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
    mockEndpoint.expectedMessageCount(1);

    context.getComponent("sql", SqlComponent.class).setDataSource(db);
    context.getRouteDefinition("BatchProcessResources").autoStartup(false);

    //Configure and use adviceWith to mock for testing purpose
    context.getRouteDefinition("BatchProcessAddResourceObjects").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override/*from ww w  . j ava2s.c  om*/
                public void configure() throws Exception {
                    weaveById("httpGetResourceList").replace().setBody(simple(resourceListXML));

                    weaveByToString(".*bean:batchRequestControllerBean.*").replace().setHeader("correlationId",
                            simple(correlationId));

                    weaveAddLast().to("mock:result");

                }
            });

    HttpPost post = new HttpPost(BASE_URL + "/addResourceObjects/" + parentPid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);

    // Add filelist xml URL upload
    builder.addTextBody("resourceFileList", resourceFileList, ContentType.TEXT_PLAIN);
    // Add metadata xml file URL upload
    builder.addTextBody("ds_metadata", ds_metadata, ContentType.TEXT_PLAIN);
    // Add sidora xml URL upload
    builder.addTextBody("ds_sidora", ds_sidora, ContentType.TEXT_PLAIN);
    // Add association xml URL upload
    builder.addTextBody("association", association, ContentType.TEXT_PLAIN);
    // Add resourceOwner string
    builder.addTextBody("resourceOwner", resourceOwner, ContentType.TEXT_PLAIN);

    post.setEntity(builder.build());

    HttpResponse response = httpClient.execute(post);
    assertEquals(200, response.getStatusLine().getStatusCode());
    String responseBody = EntityUtils.toString(response.getEntity());
    log.debug("======================== [ RESPONSE ] ========================\n" + responseBody);

    assertEquals(expectedHTTPResponseBody, responseBody);

    log.debug("===============[ DB Requests ]================\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchRequests"));
    log.debug("===============[ DB Resources ]===============\n{}",
            jdbcTemplate.queryForList("select * from sidora.camelBatchResources"));

    BatchRequestResponse camelResultBody = (BatchRequestResponse) mockEndpoint.getExchanges().get(0).getIn()
            .getBody();

    assertIsInstanceOf(BatchRequestResponse.class, camelResultBody);
    assertEquals(camelResultBody.getParentPID(), parentPid);
    assertEquals(camelResultBody.getCorrelationId(), correlationId);

    assertMockEndpointsSatisfied();

}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java

@Test
public void doPostTest() throws URISyntaxException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL fileUrl = loader.getResource(INPUT_FILENAME);
    File inputFile = new File(fileUrl.toURI());
    assertNotNull(inputFile);// w w w. j a  va2 s . co  m
    assertTrue(inputFile.exists());
    assertTrue(inputFile.isFile());
    assertTrue(inputFile.canRead());

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(LOCAL_TOMCAT_SERVICE_URL);
    FileBody fileContent = new FileBody(inputFile);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, fileContent).build();
    httpPost.setEntity(reqEntity);

    CloseableHttpResponse response = null;
    try {
        logger.debug("executing request " + httpPost.getRequestLine());
        response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        logger.debug("Response status line : " + statusLine);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                logger.debug("len: " + len);
                logger.debug(EntityUtils.toString(entity));
            } else {
                logger.debug("len: " + len);
                Header[] allHeaders = response.getAllHeaders();
                for (Header h : allHeaders) {
                    logger.debug("Header: name:" + h.getName() + " -- value: " + h.getValue()
                            + " -- toString(): " + h);
                }
                Header header = entity.getContentEncoding();
                // logger.debug("header encoding: " + header.toString());
                header = entity.getContentType();
                logger.debug("header content type: " + header.toString());
                header = response.getFirstHeader("filename");
                String filename = header.getValue();
                String savedFilename = filename == null ? "file.pdf" : filename;
                InputStream is = entity.getContent();
                OutputStream out = new FileOutputStream("target/" + savedFilename);
                int bytesCnt;
                while ((bytesCnt = is.read()) != -1) {
                    out.write(bytesCnt);
                }
                out.close();
            }
        }
    } catch (IOException e) {
        logger.error("Something went wrong...", e);
        fail(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // nothing to do
                ;
            }
        }
    }
    logger.debug("DONE");

}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

@VisibleForTesting
String post(HttpRequestBase requestBase //
        , ReturningTextProcessor contentProcessable, HttpAction ha) {
    Post post = (Post) ha;//from w  w w  .j ava  2s  .  c  om
    Charset charset = Charset.forName(post.getCharset());
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    ImmutableMap<String, Object> postParams = post.getParams();
    for (Map.Entry<String, Object> entry : postParams.entrySet()) {
        applyToEntityBuilder(entry.getKey(), entry.getValue(), charset, entityBuilder);
    }
    ((HttpPost) requestBase).setEntity(entityBuilder.build());

    return executeAndProcess(requestBase, contentProcessable, ha);
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testUrlMatrixParamsShouldReplaceJobVariables() throws Exception {
    File jobFile = new File(RestSchedulerJobTaskTest.class.getResource("config/job_matrix_params.xml").toURI());

    String schedulerUrl = getResourceUrl("submit;var=matrix_param_val");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);//from   w ww.j ava 2s . com

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("file",
            new FileBody(jobFile, ContentType.APPLICATION_XML));
    httpPost.setEntity(multipartEntityBuilder.build());

    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    JSONObject jsonObj = toJsonObject(response);
    final String jobId = jsonObj.get("id").toString();
    assertNotNull(jobId);

    waitJobState(jobId, JobStatus.FINISHED, TimeUnit.MINUTES.toMillis(1));
}

From source file:de.yaio.commons.http.HttpUtils.java

/** 
 * execute POST-Request for url with params
 * @param baseUrl                the url to call
 * @param username               username for auth
 * @param password               password for auth
 * @param params                 params for the request
 * @param textFileParams         text-files to upload
 * @param binFileParams          bin-files to upload
 * @return                       HttpResponse
 * @throws IOException           possible Exception if Request-state <200 > 299 
 *///from   w w w .j  av a2s.c o m
public static HttpResponse callPostUrlPure(final String baseUrl, final String username, final String password,
        final Map<String, String> params, final Map<String, String> textFileParams,
        final Map<String, String> binFileParams) throws IOException {
    // create request
    HttpPost request = new HttpPost(baseUrl);

    // map params
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    if (MapUtils.isNotEmpty(params)) {
        for (String key : params.keySet()) {
            builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN);
        }
    }

    // map files
    if (MapUtils.isNotEmpty(textFileParams)) {
        for (String key : textFileParams.keySet()) {
            File file = new File(textFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key));
        }
    }
    // map files
    if (MapUtils.isNotEmpty(binFileParams)) {
        for (String key : binFileParams.keySet()) {
            File file = new File(binFileParams.get(key));
            builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key));
        }
    }

    // set request
    HttpEntity multipart = builder.build();
    request.setEntity(multipart);

    // add request header
    request.addHeader("User-Agent", "YAIOCaller");

    // call url
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Sending 'POST' request to URL : " + baseUrl);
    }
    HttpResponse response = executeRequest(request, username, password);

    // get response
    int retCode = response.getStatusLine().getStatusCode();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Response Code : " + retCode);
    }
    return response;
}

From source file:guru.nidi.ramltester.ServletRamlMessageTest.java

@Test
public void multipartForm() throws Exception {
    final HttpPost post = new HttpPost(url("test/more"));
    final HttpEntity entity = MultipartEntityBuilder.create()
            .addBinaryBody("binary", new byte[] { 65, 66, 67 }, ContentType.APPLICATION_OCTET_STREAM,
                    "filename")
            .addTextBody("param", "value").addTextBody("param", "v2").addTextBody("p2", "+$% ").build();
    post.setEntity(entity);/*from www .  java  2 s  .  c  o  m*/

    execute(post, new MessageTester() {
        @Override
        public void test(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
                RamlRequest ramlRequest, RamlResponse ramlResponse) throws IOException {
            final Values values = new Values().addValue("binary", new FileValue()).addValue("param", "value")
                    .addValue("param", "v2").addValue("p2", "+$% ");
            assertEquals(values, ramlRequest.getFormValues());
        }
    });
}

From source file:org.eclipse.vorto.repository.RestModelRepository.java

@Override
public UploadResult upload(String name, byte[] model) {
    Objects.requireNonNull(model, "Model should not be null.");
    Objects.requireNonNull(name, "Name should not be null.");
    try {/*  w ww. j a  va  2  s.c  o  m*/
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody(FILE_PARAMETER_NAME, model, ContentType.APPLICATION_OCTET_STREAM, name);
        HttpEntity fileToUpload = builder.build();

        UploadResultView uploadResult = httpClient.executePost("secure", fileToUpload, uploadResponseConverter);

        return uploadResultConverter.apply(uploadResult);
    } catch (Exception e) {
        throw new CheckInModelException("Error in uploading file to remote repository", e);
    }
}

From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java

static void getTokensFromCode() {
    access_token = null;/*from   ww  w.  j  a  v a2s.c om*/
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("refresh.txt").delete();

    if (gProps == null) {
        initGProps();
    }
    // Query for token now that user has gone through browser part
    // of
    // flow
    HttpPost tokenRequest = new HttpPost(gProps.token_uri);

    MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create();
    tokenRequestParams.addTextBody("client_id", gProps.client_id);
    tokenRequestParams.addTextBody("client_secret", gProps.client_secret);
    tokenRequestParams.addTextBody("code", device_code);
    tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0");

    HttpEntity reqEntity = tokenRequestParams.build();

    tokenRequest.setEntity(reqEntity);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(tokenRequest);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String responseJSON = EntityUtils.toString(resEntity);
                ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                access_token = root.get("access_token").asText();
                refresh_token = root.get("refresh_token").asText();
                token_start_time = System.currentTimeMillis() / 1000;
                expires_in = root.get("expires_in").asInt();
            }
        } else {
            log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadVideoRequest.java

/**
 * Create the required multipart entity//w ww  . j  a v  a2  s .  c  om
 * @param uploadId Session ID
 * @return Entity to submit to the upload
 * @throws ClientProtocolException
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("media_type", "2");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java

public String sendMultipartPostRequest(RestParams restParams, File file) throws SDKBadRequestException {
    if (restParams.getType() != HttpMethodType.POST) {
        throw new SDKBadRequestException(SDKErrorEnum.badRequestError, null, null, null, SdkConstants.APPLIANCE,
                null);//from  w  ww .  j a v a  2 s  . c o m
    }

    try {
        HttpPost post = new HttpPost(buildURI(restParams));

        HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("file", file)
                .setContentType(ContentType.MULTIPART_FORM_DATA).build();

        post.setEntity(entity);
        post.setConfig(createRequestTimeoutConfiguration());

        post.setHeader("uploadfilename", file.getName());
        post.setHeader("Auth", restParams.getSessionId());
        post.setHeader("X-Api-Version", String.valueOf(restParams.getApiVersion().getValue()));
        post.setHeader("Accept", restParams.getHeaders().get("Accept"));
        post.setHeader("accept-language", restParams.getHeaders().get("accept-language"));

        return getResponse(post, restParams, false);
    } catch (IllegalArgumentException e) {
        throw new SDKBadRequestException(SDKErrorEnum.badRequestError, null, null, null, SdkConstants.APPLIANCE,
                e);
    }
}