Example usage for java.net ProxySelector select

List of usage examples for java.net ProxySelector select

Introduction

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

Prototype

public abstract List<Proxy> select(URI uri);

Source Link

Document

Selects all the applicable proxies based on the protocol to access the resource with and a destination address to access the resource at.

Usage

From source file:es.eucm.eadventure.editor.plugin.vignette.ProxySetup.java

private static Proxy getProxy() {
    List<Proxy> l = null;
    try {/*from   w ww  .j a v a  2 s. c  o  m*/
        ProxySelector def = ProxySelector.getDefault();

        l = def.select(new URI("http://foo/bar"));
        ProxySelector.setDefault(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (l != null) {
        for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
            java.net.Proxy proxy = iter.next();
            return proxy;
        }
    }
    return null;
}

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

public static int runApp(String[] args, Function<String, Integer> run) {
    try {//from   w w w.j  a  va  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:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;//from w  w  w.  j av a 2  s  . co  m
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpGet, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Retrieve Proxy Selector// w w w .jav a 2 s  . c om
 *
 * @param uri target uri
 * @return proxy selector
 */
private static List<Proxy> getProxyForURI(java.net.URI uri) {
    LOGGER.debug("get Default proxy selector");
    ProxySelector proxySelector = ProxySelector.getDefault();
    LOGGER.debug("getProxyForURI(" + uri + ')');
    List<Proxy> proxies = proxySelector.select(uri);
    LOGGER.debug("got system proxies:" + proxies);
    return proxies;
}

From source file:org.sonar.api.utils.HttpDownloaderTest.java

@Test
public void shouldGetDirectProxySynthesis() throws URISyntaxException {
    ProxySelector proxySelector = mock(ProxySelector.class);
    when(proxySelector.select((URI) anyObject())).thenReturn(Arrays.asList(Proxy.NO_PROXY));
    assertThat(HttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector), is("no proxy"));
}

From source file:org.sonar.api.utils.HttpDownloaderTest.java

@Test
public void shouldGetProxySynthesis() throws URISyntaxException {
    ProxySelector proxySelector = mock(ProxySelector.class);
    when(proxySelector.select((URI) anyObject())).thenReturn(Arrays.asList((Proxy) new FakeProxy()));
    assertThat(HttpDownloader.getProxySynthesis(new URI("http://an_url"), proxySelector),
            is("proxy: http://proxy_url:4040"));
}

From source file:org.ulteo.utils.ProxyManager.java

public void detect(String remoteHost) {
    Logger.debug("Detect proxy");
    List<Proxy> proxyList = null;
    System.setProperty("java.net.useSystemProxies", "true");
    ProxySelector ps = ProxySelector.getDefault();

    if (ps == null) {
        Logger.warn("Unable to detect a proxy: no proxySelector available");
        return;/*w  w w .j av a 2 s. c  om*/
    }
    try {
        URI uri = new URI("https://" + remoteHost);
        proxyList = ps.select(uri);
    } catch (URISyntaxException e) {
        Logger.warn("Unable to detect a proxy: bad URL");
        return;
    }
    if (proxyList != null) {
        for (Proxy proxy : proxyList) {
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            if (addr != null) {
                this.host = addr.getHostName();
                this.port = addr.getPort();
                System.setProperty("https.proxyHost", this.host);
                System.setProperty("https.proxyPort", new Integer(this.port).toString());
                Logger.debug("using proxy[" + this.host + ":" + this.port + "]");
                break;
            }
        }
    }
}

From source file:com.joyent.manta.http.MantaConnectionFactory.java

/**
 * Finds the host of the proxy server that was configured as part of the
 * JVM settings.// ww w . j  a  v  a2  s. c o  m
 *
 * @return proxy server as {@link HttpHost}, if no proxy then null
 */
protected HttpHost findProxyServer() {
    final ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> proxies = proxySelector.select(URI.create(config.getMantaURL()));

    if (!proxies.isEmpty()) {
        /* The Apache HTTP Client doesn't understand the concept of multiple
         * proxies, so we use only the first one returned. */
        final Proxy proxy = proxies.get(0);

        switch (proxy.type()) {
        case DIRECT:
            return null;
        case SOCKS:
            throw new ConfigurationException("SOCKS proxies are unsupported");
        default:
            // do nothing and fall through
        }

        if (proxy.address() instanceof InetSocketAddress) {
            InetSocketAddress sa = (InetSocketAddress) proxy.address();

            return new HttpHost(sa.getHostName(), sa.getPort());
        } else {
            String msg = String.format(
                    "Expecting proxy to be instance of InetSocketAddress. " + " Actually: %s", proxy.address());
            throw new ConfigurationException(msg);
        }
    } else {
        return null;
    }
}

From source file:org.mapfish.print.config.Config.java

/**
 * Get or create the http client to be used to fetch all the map data.
 *///from  w w w  .java2s  .co m
public HttpClient getHttpClient(URI uri) {
    MultiThreadedHttpConnectionManager connectionManager = getConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);

    // httpclient is a bit pesky about loading everything in memory...
    // disabling the warnings.
    Logger.getLogger(HttpMethodBase.class).setLevel(Level.ERROR);

    // configure proxies for URI
    ProxySelector selector = ProxySelector.getDefault();

    List<Proxy> proxyList = selector.select(uri);
    Proxy proxy = proxyList.get(0);

    if (!proxy.equals(Proxy.NO_PROXY)) {
        InetSocketAddress socketAddress = (InetSocketAddress) proxy.address();
        String hostName = socketAddress.getHostName();
        int port = socketAddress.getPort();

        httpClient.getHostConfiguration().setProxy(hostName, port);
    }

    for (SecurityStrategy sec : security)
        if (sec.matches(uri)) {
            sec.configure(uri, httpClient);
            break;
        }
    return httpClient;
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

private ProxyHost getProxyHost() {
    ProxyHost theProxyHost = null;//from w ww. j a v a2  s .co  m
    ProxySelector ps = ProxySelector.getDefault();
    List<Proxy> p = null;
    // select the proxy for the URI of this repository
    try {
        if (ps != null) {
            // log.info( "Getting Proxy List." );
            p = ps.select(new java.net.URI(this.servletURL));
        }
    } catch (Exception e) {
        // log.warn( "Exception getting proxy: " + e.toString() );
    }
    if (p == null) {
        // log.warn( "No proxy information available." );
    } else {
        // log.info( "Received proxy list: " + p.toString() );
        Iterator<Proxy> proxies = p.iterator();
        // just take the first for now
        if (proxies != null && proxies.hasNext()) {
            Proxy theProxy = (Proxy) proxies.next();
            // log.info( "Proxy set to: " + theProxy.toString() );
            if (!Proxy.NO_PROXY.equals(theProxy)) {
                InetSocketAddress theSock = (InetSocketAddress) theProxy.address();
                theProxyHost = new ProxyHost(theSock.getHostName(), theSock.getPort());
            }
        } else {
            // log.warn( "Proxy list has zero members." );
        }
    }
    return theProxyHost;
}