Search in sources :

Example 81 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project carbon-apimgt by wso2.

the class BlockingConditionRetrieverTest method run.

@Test
public void run() throws Exception {
    String content = "{\"api\":[\"/pizzashack/1.0.0\"],\"application\":[\"admin:DefaultApplication\"]," + "\"ip\":[{\"fixedIp\":\"127.0.0.1\",\"invert\":false,\"type\":\"IP\",\"tenantDomain\":\"carbon" + ".super\"}],\"user\":[\"admin\"],\"custom\":[]}";
    PowerMockito.mockStatic(APIUtil.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream(content.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    StatusLine status = Mockito.mock(StatusLine.class);
    Mockito.when(status.getStatusCode()).thenReturn(200);
    Mockito.when(httpResponse.getStatusLine()).thenReturn(status);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
    BDDMockito.given(APIUtil.getHttpClient(Mockito.anyInt(), Mockito.anyString())).willReturn(httpClient);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setUsername("admin");
    eventHubConfigurationDto.setPassword("admin".toCharArray());
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setServiceUrl("http://localhost:18083/internal/data/v1");
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    BlockingConditionRetriever blockingConditionRetriever = new BlockingConditionRetrieverWrapper(eventHubConfigurationDto, throttleDataHolder);
    blockingConditionRetriever.run();
    Assert.assertTrue(throttleDataHolder.isRequestBlocked("/pizzashack/1.0.0", "admin:DefaultApplication", "admin", "127.0.0.1", "carbon.super", "/pizzashack/1.0.0:1.0.0:admin-DefaultApplication"));
}
Also used : StatusLine(org.apache.http.StatusLine) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) ThrottleDataHolder(org.wso2.carbon.apimgt.gateway.throttling.ThrottleDataHolder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 82 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project cxf by apache.

the class AsyncHTTPConduit method setupConnection.

@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;
    }
    propagateJaxwsSpecTimeoutSettings(message, csPolicy);
    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 ("https".equals(uri.getScheme()) && 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 (!PropertyUtils.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("/");
    }
    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.getConnectionRequestTimeout());
    Proxy p = proxyFactory.createProxy(csPolicy, uri);
    if (p != null && p.type() != Proxy.Type.DIRECT) {
        InetSocketAddress isa = (InetSocketAddress) p.address();
        HttpHost proxy = new HttpHost(isa.getHostString(), isa.getPort());
        b.setProxy(proxy);
    }
    e.setConfig(b.build());
    message.put(CXFHttpRequest.class, e);
}
Also used : TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) RequestConfig(org.apache.http.client.config.RequestConfig) MalformedURLException(java.net.MalformedURLException) InetSocketAddress(java.net.InetSocketAddress) Address(org.apache.cxf.transport.http.Address) InetSocketAddress(java.net.InetSocketAddress) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Proxy(java.net.Proxy) HttpHost(org.apache.http.HttpHost)

Example 83 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project gocd by gocd.

the class HttpServiceTest method shouldDownloadArtifact.

@Test
public void shouldDownloadArtifact() throws IOException, URISyntaxException {
    String url = "http://blah";
    FetchHandler fetchHandler = mock(FetchHandler.class);
    HttpGet mockGetMethod = mock(HttpGet.class);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
    ByteArrayInputStream instream = new ByteArrayInputStream(new byte[] {});
    basicHttpEntity.setContent(instream);
    when(response.getEntity()).thenReturn(basicHttpEntity);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    when(httpClient.execute(mockGetMethod)).thenReturn(response);
    when(httpClientFactory.createGet(url)).thenReturn(mockGetMethod);
    when(mockGetMethod.getURI()).thenReturn(new URI(url));
    service.download(url, fetchHandler);
    verify(httpClient).execute(mockGetMethod);
    verify(fetchHandler).handle(instream);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) FetchHandler(com.thoughtworks.go.domain.FetchHandler) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) URI(java.net.URI) BasicStatusLine(org.apache.http.message.BasicStatusLine) Test(org.junit.jupiter.api.Test)

Example 84 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project robolectric by robolectric.

the class ShadowDefaultRequestDirector method interceptResponseContent.

private void interceptResponseContent(HttpResponse response) {
    HttpEntity entity = response.getEntity();
    if (entity instanceof HttpEntityWrapper) {
        HttpEntityWrapper entityWrapper = (HttpEntityWrapper) entity;
        try {
            Field wrappedEntity = HttpEntityWrapper.class.getDeclaredField("wrappedEntity");
            wrappedEntity.setAccessible(true);
            entity = (HttpEntity) wrappedEntity.get(entityWrapper);
        } catch (Exception e) {
        // fail to record
        }
    }
    if (entity instanceof BasicHttpEntity) {
        BasicHttpEntity basicEntity = (BasicHttpEntity) entity;
        try {
            Field contentField = BasicHttpEntity.class.getDeclaredField("content");
            contentField.setAccessible(true);
            InputStream content = (InputStream) contentField.get(basicEntity);
            byte[] buffer = Util.readBytes(content);
            FakeHttp.getFakeHttpLayer().addHttpResponseContent(buffer);
            contentField.set(basicEntity, new ByteArrayInputStream(buffer));
        } catch (Exception e) {
        // fail to record
        }
    }
}
Also used : Field(java.lang.reflect.Field) HttpEntity(org.apache.http.HttpEntity) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) HttpEntityWrapper(org.apache.http.entity.HttpEntityWrapper) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) IOException(java.io.IOException) HttpException(org.apache.http.HttpException)

Example 85 with BasicHttpEntity

use of org.apache.http.entity.BasicHttpEntity in project spring-cloud-netflix by spring-cloud.

the class RibbonLoadBalancingHttpClientTests method testRetryOnStatusCode.

@Test
public void testRetryOnStatusCode() throws Exception {
    int retriesNextServer = 0;
    int retriesSameServer = 1;
    boolean retryable = true;
    boolean retryOnAllOps = false;
    String serviceName = "foo";
    String host = serviceName;
    int port = 80;
    HttpMethod method = HttpMethod.GET;
    URI uri = new URI("http://" + host + ":" + port);
    CloseableHttpClient delegate = mock(CloseableHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    Locale locale = new Locale("en");
    doReturn(locale).when(response).getLocale();
    StatusLine statusLine = mock(StatusLine.class);
    doReturn(200).when(statusLine).getStatusCode();
    doReturn(statusLine).when(response).getStatusLine();
    final CloseableHttpResponse fourOFourResponse = mock(CloseableHttpResponse.class);
    doReturn(locale).when(fourOFourResponse).getLocale();
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContentLength(5);
    entity.setContent(new ByteArrayInputStream("error".getBytes()));
    doReturn(entity).when(fourOFourResponse).getEntity();
    StatusLine fourOFourStatusLine = mock(StatusLine.class);
    doReturn(404).when(fourOFourStatusLine).getStatusCode();
    doReturn(fourOFourStatusLine).when(fourOFourResponse).getStatusLine();
    doReturn(fourOFourResponse).doReturn(response).when(delegate).execute(any(HttpUriRequest.class));
    ILoadBalancer lb = mock(ILoadBalancer.class);
    MyBackOffPolicy myBackOffPolicy = new MyBackOffPolicy();
    RetryableRibbonLoadBalancingHttpClient client = setupClientForRetry(retriesNextServer, retriesSameServer, retryable, retryOnAllOps, serviceName, host, port, delegate, lb, "404", myBackOffPolicy);
    RibbonApacheHttpRequest request = mock(RibbonApacheHttpRequest.class);
    doReturn(uri).when(request).getURI();
    doReturn(method).when(request).getMethod();
    doReturn(request).when(request).withNewUri(any(URI.class));
    HttpUriRequest uriRequest = mock(HttpUriRequest.class);
    doReturn(uri).when(uriRequest).getURI();
    doReturn(uriRequest).when(request).toRequest(any(RequestConfig.class));
    client.execute(request, null);
    verify(fourOFourResponse, times(1)).close();
    verify(delegate, times(2)).execute(any(HttpUriRequest.class));
    verify(lb, times(1)).chooseServer(eq(serviceName));
    assertEquals(1, myBackOffPolicy.getCount());
}
Also used : Locale(java.util.Locale) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) URI(java.net.URI) StatusLine(org.apache.http.StatusLine) ByteArrayInputStream(java.io.ByteArrayInputStream) ILoadBalancer(com.netflix.loadbalancer.ILoadBalancer) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpMethod(org.springframework.http.HttpMethod) Test(org.junit.Test)

Aggregations

BasicHttpEntity (org.apache.http.entity.BasicHttpEntity)139 ByteArrayInputStream (java.io.ByteArrayInputStream)104 Test (org.junit.Test)89 InputStream (java.io.InputStream)60 IOException (java.io.IOException)24 HttpResponse (org.apache.http.HttpResponse)15 StatusLine (org.apache.http.StatusLine)12 BasicStatusLine (org.apache.http.message.BasicStatusLine)11 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)9 HttpException (org.apache.http.HttpException)8 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)8 HttpContext (org.apache.http.protocol.HttpContext)8 URISyntaxException (java.net.URISyntaxException)7 Map (java.util.Map)7 URI (java.net.URI)6 Header (org.apache.http.Header)6 ProtocolVersion (org.apache.http.ProtocolVersion)6 HttpGet (org.apache.http.client.methods.HttpGet)6 ChunkedInputStream (org.apache.http.impl.io.ChunkedInputStream)6 ContentLengthInputStream (org.apache.http.impl.io.ContentLengthInputStream)6