Example usage for org.apache.http.entity ContentType DEFAULT_BINARY

List of usage examples for org.apache.http.entity ContentType DEFAULT_BINARY

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType DEFAULT_BINARY.

Prototype

ContentType DEFAULT_BINARY

To view the source code for org.apache.http.entity ContentType DEFAULT_BINARY.

Click Source Link

Usage

From source file:nl.nn.adapterframework.http.mime.MultipartEntityBuilder.java

public MultipartEntityBuilder addBinaryBody(String name, byte[] b) {
    return addBinaryBody(name, b, ContentType.DEFAULT_BINARY, null);
}

From source file:org.rapidoid.http.HttpClientUtil.java

private static NByteArrayEntity paramsBody(Map<String, Object> data, Map<String, List<Upload>> files) {
    data = U.safe(data);//  www .j  a  v  a 2s  .  c om
    files = U.safe(files);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    for (Map.Entry<String, List<Upload>> entry : files.entrySet()) {
        for (Upload file : entry.getValue()) {
            builder = builder.addBinaryBody(entry.getKey(), file.content(), ContentType.DEFAULT_BINARY,
                    file.filename());
        }
    }

    for (Map.Entry<String, Object> entry : data.entrySet()) {
        String name = entry.getKey();
        String value = String.valueOf(entry.getValue());
        builder = builder.addTextBody(name, value, ContentType.DEFAULT_TEXT);
    }

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        builder.build().writeTo(stream);
    } catch (IOException e) {
        throw U.rte(e);
    }

    byte[] bytes = stream.toByteArray();
    return new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);
}

From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java

@Test(expected = TransportException.class)
public void testGzipErrorsResponse() throws TransportException, IOException {
    byte[] respPayload = "gzip resp".getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream os = new GZIPOutputStream(baos);
    os.write(respPayload);/*w  w  w . java  2  s.c o  m*/
    os.close();
    byte[] compressedResponse = baos.toByteArray();

    HttpClient client = getMockClientWithResponse(compressedResponse, ContentType.DEFAULT_BINARY,
            HttpStatus.SC_INTERNAL_SERVER_ERROR, true);
    HttpTransport transport = new HttpTransport(client, "", true, 1, 1);

    try {
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("http transport call failed because \"expected failure\" payload response \"gzip resp\"",
                e.getCause().getMessage());
        throw e;
    }
}

From source file:nl.nn.adapterframework.http.mime.MultipartEntityBuilder.java

public MultipartEntityBuilder addBinaryBody(String name, File file) {
    return addBinaryBody(name, file, ContentType.DEFAULT_BINARY, file != null ? file.getName() : null);
}

From source file:org.lokra.seaweedfs.core.FileTemplate.java

/**
 * Save files by stream map.// ww  w.j a  v a2 s .  c om
 *
 * @param streamMap Map of file name and file stream.
 * @return Files status.
 * @throws IOException Http connection is fail or server response within some error message.
 */
public LinkedHashMap<String, FileHandleStatus> saveFilesByStreamMap(
        LinkedHashMap<String, InputStream> streamMap) throws IOException {
    return saveFilesByStreamMap(streamMap, ContentType.DEFAULT_BINARY);
}

From source file:com.app.precared.utils.MultipartEntityBuilder.java

public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream) {
    return addBinaryBody(name, stream, ContentType.DEFAULT_BINARY, null);
}

From source file:com.hpe.application.automation.tools.pc.MockPcRestProxy.java

@Override
protected HttpResponse executeRequest(HttpRequestBase request)
        throws PcException, ClientProtocolException, IOException {
    HttpResponse response = null;/* ww w . j ava2s. c  om*/
    String requestUrl = request.getURI().toString();
    if (requestUrl
            .equals(String.format(AUTHENTICATION_LOGIN_URL, PcTestBase.WEB_PROTOCOL, PcTestBase.PC_SERVER_NAME))
            || requestUrl.equals(String.format(AUTHENTICATION_LOGOUT_URL, PcTestBase.WEB_PROTOCOL,
                    PcTestBase.PC_SERVER_NAME))
            || requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s", RUNS_RESOURCE_NAME,
                    PcTestBase.RUN_ID, PcTestBase.STOP_MODE))) {
        response = getOkResponse();
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s", RUNS_RESOURCE_NAME)) || requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", RUNS_RESOURCE_NAME, PcTestBase.RUN_ID))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.runResponseEntity));
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s", TESTS_RESOURCE_NAME)) || requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", TESTS_RESOURCE_NAME, PcTestBase.TEST_ID))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.testResponseEntity));
    } else if (requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", RUNS_RESOURCE_NAME, PcTestBase.RUN_ID_WAIT))) {
        response = getOkResponse();
        response.setEntity(
                new StringEntity(PcTestBase.runResponseEntity.replace("*", runState.next().value())));
        if (!runState.hasNext())
            runState = initializeRunStateIterator();
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s", RUNS_RESOURCE_NAME,
            PcTestBase.RUN_ID, RESULTS_RESOURCE_NAME))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.runResultsEntity));
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s/%s/data", RUNS_RESOURCE_NAME,
            PcTestBase.RUN_ID, RESULTS_RESOURCE_NAME, PcTestBase.REPORT_ID))) {
        response = getOkResponse();
        response.setEntity(
                new FileEntity(new File(getClass().getResource(PcBuilder.pcReportArchiveName).getPath()),
                        ContentType.DEFAULT_BINARY));
    }
    if (response == null)
        throw new PcException(
                String.format("%s %s is not recognized by PC Rest Proxy", request.getMethod(), requestUrl));
    return response;
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {// w w  w . j a va  2s . c om
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransporterTest.java

@Test(expected = TransportException.class)
public void testGzipErrorsResponse() throws TransportException, IOException {
    byte[] respPayload = getResponse().getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream os = new GZIPOutputStream(baos);
    os.write(respPayload);// ww w. java  2  s . c om
    os.close();
    byte[] compressedResponse = baos.toByteArray();

    HttpClient client = getMockClientWithResponse(compressedResponse, ContentType.DEFAULT_BINARY,
            HttpStatus.SC_OK);
    ElasticSearchTransport transport = new ElasticSearchTransport(client, true);

    try {
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("es call failed because expected failure", e.getCause().getMessage());
        throw e;
    }
}

From source file:objective.taskboard.it.TemplateIT.java

private HttpResponse uploadTemplate(File file) throws URISyntaxException, IOException {
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody templateName = new StringBody(file.getName(), ContentType.MULTIPART_FORM_DATA);
    StringBody roles = new StringBody("Role", ContentType.MULTIPART_FORM_DATA);
    builder.addPart("file", fileBody);
    builder.addPart("name", templateName);
    builder.addPart("roles", roles);
    HttpEntity entity = builder.build();

    HttpPost post = new HttpPost();
    post.setURI(new URI("http://localhost:8900/api/templates"));
    post.setHeaders(session);//ww w .  java 2 s  .  com
    post.setEntity(entity);

    return client.execute(post);
}