Java Code Examples for java.net.ProxySelector

The following are top voted examples for showing how to use java.net.ProxySelector. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: Address.java   Source Code and License 9 votes vote down vote up
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;
}
 
Example 2
Project: boohee_v5.6   File: OkHttpClient.java   Source Code and License 9 votes vote down vote up
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;
}
 
Example 3
Project: GitHub   File: Address.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 4
Project: LoRaWAN-Smart-Parking   File: OkHttpClient.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 5
Project: LoRaWAN-Smart-Parking   File: OkHttpClient.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 6
Project: incubator-netbeans   File: URLResourceRetriever.java   Source Code and License 6 votes vote down vote up
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;
    
}
 
Example 7
Project: incubator-netbeans   File: DockerAction.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 8
Project: incubator-netbeans   File: ExceptionHandlerTest.java   Source Code and License 6 votes vote down vote up
@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();
    }
}
 
Example 9
Project: AndroidVideoCache   File: ProxySelectorTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 10
Project: OpenJSharp   File: EndpointAddress.java   Source Code and License 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 11
Project: jdk8u-jdk   File: MultiThreadedSystemProxies.java   Source Code and License 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
Project: openvisualtraceroute   File: Env.java   Source Code and License 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 13
Project: openjdk-jdk10   File: MultiThreadedSystemProxies.java   Source Code and License 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 14
Project: openjdk-jdk10   File: EndpointAddress.java   Source Code and License 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
Project: client-java-rest-core   File: AuthClientFactory.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Project: proxy-vole   File: JavaProxySearchStrategy.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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;
}
 
Example 17
Project: proxy-vole   File: JavaProxySearchStrategy.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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);
}
 
Example 18
Project: EasyVPN-Free   File: ProxyDetection.java   Source Code and License 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 19
Project: proxy-vole   File: WpadProxySearchStrategyWithDHPC.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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);
	}
}
 
Example 20
Project: proxy-vole   File: WpadProxySearchStrategy.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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);
  }
}
 
Example 21
Project: proxy-vole   File: GnomeProxySearchStrategy.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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;
}
 
Example 22
Project: proxy-vole   File: GnomeDConfProxySearchStrategy.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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;
}
 
Example 23
Project: smart-mirror-app   File: OkHttpClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 24
Project: proxy-vole   File: OsxProxySearchStrategy.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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;
}
 
Example 25
Project: proxy-vole   File: ProxySearch.java   Source Code and License 6 votes vote down vote up
/*************************************************************************
 * 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;
}
 
Example 26
Project: lookaside_java-1.8.0-openjdk   File: MultiThreadedSystemProxies.java   Source Code and License 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 27
Project: proxy-vole   File: Examples.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 28
Project: cordova-plugin-background-mode   File: OkHttpClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 29
Project: Reer   File: HttpClientConfigurer.java   Source Code and License 5 votes vote down vote up
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()));
}
 
Example 30
Project: incubator-netbeans   File: JGitSshSessionFactory.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 31
Project: incubator-netbeans   File: SvnConfigFilesTest.java   Source Code and License 5 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();
    System.setProperty("netbeans.user", System.getProperty("data.root.dir") + "/cache");
    
    if (defaultPS == null) {
        defaultPS = ProxySelector.getDefault();
    }
    
}
 
Example 32
Project: incubator-netbeans   File: CoreBridgeImpl.java   Source Code and License 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 33
Project: incubator-netbeans   File: CanProxyToLocalhostTest.java   Source Code and License 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 34
Project: incubator-netbeans   File: NonProxyHostsTest.java   Source Code and License 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 35
Project: AndroidVideoCache   File: ProxyCacheTestUtils.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 36
Project: AndroidVideoCache   File: Pinger.java   Source Code and License 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 37
Project: owa-notifier   File: RestfullAcessProxy.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 38
Project: Cybernet-VPN   File: ProxyDetection.java   Source Code and License 5 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 39
Project: lams   File: ProxySelectorRoutePlanner.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 40
Project: encdroidMC   File: SardineImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 41
Project: boohee_v5.6   File: Address.java   Source Code and License 5 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
               SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
               CertificatePinner certificatePinner, Authenticator authenticator, Proxy proxy,
               List<Protocol> protocols, List<ConnectionSpec> connectionSpecs, ProxySelector
                       proxySelector) {
    this.url = new Builder().scheme(sslSocketFactory != null ? b.a : "http").host(uriHost)
            .port(uriPort).build();
    if (dns == null) {
        throw new IllegalArgumentException("dns == null");
    }
    this.dns = dns;
    if (socketFactory == null) {
        throw new IllegalArgumentException("socketFactory == null");
    }
    this.socketFactory = socketFactory;
    if (authenticator == null) {
        throw new IllegalArgumentException("authenticator == null");
    }
    this.authenticator = authenticator;
    if (protocols == null) {
        throw new IllegalArgumentException("protocols == null");
    }
    this.protocols = Util.immutableList((List) protocols);
    if (connectionSpecs == null) {
        throw new IllegalArgumentException("connectionSpecs == null");
    }
    this.connectionSpecs = Util.immutableList((List) connectionSpecs);
    if (proxySelector == null) {
        throw new IllegalArgumentException("proxySelector == null");
    }
    this.proxySelector = proxySelector;
    this.proxy = proxy;
    this.sslSocketFactory = sslSocketFactory;
    this.hostnameVerifier = hostnameVerifier;
    this.certificatePinner = certificatePinner;
}
 
Example 42
Project: LoRaWAN-Smart-Parking   File: RouteSelector.java   Source Code and License 5 votes vote down vote up
public RouteSelector(Address address, URI uri, ProxySelector proxySelector, ConnectionPool pool,
    Dns dns, RouteDatabase routeDatabase) {
  this.address = address;
  this.uri = uri;
  this.proxySelector = proxySelector;
  this.pool = pool;
  this.dns = dns;
  this.routeDatabase = routeDatabase;
  this.postponedRoutes = new LinkedList<Route>();

  resetNextProxy(uri, address.getProxy());
}
 
Example 43
Project: LoRaWAN-Smart-Parking   File: RouteSelector.java   Source Code and License 5 votes vote down vote up
public RouteSelector(Address address, URI uri, ProxySelector proxySelector, ConnectionPool pool,
    Dns dns, RouteDatabase routeDatabase) {
  this.address = address;
  this.uri = uri;
  this.proxySelector = proxySelector;
  this.pool = pool;
  this.dns = dns;
  this.routeDatabase = routeDatabase;
  this.postponedRoutes = new LinkedList<Route>();

  resetNextProxy(uri, address.getProxy());
}
 
Example 44
Project: jdk8u-jdk   File: BadProxySelector.java   Source Code and License 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 45
Project: jdk8u-jdk   File: B8035158.java   Source Code and License 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 46
Project: jdk8u-jdk   File: B6563259.java   Source Code and License 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 47
Project: openjdk-jdk10   File: HttpRequestImpl.java   Source Code and License 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 48
Project: openjdk-jdk10   File: Security.java   Source Code and License 5 votes vote down vote up
private static void directProxyTest(int proxyPort, boolean samePort)
    throws IOException, InterruptedException
{
    Object proxy = null;
    try {
        proxy = getProxy(proxyPort, true);
    } catch (BindException e) {
        System.out.println("Bind failed");
        throw e;
    } catch (Throwable ee) {
        throw new RuntimeException(ee);
    }
    System.out.println("Proxy port = " + proxyPort);
    if (!samePort)
        proxyPort++;

    InetSocketAddress addr = new InetSocketAddress("127.0.0.1", proxyPort);
    HttpClient cl = HttpClient.newBuilder()
                                .proxy(ProxySelector.of(addr))
                                .build();
    clients.add(cl);

    URI u = URI.create("http://127.0.0.1:" + port + "/files/foo.txt");
    HttpRequest request = HttpRequest.newBuilder(u)
                                     .headers("X-Foo", "bar", "X-Bar", "foo")
                                     .build();
    HttpResponse<?> response = cl.send(request, asString());
}
 
Example 49
Project: openjdk-jdk10   File: WebSocketExample.java   Source Code and License 5 votes vote down vote up
public void newBuilderExample1() {
    InetSocketAddress addr = new InetSocketAddress("proxy.example.com", 80);
    HttpClient client = HttpClient.newBuilder()
            .proxy(ProxySelector.of(addr))
            .build();
    WebSocket.Builder builder = client.newWebSocketBuilder(
            URI.create("ws://websocket.example.com"),
            listener);
}
 
Example 50
Project: openjdk-jdk10   File: APIErrors.java   Source Code and License 5 votes vote down vote up
static void test2() throws Exception {
    System.out.println("Test 2");
    HttpClient.Builder cb = HttpClient.newBuilder();
    InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 5000);
    cb.proxy(ProxySelector.of(addr));
    HttpClient c = cb.build();
    clients.add(c);
    checkNonNull(()-> c.executor());
    assertTrue(()-> c.followRedirects() == HttpClient.Redirect.NEVER);
    assertTrue(()-> !c.authenticator().isPresent());
}
 
Example 51
Project: openjdk-jdk10   File: ProxyTest2.java   Source Code and License 5 votes vote down vote up
public static void test(Http2TestServer server, HttpClient.Version version)
        throws Exception
{
    System.out.println("Server is: " + server.getAddress().toString());
    URI uri = new URI("https://localhost:" + server.getAddress().getPort() + PATH + "x");
    TunnelingProxy proxy = new TunnelingProxy(server);
    proxy.start();
    try {
        System.out.println("Proxy started");
        Proxy p = new Proxy(Proxy.Type.HTTP,
                InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort()));
        System.out.println("Setting up request with HttpClient for version: "
                + version.name() + "URI=" + uri);
        ProxySelector ps = ProxySelector.of(
                InetSocketAddress.createUnresolved("localhost", proxy.getAddress().getPort()));
        HttpClient client = HttpClient.newBuilder()
            .version(version)
            .proxy(ps)
            .build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(uri)
            .GET()
            .build();

        System.out.println("Sending request with HttpClient");
        HttpResponse<String> response
            = client.send(request, HttpResponse.BodyHandler.asString());
        System.out.println("Got response");
        String resp = response.body();
        System.out.println("Received: " + resp);
        if (!RESPONSE.equals(resp)) {
            throw new AssertionError("Unexpected response");
        }
    } finally {
        System.out.println("Stopping proxy");
        proxy.stop();
        System.out.println("Proxy stopped");
    }
}
 
Example 52
Project: openjdk-jdk10   File: ProxyAuthTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (ServerSocket ss = new ServerSocket(0)) {
        int port = ss.getLocalPort();
        MyProxy proxy = new MyProxy(ss);
        (new Thread(proxy)).start();
        System.out.println("Proxy listening port " + port);

        Auth auth = new Auth();
        InetSocketAddress paddr = new InetSocketAddress("localhost", port);

        URI uri = new URI("http://www.google.ie/");
        HttpClient client = HttpClient.newBuilder()
                                      .proxy(ProxySelector.of(paddr))
                                      .authenticator(auth)
                                      .build();
        HttpRequest req = HttpRequest.newBuilder(uri).GET().build();
        HttpResponse<?> resp = client.sendAsync(req, discard(null)).get();
        if (resp.statusCode() != 404) {
            throw new RuntimeException("Unexpected status code: " + resp.statusCode());
        }

        if (auth.isCalled) {
            System.out.println("Authenticator is called");
        } else {
            throw new RuntimeException("Authenticator is not called");
        }

        if (!proxy.matched) {
            throw new RuntimeException("Proxy authentication failed");
        }
    }
}
 
Example 53
Project: openjdk-jdk10   File: BadProxySelector.java   Source Code and License 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 54
Project: openjdk-jdk10   File: B8035158.java   Source Code and License 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 55
Project: openjdk-jdk10   File: B6563259.java   Source Code and License 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 56
Project: openjdk-jdk10   File: NoProxyTest.java   Source Code and License 5 votes vote down vote up
public static void main(String args[]) throws MalformedURLException {
    ProxySelector.setDefault(new NoProxyTestSelector());

    URL url = URI.create("http://127.0.0.1/").toURL();
    URLConnection connection;
    try {
        connection = url.openConnection(Proxy.NO_PROXY);
        connection.connect();
    } catch (IOException ignore) {
        //ignore
    }
}
 
Example 57
Project: geomapapp   File: Tile512Overlay.java   Source Code and License 5 votes vote down vote up
private static BufferedImage readHTTPImage(URI uri,
		HostConfiguration hostConfiguration, HttpClient client,
		ConnectionWrapper wrapper) {
	List<Proxy> list = ProxySelector.getDefault().select(uri);
	for (Proxy p : list)
	{
		InetSocketAddress addr = (InetSocketAddress) p.address();
		
		if (addr == null)
			hostConfiguration.setProxyHost(null);
		else
			hostConfiguration.setProxy(addr.getHostName(), addr.getPort());
		
		try {
			HttpMethod method = new GetMethod(uri.toString());
			synchronized (wrapper) {
				wrapper.connection = method;
			}
			
			int sc = client.executeMethod(hostConfiguration, method);
			
			if (sc != HttpStatus.SC_OK) {
				continue;
			}
			
			// Check Content Type
			Header h = method.getResponseHeader("Content-Type");
			if (h == null || !h.getValue().contains("image")) 
				continue;
			
			return ImageIO.read( method.getResponseBodyAsStream() );
		} catch (IOException ex) {
			continue;
		}
	}
	return null;
}
 
Example 58
Project: openjdk9   File: HttpRequestImpl.java   Source Code and License 5 votes vote down vote up
InetSocketAddress proxy() {
    ProxySelector ps = this.proxy;
    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 59
Project: openjdk9   File: B8035158.java   Source Code and License 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 60
Project: java-triton   File: CloudApiConnectionFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the host of the proxy server that was configured as part of the
 * JVM settings.
 *
 * @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.getCloudAPIURL()));

    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;
    }
}