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

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

Introduction

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

Prototype

ContentType APPLICATION_OCTET_STREAM

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

Click Source Link

Usage

From source file:com.wudaosoft.net.httpclient.Request.java

/**
 * /*w  w  w .  j  a v a2 s. c  o m*/
 * @param workerBuilder
 * @param responseHandler
 * @return
 * @throws Exception
 */
public <T> T doRequest(WorkerBuilder workerBuilder, ResponseHandler<T> responseHandler) throws Exception {

    String method = workerBuilder.getMethod();
    String url = workerBuilder.getUrl();

    Args.notNull(workerBuilder, "WorkerBuilder");
    Args.notEmpty(method, "WorkerBuilder.getMethod()");
    Args.notEmpty(url, "WorkerBuilder.getUrl()");
    Args.notNull(responseHandler, "responseHandler");

    //      if(!workerBuilder.isAnyHost()) {
    if (!isFullUrl(url)) {
        //         notFullUrl(url);
        Args.notEmpty(hostConfig.getHostUrl(), "HostConfig.getHostUrl()");
        url = hostConfig.getHostUrl() + url;
    }

    Charset charset = hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset();
    String stringBody = workerBuilder.getStringBody();
    File fileBody = workerBuilder.getFileBody();
    InputStream streamBody = workerBuilder.getStreamBody();
    Map<String, String> params = workerBuilder.getParameters();

    String contentType = null;

    if (responseHandler instanceof JsonResponseHandler) {
        contentType = MediaType.APPLICATION_JSON_VALUE;
    } else if (responseHandler instanceof SAXSourceResponseHandler
            || responseHandler instanceof XmlResponseHandler) {
        contentType = MediaType.APPLICATION_XML_VALUE;
    } else if (responseHandler instanceof FileResponseHandler || responseHandler instanceof ImageResponseHandler
            || responseHandler instanceof OutputStreamResponseHandler) {
        contentType = MediaType.ALL_VALUE;
    } else if (responseHandler instanceof NoResultResponseHandler) {
        contentType = ((NoResultResponseHandler) responseHandler).getContentType().getMimeType();
    } else {
        contentType = MediaType.TEXT_PLAIN_VALUE;
    }

    RequestBuilder requestBuilder = RequestBuilder.create(method).setCharset(charset).setUri(url);

    if (stringBody != null) {

        StringEntity reqEntity = new StringEntity(stringBody, charset);
        reqEntity.setContentType(contentType + ";charset=" + charset.name());
        requestBuilder.setEntity(reqEntity);

    } else if (fileBody != null || streamBody != null) {

        String filename = workerBuilder.getFilename();

        MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create().setLaxMode();

        if (fileBody != null) {
            Args.check(fileBody.isFile(), "fileBody must be a file");
            Args.check(fileBody.canRead(), "fileBody must be readable");

            if (filename == null && streamBody == null)
                filename = fileBody.getName();

            FileBody bin = new FileBody(fileBody, ContentType.APPLICATION_OCTET_STREAM,
                    streamBody != null ? fileBody.getName() : filename);
            reqEntity.addPart(workerBuilder.getFileFieldName(), bin);
        }

        Args.notEmpty(filename, "filename");

        if (streamBody != null)
            reqEntity.addBinaryBody(workerBuilder.getFileFieldName(), streamBody,
                    ContentType.APPLICATION_OCTET_STREAM, filename);

        buildParameters(reqEntity, params, charset);

        requestBuilder.setEntity(reqEntity.build());
    }

    if (fileBody == null && streamBody == null) {
        buildParameters(requestBuilder, params);
    }

    if (workerBuilder.getReadTimeout() > -1) {

        requestBuilder.setConfig(RequestConfig.copy(this.hostConfig.getRequestConfig())
                .setSocketTimeout(workerBuilder.getReadTimeout()).build());
    }

    HttpUriRequest httpRequest = ParameterRequestBuilder.build(requestBuilder);

    setAcceptHeader(httpRequest, contentType);

    if (workerBuilder.isAjax())
        setAjaxHeader(httpRequest);

    HttpClientContext context = workerBuilder.getContext();
    if (context == null)
        context = defaultHttpContext;

    T result = getHttpClient().execute(httpRequest, responseHandler, context);

    if (log.isDebugEnabled()) {
        log.debug(String.format("Send data to path:[%s]\"%s\". result: %s", method, url, result));
    }

    return result;
}

From source file:com.threatconnect.sdk.client.writer.AbstractWriterAdapter.java

protected <T extends ApiEntitySingleResponse> T uploadFile(String propName, Class<T> type, String ownerName,
        HttpEntity requestEntity, Map<String, Object> paramMap, UploadMethodType uploadMethodType,
        Boolean updateIfExists) throws FailedResponseException, UnsupportedEncodingException {
    return uploadFile(propName, type, ownerName, requestEntity, paramMap, uploadMethodType, updateIfExists,
            ContentType.APPLICATION_OCTET_STREAM.toString());
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java

public void canCreateMpuRequestBodyJsonWithHeadersAndMetadata() throws IOException {
    final String path = "/user/stor/object";
    final MantaHttpHeaders headers = new MantaHttpHeaders();

    headers.setDurabilityLevel(5);//from   w w w .j a v a  2  s  .  c om
    headers.setContentLength(423534L);
    headers.setContentMD5("e59ff97941044f85df5297e1c302d260");
    headers.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString());
    final Set<String> roles = new HashSet<>();
    roles.add("manta");
    roles.add("role2");
    headers.setRoles(roles);

    final MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-mykey1", "key value 1");
    metadata.put("m-mykey2", "key value 2");
    metadata.put("e-mykey", "i should be ignored");

    final byte[] json = ServerSideMultipartManager.createMpuRequestBody(path, metadata, headers);

    ObjectNode jsonObject = mapper.readValue(json, ObjectNode.class);

    try {
        Assert.assertEquals(jsonObject.get("objectPath").textValue(), path);
        ObjectNode jsonHeaders = (ObjectNode) jsonObject.get("headers");

        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_DURABILITY_LEVEL.toLowerCase()).asInt(),
                headers.getDurabilityLevel().intValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_LENGTH.toLowerCase()).asLong(),
                headers.getContentLength().longValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_MD5.toLowerCase()).textValue(),
                headers.getContentMD5());
        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()).textValue(),
                headers.getFirstHeaderStringValue(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()));
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_TYPE.toLowerCase()).textValue(),
                "application/octet-stream");

        Assert.assertEquals(jsonHeaders.get("m-mykey1").textValue(), metadata.get("m-mykey1"));
        Assert.assertEquals(jsonHeaders.get("m-mykey2").textValue(), metadata.get("m-mykey2"));

        Assert.assertNull(jsonHeaders.get("e-mykey"), "Encrypted headers should not be included");
    } catch (AssertionError e) {
        System.err.println(new String(json, StandardCharsets.UTF_8));
        throw e;
    }
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * //  w w  w.jav a 2s. c  o  m
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param tableName  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromDAS(String datasetName, String version, String tableName)
        throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("description",
                new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourceType", new StringBody("das", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourcePath", new StringBody(tableName, ContentType.TEXT_PLAIN));

        if (datasetName != null) {
            multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN));
        }
        if (version != null) {
            multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN));
        }
        multipartEntityBuilder.addBinaryBody("file", new byte[] {}, ContentType.APPLICATION_OCTET_STREAM,
                "IndiansDiabetes.csv");
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to upload dataset from DAS " + tableName, e);
    }
}

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testCreateMedia() throws Exception {
    // treating update and create as same for now, as there is details about
    // how entity payload and media payload can be sent at same time in request's body
    String editUrl = baseURL + "/Photos(1)/$value";
    HttpPut request = new HttpPut(editUrl);
    request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java

/**
 * Create an HTTP post request suitable for sending to the API server.
 *
 * @param environment The current VMApiProxyEnvironment
 * @param packageName The API call package
 * @param methodName The API call method
 * @param requestData The POST payload./*  ww w . ja va  2 s  . c o m*/
 * @param timeoutMs The timeout for this request
 * @return an HttpPost object to send to the API.
 */
// 
static HttpPost createRequest(VmApiProxyEnvironment environment, String packageName, String methodName,
        byte[] requestData, int timeoutMs) {
    // Wrap the payload in a RemoteApi Request.
    RemoteApiPb.Request remoteRequest = new RemoteApiPb.Request();
    remoteRequest.setServiceName(packageName);
    remoteRequest.setMethod(methodName);
    remoteRequest.setRequestId(environment.getTicket());
    remoteRequest.setRequestAsBytes(requestData);

    HttpPost request = new HttpPost("http://" + environment.getServer() + REQUEST_ENDPOINT);
    request.setHeader(RPC_STUB_ID_HEADER, REQUEST_STUB_ID);
    request.setHeader(RPC_METHOD_HEADER, REQUEST_STUB_METHOD);

    // Set TCP connection timeouts.
    HttpParams params = new BasicHttpParams();
    params.setLongParameter(ConnManagerPNames.TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutMs + ADDITIONAL_HTTP_TIMEOUT_BUFFER_MS);

    // Performance tweaks.
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.TRUE);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, Boolean.FALSE);
    request.setParams(params);

    // The request deadline can be overwritten by the environment, read deadline if available.
    Double deadline = (Double) (environment.getAttributes().get(API_DEADLINE_KEY));
    if (deadline == null) {
        request.setHeader(RPC_DEADLINE_HEADER,
                Double.toString(TimeUnit.SECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS)));
    } else {
        request.setHeader(RPC_DEADLINE_HEADER, Double.toString(deadline));
    }

    // If the incoming request has a dapper trace header: set it on outgoing API calls
    // so they are tied to the original request.
    Object dapperHeader = environment.getAttributes()
            .get(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.attributeKey);
    if (dapperHeader instanceof String) {
        request.setHeader(VmApiProxyEnvironment.AttributeMapping.DAPPER_ID.headerKey, (String) dapperHeader);
    }

    // If the incoming request has a Cloud trace header: set it on outgoing API calls
    // so they are tied to the original request.
    // TODO(user): For now, this uses the incoming span id - use the one from the active span.
    Object traceHeader = environment.getAttributes()
            .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey);
    if (traceHeader instanceof String) {
        request.setHeader(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.headerKey,
                (String) traceHeader);
    }

    ByteArrayEntity postPayload = new ByteArrayEntity(remoteRequest.toByteArray(),
            ContentType.APPLICATION_OCTET_STREAM);
    postPayload.setChunked(false);
    request.setEntity(postPayload);

    return request;
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * @throws MLHttpClientException// w ww  .java 2s.  c o  m
 */
public CloseableHttpResponse predictFromCSV(long modelId, String resourcePath) throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/models/predict");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("modelId", new StringBody(modelId + "", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));

        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetesPredict.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to predict from csv " + resourcePath, e);
    }
}

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testCreateStream() throws Exception {
    // treating update and create as same for now, as there is details about
    // how entity payload and media payload can be sent at same time in request's body
    String editUrl = baseURL + "/Airlines('AA')/Picture";
    HttpPost request = new HttpPost(editUrl);
    request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
    // method not allowed
    HttpResponse response = httpSend(request, 405);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:org.infinispan.server.test.configs.ExampleConfigsTest.java

@Test
@WithRunningServer("standalone-compatibility-mode")
public void testCompatibilityModeConfig() throws Exception {
    MemcachedClient memcachedClient = null;
    CloseableHttpClient restClient = null;
    try {/* w w  w.j  av a  2 s. com*/
        RemoteInfinispanMBeans s1 = createRemotes("standalone-compatibility-mode", "local", DEFAULT_CACHE_NAME);
        RemoteCache<Object, Object> s1Cache = createCache(s1);
        restClient = HttpClients.createDefault();
        String restUrl = "http://" + s1.server.getHotrodEndpoint().getInetAddress().getHostName() + ":8080"
                + s1.server.getRESTEndpoint().getContextPath() + "/" + DEFAULT_CACHE_NAME;
        memcachedClient = new MemcachedClient(s1.server.getMemcachedEndpoint().getInetAddress().getHostName(),
                s1.server.getMemcachedEndpoint().getPort());
        String key = "1";

        // 1. Put with Hot Rod
        assertEquals(null, s1Cache.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1".getBytes()));
        assertArrayEquals("v1".getBytes(), (byte[]) s1Cache.get(key));

        // 2. Get with REST
        HttpGet get = new HttpGet(restUrl + "/" + key);
        HttpResponse getResponse = restClient.execute(get);
        assertEquals(HttpServletResponse.SC_OK, getResponse.getStatusLine().getStatusCode());
        assertArrayEquals("v1".getBytes(), EntityUtils.toByteArray(getResponse.getEntity()));

        // 3. Get with Memcached
        assertArrayEquals("v1".getBytes(), readWithMemcachedAndDeserialize(key, memcachedClient));

        key = "2";

        // 1. Put with REST
        HttpPut put = new HttpPut(restUrl + "/" + key);
        put.setEntity(new ByteArrayEntity("<hey>ho</hey>".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
        HttpResponse putResponse = restClient.execute(put);
        assertEquals(HttpServletResponse.SC_OK, putResponse.getStatusLine().getStatusCode());

        // 2. Get with Hot Rod
        assertArrayEquals("<hey>ho</hey>".getBytes(), (byte[]) s1Cache.get(key));

        // 3. Get with Memcached
        assertArrayEquals("<hey>ho</hey>".getBytes(), readWithMemcachedAndDeserialize(key, memcachedClient));
    } finally {
        if (restClient != null) {
            restClient.close();
        }
        if (memcachedClient != null) {
            memcachedClient.close();
        }
    }
}