List of usage examples for org.apache.http.impl.conn ProxySelectorRoutePlanner ProxySelectorRoutePlanner
public ProxySelectorRoutePlanner(final SchemeRegistry schreg, final ProxySelector prosel)
From source file:wirschauenplugin.OmdbConnection.java
/** * Creates a new OmdbConnection with the Proxy Settings from the System Properties. *///w w w . j av a2 s .c o m public OmdbConnection() { super(); mHttpClient = new DefaultHttpClient(); //the proxy settings for the tvbrowser are saved in the system properties. see tvbrowser.TVBrowser.updateProxySettings(). //the ProxySelectorRoutePlanner will take these into account. ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( mHttpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); mHttpClient.setRoutePlanner(routePlanner); }
From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java
private HttpClient getHttpClient() { DefaultHttpClient httpclient = new DefaultHttpClient(); if (useJreProxy) { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpclient.setRoutePlanner(routePlanner); }//from w ww . jav a 2 s . c om return httpclient; }
From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java
public HttpClientWrapperImpl() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion(); final HttpParams ps = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(ps); final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000); HttpConnectionParams.setConnectionTimeout(ps, timeout); HttpConnectionParams.setSoTimeout(ps, timeout); HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion); final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault(); final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate"); }// w w w. ja v a2 s . c o m }) { @Override public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { if (socket instanceof SSLSocket) { try { PropertyUtils.setProperty(socket, "host", host.getHostName()); } catch (Exception ex) { LOG.warn(String.format( "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s", ex.toString())); } } return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); } }; schemaRegistry.register(new Scheme("https", 443, sslSocketFactory)); final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry), ps); setupProxy(httpclient); httpclient.setRoutePlanner(new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); httpclient.addRequestInterceptor(new RequestAcceptEncoding()); httpclient.addResponseInterceptor(new ResponseContentEncoding()); httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); myClient = httpclient; }
From source file:com.villemos.ispace.webster.WebsterProducer.java
public void process(Exchange exchange) throws Exception { /** Always ignore authentication protocol errors. */ if (ignoreAuthenticationFailure) { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom()); SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", sf, 443); schemeRegistry.register(httpsScheme); SocketFactory sfa = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", sfa, 80); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else {// w w w. ja v a 2s . c om client = new DefaultHttpClient(); } String proxyHost = getWebsterEndpoint().getProxyHost(); Integer proxyPort = getWebsterEndpoint().getProxyPort(); if (proxyHost != null && proxyPort != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } /** The target location may demand authentication. We setup preemptive authentication. */ if (getWebsterEndpoint().getAuthenticationUser() != null && getWebsterEndpoint().getAuthenticationPassword() != null) { client.getCredentialsProvider().setCredentials( new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()), new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(), getWebsterEndpoint().getAuthenticationPassword())); } /** Set default cookie policy and store. Can be overridden for a specific method using for example; * method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); */ client.setCookieStore(cookieStore); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/" + getWebsterEndpoint().getPath(); if (getWebsterEndpoint().getPort() != 80) { uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath(); } /** Break the query into its elements and search for each. */ for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) { uriStr += "/" + word; URI uri = new URI(uriStr); if (getWebsterEndpoint().getPort() != 80) { target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(), getWebsterEndpoint().getProtocol()); } else { target = new HttpHost(getWebsterEndpoint().getDomain()); } localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpUriRequest method = new HttpGet(uri); HttpResponse response = client.execute(target, method, localContext); if (response.getStatusLine().getStatusCode() == 200) { /** Extract result. */ String page = HttpClientConfigurer.readFully(response.getEntity().getContent()); ResultSet set = new ResultSet(); Matcher matcher = pattern.matcher(page); if (matcher.find()) { String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " "); /** Create ResultSet*/ InformationObject io = new InformationObject(); io.hasUri = uriStr; io.fromSource = "Webster"; io.hasTitle = "Webster definition of '" + word + "'."; io.ofEntityType = "Definition"; io.ofMimeType = "text/html"; io.withRawText = result; io.score = 20; set.informationobjects.add(io); } matcher = spellPattern.matcher(page); if (matcher.find()) { String result = matcher.group(1); String[] elements = result.split("<li><a href=.*?>"); for (String element : elements) { if (element.trim().equals("") == false) { set.suggestions .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster")); } } } if (exchange.getIn().getHeader(SolrOptions.stream) != null) { for (InformationObject io : set.informationobjects) { Exchange newExchange = new DefaultExchange(endpoint.getCamelContext()); newExchange.getIn().setBody(io); endpoint.getCamelContext().createProducerTemplate() .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange); } for (Suggestion suggestion : set.suggestions) { Exchange newExchange = new DefaultExchange(endpoint.getCamelContext()); newExchange.getIn().setBody(suggestion); endpoint.getCamelContext().createProducerTemplate() .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange); } } else { exchange.getOut().setBody(set); } } else { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); String page = HttpClientConfigurer.readFully(response.getEntity().getContent()); System.out.println(page); } } }
From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java
public int poll() throws Exception { /** Always ignore authentication protocol errors. */ if (ignoreAuthenticationFailure) { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom()); SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", sf, 443); schemeRegistry.register(httpsScheme); SocketFactory sfa = new PlainSocketFactory(); Scheme httpScheme = new Scheme("http", sfa, 80); schemeRegistry.register(httpScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(cm, params); } else {/*ww w . ja v a 2s. c om*/ client = new DefaultHttpClient(); } String proxyHost = getHttpCrawlerEndpoint().getProxyHost(); Integer proxyPort = getHttpCrawlerEndpoint().getProxyPort(); if (proxyHost != null && proxyPort != null) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } /** The target location may demand authentication. We setup preemptive authentication. */ if (getHttpCrawlerEndpoint().getAuthenticationUser() != null && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) { client.getCredentialsProvider().setCredentials( new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()), new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(), getHttpCrawlerEndpoint().getAuthenticationPassword())); } /** Set default cookie policy and store. Can be overridden for a specific method using for example; * method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); */ client.setCookieStore(cookieStore); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); String uriStr = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain(); if (getHttpCrawlerEndpoint().getPort() != 80) { uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath(); } else { uriStr += getHttpCrawlerEndpoint().getPath(); } URI uri = new URI(uriStr); if (getHttpCrawlerEndpoint().getPort() != 80) { target = new HttpHost(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort(), getHttpCrawlerEndpoint().getProtocol()); } else { target = new HttpHost(getHttpCrawlerEndpoint().getDomain()); } localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); /** Default boundary is the domain. */ getHttpCrawlerEndpoint().getBoundaries() .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain()); HttpUriRequest method = createInitialRequest(uri); HttpResponse response = client.execute(target, method, localContext); if (response.getStatusLine().getStatusCode() == 200) { processSite(uri, response); } else if (response.getStatusLine().getStatusCode() == 302) { HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpGet get = new HttpGet(target.toURI()); // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php"); /** Read the response fully, to clear it. */ HttpEntity entity = response.getEntity(); HttpClientConfigurer.readFully(entity.getContent()); response = client.execute(target, get, localContext); processSite(uri, response); System.out.println("Final target: " + target); } else { HttpEntity entity = response.getEntity(); InputStream instream = entity.getContent(); System.out.println(HttpClientConfigurer.readFully(instream)); } return 0; }
From source file:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java
/** * Method to create the {@link HttpClient} * /*from w w w.j av a 2s .c o m*/ * @return the {@link DefaultHttpClient} */ private DefaultHttpClient createClient() { DefaultHttpClient client = new DefaultHttpClient(); if (server.isSecured()) { log.debug("The Server is secured, create the BasicHttpContext to handle preemptive authentication."); client.getCredentialsProvider().setCredentials(getAuthScope(), new UsernamePasswordCredentials(server.getUsername(), server.getPassword())); localContext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); // Add as the first request intercepter client.addRequestInterceptor(new PreemptiveAuth(), 0); } if (StringUtils.isNotBlank(System.getProperty("http.proxyHost")) || StringUtils.isNotBlank(System.getProperty("https.proxyHost"))) { log.debug("A System HTTP(S) proxy is set, set the ProxySelectorRoutePlanner for the client"); System.setProperty("java.net.useSystemProxies", "true"); // Set the ProxySelectorRoute Planner to automatically select the system proxy host if set. client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); } return client; }
From source file:gov.nih.nci.nbia.StandaloneDMV1.java
private static List<String> connectAndReadFromURL(URL url, String fileName) { List<String> data = null; DefaultHttpClient httpClient = null; TrustStrategy easyStrategy = new TrustStrategy() { @Override//from w ww .j av a 2 s.c o m public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }; try { // SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything // sslContext.init(null, new TrustManager[] { new // EasyX509TrustManager(null)}, null); SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sslsf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 50000); HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000)); httpClient = new DefaultHttpClient(ccm, httpParams); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault())); // // Additions by lrt for tcia - // // attempt to reduce errors going through a Coyote Point // Equalizer load balance switch httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000)); httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384)); httpClient.getParams().setParameter("http.tcp.nodelay", true); httpClient.getParams().setParameter("http.connection.stalecheck", false); // // end lrt additions HttpPost httpPostMethod = new HttpPost(url.toString()); List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); postParams.add(new BasicNameValuePair("serverjnlpfileloc", fileName)); UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams); httpPostMethod.setEntity(query); HttpResponse response = httpClient.execute(httpPostMethod); // int responseCode = response.getStatusLine().getStatusCode(); // System.out.println("Response code for requesting datda file: " + // responseCode); InputStream inputStream = response.getEntity().getContent(); data = IOUtils.readLines(inputStream); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } return data; }
From source file:org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java
@Provides @Singleton/*from www . j a v a 2 s . c o m*/ final HttpClient newDefaultHttpClient(ProxyConfig config, BasicHttpParams params, ClientConnectionManager cm) { DefaultHttpClient client = new DefaultHttpClient(cm, params); if (config.useSystem()) { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); } return client; }
From source file:org.trancecode.xproc.step.HttpRequestStepProcessor.java
private HttpClient prepareHttpClient(final XProcHttpRequest xProcRequest, final BasicHttpContext localContext) { final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry); final DefaultHttpClient httpClient = new DefaultHttpClient(connManager); final ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); if (xProcRequest.getCredentials() != null) { final List<String> authPref = Lists.newArrayList(AuthPolicy.BASIC, AuthPolicy.DIGEST); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref); httpClient.setCredentialsProvider(xProcRequest.getCredentials()); final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicAuth = new BasicScheme(); authCache.put(xProcRequest.getHttpHost(), basicAuth); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }//from w w w . j a v a 2 s .c o m return httpClient; }
From source file:com.anaplan.client.transport.ApacheHttpProvider.java
protected ApacheHttpProvider() { super();/*from w w w .ja va 2 s. co m*/ httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE); httpClient.setCredentialsProvider(new ApacheCredentialsProvider()); try { Class<?> engineClass = Class.forName("com.anaplan.client.transport.JCIFSEngine"); final NTLMEngine ntlmEngine = (NTLMEngine) engineClass.newInstance(); httpClient.getAuthSchemes().register("ntlm", new AuthSchemeFactory() { public AuthScheme newInstance(final HttpParams params) { return new NTLMScheme(ntlmEngine); } }); } catch (InstantiationException instantiationException) { // Normal - the jcifs jar file is not present in the lib folder. } catch (Throwable thrown) { // Abnormal thrown.printStackTrace(); } routePlanner = new ProxySelectorRoutePlanner(httpClient.getConnectionManager().getSchemeRegistry(), getProxySelector()) { private boolean suppressed; @Override public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { HttpRoute httpRoute = super.determineRoute(target, request, context); if (getDebugLevel() >= 1 && !suppressed) { System.err.println( httpRoute.toString() + " (" + getProxySelector().getClass().getSimpleName() + ")"); if (getDebugLevel() == 1) suppressed = true; } return httpRoute; } }; httpClient.setRoutePlanner(routePlanner); }