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.linkedin.multitenant.db.ProxyDatabase.java

@Override
public DatabaseResult doUpdate(Query q) {
    HttpPut put = new HttpPut(m_connStr + q.getKey());

    ByteArrayEntity bae = new ByteArrayEntity(q.getValue());
    bae.setContentType("octet-stream");
    put.setEntity(bae);/*from w  w w . ja  v  a  2 s .co  m*/

    try {
        @SuppressWarnings("unused")
        String responseBody = m_client.execute(put, m_handler);
        return DatabaseResult.OK;
    } catch (Exception e) {
        m_log.error("Error in executing doUpdate", e);
        return DatabaseResult.FAIL;
    }
}

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

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

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

    HttpPut request = new HttpPut(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);// ww w .  j  av a  2s . c  om
    HttpEntity entity = new ByteArrayEntity(os.toByteArray());
    request.setEntity(entity);

    HttpResponse response = httpClient.execute(request);

    return response;
}

From source file:CB_Core.Api.GroundspeakAPI.java

/**
 * Upload FieldNotes//from   w ww .  ja va  2 s  .  c om
 * 
 * @param Staging
 *            Config.settings.StagingAPI.getValue()
 * @param accessToken
 * @param cacheCode
 * @param wptLogTypeId
 * @param dateLogged
 * @param note
 * @return
 */
public static int CreateFieldNoteAndPublish(String cacheCode, int wptLogTypeId, Date dateLogged, String note,
        boolean directLog, final ICancel icancel) {
    int chk = chkMembership(true);
    if (chk < 0)
        return chk;

    String URL = CB_Core_Settings.StagingAPI.getValue() ? STAGING_GS_LIVE_URL : GS_LIVE_URL;

    try {
        HttpPost httppost = new HttpPost(URL + "CreateFieldNoteAndPublish?format=json");
        String requestString = "";
        requestString = "{";
        requestString += "\"AccessToken\":\"" + GetAccessToken() + "\",";
        requestString += "\"CacheCode\":\"" + cacheCode + "\",";
        requestString += "\"WptLogTypeId\":" + String.valueOf(wptLogTypeId) + ",";
        requestString += "\"UTCDateLogged\":\"" + GetUTCDate(dateLogged) + "\",";
        requestString += "\"Note\":\"" + ConvertNotes(note) + "\",";
        if (directLog) {
            requestString += "\"PromoteToLog\":true,";
        } else {
            requestString += "\"PromoteToLog\":false,";
        }

        requestString += "\"FavoriteThisCache\":false";
        requestString += "}";

        httppost.setEntity(new ByteArrayEntity(requestString.getBytes("UTF8")));

        // set time outs
        HttpUtils.conectionTimeout = CB_Core_Settings.conection_timeout.getValue();
        HttpUtils.socketTimeout = CB_Core_Settings.socket_timeout.getValue();

        // Execute HTTP Post Request
        String result = HttpUtils.Execute(httppost, icancel);

        if (result.contains("The service is unavailable")) {
            return API_IS_UNAVAILABLE;
        }

        // Parse JSON Result
        try {
            JSONTokener tokener = new JSONTokener(result);
            JSONObject json = (JSONObject) tokener.nextValue();
            JSONObject status = json.getJSONObject("Status");
            if (status.getInt("StatusCode") == 0) {
                result = "";
                LastAPIError = "";
            } else {
                result = "StatusCode = " + status.getInt("StatusCode") + "\n";
                result += status.getString("StatusMessage") + "\n";
                result += status.getString("ExceptionDetails");
                LastAPIError = result;
                return ERROR;
            }

        } catch (JSONException e) {
            e.printStackTrace();
            logger.error("UploadFieldNotesAPI", e);
            LastAPIError = e.getMessage();
            return ERROR;
        }

    } catch (ConnectTimeoutException e) {
        logger.error("UploadFieldNotesAPI ConnectTimeoutException", e);
        return CONNECTION_TIMEOUT;
    } catch (UnsupportedEncodingException e) {
        logger.error("UploadFieldNotesAPI UnsupportedEncodingException", e);
        return ERROR;
    } catch (ClientProtocolException e) {
        logger.error("UploadFieldNotesAPI ClientProtocolException", e);
        return ERROR;
    } catch (IOException e) {
        logger.error("UploadFieldNotesAPI IOException", e);
        return ERROR;
    }

    LastAPIError = "";
    return IO;
}

From source file:org.jsnap.http.base.HttpServlet.java

protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)
        throws HttpException, IOException {
    // Client might keep the executing thread blocked for very long unless this header is added.
    response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    // Create a wrapped request object.
    String uri, data;//  w  w  w  .j  a v  a2 s .  co  m
    String method = request.getRequestLine().getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        BasicHttpRequest get = (BasicHttpRequest) request;
        data = get.getRequestLine().getUri();
        int ix = data.indexOf('?');
        uri = (ix < 0 ? data : data.substring(0, ix));
        data = (ix < 0 ? "" : data.substring(ix + 1));
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request;
        HttpEntity postedEntity = post.getEntity();
        uri = post.getRequestLine().getUri();
        data = EntityUtils.toString(postedEntity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
        response.setHeader(new Header(HTTP.CONTENT_LEN, "0"));
        return;
    }
    String cookieLine = "";
    if (request.containsHeader(COOKIE)) {
        Header[] cookies = request.getHeaders(COOKIE);
        for (Header cookie : cookies) {
            if (cookieLine.length() > 0)
                cookieLine += "; ";
            cookieLine += cookie.getValue();
        }
    }
    HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine);
    // Create a wrapped response object.
    ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    HttpResponse resp = new HttpResponse(out);
    // Do implementation specific processing.
    doServiceImpl(req, resp);
    out.flush(); // It's good practice to do this.
    // Do the actual writing to the actual response object.
    if (resp.redirectTo != null) {
        // Redirection is requested.
        resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY;
        response.setStatusCode(resp.statusCode);
        Header redirection = new Header(LOCATION, resp.redirectTo);
        response.setHeader(redirection);
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString());
    } else {
        // There will be a response entity.
        response.setStatusCode(resp.statusCode);
        HttpEntity entity;
        Header contentTypeHeader;
        boolean text = resp.contentType.startsWith(Formatter.TEXT);
        if (text) { // text/* ...
            entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet);
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE,
                    resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet);
        } else { // application/octet-stream, image/* ...
            entity = new ByteArrayEntity(out.toByteArray());
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType);
        }
        boolean acceptsGzip = clientAcceptsGzip(request);
        long contentLength = entity.getContentLength();
        // If client accepts gzipped content, the implementing object requested that response
        // gets gzipped and size of the response exceeds implementing object's size threshold
        // response entity will be gzipped.
        boolean gzipped = false;
        if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) {
            ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE);
            GZIPOutputStream gzos = new GZIPOutputStream(zipped);
            entity.writeTo(gzos);
            gzos.close();
            entity = new ByteArrayEntity(zipped.toByteArray());
            contentLength = zipped.size();
            gzipped = true;
        }
        // This is where true writes are made.
        Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength));
        Header contentEncodingHeader = null;
        response.setHeader(contentTypeHeader);
        response.setHeader(contentLengthHeader);
        if (gzipped) {
            contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP);
            response.setHeader(contentEncodingHeader);
        }
        response.setEntity(entity);
        // Log critical headers.
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString());
        if (gzipped)
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString());
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString());
    }
    // Log cookies.
    for (Cookie cookie : resp.cookies) {
        if (cookie.valid()) {
            Header h = new Header(SET_COOKIE, cookie.toString());
            response.addHeader(h);
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString());
        }
    }
}

From source file:org.soyatec.windowsazure.blob.internal.PageBlob.java

public void writePages(final BlobStream pageData, final IPageRange range,
        final NameValueCollection headerParameters) throws StorageException {

    if (blobName == null || blobName.equals("")) {
        throw new IllegalArgumentException("Blob name is empty.");
    }/*from   w  w  w .j a  v  a  2  s  . c  o  m*/

    String containerName = container.getName();
    if (containerName.equals(IBlobContainer.ROOT_CONTAINER)) {
        containerName = "";
    }

    NameValueCollection queryParams = new NameValueCollection();
    queryParams.put(QueryParams.QueryParamComp, CompConstants.Page);

    final ResourceUriComponents uriComponents = new ResourceUriComponents(container.getAccountName(),
            containerName, blobName);
    final URI blobUri = HttpUtilities.createRequestUri(container.getBaseUri(), container.isUsePathStyleUris(),
            container.getAccountName(), containerName, blobName, container.getTimeout(), queryParams,
            uriComponents, container.getCredentials());

    container.getRetryPolicy().execute(new Callable<Boolean>() {
        public Boolean call() throws Exception {
            HttpRequest request = HttpUtilities.createHttpRequestWithCommonHeaders(blobUri, HttpMethod.Put,
                    container.getTimeout());

            // add header
            request.addHeader(HeaderNames.ApiVersion, XmsVersion.VERSION_2009_09_19);
            request.addHeader(HeaderNames.Range, range.toString());
            container.appendHeaders(request, headerParameters);
            try {
                if (pageData == null) {
                    request.addHeader(HeaderNames.PageWrite, HeaderValues.Clear);
                    // request.addHeader(HeaderNames.ContentLength, "0");
                    container.getCredentials().signRequest(request, uriComponents);
                } else {
                    request.addHeader(HeaderNames.PageWrite, HeaderValues.Update);
                    request.addHeader(HeaderNames.ContentLength, String.valueOf(range.length()));
                    container.getCredentials().signRequest(request, uriComponents);
                    BlobStream requestStream = new BlobMemoryStream();
                    Utilities.copyStream(pageData, requestStream, (int) range.length());
                    ((HttpEntityEnclosingRequest) request)
                            .setEntity(new ByteArrayEntity(requestStream.getBytes()));
                }
                // avoid error using put
                request.removeHeaders(HeaderNames.ContentLength);
                HttpWebResponse response = HttpUtilities.getResponse(request);
                if (response.getStatusCode() == HttpStatus.SC_CREATED) {
                    response.close();
                    return Boolean.TRUE;
                } else {
                    XmlUtil.load(response.getStream());
                    HttpUtilities.processUnexpectedStatusCode(response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof StorageServerException) {
                    StorageServerException sse = (StorageServerException) e;
                    String detailMessage = sse.getMessage();
                    StorageErrorCode errorCode = sse.getErrorCode();
                    if (detailMessage != null
                            && detailMessage.startsWith(StorageErrorCodeStrings.InvalidPageRange)
                            && errorCode == StorageErrorCode.ServiceBadResponse) {
                        throw new StorageServerException(StorageErrorCode.BadRange, detailMessage,
                                sse.getStatusCode(), null);
                    }
                }
            }
            return Boolean.FALSE;
        }
    });
}

From source file:com.comcast.drivethru.client.DefaultRestClient.java

@Override
public RestResponse execute(RestRequest request) throws HttpException {
    /* Build the URL String */
    String url = request.getUrl().setDefaultBaseUrl(defaultBaseUrl).build();

    /* Get our Apache RestRequest object */
    Method method = request.getMethod();
    HttpRequestBase req = method.getRequest(url);
    req.setConfig(request.getConfig());//from   w  w w  . ja v  a  2 s  .co m

    /* Add the Body */
    byte[] payload = request.getBody();
    if (null != payload) {
        if (req instanceof HttpEntityEnclosingRequest) {
            HttpEntity entity = new ByteArrayEntity(payload);
            ((HttpEntityEnclosingRequest) req).setEntity(entity);
        } else {
            throw new HttpException("Cannot attach a body to a " + method.name() + " request");
        }
    }

    /* Add all Headers */
    for (Entry<String, String> pair : defaultHeaders.entrySet()) {
        req.addHeader(pair.getKey(), pair.getValue());
    }
    for (Entry<String, String> pair : request.getHeaders().entrySet()) {
        req.addHeader(pair.getKey(), pair.getValue());
    }

    /* If there is a security provider, sign */
    if (null != securityProvider) {
        securityProvider.sign(req);
    }

    /* Closed in the finally block */
    InputStream in = null;
    ByteArrayOutputStream baos = null;

    try {
        /* Finally, execute the thing */
        org.apache.http.HttpResponse resp = delegate.execute(req);

        /* Create our response */
        RestResponse response = new RestResponse(resp.getStatusLine());

        /* Add all Headers */
        response.addAll(resp.getAllHeaders());

        /* Add the content */
        HttpEntity body = resp.getEntity();
        if (null != body) {
            in = body.getContent();
            baos = new ByteArrayOutputStream();
            IOUtils.copy(in, baos);
            response.setBody(baos.toByteArray());
        }

        return response;
    } catch (RuntimeException ex) {
        // release resources immediately
        req.abort();
        throw ex;
    } catch (HttpResponseException hrex) {
        throw new HttpStatusException(hrex.getStatusCode());
    } catch (ClientProtocolException cpex) {
        throw new HttpException("HTTP Protocol error occurred.", cpex);
    } catch (IOException ioex) {
        throw new HttpException("Error establishing connection.", ioex);
    } finally {
        req.abort();
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(baos);
    }
}

From source file:org.fcrepo.camel.FcrepoClientTest.java

@Test
public void testPutWithResponseBody() throws IOException, FcrepoOperationFailedException {
    final int status = 201;
    final URI uri = create(baseUrl);

    doSetupMockRequest(null, new ByteArrayEntity(uri.toString().getBytes()), status);

    final FcrepoResponse response = testClient.put(uri, null, null);

    assertEquals(response.getUrl(), uri);
    assertEquals(response.getStatusCode(), status);
    assertEquals(response.getContentType(), null);
    assertEquals(response.getLocation(), null);
    assertEquals(IOUtils.toString(response.getBody()), uri.toString());
}

From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java

private HttpRequestBase getNewHttpRequest(final HttpServletRequest req, final String url) throws IOException {
    HttpRequestBase newReq = null;/*from w w w  .j  a  va2s  .com*/
    if (req == null || req.getMethod().equalsIgnoreCase("get")) {
        newReq = new HttpGet(url);
    } else {
        final HttpPost post = new HttpPost(url);
        final ByteArrayOutputStream reqBody = new ByteArrayOutputStream();
        copyHeaders(post, req);
        IOUtils.copy(req.getInputStream(), reqBody);
        post.setEntity(new ByteArrayEntity(reqBody.toByteArray()));
        newReq = post;
    }

    return newReq;
}

From source file:org.gbif.registry.metasync.protocols.digir.DigirMetadataSynchroniserTest.java

public HttpResponse prepareResponse(int responseStatus, String fileName) throws IOException {
    HttpResponse response = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseStatus, ""));
    response.setStatusCode(responseStatus);
    byte[] bytes = Resources.toByteArray(Resources.getResource(fileName));
    response.setEntity(new ByteArrayEntity(bytes));
    return response;
}

From source file:org.apache.blur.thirdparty.thrift_0_9_0.transport.THttpClient.java

private void flushUsingHttpClient() throws TTransportException {

    if (null == this.client) {
        throw new TTransportException("Null HttpClient, aborting.");
    }//  w  ww.j  av  a 2 s.  com

    // Extract request and reset buffer
    byte[] data = requestBuffer_.toByteArray();
    requestBuffer_.reset();

    HttpPost post = null;

    InputStream is = null;

    try {
        // Set request to path + query string
        post = new HttpPost(this.url_.getFile());

        //
        // Headers are added to the HttpPost instance, not
        // to HttpClient.
        //

        post.setHeader("Content-Type", "application/x-thrift");
        post.setHeader("Accept", "application/x-thrift");
        post.setHeader("User-Agent", "Java/THttpClient/HC");

        if (null != customHeaders_) {
            for (Map.Entry<String, String> header : customHeaders_.entrySet()) {
                post.setHeader(header.getKey(), header.getValue());
            }
        }

        post.setEntity(new ByteArrayEntity(data));

        HttpResponse response = this.client.execute(this.host, post);
        int responseCode = response.getStatusLine().getStatusCode();

        //      
        // Retrieve the inputstream BEFORE checking the status code so
        // resources get freed in the finally clause.
        //

        is = response.getEntity().getContent();

        if (responseCode != HttpStatus.SC_OK) {
            throw new TTransportException("HTTP Response code: " + responseCode);
        }

        // Read the responses into a byte array so we can release the connection
        // early. This implies that the whole content will have to be read in
        // memory, and that momentarily we might use up twice the memory (while the
        // thrift struct is being read up the chain).
        // Proceeding differently might lead to exhaustion of connections and thus
        // to app failure.

        byte[] buf = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int len = 0;
        do {
            len = is.read(buf);
            if (len > 0) {
                baos.write(buf, 0, len);
            }
        } while (-1 != len);

        try {
            // Indicate we're done with the content.
            EntityUtils.consume(response.getEntity());
        } catch (IOException ioe) {
            // We ignore this exception, it might only mean the server has no
            // keep-alive capability.
        }

        inputStream_ = new ByteArrayInputStream(baos.toByteArray());
    } catch (IOException ioe) {
        // Abort method so the connection gets released back to the connection manager
        if (null != post) {
            post.abort();
        }
        throw new TTransportException(ioe);
    } finally {
        if (null != is) {
            // Close the entity's input stream, this will release the underlying connection
            try {
                is.close();
            } catch (IOException ioe) {
                throw new TTransportException(ioe);
            }
        }
    }
}