Example usage for java.net ProxySelector ProxySelector

List of usage examples for java.net ProxySelector ProxySelector

Introduction

In this page you can find the example usage for java.net ProxySelector ProxySelector.

Prototype

ProxySelector

Source Link

Usage

From source file:Utils.java

private static void installProxySelector(final String hostName, final int portNum) {
    ProxySelector.setDefault(new ProxySelector() {
        public List select(URI uri) {
            List list = new ArrayList();
            list.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostName, portNum)));
            return list;
        }/*from   w w w .ja v a  2s  .co m*/

        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        }
    });
}

From source file:com.orange.cloud.servicebroker.filter.core.config.OkHttpClientConfig.java

@Bean
public OkHttpClient squareHttpClient() {
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override/*from   w w  w .j  a  va  2 s . co  m*/
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCerts() };

    SSLSocketFactory sslSocketFactory = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        sslSocketFactory = (SSLSocketFactory) sc.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        new IllegalArgumentException(e);
    }

    log.info("===> configuring OkHttp");
    OkHttpClient.Builder ohc = new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1))
            .followRedirects(true).followSslRedirects(true).hostnameVerifier(hostnameVerifier)
            .sslSocketFactory(sslSocketFactory).addInterceptor(LOGGING_INTERCEPTOR);

    if ((this.proxyHost != null) && (this.proxyHost.length() > 0)) {
        log.info("Activating proxy on host {} port {}", this.proxyHost, this.proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort));
        ohc.proxy(proxy);
        ohc.proxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress socket, IOException e) {
                throw new IllegalArgumentException("connection to proxy failed", e);
            }
        });
    }

    return ohc.build();
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

/**
 * This method is used to get set the proxy to clone the repositories under this proxy
 * /*w  ww.j  av a  2  s  .  com*/
 * @param proxy proxy instance created by using proxy details provided by user
 */
private void setProxy(final Proxy proxy) {
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(URI uri) {
            return Arrays.asList(proxy);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can not be null.");
            }
        }

    });

}

From source file:com.microsoft.azure.servicebus.samples.queueswithproxy.QueuesWithProxy.java

public static int runApp(String[] args, Function<String, Integer> run) {
    try {//w ww .  java 2 s. c om

        String connectionString;
        String proxyHostName;
        String proxyPortString;
        int proxyPort;

        // Add command line options and create parser
        Options options = new Options();
        options.addOption(new Option("c", true, "Connection string"));
        options.addOption(new Option("n", true, "Proxy hostname"));
        options.addOption(new Option("p", true, "Proxy port"));

        CommandLineParser clp = new DefaultParser();
        CommandLine cl = clp.parse(options, args);

        // Pull variables from command line options or environment variables
        connectionString = getOptionOrEnv(cl, "c", SB_SAMPLES_CONNECTIONSTRING);
        proxyHostName = getOptionOrEnv(cl, "n", SB_SAMPLES_PROXY_HOSTNAME);
        proxyPortString = getOptionOrEnv(cl, "p", SB_SAMPLES_PROXY_PORT);

        // Check for bad input
        if (StringUtil.isNullOrEmpty(connectionString) || StringUtil.isNullOrEmpty(proxyHostName)
                || StringUtil.isNullOrEmpty(proxyPortString)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("run jar with", "", options, "", true);
            return 2;
        }

        if (!NumberUtils.isCreatable(proxyPortString)) {
            System.err.println("Please provide a numerical value for the port");
        }
        proxyPort = Integer.parseInt(proxyPortString);

        // ProxySelector set up for an HTTP proxy
        final ProxySelector systemDefaultSelector = ProxySelector.getDefault();
        ProxySelector.setDefault(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (uri != null && uri.getHost() != null && uri.getHost().equalsIgnoreCase(proxyHostName)) {
                    List<Proxy> proxies = new LinkedList<>();
                    proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort)));
                    return proxies;
                }
                return systemDefaultSelector.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.");
                }
                systemDefaultSelector.connectFailed(uri, sa, ioe);
            }
        });

        return run.apply(connectionString);
    } catch (Exception e) {
        System.out.printf("%s", e.toString());
        return 3;
    }
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void httpProxy_fromSystemProperty() throws Exception {
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    try {// ww  w  . j  av  a  2s.co m
        ProxySelector.setDefault(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                InetSocketAddress address = new InetSocketAddress(HTTP_PROXY.getHost(), HTTP_PROXY.getPort());
                Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
                return Collections.singletonList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {

            }
        });
        String repoUrl = "https://myrepo/repo.git";
        new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
                .properties(new String[] { "spring.cloud.config.server.git.uri=" + repoUrl }).run();
        HttpClient httpClient = getHttpClientForUrl(repoUrl);
        this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class),
                hasProperty("message", containsString(HTTP_PROXY.getHost()))));

        makeRequest(httpClient, "http://somehost");
    } finally {
        ProxySelector.setDefault(defaultProxySelector);
    }
}

From source file:com.intuit.tank.proxy.Main.java

/**
 * Returns a proxy selector/*from   w w  w  .  j  a v a2s.com*/
 * 
 * @param proxy
 * @return
 */
static ProxySelector getProxySelector(String proxy) {
    final java.net.Proxy upstream;
    if ("DIRECT".equals(proxy)) {
        upstream = java.net.Proxy.NO_PROXY;
    } else {
        java.net.Proxy.Type type = null;
        if (proxy.startsWith("PROXY ")) {
            type = java.net.Proxy.Type.HTTP;
        } else if (proxy.startsWith("SOCKS ")) {
            type = java.net.Proxy.Type.SOCKS;
        } else
            throw new IllegalArgumentException("Unknown Proxy type: " + proxy);
        proxy = proxy.substring(6); // "SOCKS " or "PROXY "
        int c = proxy.indexOf(':');
        if (c == -1)
            throw new IllegalArgumentException("Illegal proxy address: " + proxy);
        InetSocketAddress addr = new InetSocketAddress(proxy.substring(0, c),
                Integer.parseInt(proxy.substring(c + 1)));
        upstream = new java.net.Proxy(type, addr);
    }
    ProxySelector ps = new ProxySelector() {

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            logger.info("Proxy connection to " + uri + " via " + sa + " failed! " + ioe.getLocalizedMessage());
        }

        @Override
        public List<java.net.Proxy> select(URI uri) {
            return Arrays.asList(upstream);
        }
    };
    return ps;
}

From source file:org.owasp.proxy.Main.java

private static ProxySelector getProxySelector(Configuration config) {
    String proxy = config.proxy;/*w  ww . j a  va  2s  .c  o  m*/
    final java.net.Proxy upstream;
    if ("DIRECT".equals(proxy)) {
        upstream = java.net.Proxy.NO_PROXY;
    } else {
        java.net.Proxy.Type type = null;
        if (proxy.startsWith("PROXY ")) {
            type = java.net.Proxy.Type.HTTP;
        } else if (proxy.startsWith("SOCKS ")) {
            type = java.net.Proxy.Type.SOCKS;
        } else
            throw new IllegalArgumentException("Unknown Proxy type: " + proxy);
        proxy = proxy.substring(6); // "SOCKS " or "PROXY "
        int c = proxy.indexOf(':');
        if (c == -1)
            throw new IllegalArgumentException("Illegal proxy address: " + proxy);
        InetSocketAddress addr = new InetSocketAddress(proxy.substring(0, c),
                Integer.parseInt(proxy.substring(c + 1)));
        upstream = new java.net.Proxy(type, addr);
    }
    ProxySelector ps = new ProxySelector() {

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            logger.info("Proxy connection to " + uri + " via " + sa + " failed! " + ioe.getLocalizedMessage());
        }

        @Override
        public List<java.net.Proxy> select(URI uri) {
            return Arrays.asList(upstream);
        }
    };
    return ps;
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void addProxySelector() {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override//from www .  ja  v a 2  s .  com
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }

    final ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals("fastdl.mongodb.org")) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override//from w ww.  j a  v  a  2 s  . 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:org.fuin.esmp.AbstractEventStoreMojo.java

private void addProxySelector(final String proxyHost, final int proxyPort, final String proxyUser,
        final String proxyPassword, final URL downloadUrl) throws URISyntaxException {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override//from w ww  . ja va 2  s  .  c  o  m
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }
    final ProxySelector defaultProxySelector = ProxySelector.getDefault();

    final URI downloadUri = downloadUrl.toURI();

    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals(downloadUri.getHost()) && proxyHost != null && proxyHost.length() != 0) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}