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.fcrepo.camel.FcrepoClientAuthTest.java

@Test
public void testAuthWithHost() throws IOException, FcrepoOperationFailedException {
    final int status = 200;
    final URI uri = create(baseUrl);
    final ByteArrayEntity entity = new ByteArrayEntity(rdfXml.getBytes());

    testClient = new FcrepoClient("user", "pass", "localhost", true);
    setField(testClient, "httpclient", mockHttpclient);
    entity.setContentType(RDF_XML);//from  w w  w. ja va2 s  .  c  o  m
    doSetupMockRequest(RDF_XML, entity, status);

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

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

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

@Test
public void testGet() throws IOException, FcrepoOperationFailedException {
    final int status = 200;
    final URI uri = create(baseUrl);
    final ByteArrayEntity entity = new ByteArrayEntity(rdfXml.getBytes());
    entity.setContentType(RDF_XML);/* w  ww . j a va2 s . co  m*/

    doSetupMockRequest(RDF_XML, entity, status);

    final FcrepoResponse response = testClient.get(uri, RDF_XML, "return=minimal");

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

From source file:io.wcm.caravan.io.http.impl.RequestUtil.java

/**
 * @param urlPrefix URL prefix//from   w  ww.j a  v a2 s.  c om
 * @param request Requset
 * @return HTTP client request object
 */
public static HttpUriRequest buildHttpRequest(String urlPrefix, Request request) {
    String url = urlPrefix + request.url();

    // http method
    HttpUriRequest httpRequest;
    String method = StringUtils.upperCase(request.method());
    switch (method) {
    case HttpGet.METHOD_NAME:
        httpRequest = new HttpGet(url);
        break;
    case HttpPost.METHOD_NAME:
        httpRequest = new HttpPost(url);
        break;
    case HttpPut.METHOD_NAME:
        httpRequest = new HttpPut(url);
        break;
    case HttpDelete.METHOD_NAME:
        httpRequest = new HttpDelete(url);
        break;
    default:
        throw new IllegalArgumentException("Unsupported HTTP method type: " + request.method());
    }

    // headers
    for (Entry<String, Collection<String>> entry : request.headers().entrySet()) {
        Streams.of(entry.getValue()).forEach(value -> httpRequest.addHeader(entry.getKey(), value));
    }

    // body
    if ((httpRequest instanceof HttpEntityEnclosingRequest) && request.body() != null) {
        HttpEntityEnclosingRequest entityHttpRequest = (HttpEntityEnclosingRequest) httpRequest;
        if (request.charset() != null) {
            entityHttpRequest.setEntity(
                    new StringEntity(new String(request.body(), request.charset()), request.charset()));
        } else {
            entityHttpRequest.setEntity(new ByteArrayEntity(request.body()));
        }
    }

    return httpRequest;
}

From source file:org.androidx.frames.libs.volley.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 */// w w w  . j  a  v a 2 s  .  c om
/* 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());
        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.google.ipc.invalidation.ticl.android.AndroidChannelBase.java

/** Sends {@code outgoingMessage} to . */
void deliverOutboundMessage(final byte[] outgoingMessage) {
    getLogger().fine("Delivering outbound message: %s bytes", outgoingMessage.length);
    StringBuilder target = new StringBuilder();

    // Build base URL that targets the inbound request service with the encoded network endpoint id
    target.append(channelUrl);//from w  ww .  ja va 2  s  .c  om
    target.append(AndroidHttpConstants.REQUEST_URL);
    target.append(getWebEncodedEndpointId());

    // Add query parameter indicating the service to authenticate against
    target.append('?');
    target.append(AndroidHttpConstants.SERVICE_PARAMETER);
    target.append('=');
    target.append(authType);

    // Construct entity containing the outbound protobuf msg
    ByteArrayEntity contentEntity = new ByteArrayEntity(outgoingMessage);
    contentEntity.setContentType(AndroidHttpConstants.PROTO_CONTENT_TYPE);

    // Construct POST request with the entity content and appropriate authorization
    HttpPost httpPost = new HttpPost(target.toString());
    httpPost.setEntity(contentEntity);
    setPostHeaders(httpPost);
    try {
        String response = httpClient.execute(httpPost, new BasicResponseHandler());
    } catch (ClientProtocolException exception) {
        // TODO: Distinguish between key HTTP error codes and handle more specifically
        // where appropriate.
        getLogger().warning("Error from server on request: %s", exception);
    } catch (IOException exception) {
        getLogger().warning("Error writing request: %s", exception);
    } catch (RuntimeException exception) {
        getLogger().warning("Runtime exception writing request: %s", exception);
    }
}

From source file:org.fcrepo.mint.HttpPidMinterTest.java

@Test
public void testMintPidXPath() throws Exception {
    final HttpPidMinter testMinter = new HttpPidMinter("http://localhost/minter", "POST", "", "", "",
            "/test/id");

    final HttpClient mockClient = mock(HttpClient.class);
    final HttpResponse mockResponse = mock(HttpResponse.class);
    final ByteArrayEntity entity = new ByteArrayEntity("<test><id>baz</id></test>".getBytes());
    testMinter.client = mockClient;/*  w w  w  .j  a v a  2s. c o m*/

    when(mockClient.execute(isA(HttpUriRequest.class))).thenReturn(mockResponse);
    when(mockResponse.getEntity()).thenReturn(entity);

    final String pid = testMinter.get();
    verify(mockClient).execute(isA(HttpUriRequest.class));
    assertEquals(pid, "baz");
}

From source file:ua.privatbank.cryptonite.CryptoniteX.java

private static byte[] request(final String url, final byte[] data) throws IOException {
    final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();

    try {/*from ww w.j  ava  2 s  . com*/
        httpclient.start();

        final HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(data));
        request.setHeader("Content-type", "application/octet-stream");
        Future<HttpResponse> future = httpclient.execute(request, null);
        // and wait until a response is received

        HttpResponse response = null;
        byte[] tspAnswer = null;
        try {
            response = future.get();
            tspAnswer = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (Exception e) {
            throw new RuntimeException("Error response for url:" + url, e);
        }

        return tspAnswer;
    } finally {
        httpclient.close();
    }
}

From source file:com.flipkart.phantom.http.impl.HttpProxy.java

/**
 * Creates a HttpRequestBase object understood by the apache http library
 * @param method HTTP request method/*  w w  w  .j ava 2  s . com*/
 * @param uri HTTP request URI
 * @param data HTTP request data
 * @return
 * @throws Exception
 */
private HttpRequestBase createRequest(String method, String uri, byte[] data) throws Exception {

    // get
    if ("GET".equals(method)) {
        HttpGet r = new HttpGet(pool.constructUrl(uri));
        return r;

        // put
    } else if ("PUT".equals(method)) {
        HttpPut r = new HttpPut(pool.constructUrl(uri));
        r.setEntity(new ByteArrayEntity(data));
        return r;

        // post
    } else if ("POST".equals(method)) {
        HttpPost r = new HttpPost(pool.constructUrl(uri));
        r.setEntity(new ByteArrayEntity(data));
        return r;

        // delete
    } else if ("DELETE".equals(method)) {
        HttpDelete r = new HttpDelete(pool.constructUrl(uri));
        return r;

        // invalid
    } else {
        return null;
    }
}

From source file:net.volcore.wtvmaster.upload.HomepageDispatcher.java

/** Public functionality */
public void dispatch(final int gameid) {
    workerThreadPool.submit(new Runnable() {
        public void run() {
            String str = "";
            try {
                HttpClient httpclient = new DefaultHttpClient();
                Game game = wtvMaster.gameDB.fetchGame(gameid);

                GameInfo gi = game.getParsedGameInfo();

                String version = "";

                if (gi.gameTag == 1462982736)
                    version = "W3XP 1." + gi.gameVersion;
                else
                    version = "WAR3 1." + gi.gameVersion;

                HttpPost httppost = new HttpPost(url);
                str = "{" + "\"id\":" + gameid + "," + "\"s\":" + ((gameid * 5039) % 2311) + "," + "\"status\":"
                        + game.getHpStatus() + "," + "\"date\":" + game.getDate() + "," + "\"name\":\""
                        + escape(game.getName()) + "\"," + "\"players\":\"" + escape(game.getComment()) + "\","
                        + "\"streamer\":\"" + escape(game.getStreamer()) + "\"," + "\"length\":"
                        + game.getGameLength() + "," + "\"version\":\"" + version + "\"," + "\"mapname\":\""
                        + escape(gi.mapName) + "\"," + "\"mapcheck\":" + gi.mapCheck + "," + "\"certified\": "
                        + game.getCertified() + "," + "\"organisation\": \"" + escape(game.getOrganisation())
                        + "\"" + "}";
                httppost.setEntity(new ByteArrayEntity(str.getBytes()));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httppost, responseHandler);
            } catch (Exception e) {
                logger.error("Failed to update hp: " + e);
                logger.error("Request was: " + str);
                e.printStackTrace();//from   ww w . java 2 s. c o  m
            }

        }
    });
}

From source file:talkeeg.server.BarcodeProvider.java

@Override
public void handle(HttpRequest data, HttpAsyncExchange httpExchange, HttpContext context)
        throws HttpException, IOException {
    final BinaryData barcodeData = this.helloProvider.get().helloAsBinaryData();
    final BitMatrix matrix = this.barcodeServiceProvider.get().encode(barcodeData);
    final BufferedImage image = BarcodeUtilsSE.toBufferedImage(matrix);
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ImageIO.write(image, "png", tmp);
    final HttpResponse response = httpExchange.getResponse();
    response.setHeader("Content-Type", "image/png");
    response.setEntity(new ByteArrayEntity(tmp.toByteArray()));
    response.setStatusCode(HttpStatus.SC_OK);
    httpExchange.submitResponse(new BasicAsyncResponseProducer(response));
}