private CloseableHttpAsyncClient createHttpAsyncClient(YunpianConf conf) throws IOReactorException { IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(Runtime.getRuntime().availableProcessors()) .setConnectTimeout(conf.getConfInt(YunpianConf.HTTP_CONN_TIMEOUT, "10000")) .setSoTimeout(conf.getConfInt(YunpianConf.HTTP_SO_TIMEOUT, "30000")).build(); ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor); ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(Charset.forName(conf.getConf(YunpianConf.HTTP_CHARSET, YunpianConf.HTTP_CHARSET_DEFAULT))).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setMaxTotal(conf.getConfInt(YunpianConf.HTTP_CONN_MAXTOTAL, "100")); connManager.setDefaultMaxPerRoute(conf.getConfInt(YunpianConf.HTTP_CONN_MAXPERROUTE, "10")); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(connManager).build(); httpclient.start(); return httpclient; }
public static CloseableHttpClient getHttpClient() { if(httpClient==null){ synchronized (HttpPoolManager.class) { if(httpClient==null){ System.out.println(COUNT++); ConnectionConfig config = ConnectionConfig.custom() .setBufferSize(4128) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultConnectionConfig(config) .build(); } } } return httpClient; }
public static CloseableHttpClient getHttpClient(HttpClientConnectionManager connectionManager, int maxConnections) { RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build(); ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build(); SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true) .setSoReuseAddress(true).build(); String userAgent = MessageFormat .format("MyCoRe/{0} ({1}; java {2})", MCRCoreVersion.getCompleteVersion(), MCRConfiguration.instance() .getString("MCR.NameOfProject", "undefined"), System.getProperty("java.version")); //setup http client return HttpClients.custom().setConnectionManager(connectionManager) .setUserAgent(userAgent).setRetryHandler(new MCRRetryHandler(maxConnections)) .setDefaultRequestConfig(requestConfig).setDefaultConnectionConfig(connectionConfig) .setDefaultSocketConfig(socketConfig).build(); }
/** * @since 4.3 */ public ProxyClient( final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final ConnectionConfig connectionConfig, final RequestConfig requestConfig) { super(); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT; this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT; this.httpProcessor = new ImmutableHttpProcessor( new RequestTargetHostHC4(), new RequestClientConnControl(), new RequestUserAgentHC4()); this.requestExec = new HttpRequestExecutor(); this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); this.authenticator = new HttpAuthenticator(); this.proxyAuthState = new AuthStateHC4(); this.authSchemeRegistry = new AuthSchemeRegistry(); this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactoryHC4()); this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactoryHC4()); this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory()); this.reuseStrategy = new DefaultConnectionReuseStrategyHC4(); }
public ManagedHttpClientConnection create(final HttpRoute route) throws IOException { ConnectionConfig config = null; if (route.getProxyHost() != null) { config = this.configData.getConnectionConfig(route.getProxyHost()); } if (config == null) { config = this.configData.getConnectionConfig(route.getTargetHost()); } if (config == null) { config = this.configData.getDefaultConnectionConfig(); } if (config == null) { config = ConnectionConfig.DEFAULT; } return this.connFactory.create(route, config); }
/** * @since 4.3 */ public ProxyClient( final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final ConnectionConfig connectionConfig, final RequestConfig requestConfig) { super(); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT; this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT; this.httpProcessor = new ImmutableHttpProcessor( new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent()); this.requestExec = new HttpRequestExecutor(); this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); this.authenticator = new HttpAuthenticator(); this.proxyAuthState = new AuthState(); this.authSchemeRegistry = new AuthSchemeRegistry(); this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); this.reuseStrategy = new DefaultConnectionReuseStrategy(); }
@Override public ManagedHttpClientConnection create(final HttpRoute route) throws IOException { ConnectionConfig config = null; if (route.getProxyHost() != null) { config = this.configData.getConnectionConfig(route.getProxyHost()); } if (config == null) { config = this.configData.getConnectionConfig(route.getTargetHost()); } if (config == null) { config = this.configData.getDefaultConnectionConfig(); } if (config == null) { config = ConnectionConfig.DEFAULT; } return this.connFactory.create(route, config); }
@Test public void testLeaseReleaseNonReusable() throws Exception { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(connFactory.create( Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); Assert.assertFalse(conn1.isOpen()); mgr.releaseConnection(conn1, null, 100, TimeUnit.MILLISECONDS); Assert.assertNull(mgr.getRoute()); Assert.assertNull(mgr.getState()); final ConnectionRequest connRequest2 = mgr.requestConnection(route, null); final HttpClientConnection conn2 = connRequest2.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn2); Assert.assertFalse(conn2.isOpen()); Mockito.verify(connFactory, Mockito.times(2)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); }
@Test(expected=IllegalStateException.class) public void testAlreadyLeased() throws Exception { final HttpHost target = new HttpHost("somehost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(connFactory.create( Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); mgr.releaseConnection(conn1, null, 100, TimeUnit.MILLISECONDS); mgr.getConnection(route, null); mgr.getConnection(route, null); }
public static CloseableHttpClient newClient(int timeout) { HttpClientBuilder builder = HttpClients.custom(); builder.useSystemProperties(); builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING); builder.disableAutomaticRetries(); builder.setSSLContext(SSL_CONTEXT); builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); RequestConfig.Builder configBuilder = RequestConfig.custom(); configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); configBuilder.setSocketTimeout(timeout); configBuilder.setConnectTimeout(timeout); configBuilder.setConnectionRequestTimeout(timeout); builder.setDefaultRequestConfig(configBuilder.build()); builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build()); return builder.build(); }
private ConnectionConfig buildConnectionConfig(HttpClientSettings settings) { int socketBufferSize = Math.max(settings.getSocketBufferSize()[0], settings.getSocketBufferSize()[1]); return socketBufferSize <= 0 ? null : ConnectionConfig.custom() .setBufferSize(socketBufferSize) .build(); }
/** Creates a new fetching thread. * * @param frontier a reference to the {@link Frontier}. * @param index the index of this thread (only for logging purposes). */ public FetchingThread(final Frontier frontier, final int index) throws NoSuchAlgorithmException, IllegalArgumentException, IOException { setName(this.getClass().getSimpleName() + '-' + index); setPriority(Thread.MIN_PRIORITY); // Low priority; there will be thousands of this guys around. this.frontier = frontier; final BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManagerWithAlternateDNS(frontier.rc.dnsResolver); connManager.closeIdleConnections(0, TimeUnit.MILLISECONDS); connManager.setConnectionConfig(ConnectionConfig.custom().setBufferSize(8 * 1024).build()); // TODO: make this configurable cookieStore = new BasicCookieStore(); BasicHeader[] headers = { new BasicHeader("From", frontier.rc.userAgentFrom), new BasicHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.95,text/*;q=0.9,*/*;q=0.8") }; httpClient = HttpClients.custom() .setSSLContext(frontier.rc.acceptAllCertificates ? TRUST_ALL_CERTIFICATES_SSL_CONTEXT : TRUST_SELF_SIGNED_SSL_CONTEXT) .setConnectionManager(connManager) .setConnectionReuseStrategy(frontier.rc.keepAliveTime == 0 ? NoConnectionReuseStrategy.INSTANCE : DefaultConnectionReuseStrategy.INSTANCE) .setUserAgent(frontier.rc.userAgent) .setDefaultCookieStore(cookieStore) .setDefaultHeaders(ObjectArrayList.wrap(headers)) .build(); fetchData = new FetchData(frontier.rc); }
public SimpleHttpClient() { ConnectionConfig config = ConnectionConfig.DEFAULT; RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(3000) .setConnectionRequestTimeout(3000) .build(); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultConnectionConfig(config); builder.setDefaultRequestConfig(requestConfig); client = builder.build(); httpClientContext = HttpClientContext.create(); }
public static ConnectionConfig getConnectionConfig(final HttpParams params) { final MessageConstraints messageConstraints = getMessageConstraints(params); final String csname = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET); return ConnectionConfig.custom() .setCharset(csname != null ? Charset.forName(csname) : null) .setMessageConstraints(messageConstraints) .build(); }
/** * @since 4.3 */ public BasicConnFactory( final SocketFactory plainfactory, final SSLSocketFactory sslfactory, final int connectTimeout, final SocketConfig sconfig, final ConnectionConfig cconfig) { super(); this.plainfactory = plainfactory; this.sslfactory = sslfactory; this.connectTimeout = connectTimeout; this.sconfig = sconfig != null ? sconfig : SocketConfig.DEFAULT; this.connFactory = new DefaultBHttpClientConnectionFactory( cconfig != null ? cconfig : ConnectionConfig.DEFAULT); }
public DefaultBHttpClientConnectionFactory( final ConnectionConfig cconfig, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final HttpMessageWriterFactory<HttpRequest> requestWriterFactory, final HttpMessageParserFactory<HttpResponse> responseParserFactory) { super(); this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; this.incomingContentStrategy = incomingContentStrategy; this.outgoingContentStrategy = outgoingContentStrategy; this.requestWriterFactory = requestWriterFactory; this.responseParserFactory = responseParserFactory; }
public static CharsetDecoder createDecoder(final ConnectionConfig cconfig) { if (cconfig == null) { return null; } final Charset charset = cconfig.getCharset(); final CodingErrorAction malformed = cconfig.getMalformedInputAction(); final CodingErrorAction unmappable = cconfig.getUnmappableInputAction(); if (charset != null) { return charset.newDecoder() .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT) .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT); } else { return null; } }
public static CharsetEncoder createEncoder(final ConnectionConfig cconfig) { if (cconfig == null) { return null; } final Charset charset = cconfig.getCharset(); if (charset != null) { final CodingErrorAction malformed = cconfig.getMalformedInputAction(); final CodingErrorAction unmappable = cconfig.getUnmappableInputAction(); return charset.newEncoder() .onMalformedInput(malformed != null ? malformed : CodingErrorAction.REPORT) .onUnmappableCharacter(unmappable != null ? unmappable: CodingErrorAction.REPORT); } else { return null; } }
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 LoggingManagedHttpClientConnection( id, cconfig.getBufferSize(), cconfig.getFragmentSizeHint(), chardecoder, charencoder, cconfig.getMessageConstraints(), null, null, requestWriterFactory, responseParserFactory); }
public BasicHttpClientConnectionManager( final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); this.connectionOperator = new HttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.expiry = Long.MAX_VALUE; this.socketConfig = SocketConfig.DEFAULT; this.connConfig = ConnectionConfig.DEFAULT; this.isShutdown = new AtomicBoolean(false); }
public DefaultBHttpServerConnectionFactory( final ConnectionConfig cconfig, final ContentLengthStrategy incomingContentStrategy, final ContentLengthStrategy outgoingContentStrategy, final HttpMessageParserFactory<HttpRequest> requestParserFactory, final HttpMessageWriterFactory<HttpResponse> responseWriterFactory) { super(); this.cconfig = cconfig != null ? cconfig : ConnectionConfig.DEFAULT; this.incomingContentStrategy = incomingContentStrategy; this.outgoingContentStrategy = outgoingContentStrategy; this.requestParserFactory = requestParserFactory; this.responseWriterFactory = responseWriterFactory; }
private static void subscriptionListenHttpComponents(ObjectMapper objectMapper, Listener<SalesOrderPlaced> listener) throws IOException { final RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(60000) .setConnectTimeout(2000) .setConnectionRequestTimeout(8000) .setContentCompressionEnabled(false) .build(); final ConnectionConfig connectionConfig = ConnectionConfig.custom() .setBufferSize(512) .build(); final CloseableHttpClient httpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setDefaultConnectionConfig(connectionConfig) .setConnectionTimeToLive(30, TimeUnit.SECONDS) .disableAutomaticRetries() .disableRedirectHandling() .setMaxConnTotal(8) .setMaxConnPerRoute(2) .build(); final RequestFactory requestFactory = new HttpComponentsRequestFactory(httpClient); final NakadiClient nakadiClient = NakadiClient.builder(NAKADI_URI) .withRequestFactory(requestFactory) .withAccessTokenProvider(new ZignAccessTokenProvider()) .build(); final Subscription subscription = nakadiClient.subscription("fahrschein-demo", SALES_ORDER_SERVICE_ORDER_PLACED) .withConsumerGroup("fahrschein-demo") .readFromEnd() .subscribe(); nakadiClient.stream(subscription) .withObjectMapper(objectMapper) .listen(SalesOrderPlaced.class, listener); }
@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 LoggingManagedHttpClientConnection( id, log, headerlog, wirelog, cconfig.getBufferSize(), cconfig.getFragmentSizeHint(), chardecoder, charencoder, cconfig.getMessageConstraints(), incomingContentStrategy, outgoingContentStrategy, requestWriterFactory, responseParserFactory); }
/** * @since 4.4 */ public BasicHttpClientConnectionManager( final HttpClientConnectionOperator httpClientConnectionOperator, final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory) { super(); this.connectionOperator = Args.notNull(httpClientConnectionOperator, "Connection operator"); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.expiry = Long.MAX_VALUE; this.socketConfig = SocketConfig.DEFAULT; this.connConfig = ConnectionConfig.DEFAULT; this.isShutdown = new AtomicBoolean(false); }
@Test public void testLeaseReleaseReusable() throws Exception { final HttpHost target = new HttpHost("somehost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(connFactory.create(Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE); mgr.releaseConnection(conn1, null, 10000, TimeUnit.MILLISECONDS); Assert.assertEquals(route, mgr.getRoute()); Assert.assertEquals(null, mgr.getState()); final ConnectionRequest connRequest2 = mgr.requestConnection(route, null); final HttpClientConnection conn2 = connRequest2.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn2); Assert.assertTrue(conn2.isOpen()); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); }
@Test public void testLeaseReleaseReusableWithState() throws Exception { final HttpHost target = new HttpHost("somehost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(connFactory.create( Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route, "some state"); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE); mgr.releaseConnection(conn1, "some other state", 10000, TimeUnit.MILLISECONDS); Assert.assertEquals(route, mgr.getRoute()); Assert.assertEquals("some other state", mgr.getState()); final ConnectionRequest connRequest2 = mgr.requestConnection(route, "some other state"); final HttpClientConnection conn2 = connRequest2.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn2); Assert.assertTrue(conn2.isOpen()); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); }
@Test public void testLeaseDifferentRoute() throws Exception { final HttpHost target1 = new HttpHost("somehost", 80); final HttpRoute route1 = new HttpRoute(target1); Mockito.when(connFactory.create( Mockito.<HttpRoute>any(), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route1, null); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route1), Mockito.<ConnectionConfig>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE, Boolean.FALSE); mgr.releaseConnection(conn1, null, 0, TimeUnit.MILLISECONDS); Assert.assertEquals(route1, mgr.getRoute()); Assert.assertEquals(null, mgr.getState()); final HttpHost target2 = new HttpHost("otherhost", 80); final HttpRoute route2 = new HttpRoute(target2); final ConnectionRequest connRequest2 = mgr.requestConnection(route2, null); final HttpClientConnection conn2 = connRequest2.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn2); Assert.assertFalse(conn2.isOpen()); Mockito.verify(conn).close(); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route1), Mockito.<ConnectionConfig>any()); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route2), Mockito.<ConnectionConfig>any()); }
@Test public void testLeaseExpired() throws Exception { final HttpHost target = new HttpHost("somehost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(connFactory.create( Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE, Boolean.FALSE); mgr.releaseConnection(conn1, null, 10, TimeUnit.MILLISECONDS); Assert.assertEquals(route, mgr.getRoute()); Assert.assertEquals(null, mgr.getState()); Thread.sleep(50); final ConnectionRequest connRequest2 = mgr.requestConnection(route, null); final HttpClientConnection conn2 = connRequest2.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn2); Assert.assertFalse(conn2.isOpen()); Mockito.verify(conn).close(); Mockito.verify(connFactory, Mockito.times(2)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); }
@Test public void testShutdown() throws Exception { final HttpHost target = new HttpHost("somehost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(connFactory.create( Mockito.eq(route), Mockito.<ConnectionConfig>any())).thenReturn(conn); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); final HttpClientConnection conn1 = connRequest1.get(0, TimeUnit.MILLISECONDS); Assert.assertNotNull(conn1); Mockito.verify(connFactory, Mockito.times(1)).create( Mockito.eq(route), Mockito.<ConnectionConfig>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE); mgr.releaseConnection(conn1, null, 0, TimeUnit.MILLISECONDS); mgr.shutdown(); Mockito.verify(conn, Mockito.times(1)).shutdown(); try { final ConnectionRequest connRequest2 = mgr.requestConnection(route, null); connRequest2.get(0, TimeUnit.MILLISECONDS); Assert.fail("IllegalStateException expected"); } catch (final IllegalStateException ex) { } // Should have no effect mgr.closeExpiredConnections(); mgr.closeIdleConnections(0L, TimeUnit.MILLISECONDS); mgr.shutdown(); Mockito.verify(conn, Mockito.times(1)).shutdown(); }
private static CloseableHttpClient client() { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(100); cm.setMaxTotal(400); MessageConstraints messageConstraints = MessageConstraints.custom() .setMaxHeaderCount(200) .setMaxLineLength(2000) .build(); ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints) .build(); RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); cm.setDefaultConnectionConfig(connectionConfig); return HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(defaultRequestConfig) .build(); }
@Test public void testPrepareUserAgentHeaderSetOnBuilder() { // Setup String expectedUserAgentHeader = "Nexus/Agent my user agent"; HttpClientPlan plan = mock(HttpClientPlan.class); doReturn(expectedUserAgentHeader).when(plan).getUserAgent(); HttpClientBuilder builder = mock(HttpClientBuilder.class); doReturn(builder).when(plan).getClient(); ConnectionConfig.Builder conn = mock(ConnectionConfig.Builder.class); SocketConfig.Builder sock = mock(SocketConfig.Builder.class); RequestConfig.Builder req = mock(RequestConfig.Builder.class); doReturn(null).when(conn).build(); doReturn(null).when(sock).build(); doReturn(null).when(req).build(); doReturn(conn).when(plan).getConnection(); doReturn(sock).when(plan).getSocket(); doReturn(req).when(plan).getRequest(); HttpClientManagerImpl spy = spy(underTest); doReturn(plan).when(spy).httpClientPlan(); // Execute HttpClientBuilder returned = spy.prepare(null); // Verify assertNotNull("Returned builder must not be null.", returned); assertEquals("Returned builder must be expected builder.", builder, returned); verify(spy).setUserAgent(builder, expectedUserAgentHeader); }
public HttpClientPlan() { this.client = HttpClientBuilder.create(); this.connection = ConnectionConfig.copy(ConnectionConfig.DEFAULT); this.socket = SocketConfig.copy(SocketConfig.DEFAULT); this.request = RequestConfig.copy(RequestConfig.DEFAULT); this.headers = new HashMap<>(); this.attributes = new HashMap<>(); }