Java 类java.net.ProxySelector 实例源码

项目:GitHub    文件:Address.java   
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
    CertificatePinner certificatePinner, Authenticator proxyAuthenticator, Proxy proxy,
    List<Protocol> protocols, List<ConnectionSpec> connectionSpecs, ProxySelector proxySelector) {
  this.url = new HttpUrl.Builder()
      .scheme(sslSocketFactory != null ? "https" : "http")
      .host(uriHost)
      .port(uriPort)
      .build();

  if (dns == null) throw new NullPointerException("dns == null");
  this.dns = dns;

  if (socketFactory == null) throw new NullPointerException("socketFactory == null");
  this.socketFactory = socketFactory;

  if (proxyAuthenticator == null) {
    throw new NullPointerException("proxyAuthenticator == null");
  }
  this.proxyAuthenticator = proxyAuthenticator;

  if (protocols == null) throw new NullPointerException("protocols == null");
  this.protocols = Util.immutableList(protocols);

  if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
  this.connectionSpecs = Util.immutableList(connectionSpecs);

  if (proxySelector == null) throw new NullPointerException("proxySelector == null");
  this.proxySelector = proxySelector;

  this.proxy = proxy;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.certificatePinner = certificatePinner;
}
项目:GitHub    文件:Address.java   
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    @Nullable SSLSocketFactory sslSocketFactory, @Nullable HostnameVerifier hostnameVerifier,
    @Nullable CertificatePinner certificatePinner, Authenticator proxyAuthenticator,
    @Nullable Proxy proxy, List<Protocol> protocols, List<ConnectionSpec> connectionSpecs,
    ProxySelector proxySelector) {
  this.url = new HttpUrl.Builder()
      .scheme(sslSocketFactory != null ? "https" : "http")
      .host(uriHost)
      .port(uriPort)
      .build();

  if (dns == null) throw new NullPointerException("dns == null");
  this.dns = dns;

  if (socketFactory == null) throw new NullPointerException("socketFactory == null");
  this.socketFactory = socketFactory;

  if (proxyAuthenticator == null) {
    throw new NullPointerException("proxyAuthenticator == null");
  }
  this.proxyAuthenticator = proxyAuthenticator;

  if (protocols == null) throw new NullPointerException("protocols == null");
  this.protocols = Util.immutableList(protocols);

  if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
  this.connectionSpecs = Util.immutableList(connectionSpecs);

  if (proxySelector == null) throw new NullPointerException("proxySelector == null");
  this.proxySelector = proxySelector;

  this.proxy = proxy;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.certificatePinner = certificatePinner;
}
项目:boohee_v5.6    文件:OkHttpClient.java   
OkHttpClient copyWithDefaults() {
    OkHttpClient result = new OkHttpClient(this);
    if (result.proxySelector == null) {
        result.proxySelector = ProxySelector.getDefault();
    }
    if (result.cookieHandler == null) {
        result.cookieHandler = CookieHandler.getDefault();
    }
    if (result.socketFactory == null) {
        result.socketFactory = SocketFactory.getDefault();
    }
    if (result.sslSocketFactory == null) {
        result.sslSocketFactory = getDefaultSSLSocketFactory();
    }
    if (result.hostnameVerifier == null) {
        result.hostnameVerifier = OkHostnameVerifier.INSTANCE;
    }
    if (result.certificatePinner == null) {
        result.certificatePinner = CertificatePinner.DEFAULT;
    }
    if (result.authenticator == null) {
        result.authenticator = AuthenticatorAdapter.INSTANCE;
    }
    if (result.connectionPool == null) {
        result.connectionPool = ConnectionPool.getDefault();
    }
    if (result.protocols == null) {
        result.protocols = DEFAULT_PROTOCOLS;
    }
    if (result.connectionSpecs == null) {
        result.connectionSpecs = DEFAULT_CONNECTION_SPECS;
    }
    if (result.dns == null) {
        result.dns = Dns.SYSTEM;
    }
    return result;
}
项目:LoRaWAN-Smart-Parking    文件:OkHttpClient.java   
/**
 * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
 * each field that hasn't been explicitly configured.
 */
private OkHttpClient copyWithDefaults() {
  OkHttpClient result = new OkHttpClient(this);
  result.proxy = proxy;
  result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  result.sslSocketFactory = sslSocketFactory != null
      ? sslSocketFactory
      : HttpsURLConnection.getDefaultSSLSocketFactory();
  result.hostnameVerifier = hostnameVerifier != null
      ? hostnameVerifier
      : OkHostnameVerifier.INSTANCE;
  result.authenticator = authenticator != null
      ? authenticator
      : HttpAuthenticator.SYSTEM_DEFAULT;
  result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  result.followProtocolRedirects = followProtocolRedirects;
  result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  result.connectTimeout = connectTimeout;
  result.readTimeout = readTimeout;
  return result;
}
项目:LoRaWAN-Smart-Parking    文件:OkHttpClient.java   
/**
 * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
 * each field that hasn't been explicitly configured.
 */
private OkHttpClient copyWithDefaults() {
  OkHttpClient result = new OkHttpClient(this);
  result.proxy = proxy;
  result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  result.sslSocketFactory = sslSocketFactory != null
      ? sslSocketFactory
      : HttpsURLConnection.getDefaultSSLSocketFactory();
  result.hostnameVerifier = hostnameVerifier != null
      ? hostnameVerifier
      : OkHostnameVerifier.INSTANCE;
  result.authenticator = authenticator != null
      ? authenticator
      : HttpAuthenticator.SYSTEM_DEFAULT;
  result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  result.followProtocolRedirects = followProtocolRedirects;
  result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  result.connectTimeout = connectTimeout;
  result.readTimeout = readTimeout;
  return result;
}
项目:incubator-netbeans    文件:URLResourceRetriever.java   
public HashMap<String, InputStream> retrieveDocument(String baseAddress,
        String documentAddress) throws IOException,URISyntaxException{

    String effAddr = getEffectiveAddress(baseAddress, documentAddress);
    if(effAddr == null)
        return null;
    URI currURI = new URI(effAddr);
    HashMap<String, InputStream> result = null;

    InputStream is = getInputStreamOfURL(currURI.toURL(), ProxySelector.
            getDefault().select(currURI).get(0));
    result = new HashMap<String, InputStream>();
    result.put(effectiveURL.toString(), is);
    return result;

}
项目:incubator-netbeans    文件:DockerAction.java   
private Endpoint createEndpoint() throws IOException {
    URL realUrl = getUrl();
    try {
        if ("https".equals(realUrl.getProtocol())) { // NOI18N
            SSLContext context = ContextProvider.getInstance().getSSLContext(instance);
            return Endpoint.forSocket(context.getSocketFactory().createSocket(realUrl.getHost(), realUrl.getPort()));
        } else if ("http".equals(realUrl.getProtocol())) { // NOI18N
            Socket s = new Socket(ProxySelector.getDefault().select(realUrl.toURI()).get(0));
            int port = realUrl.getPort();
            if (port < 0) {
                port = realUrl.getDefaultPort();
            }
            s.connect(new InetSocketAddress(realUrl.getHost(), port));
            return Endpoint.forSocket(s);
        } else {
            throw new IOException("Unknown protocol: " + realUrl.getProtocol());
        }
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
}
项目:incubator-netbeans    文件:ExceptionHandlerTest.java   
@Override
protected void setUp() throws Exception {
    super.setUp();
    System.setProperty("netbeans.user", getWorkDir().getAbsolutePath());

    // reset
    Method m = MylynSupport.class.getDeclaredMethod("reset", new Class[0]);
    m.setAccessible(true);
    m.invoke(MylynSupport.class);

    Field f = Bugzilla.class.getDeclaredField("instance");
    f.setAccessible(true);
    f.set(Bugzilla.class, null);

    brc = Bugzilla.getInstance().getRepositoryConnector();

    WebUtil.init();

    if (defaultPS == null) {
        defaultPS = ProxySelector.getDefault();
    }
}
项目:AndroidVideoCache    文件:ProxySelectorTest.java   
@Test // https://github.com/danikula/AndroidVideoCache/issues/28
public void testIgnoring() throws Exception {
    InetSocketAddress proxyAddress = new InetSocketAddress("proxy.com", 80);
    Proxy systemProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
    ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
    when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
    ProxySelector.setDefault(mockedProxySelector);

    IgnoreHostProxySelector.install("localhost", 42);

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> githubProxies = proxySelector.select(new URI("http://github.com"));
    assertThat(githubProxies).hasSize(1);
    assertThat(githubProxies.get(0).address()).isEqualTo(proxyAddress);

    List<Proxy> localhostProxies = proxySelector.select(new URI("http://localhost:42"));
    assertThat(localhostProxies).hasSize(1);
    assertThat(localhostProxies.get(0)).isEqualTo(Proxy.NO_PROXY);

    List<Proxy> localhostPort69Proxies = proxySelector.select(new URI("http://localhost:69"));
    assertThat(localhostPort69Proxies).hasSize(1);
    assertThat(localhostPort69Proxies.get(0).address()).isEqualTo(proxyAddress);
}
项目:OpenJSharp    文件:EndpointAddress.java   
private Proxy chooseProxy() {
    ProxySelector sel =
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<ProxySelector>() {
                @Override
                public ProxySelector run() {
                    return ProxySelector.getDefault();
                }
            });

    if(sel==null)
        return Proxy.NO_PROXY;


    if(!sel.getClass().getName().equals("sun.net.spi.DefaultProxySelector"))
        // user-defined proxy. may return a different proxy for each invocation
        return null;

    Iterator<Proxy> it = sel.select(uri).iterator();
    if(it.hasNext())
        return it.next();

    return Proxy.NO_PROXY;
}
项目:jdk8u-jdk    文件:MultiThreadedSystemProxies.java   
public static void main(String[] args) throws Exception {
    System.setProperty("java.net.useSystemProxies", "true");
    final ProxySelector ps = ProxySelector.getDefault();
    final URI uri = new URI("http://ubuntu.com");
    Thread[] threads = new Thread[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ps.select(uri);
                } catch (Exception x) {
                    throw new RuntimeException(x);
                }
            }
        });
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].start();
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].join();
    }
}
项目:openvisualtraceroute    文件:Env.java   
private static Proxy getProxy() {
    List<Proxy> l = null;
    try {
        final ProxySelector def = ProxySelector.getDefault();
        l = def.select(new URI("http://foo/bar"));
        ProxySelector.setDefault(null);
    } catch (final Exception e) {

    }
    if (l != null) {
        for (final Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
            final java.net.Proxy proxy = iter.next();
            return proxy;
        }
    }
    return null;
}
项目:openjdk-jdk10    文件:MultiThreadedSystemProxies.java   
public static void main(String[] args) throws Exception {
    System.setProperty("java.net.useSystemProxies", "true");
    final ProxySelector ps = ProxySelector.getDefault();
    final URI uri = new URI("http://ubuntu.com");
    Thread[] threads = new Thread[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ps.select(uri);
                } catch (Exception x) {
                    throw new RuntimeException(x);
                }
            }
        });
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].start();
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].join();
    }
}
项目:openjdk-jdk10    文件:EndpointAddress.java   
private Proxy chooseProxy() {
    ProxySelector sel =
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<ProxySelector>() {
                @Override
                public ProxySelector run() {
                    return ProxySelector.getDefault();
                }
            });

    if(sel==null)
        return Proxy.NO_PROXY;


    if(!sel.getClass().getName().equals("sun.net.spi.DefaultProxySelector"))
        // user-defined proxy. may return a different proxy for each invocation
        return null;

    Iterator<Proxy> it = sel.select(uri).iterator();
    if(it.hasNext())
        return it.next();

    return Proxy.NO_PROXY;
}
项目:client-java-rest-core    文件:AuthClientFactory.java   
/**
 * Initializes default http client builder instance
 * 
 * @return
 */
protected HttpClientBuilder initDefaultBuilder() {
    HttpClientBuilder builder = HttpClientBuilder.create();

    if (null != credentials) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        builder.setDefaultCredentialsProvider(credentialsProvider);
    }

    builder.setMaxConnPerRoute(5);
    builder.setMaxConnTotal(20);
    // dirty hack to avoid npe in soapui client, soapui client sets default
    // proxy selector to null
    ProxySelector proxySelector = ProxySelector.getDefault();
    if (proxySelector != null)
        builder.setRoutePlanner(new SystemDefaultRoutePlanner(proxySelector));

    if (null != interceptors && !interceptors.isEmpty()) {
        for (HttpRequestInterceptor interceptor : interceptors) {
            builder.addInterceptorFirst(interceptor);
        }
    }

    return builder;
}
项目:proxy-vole    文件:JavaProxySearchStrategy.java   
/*************************************************************************
 * Loads the proxy settings from environment variables.
 * 
 * @return a configured ProxySelector, null if none is found.
 ************************************************************************/

@Override
public ProxySelector getProxySelector() {
  ProtocolDispatchSelector ps = new ProtocolDispatchSelector();

  Logger.log(getClass(), LogLevel.TRACE, "Using settings from Java System Properties");

  setupProxyForProtocol(ps, "http", 80);
  setupProxyForProtocol(ps, "https", 443);
  setupProxyForProtocol(ps, "ftp", 80);
  setupProxyForProtocol(ps, "ftps", 80);
  boolean socksAvailable = setupSocktProxy(ps);

  if (ps.size() == 0 && !socksAvailable) {
    return null;
  }

  return ps;
}
项目:proxy-vole    文件:JavaProxySearchStrategy.java   
/*************************************************************************
 * Parse properties for the given protocol.
 * 
 * @param ps
 * @param protocol
 * @throws NumberFormatException
 ************************************************************************/

private void setupProxyForProtocol(ProtocolDispatchSelector ps, String protocol, int defaultPort) {
  String host = System.getProperty(protocol + ".proxyHost");
  if (host == null || host.trim().length() == 0) {
    return;
  }

  String port = System.getProperty(protocol + ".proxyPort", Integer.toString(defaultPort));
  String whiteList = System.getProperty(protocol + ".nonProxyHosts", "").replace('|', ',');

  if ("https".equalsIgnoreCase(protocol)) { // This is dirty but https has
                                            // no own property for it.
    whiteList = System.getProperty("http.nonProxyHosts", "").replace('|', ',');
  }

  Logger.log(getClass(), LogLevel.TRACE, protocol.toUpperCase() + " proxy {0}:{1} found using whitelist: {2}", host,
      port, whiteList);

  ProxySelector protocolSelector = new FixedProxySelector(host, Integer.parseInt(port));
  if (whiteList.trim().length() > 0) {
    protocolSelector = new ProxyBypassListSelector(whiteList, protocolSelector);
  }

  ps.setSelector(protocol, protocolSelector);
}
项目:EasyVPN-Free    文件:ProxyDetection.java   
static Proxy getFirstProxy(URL url) throws URISyntaxException {
    System.setProperty("java.net.useSystemProxies", "true");

    List<Proxy> proxylist = ProxySelector.getDefault().select(url.toURI());


    if (proxylist != null) {
        for (Proxy proxy: proxylist) {
            SocketAddress addr = proxy.address();

            if (addr != null) {
                return proxy;
            }
        }

    }
    return null;
}
项目:proxy-vole    文件:WpadProxySearchStrategyWithDHPC.java   
/*************************************************************************
 * Loads the proxy settings from a PAC file. The location of the PAC file is
 * determined automatically.
 * 
 * @return a configured ProxySelector, null if none is found.
 * @throws ProxyException
 *             on error.
 ************************************************************************/

@Override
public ProxySelector getProxySelector() throws ProxyException {
    try {
        Logger.log(getClass(), LogLevel.TRACE, "Using WPAD to find a proxy");

        String pacScriptUrl = detectScriptUrlPerDHCP();
        if (pacScriptUrl == null) {
            pacScriptUrl = detectScriptUrlPerDNS();
        }
        if (pacScriptUrl == null) {
            return null;
        }
        Logger.log(getClass(), LogLevel.TRACE, "PAC script url found: {0}", pacScriptUrl);
        return ProxyUtil.buildPacSelectorForUrl(pacScriptUrl);
    } catch (IOException e) {
        Logger.log(getClass(), LogLevel.ERROR, "Error during WPAD search.", e);
        throw new ProxyException(e);
    }
}
项目:proxy-vole    文件:WpadProxySearchStrategy.java   
/*************************************************************************
 * Loads the proxy settings from a PAC file. The location of the PAC file is
 * determined automatically.
 * 
 * @return a configured ProxySelector, null if none is found.
 * @throws ProxyException
 *           on error.
 ************************************************************************/

@Override
public ProxySelector getProxySelector() throws ProxyException {
  try {
    Logger.log(getClass(), LogLevel.TRACE, "Using WPAD to find a proxy");

    String pacScriptUrl = detectScriptUrlPerDHCP();
    if (pacScriptUrl == null) {
      pacScriptUrl = detectScriptUrlPerDNS();
    }
    if (pacScriptUrl == null) {
      return null;
    }
    Logger.log(getClass(), LogLevel.TRACE, "PAC script url found: {0}", pacScriptUrl);
    return ProxyUtil.buildPacSelectorForUrl(pacScriptUrl);
  } catch (IOException e) {
    Logger.log(getClass(), LogLevel.ERROR, "Error during WPAD search.", e);
    throw new ProxyException(e);
  }
}
项目:proxy-vole    文件:GnomeProxySearchStrategy.java   
/*************************************************************************
 * Parse the fixed proxy settings and build an ProxySelector for this a
 * chained configuration.
 * 
 * @param settings
 *            the proxy settings to evaluate.
 ************************************************************************/

private ProxySelector setupFixedProxySelector(Properties settings) {
    if (!hasProxySettings(settings)) {
        return null;
    }
    ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
    installHttpSelector(settings, ps);

    if (useForAllProtocols(settings)) {
        ps.setFallbackSelector(ps.getSelector("http"));
    } else {
        installSecureSelector(settings, ps);
        installFtpSelector(settings, ps);
        installSocksSelector(settings, ps);
    }
    return ps;
}
项目:proxy-vole    文件:GnomeDConfProxySearchStrategy.java   
/*************************************************************************
 * Parse the fixed proxy settings and build an ProxySelector for this a
 * chained configuration.
 * 
 * @param settings
 *            the proxy settings to evaluate.
 ************************************************************************/

private ProxySelector setupFixedProxySelector(Properties settings) {
    if (!hasProxySettings(settings)) {
        return null;
    }
    ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
    installHttpSelector(settings, ps);

    if (useForAllProtocols(settings)) {
        ps.setFallbackSelector(ps.getSelector("http"));
    } else {
        installSecureSelector(settings, ps);
        installFtpSelector(settings, ps);
        installSocksSelector(settings, ps);
    }
    return ps;
}
项目:smart-mirror-app    文件:OkHttpClient.java   
/**
 * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
 * each field that hasn't been explicitly configured.
 */
private OkHttpClient copyWithDefaults() {
  OkHttpClient result = new OkHttpClient(this);
  result.proxy = proxy;
  result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  result.sslSocketFactory = sslSocketFactory != null
      ? sslSocketFactory
      : HttpsURLConnection.getDefaultSSLSocketFactory();
  result.hostnameVerifier = hostnameVerifier != null
      ? hostnameVerifier
      : OkHostnameVerifier.INSTANCE;
  result.authenticator = authenticator != null
      ? authenticator
      : HttpAuthenticator.SYSTEM_DEFAULT;
  result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  result.followProtocolRedirects = followProtocolRedirects;
  result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  result.connectTimeout = connectTimeout;
  result.readTimeout = readTimeout;
  return result;
}
项目:proxy-vole    文件:OsxProxySearchStrategy.java   
/*************************************************************************
 * Build a selector from the given settings.
 * 
 * @param proxySettings
 *            to parse
 * @return the configured selector
 * @throws ProxyException
 *             on error
 ************************************************************************/

private ProxySelector buildSelector(Dict proxySettings) throws ProxyException {
    ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
    installSelectorForProtocol(proxySettings, ps, "HTTP");
    installSelectorForProtocol(proxySettings, ps, "HTTPS");
    installSelectorForProtocol(proxySettings, ps, "FTP");
    installSelectorForProtocol(proxySettings, ps, "Gopher");
    installSelectorForProtocol(proxySettings, ps, "RTSP");
    installSocksProxy(proxySettings, ps);

    ProxySelector result = ps;
    result = installPacProxyIfAvailable(proxySettings, result);
    result = autodetectProxyIfAvailable(proxySettings, result);

    if (result != null) {
        result = installExceptionList(proxySettings, result);
        result = installSimpleHostFilter(proxySettings, result);
    }
    return result;
}
项目:proxy-vole    文件:ProxySearch.java   
/*************************************************************************
 * Gets the proxy selector that will use the configured search order.
 * 
 * @return a ProxySelector, null if none was found for the current builder
 *         configuration.
 ************************************************************************/

@Override
public ProxySelector getProxySelector() {
    Logger.log(getClass(), LogLevel.TRACE, "Executing search strategies to find proxy selector");
    for (ProxySearchStrategy strat : this.strategies) {
        try {
            ProxySelector selector = strat.getProxySelector();
            if (selector != null) {
                selector = installBufferingAndFallbackBehaviour(selector);
                Logger.log(getClass(), LogLevel.INFO, "Proxy found for " + strat.getName());

                return selector;
            } else {
                Logger.log(getClass(), LogLevel.INFO,
                        "No proxy found for " + strat.getName() + ". Trying next one.");
            }
        } catch (ProxyException e) {
            Logger.log(getClass(), LogLevel.DEBUG, "Strategy {0} failed trying next one.", e);
            // Ignore and try next strategy.
        }
    }

    return null;
}
项目:lookaside_java-1.8.0-openjdk    文件:MultiThreadedSystemProxies.java   
public static void main(String[] args) throws Exception {
    System.setProperty("java.net.useSystemProxies", "true");
    final ProxySelector ps = ProxySelector.getDefault();
    final URI uri = new URI("http://ubuntu.com");
    Thread[] threads = new Thread[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i] = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ps.select(uri);
                } catch (Exception x) {
                    throw new RuntimeException(x);
                }
            }
        });
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].start();
    }
    for (int i = 0; i < NUM_THREADS; i++) {
        threads[i].join();
    }
}
项目:proxy-vole    文件:Examples.java   
public void example2() {
    ProxySearch proxySearch = new ProxySearch();

    if (PlatformUtil.getCurrentPlattform() == Platform.WIN) {
        proxySearch.addStrategy(Strategy.IE);
        proxySearch.addStrategy(Strategy.FIREFOX);
        proxySearch.addStrategy(Strategy.JAVA);
    } else if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) {
        proxySearch.addStrategy(Strategy.GNOME);
        proxySearch.addStrategy(Strategy.KDE);
        proxySearch.addStrategy(Strategy.FIREFOX);
    } else {
        proxySearch.addStrategy(Strategy.OS_DEFAULT);
    }

    ProxySelector myProxySelector = proxySearch.getProxySelector();

    ProxySelector.setDefault(myProxySelector);
}
项目:cordova-plugin-background-mode    文件:OkHttpClient.java   
/**
 * Returns a shallow copy of this OkHttpClient that uses the system-wide default for
 * each field that hasn't been explicitly configured.
 */
private OkHttpClient copyWithDefaults() {
  OkHttpClient result = new OkHttpClient(this);
  result.proxy = proxy;
  result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
  result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
  result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
  result.sslSocketFactory = sslSocketFactory != null
      ? sslSocketFactory
      : HttpsURLConnection.getDefaultSSLSocketFactory();
  result.hostnameVerifier = hostnameVerifier != null
      ? hostnameVerifier
      : OkHostnameVerifier.INSTANCE;
  result.authenticator = authenticator != null
      ? authenticator
      : HttpAuthenticator.SYSTEM_DEFAULT;
  result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
  result.followProtocolRedirects = followProtocolRedirects;
  result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
  result.connectTimeout = connectTimeout;
  result.readTimeout = readTimeout;
  return result;
}
项目:Reer    文件:HttpClientConfigurer.java   
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()));
}
项目:incubator-netbeans    文件:JGitSshSessionFactory.java   
@Override
protected Session createSession (Host hc, String user, String host, int port, FS fs) throws JSchException {
    Session session = super.createSession(hc, user, host, port, fs);
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(new URI("socket",
                null,
                host,
                port == -1 ? 22 : port,
                null, null, null));
        if (proxies.size() > 0) {
            Proxy p = proxies.iterator().next();
            if (p.type() == Proxy.Type.DIRECT) {
                session.setProxy(null);
            } else {
                SocketAddress addr = p.address();
                if (addr instanceof InetSocketAddress) {
                    InetSocketAddress inetAddr = (InetSocketAddress) addr;
                    String proxyHost = inetAddr.getHostName();
                    int proxyPort = inetAddr.getPort();
                    session.setProxy(createProxy(proxyHost, proxyPort));
                }
            }
        }
    } catch (URISyntaxException ex) {
        Logger.getLogger(JGitSshSessionFactory.class.getName()).log(Level.INFO, "Invalid URI: " + host + ":" + port, ex);
    }
    return session;
}
项目:incubator-netbeans    文件:SvnConfigFilesTest.java   
protected void setUp() throws Exception {
    super.setUp();
    System.setProperty("netbeans.user", System.getProperty("data.root.dir") + "/cache");

    if (defaultPS == null) {
        defaultPS = ProxySelector.getDefault();
    }

}
项目:incubator-netbeans    文件:CoreBridgeImpl.java   
/** Register NB specific property editors.
     *  Allows property editor unit tests to work correctly without 
     *  initializing full NetBeans environment.
     *  @since 1.98 */
    private static final void doRegisterPropertyEditors() {
        //issue 31879
//        if (editorsRegistered) return;
//        String[] syspesp = PropertyEditorManager.getEditorSearchPath();
//        String[] nbpesp = new String[] {
//            "org.netbeans.beaninfo.editors", // NOI18N
//            "org.openide.explorer.propertysheet.editors", // NOI18N
//        };
//        String[] allpesp = new String[syspesp.length + nbpesp.length];
//        System.arraycopy(nbpesp, 0, allpesp, 0, nbpesp.length);
//        System.arraycopy(syspesp, 0, allpesp, nbpesp.length, syspesp.length);
//        PropertyEditorManager.setEditorSearchPath(allpesp);
//        PropertyEditorManager.registerEditor (java.lang.Character.TYPE, org.netbeans.beaninfo.editors.CharEditor.class);
//        PropertyEditorManager.registerEditor(String[].class, org.netbeans.beaninfo.editors.StringArrayEditor.class); 
//        // use replacement hintable/internationalizable primitive editors - issues 20376, 5278
//        PropertyEditorManager.registerEditor (Integer.TYPE, org.netbeans.beaninfo.editors.IntEditor.class);
//        PropertyEditorManager.registerEditor (Boolean.TYPE, org.netbeans.beaninfo.editors.BoolEditor.class);

        NodeOp.registerPropertyEditors();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                NodeOp.registerPropertyEditors();
            }
        });

        ProxySelector selector = Lookup.getDefault().lookup(ProxySelector.class);
        if (selector != null) {
            // install java.net.ProxySelector
            ProxySelector.setDefault(selector);
        }

        editorsRegistered = true;
    }
项目:incubator-netbeans    文件:CanProxyToLocalhostTest.java   
@Override
protected void setUp() throws Exception {
    MY_PS.called = 0;
    selector = Lookup.getDefault().lookup(ProxySelector.class);
    if (selector != null) {
        // install java.net.ProxySelector
        ProxySelector.setDefault(selector);
    }
    TO_LOCALHOST = new URI("http://localhost");
    TO_NB = new URI("http://netbeans.org");
}
项目:incubator-netbeans    文件:NonProxyHostsTest.java   
@Override
protected void setUp () throws Exception {
    super.setUp ();
    System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
    System.setProperty ("netbeans.system_socks_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
    System.setProperty ("netbeans.system_http_non_proxy_hosts", "*.other.org");
    System.setProperty ("http.nonProxyHosts", "*.netbeans.org");
    selector = ProxySelector.getDefault ();
    proxyPreferences  = NbPreferences.root ().node ("/org/netbeans/core");
    proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener () {
        public void preferenceChange (PreferenceChangeEvent arg0) {
            isWaiting = false;
        }
    });
    proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST);
    proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
    proxyPreferences.put ("proxySocksHost", USER_PROXY_HOST);
    proxyPreferences.put ("proxySocksPort", USER_PROXY_PORT);
    while (isWaiting);
    isWaiting = true;
    TO_LOCALHOST = new URI ("http://localhost");
    TO_LOCAL_DOMAIN_1 = new URI ("http://core.netbeans.org");
    TO_LOCAL_DOMAIN_2 = new URI ("http://core.other.org");
    TO_EXTERNAL = new URI ("http://worldwide.net");

    SOCKS_TO_LOCALHOST = new URI ("socket://localhost:8041");
    SOCKS_TO_LOCAL_DOMAIN_1 = new URI ("socket://core.netbeans.org");
    SOCKS_TO_LOCAL_DOMAIN_2 = new URI ("socket://core.other.org");
    SOCKS_TO_EXTERNAL = new URI ("socket://worldwide.net");
}
项目:AndroidVideoCache    文件:ProxyCacheTestUtils.java   
public static void installExternalSystemProxy() {
    // see proxies list at http://proxylist.hidemyass.com/
    Proxy systemProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("162.8.230.7", 11180));
    ProxySelector mockedProxySelector = Mockito.mock(ProxySelector.class);
    when(mockedProxySelector.select(Mockito.<URI>any())).thenReturn(Lists.newArrayList(systemProxy));
    ProxySelector.setDefault(mockedProxySelector);
}
项目:AndroidVideoCache    文件:Pinger.java   
private List<Proxy> getDefaultProxies() {
    try {
        ProxySelector defaultProxySelector = ProxySelector.getDefault();
        return defaultProxySelector.select(new URI(getPingUrl()));
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    }
}
项目:owa-notifier    文件:RestfullAcessProxy.java   
/**
 * Return a proxy if exist
 * @return
 *  null if no proxy, the InetSocketAddress else of proxy
 */
public static InetSocketAddress findProxy() {
    logger.info("detecting proxies");
    ProxySearch ps = ProxySearch.getDefaultProxySearch();
    ProxySelector myProxySelector = ps.getProxySelector(); 
    ProxySelector.setDefault(myProxySelector);


    List<Proxy> l = null;
    if(myProxySelector == null) {
        logger.info("No Proxy");
        return null;
    }
    try {
        l = myProxySelector.select(new URI("https://graph.microsoft.com"));
    }  
    catch (URISyntaxException e) {
        e.printStackTrace();
    }
    if (l != null) {
        for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
            java.net.Proxy proxy = (java.net.Proxy) iter.next();
            logger.info("proxy type: " + proxy.type());

            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            if (addr == null) {
                logger.info("No Proxy");
                return null;
            } 
            logger.info("Hostname: " + addr.getHostName());
            logger.info("Port : " + addr.getPort());
            return addr;
        }
    }
    logger.info("No Proxy");
    return null;
}
项目:Cybernet-VPN    文件:ProxyDetection.java   
static Proxy getFirstProxy(URL url) throws URISyntaxException {
    System.setProperty("java.net.useSystemProxies", "true");
    List<Proxy> proxylist = ProxySelector.getDefault().select(url.toURI());
    if (proxylist != null) {
        for (Proxy proxy : proxylist) {
            SocketAddress addr = proxy.address();
            if (addr != null) {
                return proxy;
            }
        }
    }
    return null;
}
项目:lams    文件:ProxySelectorRoutePlanner.java   
/**
 * Creates a new proxy selector route planner.
 *
 * @param schreg    the scheme registry
 * @param prosel    the proxy selector, or
 *                  <code>null</code> for the system default
 */
public ProxySelectorRoutePlanner(SchemeRegistry schreg,
                                 ProxySelector prosel) {

    if (schreg == null) {
        throw new IllegalArgumentException
            ("SchemeRegistry must not be null.");
    }
    schemeRegistry = schreg;
    proxySelector  = prosel;
}
项目:encdroidMC    文件:SardineImpl.java   
/**
 * Creates an AbstractHttpClient with all of the defaults.
 */
protected AbstractHttpClient createDefaultClient(ProxySelector selector) {
    SchemeRegistry schemeRegistry = this.createDefaultSchemeRegistry();
    ClientConnectionManager cm = this
            .createDefaultConnectionManager(schemeRegistry);
    HttpParams params = this.createDefaultHttpParams();
    AbstractHttpClient client = new DefaultHttpClient(cm, params);
    client.setRoutePlanner(this.createDefaultRoutePlanner(schemeRegistry,
            selector));
    return client;
}