Example usage for org.apache.http.entity BasicHttpEntity BasicHttpEntity

List of usage examples for org.apache.http.entity BasicHttpEntity BasicHttpEntity

Introduction

In this page you can find the example usage for org.apache.http.entity BasicHttpEntity BasicHttpEntity.

Prototype

public BasicHttpEntity() 

Source Link

Usage

From source file:org.apache.nifi.processors.aws.wag.TestInvokeAmazonGatewayApiMock.java

@Test
public void testSendQueryParams() throws Exception {

    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);/*from w w  w . j  av a  2 s . c  o  m*/
    Mockito.doReturn(resp).when(mockSdkClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    // add dynamic property
    runner.setProperty("dynamicHeader", "yes!");
    runner.setProperty(InvokeAWSGatewayApi.PROP_QUERY_PARAMS, "apples=oranges&dogs=cats");

    // set the regex
    runner.setProperty(InvokeAWSGatewayApi.PROP_ATTRIBUTES_TO_SEND, "F.*");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put(CoreAttributes.MIME_TYPE.key(), "application/plain-text");
    attributes.put("Foo", "Bar");
    runner.enqueue("Hello".getBytes("UTF-8"), attributes);
    // execute
    runner.assertValid();
    runner.run(1);

    Mockito.verify(mockSdkClient, times(1)).execute(argThat(new RequestMatcher<HttpUriRequest>(x -> {
        return x.getMethod().equals("GET") && x.getFirstHeader("x-api-key").getValue().equals("abcd")
                && x.getFirstHeader("Authorization").getValue().startsWith("AWS4")
                && x.getFirstHeader("dynamicHeader").getValue().equals("yes!")
                && x.getFirstHeader("Foo").getValue().equals("Bar") && x.getURI().toString().equals(
                        "https://foobar.execute-api.us-east-1.amazonaws.com/TEST?dogs=cats&apples=oranges");
    })), any(HttpContext.class));
    // check
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_SUCCESS_REQ, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RESPONSE, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_NO_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_FAILURE, 0);

    final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(InvokeAWSGatewayApi.REL_RESPONSE);
    final MockFlowFile ff0 = flowFiles.get(0);

    ff0.assertAttributeEquals(InvokeAWSGatewayApi.STATUS_CODE, "200");
    ff0.assertContentEquals("test payload");
    ff0.assertAttributeExists(InvokeAWSGatewayApi.TRANSACTION_ID);
    ff0.assertAttributeEquals(InvokeAWSGatewayApi.RESOURCE_NAME_ATTR, "/TEST");
}

From source file:com.gooddata.http.client.LoginSSTRetrievalStrategyTest.java

private void prepareLoginFailureResponse() throws IOException, ClientProtocolException {
    statusLine = new BasicStatusLine(new ProtocolVersion("https", 1, 1), HttpStatus.SC_UNAUTHORIZED,
            "Unauthorized");
    final HttpResponse response = new BasicHttpResponse(statusLine);
    response.setHeader("X-GDC-Request", REQUEST_ID);
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(FAILURE_REASON.getBytes()));
    response.setEntity(entity);//w  w w .  j  a v  a  2 s  .  c o m
    when(httpClient.execute(any(HttpHost.class), any(HttpPost.class))).thenReturn(response);
    sstStrategy.setLogger(logger);
}

From source file:org.apache.hadoop.gateway.dispatch.CappedBufferHttpEntityTest.java

@Test
public void testB_C1_FC_IB__C1_XC__C2_FC() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;/*from   ww w .jav  a  2  s. co m*/
    CappedBufferHttpEntity replay;
    InputStream stream;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new CappedBufferHttpEntity(basic, 20);

    stream = replay.getContent();
    text = blockRead(stream, UTF8, -1, 3);
    assertThat(text, is("0123456789"));
    stream.close();

    stream = replay.getContent();
    text = blockRead(stream, UTF8, -1, 3);
    assertThat(text, is("0123456789"));
}

From source file:be.cytomine.client.HttpClient.java

public int put(String data) throws IOException {
    log.debug("Put " + URL.getPath());
    HttpPut httpPut = new HttpPut(URL.toString());
    if (isAuthByPrivateKey) {
        httpPut.setHeaders(headersArray);
    }/*from w  w  w .  j  ava 2s  .c o  m*/
    log.debug("Put send :" + data.replace("\n", ""));
    //write data
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(data.getBytes()));
    entity.setContentLength((long) data.getBytes().length);
    httpPut.setEntity(entity);
    response = client.execute(targetHost, httpPut, localcontext);
    return response.getStatusLine().getStatusCode();
}

From source file:org.apache.hadoop.gateway.dispatch.PartiallyRepeatableHttpEntityTest.java

@Test
public void testB_C1_FC_IB__C1_XC__C2_FC() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;//w w  w . j  a va 2  s  .  c  o  m
    PartiallyRepeatableHttpEntity replay;
    InputStream stream;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 20);

    stream = replay.getContent();
    text = blockRead(stream, UTF8, -1, 3);
    assertThat(text, is("0123456789"));
    stream.close();

    stream = replay.getContent();
    text = blockRead(stream, UTF8, -1, 3);
    assertThat(text, is("0123456789"));
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

/**
 * Same as {@link java.net.URLConnection#getOutputStream()}.
 * <p>//w  w w.  j  av a  2 s. com
 * This implementation creates a {@link PipedOutputStream} to the Apache entity input stream.
 * It is strongly advised to <b>write to the returned stream in another thread</b>.
 * @see PipedOutputStream
 * @see PipedInputStream
 * @return an output stream that writes to this connection.
 * @throws java.io.IOException if an I/O error occurs while creating the output stream.
 */
@objid("79282b13-7e13-42d5-9917-892c78a155bd")
@Override
public OutputStream getOutputStream() throws IOException {
    if (!this.dooutput)
        throw new IllegalStateException("This is not an output connection");

    if (this.req != null && !(this.req instanceof HttpPut))
        throw new IllegalStateException("This is not an output connection");

    PipedOutputStream outPipe = new PipedOutputStream();
    PipedInputStream snk = new PipedInputStream(outPipe);
    outPipe.connect(snk);

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(snk);

    HttpPut pr = (HttpPut) getRequest();
    pr.setEntity(entity);
    return outPipe;
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit.java

@Override
protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException {
    if (factory.isShutdown()) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, address, csPolicy);
        return;//from   w w  w  .  j  a  v a 2 s  .c  om
    }
    boolean addressChanged = false;
    // need to do some clean up work on the URI address
    URI uri = address.getURI();
    String uriString = uri.toString();
    if (uriString.startsWith("hc://")) {
        try {
            uriString = uriString.substring(5);
            uri = new URI(uriString);
            addressChanged = true;
        } catch (URISyntaxException ex) {
            throw new MalformedURLException("unsupport uri: " + uriString);
        }
    }
    String s = uri.getScheme();
    if (!"http".equals(s) && !"https".equals(s)) {
        throw new MalformedURLException("unknown protocol: " + s);
    }

    Object o = message.getContextualProperty(USE_ASYNC);
    if (o == null) {
        o = factory.getUseAsyncPolicy();
    }
    switch (UseAsyncPolicy.getPolicy(o)) {
    case ALWAYS:
        o = true;
        break;
    case NEVER:
        o = false;
        break;
    case ASYNC_ONLY:
    default:
        o = !message.getExchange().isSynchronous();
        break;
    }

    // check tlsClientParameters from message header
    TLSClientParameters clientParameters = message.get(TLSClientParameters.class);
    if (clientParameters == null) {
        clientParameters = tlsClientParameters;
    }
    if (uri.getScheme().equals("https") && clientParameters != null
            && clientParameters.getSSLSocketFactory() != null) {
        //if they configured in an SSLSocketFactory, we cannot do anything
        //with it as the NIO based transport cannot use socket created from
        //the SSLSocketFactory.
        o = false;
    }
    if (!MessageUtils.isTrue(o)) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, addressChanged ? new Address(uriString, uri) : address, csPolicy);
        return;
    }
    if (StringUtils.isEmpty(uri.getPath())) {
        //hc needs to have the path be "/" 
        uri = uri.resolve("/");
        addressChanged = true;
    }

    message.put(USE_ASYNC, Boolean.TRUE);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Asynchronous connection to " + uri.toString() + " has been set up");
    }
    message.put("http.scheme", uri.getScheme());
    String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    if (httpRequestMethod == null) {
        httpRequestMethod = "POST";
        message.put(Message.HTTP_REQUEST_METHOD, httpRequestMethod);
    }
    final CXFHttpRequest e = new CXFHttpRequest(httpRequestMethod);
    BasicHttpEntity entity = new BasicHttpEntity() {
        public boolean isRepeatable() {
            return e.getOutputStream().retransmitable();
        }
    };
    entity.setChunked(true);
    entity.setContentType((String) message.get(Message.CONTENT_TYPE));
    e.setURI(uri);

    e.setEntity(entity);

    RequestConfig.Builder b = RequestConfig.custom().setConnectTimeout((int) csPolicy.getConnectionTimeout())
            .setSocketTimeout((int) csPolicy.getReceiveTimeout())
            .setConnectionRequestTimeout((int) csPolicy.getReceiveTimeout());
    Proxy p = proxyFactory.createProxy(csPolicy, uri);
    if (p != null && p.type() != Proxy.Type.DIRECT) {
        InetSocketAddress isa = (InetSocketAddress) p.address();
        HttpHost proxy = new HttpHost(isa.getHostName(), isa.getPort());
        b.setProxy(proxy);
    }
    e.setConfig(b.build());

    message.put(CXFHttpRequest.class, e);
}

From source file:org.fiware.apps.repository.it.IntegrationTestHelper.java

public HttpResponse postQuery(String query, List<Header> headers) throws IOException {
    String finalURL = queryServiceUrl;
    HttpPost request = new HttpPost(finalURL);

    //Add Headers
    for (Header header : headers) {
        request.setHeader(header);/*  w w  w .  ja va 2 s .c om*/
    }

    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream stream = new ByteArrayInputStream(query.getBytes());

    entity.setContent(stream);
    request.setEntity(entity);

    HttpResponse response = client.execute(request);
    request.releaseConnection();
    return response;
}

From source file:org.apache.hadoop.gateway.dispatch.CappedBufferHttpEntityTest.java

@Test
public void testS_C1_FC_OB__C1_XC__C2_AC__EE() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;//from  ww w . ja v  a  2s.co  m
    CappedBufferHttpEntity replay;
    InputStream stream;
    String text;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes(UTF8)));
    replay = new CappedBufferHttpEntity(basic, 5);

    stream = replay.getContent();
    try {
        text = byteRead(stream, -1);
        fail("Expected IOException");
    } catch (IOException e) {
        // Expected.
    }
}