java.net.ProxySelector Java Examples

The following examples show how to use java.net.ProxySelector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiThreadedSystemProxies.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #2
Source File: MultiThreadedSystemProxies.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #3
Source File: ProxyDetectorImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  proxySelectorSupplier = new Supplier<ProxySelector>() {
    @Override
    public ProxySelector get() {
      return proxySelector;
    }
  };
  proxyDetector = new ProxyDetectorImpl(proxySelectorSupplier, authenticator, null);
  int proxyPort = 1234;
  unresolvedProxy = InetSocketAddress.createUnresolved("10.0.0.1", proxyPort);
  proxyParmeters = new ProxyParameters(
      new InetSocketAddress(InetAddress.getByName(unresolvedProxy.getHostName()), proxyPort),
      NO_USER,
      NO_PW);
}
 
Example #4
Source File: Env.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: EndpointAddress.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: ProxyDetection.java    From SimpleOpenVpn-Android with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: EndpointAddress.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: MultiThreadedSystemProxies.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #9
Source File: EndpointAddress.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: AbstractGoogleClientFactory.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Replicates {@link ApacheHttpTransport#newDefaultHttpClient()} with one exception:
 *
 * 1 retry is allowed.
 *
 * @see DefaultHttpRequestRetryHandler
 */
DefaultHttpClient newDefaultHttpClient(
    SSLSocketFactory socketFactory, HttpParams params, ProxySelector proxySelector) {
  SchemeRegistry registry = new SchemeRegistry();
  registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  registry.register(new Scheme("https", socketFactory, 443));
  ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
  DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
  // retry only once
  defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));
  if (proxySelector != null) {
    defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));
  }
  defaultHttpClient.setKeepAliveStrategy((response, context) -> KEEP_ALIVE_DURATION);
  return defaultHttpClient;
}
 
Example #11
Source File: MultiThreadedSystemProxies.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #12
Source File: EndpointAddress.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: GitTest.java    From steady with Apache License 2.0 6 votes vote down vote up
private void setupProxy() {

		final String phost = System.getProperty("http.proxyHost");
		final String pport = System.getProperty("http.proxyPort");

		try {
			if (phost != null && pport != null) {
				System.err.println("Using proxy " + phost + ":" + pport);
				ProxySelector.setDefault(new MyProxySelector(new Proxy(
						Proxy.Type.HTTP, new InetSocketAddress(phost, Integer
								.parseInt(pport)))));
			} else {
				System.err.printf("No proxy specified, connecting directly.");
			}
		} catch (Exception e) {
			System.err.println("Error setting proxy");
			e.printStackTrace();
		}

	}
 
Example #14
Source File: EndpointAddress.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: CoreBridgeImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** 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;
    }
 
Example #16
Source File: NbProxySelector.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of NbProxySelector */
public NbProxySelector () {
    original = ProxySelector.getDefault ();
    if (original == null) {
        log.warning ("No default system ProxySelector was found thus NetBeans ProxySelector won't delegate on it");
    } else {
        log.fine ("Override the original ProxySelector: " + original);
    }
    log.fine ("java.net.useSystemProxies has been set to " + useSystemProxies ());
    log.fine ("In launcher was detected netbeans.system_http_proxy: " + System.getProperty ("netbeans.system_http_proxy", "N/A"));
    log.fine ("In launcher was detected netbeans.system_socks_proxy: " + System.getProperty ("netbeans.system_socks_proxy", "N/A"));
    ProxySettings.addPreferenceChangeListener (new ProxySettingsListener ());
    copySettingsToSystem ();
}
 
Example #17
Source File: NonProxyHostsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #18
Source File: CanProxyToLocalhostTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example #19
Source File: BadProxySelector.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ProxySelector.setDefault(new HTTPProxySelector());
    try (ServerSocket ss = new ServerSocket(0);
         Socket s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
         Socket s2 = ss.accept()) {
    }

   ProxySelector.setDefault(new NullHTTPProxySelector());
    try (ServerSocket ss = new ServerSocket(0);
         Socket s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
         Socket s2 = ss.accept()) {
    }
}
 
Example #20
Source File: B8035158.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void run() {
    System.out.printf("urlhost=%s properties=%s: proxied? %s%n",
            urlhost, localProperties, expectedProxying);

    List<Proxy> proxies = withSystemPropertiesSet(localProperties,
            () -> ProxySelector.getDefault().select(
                    URI.create(urlhost))
    );

    verify(proxies);
}
 
Example #21
Source File: BadProxySelector.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ProxySelector.setDefault(new HTTPProxySelector());
    try (ServerSocket ss = new ServerSocket(0);
         Socket s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
         Socket s2 = ss.accept()) {
    }

   ProxySelector.setDefault(new NullHTTPProxySelector());
    try (ServerSocket ss = new ServerSocket(0);
         Socket s1 = new Socket(ss.getInetAddress(), ss.getLocalPort());
         Socket s2 = ss.accept()) {
    }
}
 
Example #22
Source File: B6563259.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.setProperty("http.proxyHost", "myproxy");
    System.setProperty("http.proxyPort", "8080");
    System.setProperty("http.nonProxyHosts", "host1.*");
    ProxySelector sel = ProxySelector.getDefault();
    java.util.List<Proxy> l = sel.select(new URI("http://HOST1.sun.com/"));
    if (l.get(0) != Proxy.NO_PROXY) {
        throw new RuntimeException("ProxySelector returned the wrong proxy");
    }
}
 
Example #23
Source File: ProxyDetectorImpl.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ProxyDetectorImpl(
    Supplier<ProxySelector> proxySelector,
    AuthenticationProvider authenticationProvider,
    @Nullable String proxyEnvString) {
  this.proxySelector = checkNotNull(proxySelector);
  this.authenticationProvider = checkNotNull(authenticationProvider);
  if (proxyEnvString != null) {
    override = new ProxyParameters(overrideProxy(proxyEnvString), null, null);
  } else {
    override = null;
  }
}
 
Example #24
Source File: Pinger.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
private List<Proxy> getDefaultProxies() {
    try {
        ProxySelector defaultProxySelector = ProxySelector.getDefault();
        return defaultProxySelector.select(new URI(getPingUrl()));
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #25
Source File: RSSocketFactory.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
RSSocketFactory() {
	try {
		this.proxySelector = ProxySelector.getDefault();
	} catch (RuntimeException var2) {
		throw GenUtil.makeThrowable(var2, "gb.<init>()");
	}
}
 
Example #26
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieve Proxy Selector
 *
 * @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;
}
 
Example #27
Source File: HttpRequestImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
InetSocketAddress proxy(HttpClientImpl client) {
    ProxySelector ps = client.proxy().orElse(null);
    if (ps == null) {
        ps = client.proxy().orElse(null);
    }
    if (ps == null || method.equalsIgnoreCase("CONNECT")) {
        return null;
    }
    return (InetSocketAddress)ps.select(uri).get(0).address();
}
 
Example #28
Source File: Pinger.java    From AndriodVideoCache with Apache License 2.0 5 votes vote down vote up
private List<Proxy> getDefaultProxies() {
    try {
        ProxySelector defaultProxySelector = ProxySelector.getDefault();
        return defaultProxySelector.select(new URI(getPingUrl()));
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #29
Source File: B8035158.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
void run() {
    System.out.printf("urlhost=%s properties=%s: proxied? %s%n",
            urlhost, localProperties, expectedProxying);

    List<Proxy> proxies = withSystemPropertiesSet(localProperties,
            () -> ProxySelector.getDefault().select(
                    URI.create(urlhost))
    );

    verify(proxies);
}
 
Example #30
Source File: B6563259.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.setProperty("http.proxyHost", "myproxy");
    System.setProperty("http.proxyPort", "8080");
    System.setProperty("http.nonProxyHosts", "host1.*");
    ProxySelector sel = ProxySelector.getDefault();
    java.util.List<Proxy> l = sel.select(new URI("http://HOST1.sun.com/"));
    if (l.get(0) != Proxy.NO_PROXY) {
        throw new RuntimeException("ProxySelector returned the wrong proxy");
    }
}