对于org.apache.http.impl.conn.SystemDefaultRoutePlanner的实例源码感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解apache源码分析,并且
对于org.apache.http.impl.conn.SystemDefaultRoutePlanner的实例源码感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解apache源码分析,并且为您提供关于org.apache.camel.impl.DefaultProducerTemplate的实例源码、org.apache.camel.impl.DefaultProducer的实例源码、org.apache.http.conn.routing.HttpRoutePlanner的实例源码、org.apache.http.conn.routing.RouteTracker的实例源码的宝贵知识。
本文目录一览:- org.apache.http.impl.conn.SystemDefaultRoutePlanner的实例源码(apache源码分析)
- org.apache.camel.impl.DefaultProducerTemplate的实例源码
- org.apache.camel.impl.DefaultProducer的实例源码
- org.apache.http.conn.routing.HttpRoutePlanner的实例源码
- org.apache.http.conn.routing.RouteTracker的实例源码
org.apache.http.impl.conn.SystemDefaultRoutePlanner的实例源码(apache源码分析)
private void configureProxy(HttpClientBuilder builder,CredentialsProvider credentialsProvider,HttpSettings httpSettings) { HttpProxySettings.HttpProxy httpProxy = httpSettings.getProxySettings().getProxy(); HttpProxySettings.HttpProxy httpsProxy = httpSettings.getSecureProxySettings().getProxy(); for (HttpProxySettings.HttpProxy proxy : Lists.newArrayList(httpProxy,httpsProxy)) { if (proxy != null) { if (proxy.credentials != null) { useCredentials(credentialsProvider,proxy.host,proxy.port,Collections.singleton(new AllSchemesAuthentication(proxy.credentials))); } } } builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); }
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options,SslConfiguration sslConfiguration) throws GeneralSecurityException,IOException { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner( DefaultSchemePortResolver.INSTANCE,ProxySelector.getDefault())); if (hasSslConfiguration(sslConfiguration)) { SSLContext sslContext = getSSLContext(sslConfiguration); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContext); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setSSLContext(sslContext); } RequestConfig requestConfig = RequestConfig .custom() // .setConnectTimeout( Math.toIntExact(options.getConnectionTimeout().toMillis())) // .setSocketTimeout( Math.toIntExact(options.getReadTimeout().toMillis())) // .setAuthenticationEnabled(true) // .build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); // Support redirects httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); }
public static HttpClientBuilder getDefaultClientBuilder(int connectTimeoutInSeconds) { RequestConfig config = RequestConfig .custom() .setConnectTimeout(connectTimeoutInSeconds * 1000) .setConnectionRequestTimeout(connectTimeoutInSeconds * 1000) .build(); SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); return HttpClients .custom() .setDefaultRequestConfig(config) .setRoutePlanner(routePlanner); }
private CloseableHttpClient configureHttpClient() { final String userAgentString = UI.BUNDLE.getString("useragent"); final ProxySelector proxySelector = ProxySelector.getDefault(); LOGGER.debug("Using proxy selector: {}",proxySelector); final SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(proxySelector); final CloseableHttpClient client = HttpClientBuilder .create() .setUserAgent(userAgentString) .setRoutePlanner(routePlanner) .build(); LOGGER.info("ComeOn! uses \"{}\" as User-Agent",userAgentString); return client; }
@Override public CloseableHttpClient createHttpClient(HttpHost httpHost,boolean acceptAnyCertificate,HttpRequestInterceptor requestInterceptor,HttpResponseInterceptor responseInterceptor) { HttpClientBuilder builder = HttpClientBuilder.create(); //configure proxy from system environment builder.setRoutePlanner(new SystemDefaultRoutePlanner(null)); //accept any certificate if necessary if ("https".equals(httpHost.getSchemeName()) && acceptAnyCertificate) { SSLConnectionSocketFactory icsf = getInsecureSSLSocketFactory(); builder.setSSLSocketFactory(icsf); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https",icsf) .build(); HttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(cm); } //add an interceptor that replaces the invalid Content-Type //'none' by 'identity' builder.addInterceptorFirst(new ContentEncodingNoneInterceptor()); //add interceptors if (requestInterceptor != null) { builder.addInterceptorLast(requestInterceptor); } if (responseInterceptor != null) { builder.addInterceptorLast(responseInterceptor); } CloseableHttpClient client = builder.build(); return client; }
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options,ProxySelector.getDefault())); if (hasSslConfiguration(sslConfiguration)) { SSLContext sslContext = getSSLContext(sslConfiguration); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContext); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setSslcontext(sslContext); } RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(options.getConnectionTimeout()) .setSocketTimeout(options.getReadTimeout()) .setAuthenticationEnabled(true) .build(); httpClientBuilder.setDefaultRequestConfig(requestConfig); // Support redirects httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); // Fix weird problem `ProtocolException: Content-Length header already present` from `org.apache.http.protocol.RequestContent` httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request,HttpContext context) throws HttpException,IOException { if (request instanceof httpentityEnclosingRequest) { request.removeHeaders(HTTP.TRANSFER_ENCODING); request.removeHeaders(HTTP.CONTENT_LEN); } } }); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); }
@Override public SystemDefaultRoutePlanner proxy() { // implement? return null; }
@Override public SystemDefaultRoutePlanner proxy() { return null; }
/** * Returns a HTTP client doing Basic Auth if needed. * @param url The URL to browse. * @param user The user. Maybe null. * @param password The password. Maybe null. * @return The HTTP client. */ public static CloseableHttpClient getClient( URL url,String user,String password ) { int timeout = DEFAULT_TIMEOUT; ApplicationSettings set = Config .getInstance() .getApplicationSettings(); String ts = set.getApplicationSetting("requestTimeout_s"); if (ts != null) { try { timeout = S_TO_MS * Integer.parseInt(ts); } catch (NumberFormatException nfe) { log.log(Level.SEVERE,nfe.getMessage()); } } // Use JVM proxy settings. SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); RequestConfig requestConfig = RequestConfig. custom(). setSocketTimeout(timeout).build(); HttpClientBuilder builder = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig); builder.setRetryHandler(new StandardHttpRequestRetryHandler(1,true)); builder.setRoutePlanner(routePlanner); builder.setUserAgent(getUserAgent()); if (user != null && password != null) { UsernamePasswordCredentials defaultCreds = new UsernamePasswordCredentials(user,password); BasicCredentialsProvider credsProv = new BasicCredentialsProvider(); credsProv.setCredentials( new AuthScope(url.getHost(),url.getPort()),defaultCreds); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProv); BasicAuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost target = new HttpHost(url.getHost(),url.getPort()); authCache.put(target,basicAuth); context.setAuthCache(authCache); builder.setDefaultCredentialsProvider(credsProv); } return builder.build(); }
protected HttpRoutePlanner getRoutePlanner() { return new SystemDefaultRoutePlanner(ProxySelector.getDefault()); }
private static HttpRoutePlanner createProxyRoutePlanner() { // use the standard JRE ProxySelector to get proxy information Message.verbose("Using JRE standard ProxySelector for configuring HTTP proxy"); return new SystemDefaultRoutePlanner(ProxySelector.getDefault()); }
/** * Build an HttpClient * * @param customiser * * @return */ public CloseableHttpClient createHttpClient(final Consumer<HttpClientBuilder> customiser) { final HttpClientBuilder builder = HttpClientBuilder.create(); // By default set long call timeouts { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout((int) connectionTimeout.getMilliseconds()) .setSocketTimeout((int) socketTimeout.getMilliseconds()); builder.setDefaultRequestConfig(requestBuilder.build()); } // Set the default keepalive setting if (noKeepalive) builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); // By default share the common connection provider builder.setConnectionManager(connectionManager); // By default use the JRE default route planner for proxies builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); // If a correlation id is set locally then make sure we pass it along to the remote service // N.B. we use the value from the MDC because the correlation id Could be for a internal task builder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request,final HttpContext context) throws HttpException,IOException { final String traceId = MDC.get(LoggingMDCConstants.TRACE_ID); if (traceId != null) request.addHeader("X-Correlation-ID",traceId); } }); // Allow customisation if (customiser != null) customiser.accept(builder); return builder.build(); }
org.apache.camel.impl.DefaultProducerTemplate的实例源码
public ConsulleaderElector build() throws Exception { Objects.requireNonNull(camelContext,"No CamelContext provided!"); final ProducerTemplate producerTemplate = DefaultProducerTemplate.newInstance(camelContext,ConsulleaderElector.CONTROLBUS_ROUTE); final ConsulleaderElector consulleaderElector = new ConsulleaderElector( new ConsulFacadeBean( consulUrl,Optional.ofNullable(username),Optional.ofNullable(password),ttlInSeconds,lockDelayInSeconds,allowIslandMode,createSessionTries,retryPeriod,backOffMultiplier),serviceName,routeId,camelContext,producerTemplate,allowIslandMode); logger.debug("pollInitialDelay={} pollInterval={}",pollInitialDelay,pollInterval); executor.scheduleAtFixedrate(consulleaderElector,pollInterval,TimeUnit.SECONDS); camelContext.addLifecycleStrategy(consulleaderElector); producerTemplate.start(); return consulleaderElector; }
/** * Send a message to the landing zone queue for the given file. * * @param filePathname * the file to be ingested * * @return true if the message was successfully sent to the landing zone queue * * @throws IOException */ private void sendMessagetoLzQueue(String filePathname) { // Create a new process to invoke the ruby script to send the message. try { /* * The logic to send this message is also present in following ruby script. Any changes * here should also be made to the script. * slI/Opstools/ingestion_trigger/publish_file_uploaded.rb */ ProducerTemplate template = new DefaultProducerTemplate(camelContext); template.start(); template.sendBodyAndHeader(landingzoneQueueUri,"Sample lzfile message","filePath",filePathname); template.stop(); } catch (Exception e) { LOG.error("Error publishing sample file " + filePathname + " for ingestion",e); } }
@Test public void testRouteBoxDirectProducerOnlyRequests() throws Exception { template = new DefaultProducerTemplate(context); template.start(); context.addRoutes(new RouteBuilder() { public void configure() { from("direct:start") .to(routeBoxUri) .to("log:Routes operation performed?showAll=true"); } }); context.start(); LOG.debug("Beginning Test ---> testRouteBoxDirectSyncRequests()"); Book book = new Book("Sir Arthur Conan Doyle","The Adventures of Sherlock Holmes"); String response = sendAddToCatalogRequest(template,"direct:start","addToCatalog",book); assertEquals("Book with Author " + book.getAuthor() + " and title " + book.getTitle() + " added to Catalog",response); //Thread.sleep(2000); book = sendFindBookRequest(template,"findBook","Sir Arthur Conan Doyle"); LOG.debug("Received book with author {} and title {}",book.getAuthor(),book.getTitle()); assertEquals("The Adventures of Sherlock Holmes",book.getTitle()); LOG.debug("Completed Test ---> testRouteBoxDirectSyncRequests()"); context.stop(); }
@Test public void testRouteBoxUsingdispatchMap() throws Exception { template = new DefaultProducerTemplate(context); template.start(); context.addRoutes(new RouteBuilder() { public void configure() { from(routeBoxUri) .to("log:Routes operation performed?showAll=true"); } }); context.start(); LOG.debug("Beginning Test ---> testRouteBoxUsingdispatchMap()"); Book book = new Book("Sir Arthur Conan Doyle",routeBoxUri,response); book = sendFindBookRequest(template,book.getTitle()); assertEquals("The Adventures of Sherlock Holmes",book.getTitle()); LOG.debug("Completed Test ---> testRouteBoxUsingdispatchMap()"); context.stop(); }
@Test public void testRouteBoxUsingDefaultContextAndRouteBuilder() throws Exception { template = new DefaultProducerTemplate(context); template.start(); context.addRoutes(new RouteBuilder() { public void configure() { from(routeBoxUri) .to("log:Routes operation performed?showAll=true"); } }); context.start(); LOG.debug("Beginning Test ---> testRouteBoxUsingDefaultContextAndRouteBuilder()"); Book book = new Book("Sir Arthur Conan Doyle",book.getTitle()); LOG.debug("Completed Test ---> testRouteBoxUsingDefaultContextAndRouteBuilder()"); context.stop(); }
@Test public void testRouteBoxDirectAsyncRequests() throws Exception { template = new DefaultProducerTemplate(context); template.start(); context.addRoutes(new RouteBuilder() { public void configure() { from(routeBoxUri) .to("log:Routes operation performed?showAll=true"); } }); context.start(); LOG.debug("Beginning Test ---> testRouteBoxDirectAsyncRequests()"); Book book = new Book("Sir Arthur Conan Doyle",response); // Wait for 2 seconds before a follow-on request if the requests are sent in async mode // to allow the earlier request to take effect //Thread.sleep(2000); book = sendFindBookRequest(template,book.getTitle()); LOG.debug("Completed Test ---> testRouteBoxDirectAsyncRequests()"); context.stop(); }
@Test public void testRouteBoxSedaAsyncRequests() throws Exception { template = new DefaultProducerTemplate(context); template.start(); context.addRoutes(new RouteBuilder() { public void configure() { from(routeBoxUri) .to("log:Routes operation performed?showAll=true"); } }); context.start(); LOG.debug("Beginning Test ---> testRouteBoxSedaAsyncRequests()"); Book book = new Book("Sir Arthur Conan Doyle",book.getTitle()); LOG.debug("Completed Test ---> testRouteBoxSedaAsyncRequests()"); context.stop(); }
public void testCamelTemplates() throws Exception { DefaultProducerTemplate producer1 = getMandatoryBean(DefaultProducerTemplate.class,"producer1"); assertEquals("Inject a wrong camel context",producer1.getCamelContext().getName(),"camel1"); DefaultProducerTemplate producer2 = getMandatoryBean(DefaultProducerTemplate.class,"producer2"); assertEquals("Inject a wrong camel context",producer2.getCamelContext().getName(),"camel2"); DefaultConsumerTemplate consumer = getMandatoryBean(DefaultConsumerTemplate.class,"consumer"); assertEquals("Inject a wrong camel context",consumer.getCamelContext().getName(),"camel2"); }
public SignalkProcessor(){ nmeaProducer= new DefaultProducerTemplate(CamelContextFactory.getInstance()); nmeaProducer.setDefaultEndpointUri(RouteManager.SEDA_NMEA ); outProducer= new DefaultProducerTemplate(CamelContextFactory.getInstance()); outProducer.setDefaultEndpointUri(RouteManager.SEDA_COMMON_OUT ); inProducer= new DefaultProducerTemplate(CamelContextFactory.getInstance()); inProducer.setDefaultEndpointUri(RouteManager.SEDA_INPUT ); try { nmeaProducer.start(); outProducer.start(); inProducer.start(); } catch (Exception e) { logger.error(e.getMessage(),e); } }
public HeartbeatProcessor(){ producer= new DefaultProducerTemplate(CamelContextFactory.getInstance()); producer.setDefaultEndpointUri(RouteManager.SEDA_COMMON_OUT ); try { producer.start(); } catch (Exception e) { logger.error(e.getMessage(),e); } }
private void testScenario(String subKey,String policy,int expectedCount,NavigableSet<String> keys) throws Exception { CamelContext ctx = CamelContextFactory.getInstance(); MockEndpoint resultEndpoint = (MockEndpoint) ctx.getEndpoint("mock:resultEnd"); String session = UUID.randomUUID().toString(); Subscription sub = new Subscription(session,subKey,10,1000,FORMAT_DELTA,policy); sub.setRouteId("test"); subscriptionManager.add("ses" + session,session,ConfigConstants.OUTPUT_WS,"127.0.0.1","127.0.0.1"); subscriptionManager.addSubscription(sub); try { FullExportProcessor processor = new FullExportProcessor(session,"test"); ProducerTemplate exportProducer = new DefaultProducerTemplate(ctx); exportProducer.setDefaultEndpointUri("mock:resultEnd"); exportProducer.start(); processor.outProducer = exportProducer; resultEndpoint.expectedMessageCount(expectedCount); for (String key : keys) { processor.recordEvent(new PathEvent(key,nz.co.fortytwo.signalk.model.event.PathEvent.EventType.ADD)); logger.debug("Posted path event:" + key); } // Sleep to allow for minPeriod. if (POLICY_IDEAL.equals(policy)) { Thread.sleep(100L); } resultEndpoint.assertIsSatisfied(); } finally { subscriptionManager.removeSubscription(sub); subscriptionManager.removeWsSession(session); resultEndpoint.reset(); } }
public void init() throws Exception { template = new DefaultProducerTemplate(routeManager.getContext()); template.setDefaultEndpointUri(DIRECT_INPUT); template.start(); //get model SignalKModel model = SignalKModelFactory.getMotuTestInstance(); model.putAll(TestHelper.getBasicModel().getFullData()); JsonSerializer ser = new JsonSerializer(); jsonString=ser.write(model); }
public void init() throws Exception{ template= new DefaultProducerTemplate(routeManager.getContext()); template.setDefaultEndpointUri(DIRECT_INPUT); template.start(); SignalKModel model = SignalKModelFactory.getCleanInstance(); SignalKModelFactory.loadConfig(signalkModel); logger.debug("SignalKModel at init:"+signalkModel); model.putAll(TestHelper.getBasicModel().getFullData()); JsonSerializer ser = new JsonSerializer(); jsonString=ser.write(model); }
public void init() throws Exception{ declinationProcessor=new DeclinationHandler(); windProcessor = new TrueWindHandler(); template= new DefaultProducerTemplate(routeManager.getContext()); template.setDefaultEndpointUri(DIRECT_INPUT); template.start(); }
/** * broadcast a message to all orchestra nodes to flush their execution stats * * @param exchange * @param workNote */ private void broadcastFlushStats(Exchange exchange,WorkNote workNote) { try { ProducerTemplate template = new DefaultProducerTemplate(exchange.getContext()); template.start(); template.sendBody(this.commandTopicUri,"jobCompleted|" + workNote.getBatchJobId()); template.stop(); } catch (Exception e) { LOG.error("Error sending `that's all folks` message to the orchestra",e); } }
public Class<DefaultProducerTemplate> getobjectType() { return DefaultProducerTemplate.class; }
@Test public void testHastemplateCamel1() { DefaultProducerTemplate lookup = context1.getRegistry().lookupByNameAndType("template1",DefaultProducerTemplate.class); assertNotNull("Should lookup producer template",lookup); assertEquals("camel1",lookup.getCamelContext().getName()); }
@Test public void testHastemplateCamel2() { DefaultProducerTemplate lookup = context1.getRegistry().lookupByNameAndType("template2",lookup); assertEquals("camel2",lookup.getCamelContext().getName()); }
@Test public void createDomainOnStartIfNotExists() throws Exception { DefaultProducerTemplate.newInstance(context,"aws-sdb://NonExistingDomain?amazonSDBClient=#amazonSDBClient&operation=GetAttributes"); assertEquals("NonExistingDomain",amazonSDBClient.createDomainRequest.getDomainName()); }
@Test public void createDomainOnStartIfNotExists() throws Exception { DefaultProducerTemplate.newInstance(context,amazonSDBClient.createDomainRequest.getDomainName()); }
@Test public void whenTableIsMissingThenCreateItOnStart() throws Exception { DefaultProducerTemplate.newInstance(context,"aws-ddb://creatibleTable?amazonDDBClient=#amazonDDBClient"); assertEquals("creatibleTable",amazonDDBClient.createTableRequest.getTableName()); }
public CamelUdpnettyHandler( String outputType) throws Exception { this.outputType=outputType; producer= new DefaultProducerTemplate(CamelContextFactory.getInstance()); producer.setDefaultEndpointUri(RouteManager.SEDA_INPUT ); producer.start(); }
public void init() throws Exception{ template= new DefaultProducerTemplate(routeManager.getContext()); template.setDefaultEndpointUri(DIRECT_INPUT); template.start(); }
void send() { Endpoint endPoint = context.getEndpoint("direct:event-in"); ProducerTemplate template = new DefaultProducerTemplate(context,endPoint); template.sendBody(rawEvent); }
org.apache.camel.impl.DefaultProducer的实例源码
@Override public Producer createProducer() throws Exception { return new DefaultProducer(this) { @Override public void process(final Exchange exchange) throws Exception { executor.execute(new Runnable() { @Override public void run() { try { TradeExecutor.execute(exchange.getIn().getMandatoryBody(Message.class)); } catch (Exception e) { log.error("Error during Trade execution",e); } } }); } }; }
public Producer createProducer() throws Exception { return new DefaultProducer(this) { public void process(Exchange exchange) throws Exception { onExchange(exchange); } }; }
@Override public Producer createProducer() throws Exception { return new DefaultProducer(this) { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader("username",getUsername()); exchange.getIn().setHeader("password",getpassword()); exchange.getIn().setHeader("lines",getLines()); } }; }
@Override public Producer createProducer() throws Exception { return new DefaultProducer(this) { @Override public void process(Exchange exchange) throws Exception { throw new IllegalArgumentException("Forced"); } }; }
public Producer createProducer() throws Exception { ObjectHelper.notNull(applicationContext,"applicationContext"); return new DefaultProducer(this) { public void process(Exchange exchange) throws Exception { ApplicationEvent event = toApplicationEvent(exchange); applicationContext.publishEvent(event); } }; }
@Override protected Endpoint createEndpoint(final String uri,final String remaining,final Map<String,Object> parameters) throws Exception { final String value = String.class.cast(parameters.remove("value")); return new DefaultEndpoint() { @Override protected String createEndpointUri() { return uri; } @Override public Producer createProducer() throws Exception { return new DefaultProducer(this) { @Override public void process(final Exchange exchange) throws Exception { exchange.getIn().setBody(exchange.getIn().getBody(String.class) + value); } }; } @Override public Consumer createConsumer(final Processor processor) throws Exception { throw new UnsupportedOperationException(); } @Override public boolean isSingleton() { return true; } }; }
org.apache.http.conn.routing.HttpRoutePlanner的实例源码
@Deprecated public DefaultRequestDirector( final HttpRequestExecutor requestExec,final ClientConnectionManager conman,final ConnectionReuseStrategy reustrat,final ConnectionKeepAliveStrategy kastrat,final HttpRoutePlanner rouplan,final HttpProcessor httpProcessor,final HttpRequestRetryHandler retryHandler,final RedirectHandler redirectHandler,final AuthenticationHandler targetAuthHandler,final AuthenticationHandler proxyAuthHandler,final UserTokenHandler userTokenHandler,final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class),requestExec,conman,reustrat,kastrat,rouplan,httpProcessor,retryHandler,new DefaultRedirectStrategyAdaptor(redirectHandler),new AuthenticationStrategyAdaptor(targetAuthHandler),new AuthenticationStrategyAdaptor(proxyAuthHandler),userTokenHandler,params); }
@Deprecated public DefaultRequestDirector( final Log log,final HttpRequestExecutor requestExec,final RedirectStrategy redirectStrategy,redirectStrategy,params); }
public InternalHttpClient( final ClientExecChain execChain,final HttpClientConnectionManager connManager,final HttpRoutePlanner routePlanner,final Lookup<CookieSpecProvider> cookieSpecRegistry,final Lookup<AuthSchemeProvider> authSchemeRegistry,final CookieStore cookieStore,final CredentialsProvider credentialsProvider,final RequestConfig defaultConfig,final List<Closeable> closeables) { super(); Args.notNull(execChain,"HTTP client exec chain"); Args.notNull(connManager,"HTTP connection manager"); Args.notNull(routePlanner,"HTTP route planner"); this.execChain = execChain; this.connManager = connManager; this.routePlanner = routePlanner; this.cookieSpecRegistry = cookieSpecRegistry; this.authSchemeRegistry = authSchemeRegistry; this.cookieStore = cookieStore; this.credentialsProvider = credentialsProvider; this.defaultConfig = defaultConfig; this.closeables = closeables; }
@Deprecated public DefaultRequestDirector( final HttpRequestExecutor requestExec,params); }
@Deprecated public DefaultRequestDirector( final Log log,params); }
public InternalHttpClient( final ClientExecChain execChain,"HTTP route planner"); this.execChain = execChain; this.connManager = connManager; this.routePlanner = routePlanner; this.cookieSpecRegistry = cookieSpecRegistry; this.authSchemeRegistry = authSchemeRegistry; this.cookieStore = cookieStore; this.credentialsProvider = credentialsProvider; this.defaultConfig = defaultConfig; this.closeables = closeables; }
@SuppressWarnings("unchecked") @Before public void setup() throws Exception { execChain = Mockito.mock(ClientExecChain.class); connManager = Mockito.mock(HttpClientConnectionManager.class); routePlanner = Mockito.mock(HttpRoutePlanner.class); cookieSpecRegistry = Mockito.mock(Lookup.class); authSchemeRegistry = Mockito.mock(Lookup.class); cookieStore = Mockito.mock(CookieStore.class); credentialsProvider = Mockito.mock(CredentialsProvider.class); defaultConfig = RequestConfig.custom().build(); closeable1 = Mockito.mock(Closeable.class); closeable2 = Mockito.mock(Closeable.class); client = new InternalHttpClient(execChain,connManager,routePlanner,cookieSpecRegistry,authSchemeRegistry,cookieStore,credentialsProvider,defaultConfig,Arrays.asList(closeable1,closeable2)); }
public InternalHttpClient( final ClientExecChain execChain,"HTTP route planner"); this.execChain = execChain; this.connManager = connManager; this.routePlanner = routePlanner; this.cookieSpecRegistry = cookieSpecRegistry; this.authSchemeRegistry = authSchemeRegistry; this.cookieStore = cookieStore; this.credentialsProvider = credentialsProvider; this.defaultConfig = defaultConfig; this.closeables = closeables; }
/** This method mainly exists to make the wrapper more testable. oh,apache's insanity. */ protected RequestDirector getRequestDirector(HttpRequestExecutor requestExec,ClientConnectionManager conman,ConnectionReuseStrategy reustrat,ConnectionKeepAliveStrategy kastrat,HttpRoutePlanner rouplan,HttpProcessor httpProcessor,HttpRequestRetryHandler retryHandler,RedirectHandler redirectHandler,AuthenticationHandler targetAuthHandler,AuthenticationHandler proxyAuthHandler,UserTokenHandler stateHandler,HttpParams params ) { return new DefaultRequestDirector(requestExec,redirectHandler,targetAuthHandler,proxyAuthHandler,stateHandler,params); }
/** This method mainly exists to make the wrapper more testable. oh,params); }
public InternalHttpClient( final ClientExecChain execChain,"HTTP route planner"); this.execChain = execChain; this.connManager = connManager; this.routePlanner = routePlanner; this.cookieSpecRegistry = cookieSpecRegistry; this.authSchemeRegistry = authSchemeRegistry; this.cookieStore = cookieStore; this.credentialsProvider = credentialsProvider; this.defaultConfig = defaultConfig; this.closeables = closeables; }
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration,boolean trustSelfSignedCerts) { HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); if (trustSelfSignedCerts) { httpClientBuilder.setSslcontext(buildSslContext()); httpClientBuilder.setHostnameVerifier(broWSER_COMPATIBLE_HOSTNAME_VERIFIER); } if (httpProxyConfiguration != null) { HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(),httpProxyConfiguration.getProxyPort()); httpClientBuilder.setProxy(proxy); if (httpProxyConfiguration.isAuthrequired()) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(httpProxyConfiguration.getProxyHost(),httpProxyConfiguration.getProxyPort()),new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),httpProxyConfiguration .getpassword())); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner); } HttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return requestFactory; }
/** * @deprecated (4.1) do not use */ @Deprecated protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,final HttpParams params) { return new DefaultRequestDirector( requestExec,params); }
/** * @deprecated (4.2) do not use */ @Deprecated protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,final HttpParams params) { return new DefaultRequestDirector( log,params); }
/** * @since 4.2 */ protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,final AuthenticationStrategy targetAuthStrategy,final AuthenticationStrategy proxyAuthStrategy,targetAuthStrategy,proxyAuthStrategy,params); }
private void decorateRoutePlanner(CrawlerHttpClient crawlerHttpClient) { HttpRoutePlanner routePlanner = crawlerHttpClient.getRoutePlanner(); if (!(routePlanner instanceof ProxyBindRoutPlanner)) { log.warn("自定义了代理发生器,vscrawler的代理功能将不会生效"); return; } VSCrawlerRoutePlanner vsCrawlerRoutePlanner = new VSCrawlerRoutePlanner((ProxyBindRoutPlanner) routePlanner,ipPool,proxyPlanner,this); crawlerHttpClient.setRoutePlanner(vsCrawlerRoutePlanner); }
public RedirectExec( final ClientExecChain requestExecutor,final RedirectStrategy redirectStrategy) { super(); Args.notNull(requestExecutor,"HTTP client request executor"); Args.notNull(routePlanner,"HTTP route planner"); Args.notNull(redirectStrategy,"HTTP redirect strategy"); this.requestExecutor = requestExecutor; this.routePlanner = routePlanner; this.redirectStrategy = redirectStrategy; }
@Override public HttpClient getobject() throws Exception { HttpClientBuilder clientBuilder = HttpClients.custom(); HttpRoutePlanner routePlanner = getRoutePlanner(); if( routePlanner != null ) { clientBuilder.setRoutePlanner(routePlanner); } clientBuilder.disableCookieManagement(); clientBuilder.setMaxConnPerRoute(connectionPoolSize); if (insecureSsl) { SSLContext context = SSLContexts.custom() .loadTrustMaterial(null,new TrustSelfSignedStrategy()) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( context,new String[]{"TLSv1.2"},null,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); clientBuilder.setSSLSocketFactory(sslsf); } return clientBuilder.build(); }
private HttpRoutePlanner getRoutePlanner() { proxyHostname = Strings.nullToEmpty(proxyHostname); if (proxyHostname.isEmpty()) { proxyEnabled = false; } if (proxyEnabled) { HttpHost proxy = new HttpHost(proxyHostname,proxyPort,proxyScheme); HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) { @Override public HttpRoute determineRoute( final HttpHost host,final HttpRequest request,final HttpContext context) throws HttpException { String hostname = host.getHostName(); if (hostname.equals("127.0.0.1") || hostname.equalsIgnoreCase("localhost")) { // Return direct route return new HttpRoute(host); } return super.determineRoute(host,request,context); } }; return routePlanner; } return null; }
/** * @deprecated (4.1) do not use */ @Deprecated protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,params); }
/** * @deprecated (4.2) do not use */ @Deprecated protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,params); }
/** * @since 4.2 */ protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,params); }
public RedirectExec( final ClientExecChain requestExecutor,"HTTP redirect strategy"); this.requestExecutor = requestExecutor; this.routePlanner = routePlanner; this.redirectStrategy = redirectStrategy; }
private androidhttpclient(ClientConnectionManager paramClientConnectionManager,HttpParams paramHttpParams) { this.delegate = new DefaultHttpClient(paramClientConnectionManager,paramHttpParams) { protected final RequestDirector createClientRequestDirector(HttpRequestExecutor paramAnonymousHttpRequestExecutor,ClientConnectionManager paramAnonymousClientConnectionManager,ConnectionReuseStrategy paramAnonymousConnectionReuseStrategy,ConnectionKeepAliveStrategy paramAnonymousConnectionKeepAliveStrategy,HttpRoutePlanner paramAnonymousHttpRoutePlanner,HttpProcessor paramAnonymousHttpProcessor,HttpRequestRetryHandler paramAnonymousHttpRequestRetryHandler,RedirectHandler paramAnonymousRedirectHandler,AuthenticationHandler paramAnonymousAuthenticationHandler1,AuthenticationHandler paramAnonymousAuthenticationHandler2,UserTokenHandler paramAnonymousUserTokenHandler,HttpParams paramAnonymousHttpParams) { return new ElegantRequestDirector(paramAnonymousHttpRequestExecutor,paramAnonymousClientConnectionManager,paramAnonymousConnectionReuseStrategy,paramAnonymousConnectionKeepAliveStrategy,paramAnonymousHttpRoutePlanner,paramAnonymousHttpProcessor,paramAnonymousHttpRequestRetryHandler,paramAnonymousRedirectHandler,paramAnonymousAuthenticationHandler1,paramAnonymousAuthenticationHandler2,paramAnonymousUserTokenHandler,paramAnonymousHttpParams); } protected final HttpContext createHttpContext() { BasicHttpContext localBasicHttpContext = new BasicHttpContext(); localBasicHttpContext.setAttribute("http.authscheme-registry",getAuthSchemes()); localBasicHttpContext.setAttribute("http.cookiespec-registry",getCookieSpecs()); localBasicHttpContext.setAttribute("http.auth.credentials-provider",getCredentialsProvider()); return localBasicHttpContext; } protected final BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor localBasicHttpProcessor = super.createHttpProcessor(); localBasicHttpProcessor.addRequestInterceptor(androidhttpclient.sThreadCheckInterceptor); localBasicHttpProcessor.addRequestInterceptor(new androidhttpclient.CurlLogger(androidhttpclient.this,(byte)0)); return localBasicHttpProcessor; } }; }
public static ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration,boolean trustSelfSignedCerts,boolean disableRedirectHandling) { HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); if (trustSelfSignedCerts) { httpClientBuilder.setSslcontext(buildSslContext()); httpClientBuilder.setHostnameVerifier(broWSER_COMPATIBLE_HOSTNAME_VERIFIER); } if (disableRedirectHandling) { httpClientBuilder.disableRedirectHandling(); } if (httpProxyConfiguration != null) { HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(),httpProxyConfiguration.getpassword())); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner); } HttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return requestFactory; }
public RedirectExec( final ClientExecChain requestExecutor,"HTTP redirect strategy"); this.requestExecutor = requestExecutor; this.routePlanner = routePlanner; this.redirectStrategy = redirectStrategy; }
@Test public void expectedSendGridBeanWithProxyCreated() { loadContext("spring.sendgrid.username:user","spring.sendgrid.password:secret","spring.sendgrid.proxy.host:localhost","spring.sendgrid.proxy.port:5678"); SendGrid sendGrid = this.context.getBean(SendGrid.class); CloseableHttpClient client = (CloseableHttpClient) ReflectionTestUtils .getField(sendGrid,"client"); HttpRoutePlanner routePlanner = (HttpRoutePlanner) ReflectionTestUtils .getField(client,"routePlanner"); assertthat(routePlanner,instanceOf(DefaultProxyRoutePlanner.class)); }
public void __constructor__( HttpRequestExecutor requestExec,UserTokenHandler userTokenHandler,HttpParams params) { __constructor__( LogFactory.getLog(DefaultRequestDirector.class),params); }
public DefaultRequestDirector( final HttpRequestExecutor requestExec,final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class),params); }
protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,final UserTokenHandler stateHandler,params); }
public DefaultRequestDirector( final HttpRequestExecutor requestExec,params); }
public RedirectExec( final ClientExecChain requestExecutor,"HTTP redirect strategy"); this.requestExecutor = requestExecutor; this.routePlanner = routePlanner; this.redirectStrategy = redirectStrategy; }
@Override protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,final HttpParams params) { return new LibRequestDirector( requestExec,params); }
@Override protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec,final HttpParams params) { return new YiBoRequestDirector( requestExec,params); }
@Override protected RequestDirector createClientRequestDirector(HttpRequestExecutor requestExec,RedirectStrategy redirectStrategy,AuthenticationStrategy targetAuthStrategy,AuthenticationStrategy proxyAuthStrategy,HttpParams params) { return new RedirectRequestDirector(log,params); }
public RedirectRequestDirector(Log log,HttpRequestExecutor requestExec,HttpParams params) { super(log,params); }
/** This method mainly exists to make the wrapper more testable. oh,params); }
protected HttpRoutePlanner createHttpRoutePlanner() { return new DefaultHttpRoutePlanner(getConnectionManager().getSchemeRegistry()); }
public synchronized final HttpRoutePlanner getRoutePlanner() { if (this.routePlanner == null) { this.routePlanner = createHttpRoutePlanner(); } return this.routePlanner; }
public synchronized void setRoutePlanner(final HttpRoutePlanner routePlanner) { this.routePlanner = routePlanner; }
org.apache.http.conn.routing.RouteTracker的实例源码
public HttpPoolEntry( final Log log,final String id,final HttpRoute route,final OperatedClientConnection conn,final long timetoLive,final TimeUnit tunit) { super(id,route,conn,timetoLive,tunit); this.log = log; this.tracker = new RouteTracker(route); }
public HttpPoolEntry( final Log log,tunit); this.log = log; this.tracker = new RouteTracker(route); }
/** * Opens the underlying connection. * * @param route the route along which to open the connection * @param context the context for opening the connection * @param params the parameters for opening the connection * * @throws IOException in case of a problem */ public void open(final HttpRoute route,final HttpContext context,final HttpParams params) throws IOException { Args.notNull(route,"Route"); Args.notNull(params,"HTTP parameters"); if (this.tracker != null) { Asserts.check(!this.tracker.isConnected(),"Connection already open"); } // - collect the arguments // - call the operator // - update the tracking data // In this order,we can be sure that only a successful // opening of the connection will be tracked. this.tracker = new RouteTracker(route); final HttpHost proxy = route.getProxyHost(); connoperator.openConnection (this.connection,(proxy != null) ? proxy : route.getTargetHost(),route.getLocalAddress(),context,params); final RouteTracker localTracker = tracker; // capture volatile // If this tracker was reset while connecting,// fail early. if (localTracker == null) { throw new InterruptedioException("Request aborted"); } if (proxy == null) { localTracker.connectTarget(this.connection.isSecure()); } else { localTracker.connectProxy(proxy,this.connection.isSecure()); } }
/** * Obtains a connection. * * @param route where the connection should point to * * @return a connection that can be used to communicate * along the given route */ public ManagedClientConnection getConnection(HttpRoute route,Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } assertStillUp(); if (log.isDebugEnabled()) { log.debug("Get connection for route " + route); } synchronized (this) { if (managedConn != null) throw new IllegalStateException(MISUSE_MESSAGE); // check re-usability of the connection boolean recreate = false; boolean shutdown = false; // Kill the connection if it expired. closeExpiredConnections(); if (uniquePoolEntry.connection.isopen()) { RouteTracker tracker = uniquePoolEntry.tracker; shutdown = (tracker == null || // can happen if method is aborted !tracker.toRoute().equals(route)); } else { // If the connection is not open,create a new PoolEntry,// as the connection may have been marked not reusable,// due to aborts -- and the PoolEntry should not be reused // either. There's no harm in recreating an entry if // the connection is closed. recreate = true; } if (shutdown) { recreate = true; try { uniquePoolEntry.shutdown(); } catch (IOException iox) { log.debug("Problem shutting down connection.",iox); } } if (recreate) uniquePoolEntry = new PoolEntry(); managedConn = new ConnAdapter(uniquePoolEntry,route); return managedConn; } }
RouteTracker getTracker() { return this.tracker; }
/** * Opens the underlying connection. * * @param route the route along which to open the connection * @param context the context for opening the connection * @param params the parameters for opening the connection * * @throws IOException in case of a problem */ public void open(HttpRoute route,HttpContext context,HttpParams params) throws IOException { if (route == null) { throw new IllegalArgumentException ("Route must not be null."); } if (params == null) { throw new IllegalArgumentException ("Parameters must not be null."); } if ((this.tracker != null) && this.tracker.isConnected()) { throw new IllegalStateException("Connection already open."); } // - collect the arguments // - call the operator // - update the tracking data // In this order,params); RouteTracker localTracker = tracker; // capture volatile // If this tracker was reset while connecting,this.connection.isSecure()); } }
/** * Obtains a connection. * * @param route where the connection should point to * * @return a connection that can be used to communicate * along the given route */ public ManagedClientConnection getConnection(final HttpRoute route,final Object state) { Args.notNull(route,"Route"); assertStillUp(); if (log.isDebugEnabled()) { log.debug("Get connection for route " + route); } synchronized (this) { Asserts.check(managedConn == null,MISUSE_MESSAGE); // check re-usability of the connection boolean recreate = false; boolean shutdown = false; // Kill the connection if it expired. closeExpiredConnections(); if (uniquePoolEntry.connection.isopen()) { final RouteTracker tracker = uniquePoolEntry.tracker; shutdown = (tracker == null || // can happen if method is aborted !tracker.toRoute().equals(route)); } else { // If the connection is not open,// due to aborts -- and the PoolEntry should not be reused // either. There's no harm in recreating an entry if // the connection is closed. recreate = true; } if (shutdown) { recreate = true; try { uniquePoolEntry.shutdown(); } catch (final IOException iox) { log.debug("Problem shutting down connection.",iox); } } if (recreate) { uniquePoolEntry = new PoolEntry(); } managedConn = new ConnAdapter(uniquePoolEntry,route); return managedConn; } }
RouteTracker getTracker() { return this.tracker; }
/** * Obtains a connection. * * @param route where the connection should point to * * @return a connection that can be used to communicate * along the given route */ public synchronized ManagedClientConnection getConnection(HttpRoute route,Object state) { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } assertStillUp(); if (log.isDebugEnabled()) { log.debug("Get connection for route " + route); } if (managedConn != null) throw new IllegalStateException(MISUSE_MESSAGE); // check re-usability of the connection boolean recreate = false; boolean shutdown = false; // Kill the connection if it expired. closeExpiredConnections(); if (uniquePoolEntry.connection.isopen()) { RouteTracker tracker = uniquePoolEntry.tracker; shutdown = (tracker == null || // can happen if method is aborted !tracker.toRoute().equals(route)); } else { // If the connection is not open,// due to aborts -- and the PoolEntry should not be reused // either. There's no harm in recreating an entry if // the connection is closed. recreate = true; } if (shutdown) { recreate = true; try { uniquePoolEntry.shutdown(); } catch (IOException iox) { log.debug("Problem shutting down connection.",iox); } } if (recreate) uniquePoolEntry = new PoolEntry(); managedConn = new ConnAdapter(uniquePoolEntry,route); return managedConn; }
/** * Opens the underlying connection. * * @param route the route along which to open the connection * @param context the context for opening the connection * @param params the parameters for opening the connection * * @throws IOException in case of a problem */ public void open(HttpRoute route,params); RouteTracker localTracker = tracker; // capture volatile // If this tracker was reset while connecting,// fail early. if (localTracker == null) { throw new IOException("Request aborted"); } if (proxy == null) { localTracker.connectTarget(this.connection.isSecure()); } else { localTracker.connectProxy(proxy,this.connection.isSecure()); } }
关于org.apache.http.impl.conn.SystemDefaultRoutePlanner的实例源码和apache源码分析的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于org.apache.camel.impl.DefaultProducerTemplate的实例源码、org.apache.camel.impl.DefaultProducer的实例源码、org.apache.http.conn.routing.HttpRoutePlanner的实例源码、org.apache.http.conn.routing.RouteTracker的实例源码等相关知识的信息别忘了在本站进行查找喔。
本文标签: