org.apache.http.conn.routing.HttpRoute Java Examples

The following examples show how to use org.apache.http.conn.routing.HttpRoute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpClientAdapter.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public HttpRoute determineRoute(final HttpHost host, final HttpRequest request,
        final HttpContext context) throws HttpException {

    Boolean ignoreNoProxy = (Boolean) context.getAttribute(IGNORE_NO_PROXY);
    URI requestUri = (URI) context.getAttribute(REQUEST_URI);

    if (proxyHost != null &&
            (Boolean.TRUE.equals(ignoreNoProxy) || useProxyFor(requestUri))) {
        if (log.isDebugEnabled()) {
            log.debug("Using proxy: " + proxyHost);
        }
        return super.determineRoute(host, request, context);
    }
    if (log.isDebugEnabled()) {
        log.debug("Using a direct connection (no proxy)");
    }
    // Return direct route
    return new HttpRoute(host);
}
 
Example #2
Source File: ApacheHttpClientInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onBeforeExecute(@Advice.Argument(0) HttpRoute route,
                                    @Advice.Argument(1) HttpRequestWrapper request,
                                    @Advice.Local("span") Span span) {
    if (tracer == null || tracer.getActive() == null) {
        return;
    }
    final AbstractSpan<?> parent = tracer.getActive();
    span = HttpClientHelper.startHttpClientSpan(parent, request.getMethod(), request.getURI(), route.getTargetHost().getHostName());
    TextHeaderSetter<HttpRequest> headerSetter = headerSetterHelperClassManager.getForClassLoaderOfClass(HttpRequest.class);
    TextHeaderGetter<HttpRequest> headerGetter = headerGetterHelperClassManager.getForClassLoaderOfClass(HttpRequest.class);
    if (span != null) {
        span.activate();
        if (headerSetter != null) {
            span.propagateTraceContext(request, headerSetter);
        }
    } else if (headerGetter != null && !TraceContext.containsTraceContextTextHeaders(request, headerGetter)
        && headerSetter != null && parent != null) {
        // re-adds the header on redirects
        parent.propagateTraceContext(request, headerSetter);
    }
}
 
Example #3
Source File: HttpContextUtils.java    From micrometer with Apache License 2.0 6 votes vote down vote up
static Tags generateTagsForRoute(HttpContext context) {
    String targetScheme = "UNKNOWN";
    String targetHost = "UNKNOWN";
    String targetPort = "UNKNOWN";
    Object routeAttribute = context.getAttribute("http.route");
    if (routeAttribute instanceof HttpRoute) {
        HttpHost host = ((HttpRoute) routeAttribute).getTargetHost();
        targetScheme = host.getSchemeName();
        targetHost = host.getHostName();
        targetPort = String.valueOf(host.getPort());
    }
    return Tags.of(
            "target.scheme", targetScheme,
            "target.host", targetHost,
            "target.port", targetPort
    );
}
 
Example #4
Source File: ApacheHttpClientEdgeGridRoutePlanner.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Override
public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
    try {
        ClientCredential clientCredential = binding.getClientCredentialProvider().getClientCredential(binding.map(request));
        String hostname = clientCredential.getHost();
        int port = -1;
        final int pos = hostname.lastIndexOf(":");
        if (pos > 0) {
            try {
                port = Integer.parseInt(hostname.substring(pos + 1));
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Host contains invalid port number: " + hostname);
            }
            hostname = hostname.substring(0, pos);
        }
        HttpHost target = new HttpHost(hostname, port, "https");
        return super.determineRoute(target, request, context);
    } catch (NoMatchingCredentialException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: TracingManagedHttpClientConnectionFactory.java    From caravan with Apache License 2.0 6 votes vote down vote up
@Override
public ManagedHttpClientConnection create(final HttpRoute route, final ConnectionConfig config) {
    final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
    CharsetDecoder chardecoder = null;
    CharsetEncoder charencoder = null;
    final Charset charset = cconfig.getCharset();
    final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null ? cconfig.getMalformedInputAction() : CodingErrorAction.REPORT;
    final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null ? cconfig.getUnmappableInputAction()
            : CodingErrorAction.REPORT;
    if (charset != null) {
        chardecoder = charset.newDecoder();
        chardecoder.onMalformedInput(malformedInputAction);
        chardecoder.onUnmappableCharacter(unmappableInputAction);
        charencoder = charset.newEncoder();
        charencoder.onMalformedInput(malformedInputAction);
        charencoder.onUnmappableCharacter(unmappableInputAction);
    }
    final String id = "http-outgoing-" + Long.toString(COUNTER.getAndIncrement());
    return new TracingManagedHttpClientConnection(id, cconfig.getBufferSize(), cconfig.getFragmentSizeHint(), chardecoder, charencoder,
            cconfig.getMessageConstraints(), incomingContentStrategy, outgoingContentStrategy, requestWriterFactory, responseParserFactory, logFunc);
}
 
Example #6
Source File: TracingProtocolExec.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public CloseableHttpResponse execute(HttpRoute route,
  org.apache.http.client.methods.HttpRequestWrapper req,
  HttpClientContext context, HttpExecutionAware execAware)
  throws IOException, HttpException {
  HttpRequestWrapper request = new HttpRequestWrapper(req, context.getTargetHost());
  Span span = tracer.nextSpan(httpSampler, request);
  context.setAttribute(Span.class.getName(), span);

  CloseableHttpResponse response = null;
  Throwable error = null;
  try (SpanInScope ws = tracer.withSpanInScope(span)) {
    return response = protocolExec.execute(route, req, context, execAware);
  } catch (Throwable e) {
    error = e;
    throw e;
  } finally {
    handler.handleReceive(new HttpResponseWrapper(response, context, error), span);
  }
}
 
Example #7
Source File: ProxyFeedBackClientExecChain.java    From vscrawler with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request, HttpClientContext clientContext,
        HttpExecutionAware execAware) throws IOException, HttpException {
    Proxy proxy = (Proxy) clientContext.getAttribute(VSCrawlerConstant.VSCRAWLER_AVPROXY_KEY);
    if (proxy != null) {
        proxy.recordUsage();
    }
    try {
        return delegate.execute(route, request, clientContext, execAware);
    } catch (IOException ioe) {
        if (proxy != null) {
            proxy.recordFailed();
        }
        throw ioe;
    }
}
 
Example #8
Source File: ExtendedJestClientFactory.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected NHttpClientConnectionManager getAsyncConnectionManager() {

    PoolingNHttpClientConnectionManager connectionManager = createUnconfiguredPoolingNHttpClientConnectionManager();

    HttpClientConfig httpClientConfig = this.wrappedHttpClientConfig.getHttpClientConfig();

    final Integer maxTotal = httpClientConfig.getMaxTotalConnection();
    if (maxTotal != null) {
        connectionManager.setMaxTotal(maxTotal);
    }
    final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute();
    if (defaultMaxPerRoute != null) {
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
    }
    final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute();
    for (Map.Entry<HttpRoute, Integer> entry : maxPerRoute.entrySet()) {
        connectionManager.setMaxPerRoute(entry.getKey(), entry.getValue());
    }

    return connectionManager;
}
 
Example #9
Source File: ExtendedJestClientFactoryTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void getAsyncConnectionManagerConfiguresMaxTotalPerRouteIfConfigured() {

    // given
    HttpClientConfig.Builder config = createDefaultTestHttpClientConfigBuilder();

    HttpRoute expectedHttpRoute = new HttpRoute(new HttpHost("localhost"));
    int expectedMaxTotalConnection = random.nextInt(100) + 10;
    config.maxTotalConnectionPerRoute(expectedHttpRoute, expectedMaxTotalConnection);

    WrappedHttpClientConfig.Builder builder = createDefaultTestWrappedHttpClientConfigBuilder(config.build());
    ExtendedJestClientFactory factory = spy(new ExtendedJestClientFactory(builder.build()));

    PoolingNHttpClientConnectionManager mockedNHttpConnectionManager = mock(PoolingNHttpClientConnectionManager.class);
    when(factory.createUnconfiguredPoolingNHttpClientConnectionManager())
            .thenReturn(mockedNHttpConnectionManager);

    // when
    factory.getAsyncConnectionManager();

    // then
    verify(mockedNHttpConnectionManager).setMaxPerRoute(eq(expectedHttpRoute), eq(expectedMaxTotalConnection));

}
 
Example #10
Source File: MetricsClientFactory.java    From galaxy-sdk-java with Apache License 2.0 6 votes vote down vote up
public static HttpClient generateHttpClient(final int maxTotalConnections,
    final int maxTotalConnectionsPerRoute, int connTimeout) {
  HttpParams params = new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params, maxTotalConnections);
  ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
    @Override
    public int getMaxForRoute(HttpRoute route) {
      return maxTotalConnectionsPerRoute;
    }
  });
  HttpConnectionParams
      .setConnectionTimeout(params, connTimeout);
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(
      new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
  sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
  ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schemeRegistry);
  return new DefaultHttpClient(conMgr, params);
}
 
Example #11
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private static HttpClientConnectionManager createDefaultConnectionManager(
    HttpClientConnectionOperator operator,
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory
) {
  PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
      operator,
      connectionFactory,
      -1,
      TimeUnit.MILLISECONDS
  );

  manager.setMaxTotal(3000);
  manager.setDefaultMaxPerRoute(1500);

  return manager;
}
 
Example #12
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
  return new ConnectionRequest() {

    @Override
    public boolean cancel() {
      // Nothing to do.
      return false;
    }

    @Override
    public HttpClientConnection get(final long timeout, final TimeUnit timeUnit) {
      return connectionFactory.create(route, connectionConfig);
    }
  };
}
 
Example #13
Source File: SimpleHttpClientConnectionManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@Override
public void connect(
    HttpClientConnection connection,
    HttpRoute route,
    int connectTimeout,
    HttpContext context
) throws IOException {
  HttpHost host;

  if (route.getProxyHost() != null) {
    host = route.getProxyHost();
  } else {
    host = route.getTargetHost();
  }

  InetSocketAddress localAddress = route.getLocalSocketAddress();

  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.connect(managed, host, localAddress, connectTimeout, this.socketConfig, context);
}
 
Example #14
Source File: HttpProtocolParent.java    From dtsopensource with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(String hostname, int port) {
    ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", plainsf).register("https", sslsf).build();
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    // 将最大连接数增加
    cm.setMaxTotal(maxTotal);
    // 将每个路由基础的连接增加
    cm.setDefaultMaxPerRoute(maxPerRoute);
    HttpHost httpHost = new HttpHost(hostname, port);
    // 将目标主机的最大连接数增加
    cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
    // 请求重试处理
    return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
}
 
Example #15
Source File: PingCheckMonitor.java    From ranger with Apache License 2.0 6 votes vote down vote up
/**
 * @param timeEntity                how often the {@link #monitor()} check needs to be executed
 * @param httpRequest               http request that will be called at regular intervals
 * @param pingTimeoutInMilliseconds timeout in milliseconds for http request execution (ping response)
 * @param pingWindowSize            rolling window frame, which needs to be maintained
 * @param maxFailures               maximum failures allowed in the rolling window frame
 * @param host                      host name (could be localhost)
 * @param port                      port
 */
public PingCheckMonitor(TimeEntity timeEntity,
                        HttpRequest httpRequest,
                        Integer pingTimeoutInMilliseconds,
                        Integer pingWindowSize,
                        Integer maxFailures,
                        String host,
                        Integer port) {
    super(PingCheckMonitor.class.getSimpleName(), timeEntity);
    this.httpRequest = httpRequest;
    this.pingTimeoutInMilliseconds = pingTimeoutInMilliseconds;
    this.host = host;
    this.port = port;
    this.rollingWindowHealthQueue = new RollingWindowHealthQueue(pingWindowSize, maxFailures);
    this.executorService = Executors.newSingleThreadExecutor();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(host, port)), 2);
    this.httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();
}
 
Example #16
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 6 votes vote down vote up
protected void rewriteRequestURI(
        final RequestWrapper request,
        final HttpRoute route) throws ProtocolException {
    try {

        URI uri = request.getURI();
        if (route.getProxyHost() != null && !route.isTunnelled()) {
            // Make sure the request URI is absolute
            if (!uri.isAbsolute()) {
                HttpHost target = route.getTargetHost();
                uri = URIUtils.rewriteURI(uri, target);
                request.setURI(uri);
            }
        } else {
            // Make sure the request URI is relative
            if (uri.isAbsolute()) {
                uri = URIUtils.rewriteURI(uri, null);
                request.setURI(uri);
            }
        }

    } catch (URISyntaxException ex) {
        throw new ProtocolException("Invalid URI: "
        		+ request.getRequestLine().getUri(), ex);
    }
}
 
Example #17
Source File: PGPKeysServerClient.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void processOnRetry(RetryEvent event, Duration waitInterval,
                            HttpRoutePlanner planer, OnRetryConsumer onRetryConsumer) {

    InetAddress targetAddress = null;
    if (planer instanceof RoundRobinRouterPlaner) {
        // inform planer about error on last roue
        HttpRoute httpRoute = ((RoundRobinRouterPlaner)planer).lastRouteCauseError();
        targetAddress = Try.of(() -> httpRoute.getTargetHost().getAddress()).getOrElse((InetAddress) null);
    } else if (proxy != null) {
        targetAddress = Try.of(() -> InetAddress.getByName(proxy.getHost())).getOrElse((InetAddress) null);
    }

    // inform caller about retry
    if (onRetryConsumer != null) {
        onRetryConsumer.onRetry(targetAddress, event.getNumberOfRetryAttempts(),
                waitInterval, event.getLastThrowable());
    }
}
 
Example #18
Source File: RoundRobinRouterPlanerIT.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnTheSameAddressForSequentialCall() throws UnknownHostException, HttpException {

    InetAddress[] expected = InetAddress.getAllByName(TEST_HOST);

    RoundRobinRouterPlaner routerPlaner = new RoundRobinRouterPlaner();
    HttpHost httpHost = new HttpHost(TEST_HOST);

    // first call
    HttpRoute firstRoute = routerPlaner.determineRoute(httpHost, null, null);

    for (int i = 0; i < expected.length; i++) {
        HttpRoute httpRouteNext = routerPlaner.determineRoute(httpHost, null, null);
        assertEquals(httpRouteNext.getTargetHost().getAddress(), firstRoute.getTargetHost().getAddress());
    }
}
 
Example #19
Source File: RestClient.java    From light with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient httpClient() throws Exception {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry());

        Map<String, Object> httpClientMap = (Map<String, Object>)configMap.get(REST_TEMPLATE);
        connectionManager.setMaxTotal((Integer)httpClientMap.get(MAX_CONNECTION_TOTAL));
        connectionManager.setDefaultMaxPerRoute((Integer) httpClientMap.get(MAX_CONNECTION_PER_ROUTE));
        // Now handle all the specific route defined.
        Map<String, Object> routeMap = (Map<String, Object>)httpClientMap.get(ROUTES);
        Iterator<String> it = routeMap.keySet().iterator();
        while (it.hasNext()) {
            String route = it.next();
            Integer maxConnection = (Integer)routeMap.get(route);
            connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(
                    route)), maxConnection);
        }
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout((Integer)httpClientMap.get(TIMEOUT_MILLISECONDS))
                .build();

       return HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();
    }
 
Example #20
Source File: TracingMainExec.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public CloseableHttpResponse execute(HttpRoute route,
  org.apache.http.client.methods.HttpRequestWrapper request,
  HttpClientContext context, HttpExecutionAware execAware)
  throws IOException, HttpException {
  Span span = (Span) context.removeAttribute(Span.class.getName());

  if (span != null) {
    handler.handleSend(new HttpRequestWrapper(request, route.getTargetHost()), span);
  }

  CloseableHttpResponse response = mainExec.execute(route, request, context, execAware);
  if (span != null) {
    if (isRemote(context, span)) {
      if (serverName != null) span.remoteServiceName(serverName);
      parseTargetAddress(route.getTargetHost(), span);
    } else {
      span.kind(null); // clear as cache hit
    }
  }
  return response;
}
 
Example #21
Source File: ClientFactory.java    From galaxy-sdk-java with Apache License 2.0 6 votes vote down vote up
public static HttpClient generateHttpClient(final int maxTotalConnections,
                                            final int maxTotalConnectionsPerRoute, int connTimeout) {
  HttpParams params = new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params, maxTotalConnections);
  ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() {
    @Override
    public int getMaxForRoute(HttpRoute route) {
      return maxTotalConnectionsPerRoute;
    }
  });
  HttpConnectionParams
      .setConnectionTimeout(params, connTimeout);
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(
      new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
  sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
  ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schemeRegistry);
  return new DefaultHttpClient(conMgr, params);
}
 
Example #22
Source File: SignatureExec.java    From wechatpay-apache-httpclient with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableHttpResponse execute(HttpRoute route, HttpRequestWrapper request,
    HttpClientContext context, HttpExecutionAware execAware) throws IOException, HttpException {
  if (request.getURI().getHost().endsWith(".mch.weixin.qq.com")) {
    return executeWithSignature(route, request, context, execAware);
  } else {
    return mainExec.execute(route, request, context, execAware);
  }
}
 
Example #23
Source File: HttpClientConnectionManagementLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
// Example 4.1
public final void whenIncreasingConnectionPool_thenNoEceptions() {
    poolingConnManager = new PoolingHttpClientConnectionManager();
    poolingConnManager.setMaxTotal(5);
    poolingConnManager.setDefaultMaxPerRoute(4);

    final HttpHost localhost = new HttpHost("locahost", 80);
    poolingConnManager.setMaxPerRoute(new HttpRoute(localhost), 5);
}
 
Example #24
Source File: HttpClientUtils.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
public static Map<HttpRoute, PoolStats> getConnManagerStats() {
    if (connManager != null) {
        Set<HttpRoute> routeSet = connManager.getRoutes();
        if (routeSet != null && !routeSet.isEmpty()) {
            Map<HttpRoute, PoolStats> routeStatsMap = new HashMap<HttpRoute, PoolStats>();
            for (HttpRoute route : routeSet) {
                PoolStats stats = connManager.getStats(route);
                routeStatsMap.put(route, stats);
            }
            return routeStatsMap;
        }
    }
    return null;
}
 
Example #25
Source File: HttpClientUtils.java    From paas with Apache License 2.0 5 votes vote down vote up
public static Map<HttpRoute, PoolStats> getConnManagerStats() {
    if (connManager != null) {
        Set<HttpRoute> routeSet = connManager.getRoutes();
        if (routeSet != null && !routeSet.isEmpty()) {
            Map<HttpRoute, PoolStats> routeStatsMap = new HashMap<HttpRoute, PoolStats>();
            for (HttpRoute route : routeSet) {
                PoolStats stats = connManager.getStats(route);
                routeStatsMap.put(route, stats);
            }
            return routeStatsMap;
        }
    }
    return null;
}
 
Example #26
Source File: SessionConfigurator.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private HttpContext getContext( URI uri ) {
  HttpClientContext httpClientContext = HttpClientContext.create();
  //used by httpclient version >= 4.3
  httpClientContext
    .setAttribute( HttpClientContext.HTTP_ROUTE, new HttpRoute( new HttpHost( uri.getHost(), uri.getPort() ) ) );
  //used by httpclient version 4.2
  httpClientContext
    .setAttribute( HttpClientContext.HTTP_TARGET_HOST, new HttpHost( uri.getHost(), uri.getPort() ) );
  return httpClientContext;
}
 
Example #27
Source File: PoolingHttpClientConnectionManagerMetricsBinderTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@BeforeEach
@SuppressWarnings("unchecked")
void setup() {
    connPoolControl = (ConnPoolControl<HttpRoute>) mock(ConnPoolControl.class);
    binder = new PoolingHttpClientConnectionManagerMetricsBinder(connPoolControl, "test");
    binder.bindTo(registry);
}
 
Example #28
Source File: HttpClientConnectionManagementLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
// 7.1
public final void whenConfiguringTimeOut_thenNoExceptions() {
    route = new HttpRoute(new HttpHost("localhost", 80));
    poolingConnManager = new PoolingHttpClientConnectionManager();
    poolingConnManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom().setSoTimeout(5000).build());
    assertTrue(poolingConnManager.getSocketConfig(route.getTargetHost()).getSoTimeout() == 5000);
}
 
Example #29
Source File: HttpClientTest.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    reactor = new NioReactor();

    crusher = TcpCrusherBuilder.builder()
            .withReactor(reactor)
            .withBindAddress("127.0.0.1", CRUSHER_PORT)
            .withConnectAddress(REMOTE_HOST, REMOTE_PORT)
            .buildAndOpen();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase(REMOTE_HOST)) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] {127, 0, 0, 1}) };
            } else {
                return super.resolve(host);
            }
        }
    };

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> httpConnectionFactory =
            new ManagedHttpClientConnectionFactory();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, httpConnectionFactory, dnsResolver);

    http = HttpClients.createMinimal(connectionManager);
}
 
Example #30
Source File: ConnectionReuseTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm)
    throws IOException, HttpException {
  HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);

  req.addHeader("Host", target.getHostName());
  if (!conn.isOpen()) {
    // establish connection based on its route info
    cm.connect(conn, route, 1000, context);
    // and mark it as route complete
    cm.routeComplete(conn, route, context);
  }
  conn.sendRequestHeader(req);
  conn.flush();
  conn.receiveResponseHeader();
}