Example usage for org.apache.http.entity ByteArrayEntity ByteArrayEntity

List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity

Introduction

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

Prototype

public ByteArrayEntity(byte[] bArr) 

Source Link

Usage

From source file:org.jclouds.http.apachehc.ApacheHCUtils.java

public void addEntityForContent(HttpEntityEnclosingRequest apacheRequest, Payload payload) {
    payload = payload instanceof DelegatingPayload ? DelegatingPayload.class.cast(payload).getDelegate()
            : payload;//from w w w . j  av a2 s  . co  m
    if (payload instanceof StringPayload) {
        StringEntity nStringEntity = null;
        try {
            nStringEntity = new StringEntity((String) payload.getRawContent());
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("Encoding not supported", e);
        }
        nStringEntity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(nStringEntity);
    } else if (payload instanceof FilePayload) {
        apacheRequest.setEntity(
                new FileEntity((File) payload.getRawContent(), payload.getContentMetadata().getContentType()));
    } else if (payload instanceof ByteArrayPayload) {
        ByteArrayEntity Entity = new ByteArrayEntity((byte[]) payload.getRawContent());
        Entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(Entity);
    } else {
        InputStream inputStream = payload.getInput();
        if (payload.getContentMetadata().getContentLength() == null)
            throw new IllegalArgumentException("you must specify size when content is an InputStream");
        InputStreamEntity entity = new InputStreamEntity(inputStream,
                payload.getContentMetadata().getContentLength());
        entity.setContentType(payload.getContentMetadata().getContentType());
        apacheRequest.setEntity(entity);
    }

    // TODO Reproducing old behaviour exactly; ignoring Content-Type, Content-Length and Content-MD5
    Set<String> desiredHeaders = ImmutableSet.of("Content-Disposition", "Content-Encoding", "Content-Language",
            "Expires");
    MutableContentMetadata md = payload.getContentMetadata();
    for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {
        if (desiredHeaders.contains(entry.getKey())) {
            apacheRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }

    assert apacheRequest.getEntity() != null;
}

From source file:com.klarna.checkout.BasicConnector.java

/**
 * Create a HttpUriRequest object.//  www  .  j a v a 2  s.  c om
 *
 * @param method HTTP Method
 * @param resource IResource implementation
 * @param options Options for Connector
 *
 * @return the appropriate HttpUriRequest
 *
 * @throws UnsupportedEncodingException if the payloads encoding is not
 * supported
 */
protected HttpUriRequest createRequest(final String method, final IResource resource,
        final ConnectorOptions options) throws UnsupportedEncodingException {

    URI uri = this.getUri(options, resource);

    HttpUriRequest req;

    if (method.equals("GET")) {
        req = new HttpGet(uri);
    } else {
        HttpPost post = new HttpPost(uri);
        String payload = JSONObject.toJSONString(getData(options, resource));

        post.setEntity(new ByteArrayEntity(payload.getBytes("UTF-8")));

        post.setHeader("Content-Type", resource.getContentType());
        req = post;
    }

    req.setHeader("UserAgent", createtUserAgent().toString());
    req.setHeader("Accept", resource.getContentType());

    return req;
}

From source file:leap.lang.http.client.apache.ApacheHttpRequest.java

protected void initRequest() {
    if (null != body) {
        entity = new ByteArrayEntity(body);
    } else if (null != inputStream) {
        entity = new InputStreamEntity(inputStream);
    } else if (!formParams.isEmpty()) {
        entity = new UrlEncodedFormEntity(formParams, charset);
    }//from   ww w  . j  ava 2 s  .  c  o m

    if (null == method) {

        if (null != entity) {
            method = HTTP.Method.POST;
        } else {
            method = HTTP.Method.GET;
        }

    }
}

From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformerTest.java

@Before
public void setup() throws GeneralSecurityException, OperatorCreationException, IOException {
    objectMapper = new ObjectMapper();
    keyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM, TlsConfig.DEFAULT_KEY_SIZE);

    testToken = "testTokenTestToken";
    testCaHostname = "testCaHostname";
    testPort = 8993;//from  w  w  w . j  a v a2s  . c  o  m
    certificates = new ArrayList<>();

    when(tlsClientConfig.getToken()).thenReturn(testToken);
    when(tlsClientConfig.getCaHostname()).thenReturn(testCaHostname);
    when(tlsClientConfig.getDn()).thenReturn(new TlsConfig().calcDefaultDn(testCaHostname));
    when(tlsClientConfig.getPort()).thenReturn(testPort);
    when(tlsClientConfig.createCertificateSigningRequestPerformer())
            .thenReturn(tlsCertificateSigningRequestPerformer);
    when(tlsClientConfig.getSigningAlgorithm()).thenReturn(TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = TlsHelper.generateCertificationRequest(
            tlsClientConfig.getDn(), null, keyPair, TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    String testCsrPem = TlsHelper.pemEncodeJcaObject(jcaPKCS10CertificationRequest);
    when(httpClientBuilderSupplier.get()).thenReturn(httpClientBuilder);
    when(httpClientBuilder.build()).thenAnswer(invocation -> {
        Field sslSocketFactory = HttpClientBuilder.class.getDeclaredField("sslSocketFactory");
        sslSocketFactory.setAccessible(true);
        Object o = sslSocketFactory.get(httpClientBuilder);
        Field field = TlsCertificateAuthorityClientSocketFactory.class.getDeclaredField("certificates");
        field.setAccessible(true);
        ((List<X509Certificate>) field.get(o)).addAll(certificates);
        return closeableHttpClient;
    });
    StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenAnswer(i -> statusCode);
    when(closeableHttpClient.execute(eq(new HttpHost(testCaHostname, testPort, "https")), any(HttpPost.class)))
            .thenAnswer(invocation -> {
                HttpPost httpPost = (HttpPost) invocation.getArguments()[1];
                TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = objectMapper
                        .readValue(httpPost.getEntity().getContent(), TlsCertificateAuthorityRequest.class);
                assertEquals(tlsCertificateAuthorityRequest.getCsr(), testCsrPem);
                CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
                when(closeableHttpResponse.getEntity()).thenAnswer(i -> {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    objectMapper.writeValue(byteArrayOutputStream, tlsCertificateAuthorityResponse);
                    return new ByteArrayEntity(byteArrayOutputStream.toByteArray());
                });
                when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
                return closeableHttpResponse;
            });
    KeyPair caKeyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM,
            TlsConfig.DEFAULT_KEY_SIZE);
    caCertificate = CertificateUtils.generateSelfSignedX509Certificate(caKeyPair, "CN=fakeCa",
            TlsConfig.DEFAULT_SIGNING_ALGORITHM, TlsConfig.DEFAULT_DAYS);
    testHmac = TlsHelper.calculateHMac(testToken, caCertificate.getPublicKey());
    signedCsr = CertificateUtils.generateIssuedCertificate(
            jcaPKCS10CertificationRequest.getSubject().toString(), jcaPKCS10CertificationRequest.getPublicKey(),
            caCertificate, caKeyPair, TlsConfig.DEFAULT_SIGNING_ALGORITHM, TlsConfig.DEFAULT_DAYS);
    testSignedCsr = TlsHelper.pemEncodeJcaObject(signedCsr);

    tlsCertificateSigningRequestPerformer = new TlsCertificateSigningRequestPerformer(httpClientBuilderSupplier,
            tlsClientConfig);
}

From source file:com.nxt.zyl.data.volley.toolbox.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        final Request<?> request) throws IOException, AuthFailureError {
    if (request instanceof MultiPartRequest) {
        final UploadMultipartEntity multipartEntity = ((MultiPartRequest<?>) request).getMultipartEntity();
        httpRequest.setEntity(multipartEntity);
    } else {//from w ww.ja  v a  2  s. c om
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }
}

From source file:com.microsoft.projectoxford.face.rest.WebServiceRequest.java

private Object post(String url, Map<String, Object> data, String contentType)
        throws ClientException, IOException {
    HttpPost request = new HttpPost(url);
    boolean isStream = false;

    if (contentType != null && !(contentType.length() == 0)) {
        request.setHeader(CONTENT_TYPE, contentType);
        if (contentType.toLowerCase().contains(OCTET_STREAM)) {
            isStream = true;//  w  ww.ja  va 2 s .  c o m
        }
    } else {
        request.setHeader(CONTENT_TYPE, APPLICATION_JSON);
    }

    request.setHeader(HEADER_KEY, this.mSubscriptionKey);

    if (!isStream) {
        String json = mGson.toJson(data).toString();
        StringEntity entity = new StringEntity(json);
        request.setEntity(entity);
    } else {
        request.setEntity(new ByteArrayEntity((byte[]) data.get(DATA)));
    }

    HttpResponse response = mClient.execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
        return readInput(response.getEntity().getContent());
    } else {
        String json = readInput(response.getEntity().getContent());
        if (json != null) {
            ServiceError error = mGson.fromJson(json, ServiceError.class);
            if (error != null) {
                throw new ClientException(error.error);
            }
        }

        throw new ClientException("Error executing POST request!", statusCode);
    }
}

From source file:de.electricdynamite.pasty.PastyClient.java

public String addItem(final String Item) throws PastyException {
    String url = REST_SERVER_BASE_URL + REST_URI_ITEM;
    if (LOCAL_LOG)
        Log.v(TAG, "Starting REST call to API endpoint " + url);
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    JSONObject params = new JSONObject();

    try {/*from   w  w w .j  a  va 2s  .co  m*/
        httpPost.setHeader("Authorization", getHTTPBasicAuth());
        params.put("item", Item);
        httpPost.setEntity(new ByteArrayEntity(params.toString().getBytes("UTF8")));
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", httpUserAgent);
        System.setProperty("http.keepAlive", "false");
        HttpResponse response = client.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (LOCAL_LOG)
            Log.v(TAG, "REST call finished with status " + statusCode);
        if (statusCode == 201) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            entity = null;
            content = null;
            reader = null;
            JSONObject jsonResponse = new JSONObject(builder.toString());
            JSONObject jsonPayload = jsonResponse.getJSONObject("payload");
            String ItemId = jsonPayload.getString("_id");
            builder = null;
            client = null;
            httpPost = null;
            params = null;
            response = null;
            statusLine = null;
            return ItemId;
        } else if (statusCode == 401) {
            throw new PastyException(PastyException.ERROR_AUTHORIZATION_FAILED);
        } else {
            throw new PastyException(PastyException.ERROR_ILLEGAL_RESPONSE);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new PastyException(PastyException.ERROR_IO_EXCEPTION);
    } catch (IOException e) {
        e.printStackTrace();
        throw new PastyException(PastyException.ERROR_IO_EXCEPTION);
    } catch (JSONException e) {
        e.printStackTrace();
        throw new PastyException(PastyException.ERROR_ILLEGAL_RESPONSE);
    }
}

From source file:photosharing.api.conx.RecommendationDefinition.java

/**
 * unlike a file/*from ww  w  .  j  a  v a  2 s.co m*/
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=off&lid=f8ad2a54
 * -4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727
 * maps to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
         
 * 
 * @param bearer
 * @param lid
 * @param uid
 * @param nonce
 * @param response
 */
public void unlike(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

        // Generate the
        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("X-METHOD-OVERRIDE", "DELETE");
        post.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(recommendation.getBytes("UTF-8"));
        post.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(post);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Default to SC_NO_CONTENT (204)
        else {
            response.setStatus(HttpStatus.SC_NO_CONTENT);

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
    }
}

From source file:leap.webunit.client.THttpRequestImpl.java

protected void initRequest() {
    if (!formParams.isEmpty()) {
        entity = new UrlEncodedFormEntity(formParams, charset);
    } else if (null != body && body.length > 0) {
        entity = new ByteArrayEntity(body);
    } else if (multipart != null && !multipart.isEmpty()) {
        entity = multipart.buildEntity();
    }/*from w w w.  j a  v  a2s.c o m*/

    if (null != entity && method == null) {
        method = Method.POST;
    }
}

From source file:com.couchbase.capi.TestCAPI.java

public void testBulkDocs() throws Exception {

    HttpClient client = getClient();/*from w w  w  .  j a v  a2s. c  o  m*/

    HttpPost request = new HttpPost(String.format("http://localhost:%d/default/_bulk_docs", port));

    Map<String, Object> doc = new HashMap<String, Object>();
    doc.put("_id", "abcdef");
    doc.put("_rev", "1-xyz");

    Map<String, Object> doc2 = new HashMap<String, Object>();
    doc2.put("_id", "ghijkl");
    doc2.put("_rev", "1-pdr");

    List<Object> docs = new ArrayList<Object>();
    docs.add(doc);
    docs.add(doc2);

    Map<String, Object> bulkDocs = new HashMap<String, Object>();
    bulkDocs.put("docs", docs);

    request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(bulkDocs)));
    HttpResponse response = client.execute(request);

    HttpEntity entity = response.getEntity();
    List<Map<String, Object>> details = null;
    if (entity != null) {
        InputStream input = entity.getContent();
        try {
            details = mapper.readValue(input, List.class);
        } finally {
            input.close();
        }
    }

    Assert.assertEquals(2, details.size());
    Assert.assertEquals("abcdef", details.get(0).get("id"));
    Assert.assertEquals("1-xyz", details.get(0).get("rev"));
    Assert.assertEquals("ghijkl", details.get(1).get("id"));
    Assert.assertEquals("1-pdr", details.get(1).get("rev"));
}