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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:net.yacy.grid.http.ClientConnection.java

/**
 * POST request//from w  ww. j ava2  s.  c  o  m
 * @param urlstring
 * @param map
 * @param useAuthentication
 * @throws ClientProtocolException 
 * @throws IOException
 */
public ClientConnection(String urlstring, Map<String, byte[]> map, boolean useAuthentication)
        throws ClientProtocolException, IOException {
    this.request = new HttpPost(urlstring);
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (Map.Entry<String, byte[]> entry : map.entrySet()) {
        entityBuilder.addBinaryBody(entry.getKey(), entry.getValue());
    }
    ((HttpPost) this.request).setEntity(entityBuilder.build());
    this.request.setHeader("User-Agent",
            ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    this.init();
}

From source file:org.wisdom.test.http.MultipartBody.java

/**
 * Computes the request payload.//from   ww w .j  av  a  2  s .  c  o  m
 *
 * @return the payload containing the declared fields and files.
 */
public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (Entry<String, Object> part : parameters.entrySet()) {
            if (part.getValue() instanceof File) {
                hasFile = true;
                builder.addPart(part.getKey(), new FileBody((File) part.getValue()));
            } else {
                builder.addPart(part.getKey(),
                        new StringBody(part.getValue().toString(), ContentType.APPLICATION_FORM_URLENCODED));
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.autonomy.aci.client.transport.impl.AciHttpClientImpl.java

/**
 * Create a {@code PostMethod} and adds the ACI parameters to the request body.
 * @param serverDetails The details of the ACI server the request will be sent to
 * @param parameters    The parameters to send with the ACI action.
 * @return An {@code HttpPost} that is ready to execute the ACI action.
 * @throws UnsupportedEncodingException Will be thrown if <tt>serverDetails.getCharsetName()</tt> returns a
 *                                      charset that is not supported by the JVM
 * @throws URISyntaxException           If there was a problem construction the request URI from the
 *                                      <tt>serverDetails</tt> and <tt>parameters</tt>
 */// w w  w.j ava2 s .  c o m
private HttpUriRequest createPostMethod(final AciServerDetails serverDetails,
        final Set<? extends ActionParameter<?>> parameters)
        throws URISyntaxException, UnsupportedEncodingException {
    LOGGER.trace("createPostMethod() called...");

    // Create the URI to use...
    final URI uri = new URIBuilder()
            .setScheme(serverDetails.getProtocol().toString().toLowerCase(Locale.ENGLISH))
            .setHost(serverDetails.getHost()).setPort(serverDetails.getPort()).setPath("/").build();

    // Create the method...
    final HttpPost method = new HttpPost(uri);

    final Charset charset = Charset.forName(serverDetails.getCharsetName());

    final boolean requiresMultipart = parameters.stream().anyMatch(ActionParameter::requiresPostRequest);

    if (requiresMultipart) {
        final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setCharset(charset);

        parameters.forEach(parameter -> parameter.addToEntity(multipartEntityBuilder, charset));

        // Convert the parameters into an entity...
        method.setEntity(multipartEntityBuilder.build());
    } else {
        method.setEntity(new StringEntity(convertParameters(parameters, serverDetails.getCharsetName()),
                serverDetails.getCharsetName()));
    }

    // Return the method...
    return method;
}

From source file:com.secdec.codedx.api.client.CodeDxClient.java

/**
 * Kicks off a CodeDx analysis run on a specified project
 *
 * @return A StartAnalysisResponse object
 * @param projectId The project ID/*from w  w  w .j av  a2 s .c  o  m*/
 * @param artifacts An array of streams to send over as analysis artifacts
 * @throws ClientProtocolException
 * @throws IOException
 * @throws CodeDxClientException
 *
 */
public StartAnalysisResponse startAnalysis(int projectId, InputStream[] artifacts)
        throws ClientProtocolException, IOException, CodeDxClientException {

    HttpPost postRequest = new HttpPost(url + "projects/" + projectId + "/analysis");
    postRequest.addHeader(KEY_HEADER, key);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (InputStream artifact : artifacts) {

        builder.addPart("file[]", new InputStreamBody(artifact, "file[]"));
    }

    HttpEntity entity = builder.build();

    postRequest.setEntity(entity);

    HttpResponse response = httpClient.execute(postRequest);

    int responseCode = response.getStatusLine().getStatusCode();

    if (responseCode != 202) {

        throw new CodeDxClientException(
                "Failed to start analysis.  " + IOUtils.toString(response.getEntity().getContent()),
                responseCode);
    }

    String data = IOUtils.toString(response.getEntity().getContent());

    return gson.<StartAnalysisResponse>fromJson(data, new TypeToken<StartAnalysisResponse>() {
    }.getType());
}

From source file:org.apache.nifi.api.client.impl.AbstractNiFiAPIClient.java

public <U extends Entity> Object post(Class<? extends ApplicationResource> resourceClass, Method nifiApiMethod,
        U u, Map<String, String> pathParams, InputStream payloadData) {

    StringBuilder stringBuilder = new StringBuilder(this.baseUrl);
    stringBuilder.append(resourceClass.getAnnotation(Path.class).value());
    stringBuilder.append("/");
    stringBuilder.append(nifiApiMethod.getAnnotation(Path.class).value());

    String fullRequest = replaceUriWithPathParams(stringBuilder.toString(), pathParams);

    HttpPost request = new HttpPost(fullRequest);

    StringBuffer result = new StringBuffer();
    try {/*from  w w  w. j a v a 2s. com*/

        //Set the Accept and Content-Type headers appropriately.
        String produces = nifiApiMethod.getAnnotation(Produces.class).value()[0];
        String consumes = nifiApiMethod.getAnnotation(Consumes.class).value()[0];

        //Set POST request payload. Can only upload either Inputstream OR Object currently.
        if (u != null || payloadData != null) {
            if (u != null) {
                StringEntity input = new StringEntity(mapper.writeValueAsString(u));
                request.setEntity(input);
                request.setHeader("Content-type", consumes);
            } else {
                InputStreamEntity inputStreamEntity = new InputStreamEntity(payloadData);
                request.setEntity(inputStreamEntity);

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

                // This attaches the file to the POST:
                builder.addBinaryBody("template", payloadData, ContentType.APPLICATION_OCTET_STREAM,
                        "SomethingTest.xml");

                HttpEntity multipart = builder.build();
                request.setEntity(multipart);
            }
        }

        request.addHeader("Accept", produces);

        HttpResponse response = client.execute(request);

        //Examine the return type and handle that data appropriately.
        Header rCT = response.getHeaders("Content-Type")[0];
        if (rCT.getValue().equalsIgnoreCase("application/xml")) {
            //                TemplateDTO templateDTO = TemplateDeserializer.deserialize(response.getEntity().getContent());
            //                return templateDTO;
            return null;
        } else {
            return mapper.readValue(response.getEntity().getContent(),
                    nifiApiMethod.getAnnotation(ApiOperation.class).response());
        }

    } catch (Exception ex) {
        logger.error("Unable to complete HTTP POST due to {}", ex.getMessage());
        return null;
    }
}

From source file:org.guvnor.ala.wildfly.access.WildflyClient.java

public int deploy(File file) throws WildflyClientException {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, managementPort),
            new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {//from   w  w w .  j a  va 2s . c om
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new WildflyClientException("Error Deploying App Status Code: " + statusCode);
        }
        return statusCode;
    } catch (IOException ex) {
        LOG.error("Error Deploying App : " + ex.getMessage(), ex);
        throw new WildflyClientException("Error Deploying App : " + ex.getMessage(), ex);
    }
}

From source file:de.siegmar.securetransfer.controller.MvcTest.java

@Test
public void messageWithoutFileWithoutPassword() throws Exception {
    final String messageToSend = "my secret message";

    final String boundary = "------TestBoundary" + UUID.randomUUID();
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary(boundary)
            .addTextBody("expirationDays", "1").addTextBody("message", messageToSend);

    // Create new message and expect redirect with flash message after store
    final MvcResult createMessageResult = mockMvc
            .perform(post("/send").content(ByteStreams.toByteArray(builder.build().getContent()))
                    .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary))
            .andExpect(status().isFound()).andExpect(redirectedUrlPattern("/send/**"))
            .andExpect(flash().attribute("message", messageToSend)).andReturn();

    // receive data after redirect
    final String messageStatusUrl = createMessageResult.getResponse().getRedirectedUrl();

    final MvcResult messageStatusResult = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage = (SenderMessage) messageStatusResult.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage);/*from  w  w w . java2  s  .co m*/
    assertNotNull(senderMessage.getId());
    assertNotNull(senderMessage.getReceiverId());
    assertNotNull(senderMessage.getExpiration());
    assertNull(senderMessage.getReceived());
    assertFalse(senderMessage.isPasswordEncrypted());

    final String receiveUrl = (String) messageStatusResult.getModelAndView().getModel().get("receiveUrl");

    assertNotNull(receiveUrl);

    final String linkSecret = messageStatusUrl.replaceFirst(".*linkSecret=", "");
    HashCode.fromString(linkSecret);

    // call receiver URL
    final MvcResult confirmPage = mockMvc.perform(get(receiveUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message_confirm")).andReturn();

    final Document confirmPageDoc = Jsoup.parse(confirmPage.getResponse().getContentAsString());
    final String confirmUrl = confirmPageDoc.getElementsByTag("form").attr("action");

    // Receive message
    final MvcResult messageResult = mockMvc.perform(get(confirmUrl).param("linkSecret", linkSecret))
            .andExpect(status().isOk()).andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message")).andReturn();

    final DecryptedMessage decryptedMessage = (DecryptedMessage) messageResult.getModelAndView().getModel()
            .get("decryptedMessage");

    assertEquals(messageToSend, decryptedMessage.getMessage());
    assertEquals(0, decryptedMessage.getFiles().size());

    // Check message is burned
    mockMvc.perform(get(receiveUrl)).andExpect(status().isNotFound())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("message_not_found"));

    // Check sender status page
    final MvcResult messageStatusResult2 = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage2 = (SenderMessage) messageStatusResult2.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage2);
    assertNotNull(senderMessage2.getId());
    assertNotNull(senderMessage2.getReceiverId());
    assertNotNull(senderMessage2.getExpiration());
    assertNotNull(senderMessage2.getReceived());
    assertFalse(senderMessage.isPasswordEncrypted());
}

From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java

@Test
public void testGeoPackageImport() throws Exception {

    URL url = getClass().getResource("places.gpkg");

    // create transaction
    final String beginTransactionUrl = BASE_URL + "/beginTransaction";

    Document dom = getAsDOM(beginTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);
    String transactionId = XMLUnit.newXpathEngine().evaluate("/response/Transaction/ID", dom);

    // import geopackage
    final String importUrl = BASE_URL + "/import?format=gpkg&message=Import%20GeoPackage&transactionId="
            + transactionId;//from   w  w w.j a v  a 2 s  . c om
    final String endTransactionUrl = BASE_URL + "/endTransaction?transactionId=" + transactionId;

    // construct a multipart request with the fileUpload
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    File f = new File(url.getFile());
    builder.addBinaryBody("fileUpload", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM,
            f.getName());

    HttpEntity multipart = builder.build();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    multipart.writeTo(outputStream);
    MockHttpServletResponse response = postAsServletResponse(importUrl, outputStream.toByteArray(),
            multipart.getContentType().getValue());

    assertEquals(200, response.getStatus());

    dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()), true);
    String taskId = XMLUnit.newXpathEngine().evaluate("/task/id", dom);
    final String taskUrl = "/geogig/tasks/" + taskId + ".xml";
    while ("RUNNING".equals(XMLUnit.newXpathEngine().evaluate("/task/status", dom))) {
        Thread.sleep(100);
        dom = getAsDOM(taskUrl);
    }
    assertXpathEvaluatesTo("FINISHED", "/task/status", dom);
    String commitId = XMLUnit.newXpathEngine().evaluate("//commit/id", dom);

    // close transaction
    dom = getAsDOM(endTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);

    // verify the repo contains the import
    Repository repository = geogigData.getGeogig().getRepository();
    RevCommit head = repository.getCommit(repository.getHead().get().getObjectId());
    assertEquals(commitId, head.getId().toString());
    assertEquals("Import GeoPackage", head.getMessage());
}

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

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException// w  ww  . ja va 2s  .c o  m
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(File imageFile, 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("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

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

From source file:com.github.fabienbarbero.flickr.api.CommandArguments.java

public HttpEntity getBody(Map<String, String> additionalParameters) {
    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    for (Parameter param : params) {
        if (!param.internal) {
            if (param.value instanceof File) {
                entity.addBinaryBody(param.key, (File) param.value);
            } else if (param.value instanceof String) {
                entity.addTextBody(param.key, (String) param.value, CT_TEXT);
            }/*from ww w .  j av  a 2  s.c om*/
        }
    }
    for (Map.Entry<String, String> entry : additionalParameters.entrySet()) {
        entity.addTextBody(entry.getKey(), entry.getValue(), CT_TEXT);
    }

    return entity.build();
}