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.epam.wilma.browsermob.transformer.BrowserMobRequestUpdater.java

/**
 * Updates BrowserMob specific HTTP request. Adds wilma logger id to headers and updates URI.
 *
 * @param browserMobHttpRequest what will be updated
 * @param wilmaRequest          contains refresher data
 *//*from w  w  w . j  ava 2 s .  co  m*/
public void updateRequest(final BrowserMobHttpRequest browserMobHttpRequest,
        final WilmaHttpRequest wilmaRequest) {
    // Update the headers of the original request with extra headers added/removed by Req interceptors
    // Note, that when we redirect the request to the stub, we always add the message id to the extra headers part

    Map<String, HttpHeaderChange> headerChangeMap = wilmaRequest.getHeaderChanges();
    if (headerChangeMap != null && !headerChangeMap.isEmpty()) { //we have header change requests
        for (Map.Entry<String, HttpHeaderChange> headerChangeEntry : headerChangeMap.entrySet()) {
            String headerKey = headerChangeEntry.getKey();
            HttpHeaderChange headerChange = headerChangeEntry.getValue();
            Header header = browserMobHttpRequest.getMethod().getFirstHeader(headerKey);

            if (headerChange instanceof HttpHeaderToBeUpdated) {
                // it is HttpHeaderToBeChanged, so added, or updated
                if (header != null) {
                    ((HttpHeaderToBeUpdated) headerChange).setOriginalValue(header.getValue());
                }
                browserMobHttpRequest.getMethod().addHeader(headerKey,
                        ((HttpHeaderToBeUpdated) headerChange).getNewValue());
                headerChange.setApplied();
            } else {
                // it is HttpHeaderToBeRemoved
                if (header != null) {
                    browserMobHttpRequest.getMethod().removeHeader(header);
                    headerChange.setApplied();
                }
            }
        }
    }

    //update the body
    byte[] newBody = wilmaRequest.getNewBody();
    if (newBody != null) {
        if (browserMobHttpRequest.getMethod() instanceof HttpEntityEnclosingRequestBase) {
            HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) browserMobHttpRequest
                    .getMethod();
            enclosingRequest.setEntity(new ByteArrayEntity(wilmaRequest.getNewBody()));
        }
    }
    //set response volatility approach
    browserMobHttpRequest.setResponseVolatile(wilmaRequest.isResponseVolatile());
    //switch between original uri (proxy mode selected) or wilma internal uri (stub mode selected)
    browserMobHttpRequest.getMethod().setURI(wilmaRequest.getUri());
}

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

public <T> IndexDocumentResponse index(final String indexName, final String type, final String documentId,
        final String documentSource) {
    try {/*from w  ww . j  a  v a2s.c  o m*/
        final PathBuilder pathBuilder = new PathBuilder().append(indexName).append(type);
        final Map<String, String> params = new HashMap<>();
        if (documentId != null) {
            pathBuilder.append(documentId);
            // 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");
        }
        final Response response = client.performRequest("PUT", pathBuilder.build(), params,
                new ByteArrayEntity(documentSource.getBytes()));
        // something wrong happened
        // document id was allocated by the server and must be set in the given domain object
        return readResponse(this.jsonFactory, response, IndexDocumentResponse.class);
    } catch (ResponseException e) {
        throw new ClientResponseException("Failed to index document",
                readResponse(this.jsonFactory, e.getResponse(), ErrorResponse.class));
    } catch (IOException e) {
        throw new ClientIOException("Failed to index document", e);
    }
}

From source file:cycronix.ctlib.CThttp.java

private HttpResponse httpput(String SourceChan, byte[] body) throws IOException {

    String url = CTwebhost + "/" + SourceChan;
    final HttpPut put = new HttpPut(url);
    if (userpass != null)
        put.setHeader("Authorization", "Basic " + userpass);

    if (body != null) {
        CTinfo.debugPrint("PUT: " + url + ", userpass: " + userpass);
        put.setEntity(new ByteArrayEntity(body));
    }// w  w w .  jav a2 s.co m
    return httpclient.execute(put);
}

From source file:at.ac.tuwien.dsg.rSybl.cloudInteractionUnit.enforcementPlugins.governance.GovOpsPlugin.java

public String callPOSTMethod(String methodName, String reqType, String body) {
    try {/*from  w  ww.  j a va2  s. c o m*/

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost postRequest = new HttpPost(REST_API_URL + "/" + methodName);
        postRequest.addHeader("accept", reqType);
        HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8"));
        postRequest.setEntity(entity);
        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            System.err.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()
                    + reqType + ":" + methodName);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String o;
        System.out.println("============Output:============");
        String output = "";
        while ((o = br.readLine()) != null) {
            output += o;
        }
        return output;

    } catch (ClientProtocolException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.epam.wilma.browsermob.transformer.BrowserMobResponseUpdater.java

/**
 * Updates BrowserMob specific HTTP response. Adds extra headers to the response only.
 *
 * @param browserMobHttpResponse what will be updated
 * @param wilmaResponse          contains refresher data
 *///w  w  w .  j  ava2 s  .c  o m
public void updateResponse(final BrowserMobHttpResponse browserMobHttpResponse,
        final WilmaHttpResponse wilmaResponse) {

    //Note: update (proxy) response is an experimental feature only
    if (!wilmaResponse.isVolatile()) {
        return;
    }

    // From now on, the response is volatile

    // update the headers of the original response with extra headers added/removed by Resp interceptors
    Map<String, HttpHeaderChange> headerChangeMap = wilmaResponse.getHeaderChanges();
    if (headerChangeMap != null && !headerChangeMap.isEmpty()) { //we have header change requests
        for (Map.Entry<String, HttpHeaderChange> headerChangeEntry : headerChangeMap.entrySet()) {
            String headerKey = headerChangeEntry.getKey();
            HttpHeaderChange headerChange = headerChangeEntry.getValue();
            Header header = browserMobHttpResponse.getRawResponse().getFirstHeader(headerKey);

            if (headerChange instanceof HttpHeaderToBeUpdated) {
                // it is HttpHeaderToBeChanged, so added, or updated
                if (header != null) {
                    ((HttpHeaderToBeUpdated) headerChange).setOriginalValue(header.getValue());
                }
                browserMobHttpResponse.getRawResponse().addHeader(headerKey,
                        ((HttpHeaderToBeUpdated) headerChange).getNewValue());
                headerChange.setApplied();
            } else {
                // it is HttpHeaderToBeRemoved
                if (header != null) {
                    browserMobHttpResponse.getRawResponse().removeHeader(header);
                    headerChange.setApplied();
                }
            }
        }
    }

    byte[] newBody = wilmaResponse.getNewBody();
    if (newBody != null) {
        try {
            browserMobHttpResponse.setAnswer(newBody);
            browserMobHttpResponse.getRawResponse().setEntity(new ByteArrayEntity(wilmaResponse.getNewBody()));
        } catch (IOException e) {
            //ups, were unable to set new response correctly ...
            logger.warn(
                    "Message ont-the-fly update was failed for message: " + wilmaResponse.getWilmaMessageId(),
                    e);
        }
    }
}

From source file:org.openqa.selenium.remote.internal.ApacheHttpAsyncClient.java

@Override
public HttpResponse execute(HttpRequest request, boolean followRedirects) throws IOException {
    HttpContext context = createContext();

    String requestUrl = url.toExternalForm().replaceAll("/$", "") + request.getUri();
    HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl);
    for (String name : request.getHeaderNames()) {
        // Skip content length as it is implicitly set when the message entity is set below.
        if (!"Content-Length".equalsIgnoreCase(name)) {
            for (String value : request.getHeaders(name)) {
                httpMethod.addHeader(name, value);
            }/*  w ww.  jav a2s  . co m*/
        }
    }

    if (httpMethod instanceof HttpPost) {
        ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent()));
    }
    client.start(); // start if needed
    Future<org.apache.http.HttpResponse> future = client.execute(targetHost, httpMethod, context, null);
    try {
        org.apache.http.HttpResponse response = future.get();

        if (followRedirects) {
            response = followRedirects(client, context, response, /* redirect count */0);
        }
        return createResponse(response, context);
    } catch (InterruptedException | ExecutionException e) {
        throw new WebDriverException(e);
    }
}

From source file:com.puppetlabs.geppetto.forge.client.ForgeHttpClient.java

protected void assignJSONContent(HttpEntityEnclosingRequestBase request, Object params) {
    if (params != null) {
        request.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON + "; charset=" + UTF_8.name()); //$NON-NLS-1$
        byte[] data = toJson(params).getBytes(UTF_8);
        request.setEntity(new ByteArrayEntity(data));
    }//from w w  w.  jav  a 2s .  c  o  m
}

From source file:guru.nidi.atlassian.remote.rest.RestAccess.java

private HttpPost preparePost(String command, Object parameters) throws RestException {
    HttpPost post = post(command);//from   w  w  w. j a  v  a2s. c  o  m
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        mapper.writeValue(baos, parameters);
    } catch (Exception e) {
        throw new RestException("error serializing parameters", e);
    }
    post.setEntity(new ByteArrayEntity(baos.toByteArray()));
    return post;
}

From source file:com.volley.toolbox.HttpClientStack.java

/**
 * httprequest?httprequest?httpurlrequest
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from w  w w. j  a  v a 2s.c om
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        // body? -?
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.scut.easyfe.network.kjFrame.http.HttpClientStack.java

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