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:com.kkbox.toolkit.internal.api.APIRequest.java

public void addByteArrayPostParam(byte[] data) {
    byteArrayEntity = new ByteArrayEntity(data);
    byteArrayEntity.setContentType("application/octet-stream");
}

From source file:com.github.tomakehurst.wiremock.http.ProxyResponseRenderer.java

private static HttpEntity buildEntityFrom(Request originalRequest) {
    ContentTypeHeader contentTypeHeader = originalRequest.contentTypeHeader().or("text/plain");
    ContentType contentType = ContentType.create(contentTypeHeader.mimeTypePart(),
            contentTypeHeader.encodingPart().or("utf-8"));

    if (originalRequest.containsHeader(TRANSFER_ENCODING)
            && originalRequest.header(TRANSFER_ENCODING).firstValue().equals("chunked")) {
        return new InputStreamEntity(new ByteArrayInputStream(originalRequest.getBody()), -1, contentType);
    }/*  ww  w  .  j a v a 2  s  .  c o m*/

    return new ByteArrayEntity(originalRequest.getBody());
}

From source file:org.opensaml.soap.client.soap11.decoder.http.impl.HttpClientResponseSOAP11DecoderTest.java

private HttpResponse buildResponse(int statusResponseCode, Envelope envelope)
        throws MarshallingException, IOException {
    BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, statusResponseCode, null);
    Element envelopeElement = XMLObjectSupport.marshall(envelope);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    SerializeSupport.writeNode(envelopeElement, baos);
    baos.flush();/*  ww  w  .jav a  2  s.  c  o m*/

    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    response.setEntity(entity);
    return response;
}

From source file:org.camunda.bpm.engine.rest.standalone.AbstractEmptyBodyFilterTest.java

@Test
public void testBodyIsEmptyJSONObject() throws IOException {
    evaluatePostRequest(new ByteArrayEntity(EMPTY_JSON_OBJECT.getBytes("UTF-8")),
            ContentType.create(MediaType.APPLICATION_JSON).toString(), 200, true);
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

/**
 * {@inheritDoc}/*from w  w w.jav a  2s. com*/
 */
@Override
protected TaskResult<Boolean> doInBackground(Void... params) {
    if (PreferenceUtil.getSubscriberUrl(context, alertsEnvironment) != null)
        return new TaskResult<Boolean>(null, null);

    try {
        String gcmToken = gcmTokenObtainer.obtainToken(context, gcmSenderId);
        Log.d("registrationService", "Got GCM token: " + gcmToken);

        KeyPair keyPair = generateKeyPair();
        Log.d("registrationService", "keyPair has been generated");

        PKCS10CertificationRequest csr = generateCSR(keyPair);
        Log.d("registrationService", "csr has been generated");

        HttpClient httpClient = httpClientFactory.generateInstallerClient(context, installerKeystore);
        HttpPost post = new HttpPost(alertsEnvironment.getRegisterUrl() + "?token=" + gcmToken);
        post.setEntity(new ByteArrayEntity(csr.getEncoded()));
        post.addHeader("Content-Type", CONTENT_TYPE);
        post.addHeader("Accept", ACCEPT_TYPE);

        Log.d("registrationService",
                "Sending httpPost of Content-Type " + CONTENT_TYPE + " to " + post.getURI());

        HttpResponse response = httpClient.execute(post);

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        Log.d("registrationService", "Got a " + statusLine.getStatusCode() + " back");
        if (statusCode < 200 || statusCode >= 300) {
            throw new UnexpectedNetworkResponseException(
                    "Unexpected response (" + statusCode + ") while trying to post certificate", statusCode,
                    statusLine.getReasonPhrase());
        }

        KeyStore keyStore = createKeyStore(keyPair, response);
        keyStoreContainer.storeKeyStore(context, alertsEnvironment, keyStore);
        String location = response.getLastHeader("Location").getValue();
        PreferenceUtil.setSubscriberUrl(context, alertsEnvironment, location);
    } catch (Exception e) {
        Log.e("registration", "An exception has occurred during registration", e);
        return new TaskResult<Boolean>(false, e);
    }
    return new TaskResult<Boolean>(true, null);
}

From source file:com.oakesville.mythling.util.HttpHelper.java

private byte[] retrieveWithDigestAuth() throws IOException {
    AndroidHttpClient httpClient = null;
    InputStream is = null;/*  ww  w. j a  v  a  2s  .  c  o m*/

    try {
        long startTime = System.currentTimeMillis();

        httpClient = AndroidHttpClient.newInstance("Android");
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, getConnectTimeout());
        HttpConnectionParams.setSoTimeout(httpParams, getReadTimeout());

        HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

        HttpRequestBase job;
        if (method == Method.Get)
            job = new HttpGet(url.toString());
        else if (method == Method.Post) {
            job = new HttpPost(url.toString());
            ((HttpPost) job).setEntity(new ByteArrayEntity("".getBytes()));
        } else
            throw new IOException("Unsupported HTTP method: " + method);

        job.setHeader("Accept", "application/json");
        HttpResponse response = null;
        try {
            response = httpClient.execute(host, job,
                    getDigestAuthContext(url.getHost(), url.getPort(), user, password));
        } catch (IOException ex) {
            Log.e(TAG, ex.getMessage(), ex);
            if (ipRetrieval != null) {
                // try and retrieve the backend IP
                String ip = retrieveBackendIp();
                host = new HttpHost(ip, url.getPort(), url.getProtocol());
                response = httpClient.execute(host, job,
                        getDigestAuthContext(ip, url.getPort(), user, password));
                // save the retrieved ip as the external static one
                Editor ed = sharedPrefs.edit();
                ed.putString(AppSettings.MYTH_BACKEND_EXTERNAL_HOST, ip);
                ed.commit();
            } else {
                throw ex;
            }
        }
        is = response.getEntity().getContent();

        return extractResponseBytes(is, startTime);
    } finally {
        try {
            if (is != null)
                is.close();
            if (httpClient != null)
                httpClient.close();
        } catch (IOException ex) {
            Log.e(TAG, ex.getMessage(), ex);
        }
    }
}

From source file:org.xwiki.eclipse.storage.rest.XWikiRestClient.java

protected HttpResponse executePostXml(URI uri, java.lang.Object object) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

    HttpPost request = new HttpPost(uri);
    request.addHeader(new BasicScheme().authenticate(creds, request));
    request.addHeader("Content-type", "text/xml; charset=UTF-8");
    request.addHeader("Accept", MediaType.APPLICATION_XML);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    marshaller.marshal(object, os);/*from   www.j  a v a 2s .co m*/
    HttpEntity entity = new ByteArrayEntity(os.toByteArray());
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);

    return response;
}

From source file:com.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask.java

@Override
protected String doInBackground(String... urls) {
    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Entering doInBackground()");

    byte[] result = null;
    HttpPost post = new HttpPost(urls[0]);

    try {/*from   w  w w .jav  a 2s  .c  o  m*/
        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: Prepare for httpPostData");
        // prepare for httpPost data
        String boundary = "b0undaryFP";

        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: build the data");
        // build the data
        byte[] bytes = null;
        byte[] imageBytes = null;

        if (isImage) {
            // Get the byte[] of the media we want to upload
            imageBytes = getImageByteArray(mediaPath);
            imageBytes = resizeImage(imageBytes, maxWidth, maxHeight);
        }

        //all the stuff that comes before the media bytes
        ByteArrayOutputStream preMedia = new ByteArrayOutputStream();
        for (@SuppressWarnings("unchecked")
        Iterator<String> keys = uploadParams.keys(); keys.hasNext();) {
            String key = keys.next();
            String value = uploadParams.getString(key);
            preMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes());
            preMedia.write(("Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@".replaceFirst("%@", key)
                    .replaceFirst("%@", value)).getBytes());
        }
        preMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes());
        preMedia.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n\r\n").getBytes());

        //all the stuff that comes after the media bytes
        ByteArrayOutputStream postMedia = new ByteArrayOutputStream();
        postMedia.write(("\r\n--%@\r\n".replace("%@", boundary)).getBytes());

        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: Set content-type and content of http post");
        // Set content-type and content of http post
        post.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

        if (isImage && imageBytes != null)
            bytes = createHeaderByteArrayImage(preMedia.toByteArray(), postMedia.toByteArray(), imageBytes);
        else
            bytes = createHeaderByteArrayFile(preMedia.toByteArray(), postMedia.toByteArray(), mediaPath);

        preMedia.close();
        postMedia.close();

        if (isVideo) {
            if (bytes.length > maxDuration * 1000 * 1000) {
                status = "FILE_TOO_BIG";
                return null;
            }
        }

        if (bytes == null) {
            status = "ERROR_CREATING_HEADER";
            return null;
        }

        ByteArrayEntity entity = new ByteArrayEntity(bytes) {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                if (outstream == null) {
                    throw new IllegalArgumentException("Output stream may not be null");
                }

                InputStream instream = new ByteArrayInputStream(this.content);

                try {
                    byte[] tmp = new byte[512];
                    int total = (int) this.content.length;
                    int progress = 0;
                    int increment = 0;
                    int l;
                    int percent;

                    while ((l = instream.read(tmp)) != -1) {
                        progress = progress + l;
                        percent = Math.round(((float) progress / (float) total) * 100);

                        if (percent > increment) {
                            increment += 10;
                            // update percentage here !!
                        }
                        double percentage = (double) percent / 100.0;
                        GoogleCloudStorageUploadExtension.context
                                .dispatchStatusEventAsync("FILE_UPLOAD_PROGRESS", "" + percentage);

                        outstream.write(tmp, 0, l);
                    }

                    outstream.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    instream.close();
                }
            }
        };
        post.setEntity(entity);

        Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: execute post.");

        // execute post.
        HttpResponse httpResponse = client.execute(post);
        StatusLine statusResponse = httpResponse.getStatusLine();
        if (statusResponse.getStatusCode() == HttpURLConnection.HTTP_OK) {
            result = EntityUtils.toByteArray(httpResponse.getEntity());
            response = new String(result, "UTF-8");
            Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] ~~~ DBG: got a response: " + response);
            status = "FILE_UPLOAD_DONE";
        } else {
            status = "FILE_UPLOAD_ERROR";
            Log.d(TAG,
                    "[UploadToGoogleCloudStorageAsyncTask] ~~~ ERR: status code: " + statusResponse.toString());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        status = "FILE_UPLOAD_ERROR";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        status = "FILE_UPLOAD_ERROR";
    } catch (IOException e) {
        e.printStackTrace();
        status = "FILE_UPLOAD_ERROR";
    } catch (Exception e) {
        e.printStackTrace();
        status = "UNKNOWN_ERROR";
    }

    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Exiting doInBackground()");
    return response;
}

From source file:com.github.horrorho.liquiddonkey.cloud.client.FileGroupsClient.java

public ChunkServer.FileGroups authorizeGet(HttpClient client, String dsPrsID, String contentUrl,
        ICloud.MBSFileAuthTokens authTokens) throws IOException {

    logger.trace("<< authorizeGet() < dsPrsID: {} tokens size: {}}", dsPrsID, authTokens.getTokensCount());

    final ChunkServer.FileGroups fileGroups;
    if (authTokens.getTokensCount() == 0) {
        fileGroups = ChunkServer.FileGroups.getDefaultInstance();

    } else {/*  w  ww .  j  av  a 2  s .  c  om*/
        Header mmcsAuth = headers.mmcsAuth(
                Bytes.hex(authTokens.getTokens(0).getFileID()) + " " + authTokens.getTokens(0).getAuthToken());

        String uri = path(contentUrl, dsPrsID, "authorizeGet");
        RequestBuilder builder = RequestBuilder.get(uri).addHeader(mmcsAuth);
        headers.contentHeaders(dsPrsID).stream().forEach(builder::addHeader);
        HttpUriRequest post = builder.setEntity(new ByteArrayEntity(authTokens.toByteArray())).build();
        fileGroups = client.execute(post, filesGroupsHandler);
    }

    logger.debug(marker, "-- authorizeGet() > fileError: {}", fileGroups.getFileErrorList());
    logger.debug(marker, "-- authorizeGet() > fileChunkError: {}", fileGroups.getFileChunkErrorList());
    logger.debug(marker, "-- authorizeGet() > fileGroups: {}", fileGroups);
    logger.trace(">> authorizeGet() > {}", fileGroups.getFileGroupsCount());
    return fileGroups;
}

From source file:com.github.wnameless.spring.bulkapi.test.BulkApiTest.java

@Test
public void testSilentMode() throws Exception {
    BulkRequest req = operationTimes(1);
    BulkOperation op = new BulkOperation();
    op.setMethod("GET");
    op.setUrl("/home");
    op.getHeaders().put("Authorization", authHeader);
    op.setSilent(true);/*from  w  ww .j av  a2s. com*/
    req.getOperations().add(op);

    HttpEntity entity = new ByteArrayEntity(mapper.writeValueAsString(req).getBytes("UTF-8"));
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    String result = EntityUtils.toString(response.getEntity());
    BulkResponse res = new Gson().getAdapter(new TypeToken<BulkResponse>() {
    }).fromJson(result);

    assertEquals(1, res.getResults().size());
}