List of usage examples for java.net ProxySelector getDefault
public static ProxySelector getDefault()
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpClient createClient(int maxConnPerRoute, long connTimeoutMillis, long soTimeoutMillis, @Nullable String proxyHostAnPort) { Registry<ConnectionSocketFactory> defaultRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()).build(); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(defaultRegistry); connMgr.setDefaultMaxPerRoute(maxConnPerRoute); SocketConfig sCfg = SocketConfig.custom().setSoTimeout((int) soTimeoutMillis) .setSoTimeout((int) connTimeoutMillis).build(); connMgr.setDefaultSocketConfig(sCfg); HttpClientBuilder hcb = HttpClientBuilder.create(); hcb.setDefaultSocketConfig(sCfg).setConnectionManager(connMgr); if (proxyHostAnPort == null) { } else if ("jvm".equalsIgnoreCase(proxyHostAnPort)) { SystemDefaultRoutePlanner rp = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); hcb.setRoutePlanner(rp);// ww w.j a va 2 s .c o m } else { String[] hostAndPort = proxyHostAnPort.split(":"); Check.illegalargument.assertTrue(hostAndPort.length < 3, "wrong hostAndPort:" + proxyHostAnPort); String host = hostAndPort[0]; int port = 80; if (hostAndPort.length > 1) { port = Integer.valueOf(hostAndPort[1]); } HttpHost proxy = new HttpHost(host, port); hcb.setProxy(proxy); } HttpClient httpClient = hcb.build(); return httpClient; }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Returns the preconfigured http client, * using CertificateVerificationService, timeouts, user-agent, * hostname verifier, proxy settings are used from global java settings, * if protected site is hit asks for credentials * using util.swing.AuthenticationWindow. * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @param credentialsProvider if not null provider will bre reused * in the new client/*from ww w . j av a 2 s . c o m*/ * @param address the address we will be connecting to */ public static DefaultHttpClient getHttpClient(String usernamePropertyName, String passwordPropertyName, final String address, CredentialsProvider credentialsProvider) throws IOException { HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS); DefaultHttpClient httpClient = new DefaultHttpClient(params); HttpProtocolParams.setUserAgent(httpClient.getParams(), System.getProperty("sip-communicator.application.name") + "/" + System.getProperty("sip-communicator.version")); SSLContext sslCtx; try { sslCtx = HttpUtilActivator.getCertificateVerificationService() .getSSLContext(HttpUtilActivator.getCertificateVerificationService().getTrustManager(address)); } catch (GeneralSecurityException e) { throw new IOException(e.getMessage()); } // note to any reviewer concerned about ALLOW_ALL_HOSTNAME_VERIFIER: // the SSL context obtained from the certificate service takes care of // certificate validation try { Scheme sch = new Scheme("https", 443, new SSLSocketFactoryEx(sslCtx)); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (Throwable t) { logger.error("Error creating ssl socket factory", t); } // set proxy from default jre settings ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); if (credentialsProvider == null) credentialsProvider = new HTTPCredentialsProvider(usernamePropertyName, passwordPropertyName); httpClient.setCredentialsProvider(credentialsProvider); // enable retry connecting with default retry handler // when connecting has prompted for authentication // connection can be disconnected nefore user answers and // we need to retry connection, using the credentials provided httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); return httpClient; }
From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java
static String getProxyInfo() { StringBuffer sb = new StringBuffer("Get proxy info: "); try {//from www. j av a 2s . c o m System.setProperty("java.net.useSystemProxies", "true"); List<Proxy> l = ProxySelector.getDefault().select(new URI("https://www.google.com/")); for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) { Proxy proxy = iter.next(); sb.append("proxy type : " + proxy.type() + "\n"); InetSocketAddress addr = (InetSocketAddress) proxy.address(); if (addr == null) { sb.append("No Proxy\n"); } else { sb.append("proxy hostname : " + addr.getHostName() + "\n"); sb.append("proxy port : " + addr.getPort() + "\n"); } } } catch (Exception e) { e.printStackTrace(); sb.append(e.getMessage()); } return sb.toString(); }
From source file:org.georchestra.security.Proxy.java
private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse, RequestType requestType, String sURL, boolean localProxy) { HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling(); RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build(); htb.setDefaultRequestConfig(config); ///* ww w . j a v a2 s. c o m*/ // Handle http proxy for external request. // Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128) htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); HttpClient httpclient = htb.build(); HttpResponse proxiedResponse = null; int statusCode = 500; try { URL url = null; try { url = new URL(sURL); } catch (MalformedURLException e) { // not an url finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } // HTTP protocol is required if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) { finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "HTTP protocol expected. \"" + url.getProtocol() + "\" used."); return; } // check if proxy must filter on final host if (!strategyForFilteringRequests.allowRequest(url)) { finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "Host \"" + url.getHost() + "\" is not allowed to be requested"); return; } logger.debug("Final request -- " + sURL); HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL); headerManagement.configureRequestHeaders(request, proxyingRequest); try { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Header[] originalHeaders = proxyingRequest.getHeaders("sec-org"); String org = ""; for (Header originalHeader : originalHeaders) { org = originalHeader.getValue(); } // no OGC SERVICE log if request going through /proxy/?url= if (!request.getRequestURI().startsWith("/sec/proxy/")) { String[] roles = new String[] { "" }; try { Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles"); if (rolesHeaders.length > 0) { roles = rolesHeaders[0].getValue().split(";"); } } catch (Exception e) { logger.error("Unable to compute roles"); } statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles)); } } catch (Exception e) { logger.error("Unable to log the request into the statistics logger", e); } if (localProxy) { // // Hack for geoserver // Should not be here. We must use a ProxyTarget class and // define // if Host header should be forwarded or not. // request.getHeader("Host"); proxyingRequest.setHeader("Host", request.getHeader("Host")); if (logger.isDebugEnabled()) { logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue() + " for proxy request."); } } proxiedResponse = executeHttpRequest(httpclient, proxyingRequest); StatusLine statusLine = proxiedResponse.getStatusLine(); statusCode = statusLine.getStatusCode(); String reasonPhrase = statusLine.getReasonPhrase(); if (reasonPhrase != null && statusCode > 399) { if (logger.isWarnEnabled()) { logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase); } if (statusCode == 401) { // // Handle case of basic authentication. // Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate"); finalResponse.setHeader("WWW-Authenticate", (authHeader == null) ? "Basic realm=\"Authentication required\"" : authHeader.getValue()); } // 403 and 404 are handled by specific JSP files provided by the // security-proxy webapp if ((statusCode == 404) || (statusCode == 403)) { finalResponse.sendError(statusCode); return; } } headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse, this.targets); if (statusCode == 302 || statusCode == 301) { adjustLocation(request, proxiedResponse, finalResponse); } // get content type String contentType = null; if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) { contentType = proxiedResponse.getEntity().getContentType().getValue(); logger.debug("content-type detected: " + contentType); } // content type has to be valid if (isCharsetRequiredForContentType(contentType)) { doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType); } else { logger.debug("charset not required for contentType: " + contentType); doHandleRequest(request, finalResponse, requestType, proxiedResponse); } } catch (IOException e) { // connection problem with the host logger.error("Exception occured when trying to connect to the remote host: ", e); try { finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } catch (IOException e2) { // error occured while trying to return the // "service unavailable status" finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.eclipse.mylyn.commons.net.WebUtil.java
/** * @since 3.1// www. j a va 2 s . c o m */ @SuppressWarnings("deprecation") public static Proxy getProxy(String host, String proxyType) { Assert.isNotNull(host); Assert.isNotNull(proxyType); IProxyService service = CommonsNetPlugin.getProxyService(); if (service != null && service.isProxiesEnabled()) { // TODO e3.5 move to new proxy API IProxyData data = service.getProxyDataForHost(host, proxyType); if (data != null && data.getHost() != null) { String proxyHost = data.getHost(); int proxyPort = data.getPort(); // change the IProxyData default port to the Java default port if (proxyPort == -1) { proxyPort = 0; } AuthenticationCredentials credentials = null; if (data.isRequiresAuthentication()) { credentials = new AuthenticationCredentials(data.getUserId(), data.getPassword()); } return createProxy(proxyHost, proxyPort, credentials); } } else { try { // fall back to JDK proxy selector URI uri = new URI(proxyType, "//" + host, null); //$NON-NLS-1$ List<Proxy> proxies = ProxySelector.getDefault().select(uri); if (proxies != null && proxies.size() > 0) { Proxy proxy = proxies.iterator().next(); if (proxy != Proxy.NO_PROXY) { return proxy; } } } catch (URISyntaxException e) { // ignore } } return null; }
From source file:org.rundeck.api.ApiCall.java
/** * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates * * @return an {@link HttpClient} instance - won't be null *///from ww w .j a va 2 s.c om private CloseableHttpClient instantiateHttpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties(); // configure user-agent httpClientBuilder.setUserAgent("Rundeck API Java Client " + client.getApiVersion()); if (client.isSslHostnameVerifyAllowAll()) { httpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } if (client.isSslCertificateTrustAllowSelfSigned()) { // configure SSL try { httpClientBuilder.setSslcontext( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } } if (client.isSystemProxyEnabled()) { // configure proxy (use system env : http.proxyHost / http.proxyPort) httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); } // in case of token-based authentication, add the correct HTTP header to all requests via an interceptor httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if (client.getToken() != null) { request.addHeader(AUTH_TOKEN_HEADER, client.getToken()); //System.out.println("httpClient adding token header"); } else if (client.getSessionID() != null) { request.addHeader(COOKIE_HEADER, "JSESSIONID=" + client.getSessionID()); //System.out.println("httpClient adding session header, sessionID="+client.getSessionID()); } } }); return httpClientBuilder.build(); }
From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java
void additionalAuthentication(String passPhrase) { final String passwordPhrase = passPhrase; JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() { @Override// w w w .j a v a 2s .c o m protected void configure(OpenSshConfig.Host hc, Session session) { CredentialsProvider provider = new CredentialsProvider() { @Override public boolean isInteractive() { return false; } @Override public boolean supports(CredentialItem... items) { return true; } @Override public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { for (CredentialItem item : items) { if (item instanceof CredentialItem.StringType) { ((CredentialItem.StringType) item).setValue(passwordPhrase); } } return true; } }; UserInfo userInfo = new CredentialsProviderUserInfo(session, provider); // Unknown host key for ssh java.util.Properties config = new java.util.Properties(); config.put(STRICT_HOST_KEY_CHECKING, NO); session.setConfig(config); session.setUserInfo(userInfo); } }; SshSessionFactory.setInstance(sessionFactory); /* * Enable clone of https url by trusting those urls */ // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; final String https_proxy = System.getenv(HTTPS_PROXY); final String http_proxy = System.getenv(HTTP_PROXY); ProxySelector.setDefault(new ProxySelector() { final ProxySelector delegate = ProxySelector.getDefault(); @Override public List<Proxy> select(URI uri) { // Filter the URIs to be proxied if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) { try { URI httpsUri = new URI(https_proxy); String host = httpsUri.getHost(); int port = httpsUri.getPort(); return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port))); } catch (URISyntaxException e) { if (debugEnabled) { S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()"); } } } if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) { try { URI httpUri = new URI(http_proxy); String host = httpUri.getHost(); int port = httpUri.getPort(); return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port))); } catch (URISyntaxException e) { if (debugEnabled) { S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()"); } } } // revert to the default behaviour return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } } }); // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance(SSL); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (GeneralSecurityException e) { e.getLocalizedMessage(); } }
From source file:nz.dataview.websyncclientgui.WebSYNCClientGUIView.java
/** * try to detect if a proxy exists, and update the UI * /*ww w . ja va 2 s . c o m*/ * @return */ private void detectProxy() { try { proxyDetectedLabel.setText(""); List l = ProxySelector.getDefault().select(new URI(knURLField.getText())); for (Iterator iter = l.iterator(); iter.hasNext();) { Proxy proxy = (Proxy) iter.next(); if ("DIRECT".equals(proxy.type().toString())) { proxyEnabled = false; useProxyField.setSelected(proxyEnabled); proxyFieldsUpdate(proxyEnabled); } else { InetSocketAddress addr = (InetSocketAddress) proxy.address(); if (addr != null) { // if we have a proxy set the correct fields and state of UI proxyEnabled = true; useProxyField.setSelected(proxyEnabled); proxyHostField.setText(addr.getHostName()); proxyPortField.setText(Integer.toString(addr.getPort())); proxyFieldsUpdate(proxyEnabled); } } String text = (String) "Proxy settings detected and updated"; proxyDetectedLabel.setText(text); } } catch (Exception e) { showErrorDialog("Detect Proxy", "Problem in detecting proxy, please set proxy settings manually"); } }