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:edu.si.services.itest.UCT_AltId_IT.java

private static void ingest(String pid, Path payload) throws IOException {
    if (!checkObjecsExist(pid)) {
        HttpPost ingest = new HttpPost(
                FEDORA_URI + "/objects/" + pid + "?format=info:fedora/fedora-system:FOXML-1.1");
        ingest.setEntity(new ByteArrayEntity(Files.readAllBytes(payload)));
        ingest.setHeader("Content-type", MediaType.TEXT_XML);
        try (CloseableHttpResponse pidRes = httpClient.execute(ingest)) {
            assertEquals("Failed to ingest " + pid + "!", SC_CREATED, pidRes.getStatusLine().getStatusCode());
            logger.info("Ingested test object {}", EntityUtils.toString(pidRes.getEntity()));
        }/*from   w w  w.  j a  va 2  s .c om*/
    }
}

From source file:com.linkedin.multitenant.db.RocksdbDatabase.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);/*  w  ww  .  j av  a 2 s. c  o m*/

    try {
        String responseBody = m_client.execute(put, m_handler);
        m_log.debug("Write response: " + responseBody);
        return DatabaseResult.OK;
    } catch (Exception e) {
        m_log.error("Error in executing doUpdate", e);
        return DatabaseResult.FAIL;
    }
}

From source file:de.l3s.concatgz.data.WarcRecord.java

public String getHttpStringBody() throws IOException {
    Map<String, String> headers = getHttpHeaders();
    String charset = DEFAULT_HTTP_STRING_CHARSET;
    String type = headers.get(MIME_TYPE_HTTP_HEADER);
    if (type != null) {
        String[] split = type.split("[ =]");
        for (int i = 0; i < split.length - 1; i++) {
            if (split[i].equalsIgnoreCase("charset")) {
                charset = split[i + 1];/*w w  w. j a  v  a2  s  .  co m*/
                break;
            }
        }
    }
    return EntityUtils.toString(new ByteArrayEntity(getHttpBody()), charset);
}

From source file:com.kubeiwu.commontool.khttp.toolbox.HttpClientStack.java

/**
 * ??//w w w  .  j a va2  s  .co  m
 * 
 * @param httpRequest
 * @param request
 * @throws AuthFailureError
 */
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        // ?
        // List<NameValuePair> params = new ArrayList<NameValuePair>();
        // params.add(new BasicNameValuePair("city", "xxx"));
        // HttpParams httpParams = httpClient.getParams();
        // HttpEntity httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}

From source file:com.alibaba.dubbo.rpc.protocol.springmvc.support.ApacheHttpClient.java

HttpUriRequest toHttpUriRequest(Request request, Request.Options options)
        throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
    RequestBuilder requestBuilder = RequestBuilder.create(request.method());

    //per request timeouts
    //    RequestConfig requestConfig = RequestConfig
    //            .custom()
    //            .setConnectTimeout(options.connectTimeoutMillis())
    //            .setSocketTimeout(options.readTimeoutMillis())
    //            .build();
    //requestBuilder.setConfig(requestConfig);

    URI uri = new URIBuilder(request.url()).build();

    requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());

    //request query params
    List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name());
    for (NameValuePair queryParam : queryParams) {
        requestBuilder.addParameter(queryParam);
    }//from   w  w w.j a va 2s  .c  om

    //request headers
    boolean hasAcceptHeader = false;
    for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }

        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // The 'Content-Length' header is always set by the Apache client and it
            // doesn't like us to set it as well.
            continue;
        }

        for (String headerValue : headerEntry.getValue()) {
            requestBuilder.addHeader(headerName, headerValue);
        }
    }
    //some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }

    //request body
    if (request.body() != null) {
        HttpEntity entity = null;
        if (request.charset() != null) {
            ContentType contentType = getContentType(request);
            String content = new String(request.body(), request.charset());
            entity = new StringEntity(content, contentType);
        } else {
            entity = new ByteArrayEntity(request.body());
        }

        requestBuilder.setEntity(entity);
    }

    return requestBuilder.build();
}

From source file:com.subgraph.vega.internal.http.requests.RequestTask.java

private HttpEntity createEmptyEntity() {
    return new ByteArrayEntity(new byte[0]);
}

From source file:org.lambdamatic.internal.elasticsearch.clientdsl.Client.java

public <T> void index(final String indexName, final String type, final String documentId,
        final String documentSource, final ResponseListener responseListener) {
    final PathBuilder pathBuilder = new PathBuilder().append(indexName).append(type);
    final Map<String, String> params = new HashMap<>();
    if (documentId != null) {
        pathBuilder.append(documentId);// w ww. ja  v  a 2  s .  c o  m
        // use the "op_type=create" argument to obtain a "put-if-absent" behaviour. Will fail if
        // a document with the same id already exists
        params.put("op_type", "create");
    }
    client.performRequest("PUT", pathBuilder.build(), params, new ByteArrayEntity(documentSource.getBytes()),
            responseListener);
}

From source file:AIR.Common.Web.HttpWebHelper.java

public void sendXml(String url, IXmlSerializable inputData, OutputStream outputData) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "text/xml");
    HttpResponse response = null;//from   w  ww  . j  a  v a  2  s  .  co  m
    try {
        XMLOutputFactory output = TdsXmlOutputFactory.newInstance();
        XMLStreamWriter writer = output.createXMLStreamWriter(out);
        inputData.writeXML(writer);
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        post.setEntity(entity);
        response = _client.execute(post, _contextPool.get());
    } catch (IOException | XMLStreamException e) {
        try {
            outputData.write(String.format("HTTP client through exception: %s", e.getMessage()).getBytes());
        } catch (IOException e1) {
            // Our IOExceptioin through an IOException--bad news!!!
            _logger.error("Output stream encountered an error while attempting to process an error message",
                    e1);
            _logger.error(String.format("Original drror message was \"\"", e.getMessage()));
        }
    }
    if (response != null) {
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            String responseString = "";
            try {
                responseString = EntityUtils.toString(responseEntity);
                outputData.write(responseString.getBytes());
            } catch (IOException e) {
                // Our IOExceptioin through an IOException--bad news!!!
                _logger.error("Output stream encountered an error while attempting to process a reply", e);
                _logger.error(String.format("Original reply content was \"\"", responseString));
            }
            EntityUtils.consumeQuietly(responseEntity);
        }
    }
}

From source file:org.apache.tika.parser.captioning.tf.TensorflowRESTCaptioner.java

@Override
public List<CaptionObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata,
        ParseContext context) throws IOException, SAXException, TikaException {
    List<CaptionObject> capObjs = new ArrayList<>();
    try {//from  w w w.  j a  va 2  s.  com
        DefaultHttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost(getApiUri(metadata));

        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
            //TODO: convert this to stream, this might cause OOM issue
            // InputStreamEntity is not working
            // request.setEntity(new InputStreamEntity(stream, -1));
            IOUtils.copy(stream, byteStream);
            request.setEntity(new ByteArrayEntity(byteStream.toByteArray()));
        }

        HttpResponse response = client.execute(request);
        try (InputStream reply = response.getEntity().getContent()) {
            String replyMessage = IOUtils.toString(reply);
            if (response.getStatusLine().getStatusCode() == 200) {
                JSONObject jReply = (JSONObject) new JSONParser().parse(replyMessage);
                JSONArray jCaptions = (JSONArray) jReply.get("captions");
                for (int i = 0; i < jCaptions.size(); i++) {
                    JSONObject jCaption = (JSONObject) jCaptions.get(i);
                    String sentence = (String) jCaption.get("sentence");
                    Double confidence = (Double) jCaption.get("confidence");
                    capObjs.add(new CaptionObject(sentence, LABEL_LANG, confidence));
                }
            } else {
                LOG.warn("Status = {}", response.getStatusLine());
                LOG.warn("Response = {}", replyMessage);
            }
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return capObjs;
}

From source file:cn.bidaround.ytcore.util.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);//from   w w w .  ja  v  a 2  s . c o m
    }
}