Java Code Examples for java.net.Proxy#address()

The following examples show how to use java.net.Proxy#address() . 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: RouteSelector.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/** Resets {@link #nextInetSocketAddress} to the first option. */
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
  socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!

  String socketHost;
  if (proxy.type() == Proxy.Type.DIRECT) {
    socketHost = uri.getHost();
    socketPort = getEffectivePort(uri);
  } else {
    SocketAddress proxyAddress = proxy.address();
    if (!(proxyAddress instanceof InetSocketAddress)) {
      throw new IllegalArgumentException(
          "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
    }
    InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
    socketHost = proxySocketAddress.getHostName();
    socketPort = proxySocketAddress.getPort();
  }

  // Try each address for best behavior in mixed IPv4/IPv6 environments.
  socketAddresses = dns.getAllByName(socketHost);
  nextSocketAddressIndex = 0;
}
 
Example 2
Source File: HttpAuthenticator.java    From phonegapbootcampsite with MIT License 6 votes vote down vote up
@Override public Credential authenticateProxy(
    Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
  for (Challenge challenge : challenges) {
    if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
      continue;
    }

    InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
    PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
        proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
        url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
        Authenticator.RequestorType.PROXY);
    if (auth != null) {
      return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
    }
  }
  return null;
}
 
Example 3
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private void configureProxy(ClientConfig clientConfig, URI originalUri, String protocol) {
    List<Proxy> proxies = ProxySelector.getDefault().select(originalUri);

    for (Proxy proxy : proxies) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        if (address != null) {
            String hostname = address.getHostName();
            int port = address.getPort();

            clientConfig.property(ClientProperties.PROXY_URI, "http://" + hostname + ":" + port);

            String httpProxyUser = System.getProperty(protocol + ".proxyUser");
            if (httpProxyUser != null) {
                clientConfig.property(ClientProperties.PROXY_USERNAME, httpProxyUser);
                String httpProxyPassword = System.getProperty(protocol + ".proxyPassword");
                if (httpProxyPassword != null) {
                    clientConfig.property(ClientProperties.PROXY_PASSWORD, httpProxyPassword);
                }
            }
        }
    }
}
 
Example 4
Source File: RouteSelector.java    From cordova-android-chromeview with Apache License 2.0 6 votes vote down vote up
/** Resets {@link #nextInetSocketAddress} to the first option. */
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
  socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!

  String socketHost;
  if (proxy.type() == Proxy.Type.DIRECT) {
    socketHost = uri.getHost();
    socketPort = getEffectivePort(uri);
  } else {
    SocketAddress proxyAddress = proxy.address();
    if (!(proxyAddress instanceof InetSocketAddress)) {
      throw new IllegalArgumentException(
          "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
    }
    InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
    socketHost = proxySocketAddress.getHostName();
    socketPort = proxySocketAddress.getPort();
  }

  // Try each address for best behavior in mixed IPv4/IPv6 environments.
  socketAddresses = dns.getAllByName(socketHost);
  nextSocketAddressIndex = 0;
}
 
Example 5
Source File: RouteSelector.java    From phonegap-plugin-loading-spinner with Apache License 2.0 6 votes vote down vote up
/** Resets {@link #nextInetSocketAddress} to the first option. */
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
  socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!

  String socketHost;
  if (proxy.type() == Proxy.Type.DIRECT) {
    socketHost = uri.getHost();
    socketPort = getEffectivePort(uri);
  } else {
    SocketAddress proxyAddress = proxy.address();
    if (!(proxyAddress instanceof InetSocketAddress)) {
      throw new IllegalArgumentException(
          "Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
    }
    InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
    socketHost = proxySocketAddress.getHostName();
    socketPort = proxySocketAddress.getPort();
  }

  // Try each address for best behavior in mixed IPv4/IPv6 environments.
  socketAddresses = dns.getAllByName(socketHost);
  nextSocketAddressIndex = 0;
}
 
Example 6
Source File: HttpAuthenticator.java    From wildfly-samples with MIT License 6 votes vote down vote up
@Override public Credential authenticateProxy(
    Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
  for (Challenge challenge : challenges) {
    if (!"Basic".equalsIgnoreCase(challenge.getScheme())) {
      continue;
    }

    InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
    PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(
        proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(),
        url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url,
        Authenticator.RequestorType.PROXY);
    if (auth != null) {
      return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
    }
  }
  return null;
}
 
Example 7
Source File: ProxyFactoryBeanTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void normal() {
	Proxy.Type type = Proxy.Type.HTTP;
	factoryBean.setType(type);
	String hostname = "example.com";
	factoryBean.setHostname(hostname);
	int port = 8080;
	factoryBean.setPort(port);
	factoryBean.afterPropertiesSet();

	Proxy result = factoryBean.getObject();

	assertEquals(type, result.type());
	InetSocketAddress address = (InetSocketAddress) result.address();
	assertEquals(hostname, address.getHostName());
	assertEquals(port, address.getPort());
}
 
Example 8
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 9
Source File: HttpAsyncDownloaderBuilder.java    From JMCCC with MIT License 5 votes vote down vote up
private static HttpHost resolveProxy(Proxy proxy) {
	if (proxy.type() == Proxy.Type.DIRECT) {
		return null;
	}
	if (proxy.type() == Proxy.Type.HTTP) {
		SocketAddress socketAddress = proxy.address();
		if (socketAddress instanceof InetSocketAddress) {
			InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
			return new HttpHost(inetSocketAddress.getAddress(), inetSocketAddress.getPort());
		}
	}
	throw new IllegalArgumentException("Proxy '" + proxy + "' is not supported");
}
 
Example 10
Source File: HttpAuthenticator.java    From phonegap-plugin-loading-spinner with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the authorization credentials that may satisfy the challenge.
 * Returns null if a challenge header was not provided or if credentials
 * were not available.
 */
private static String getCredentials(RawHeaders responseHeaders, String challengeHeader,
    Proxy proxy, URL url) throws IOException {
  List<Challenge> challenges = parseChallenges(responseHeaders, challengeHeader);
  if (challenges.isEmpty()) {
    return null;
  }

  for (Challenge challenge : challenges) {
    // Use the global authenticator to get the password.
    PasswordAuthentication auth;
    if (responseHeaders.getResponseCode() == HTTP_PROXY_AUTH) {
      InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
      auth = Authenticator.requestPasswordAuthentication(proxyAddress.getHostName(),
          getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.getProtocol(),
          challenge.realm, challenge.scheme, url, Authenticator.RequestorType.PROXY);
    } else {
      auth = Authenticator.requestPasswordAuthentication(url.getHost(),
          getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(), challenge.realm,
          challenge.scheme, url, Authenticator.RequestorType.SERVER);
    }
    if (auth == null) {
      continue;
    }

    // Use base64 to encode the username and password.
    String usernameAndPassword = auth.getUserName() + ":" + new String(auth.getPassword());
    byte[] bytes = usernameAndPassword.getBytes("ISO-8859-1");
    String encoded = Base64.encode(bytes);
    return challenge.scheme + " " + encoded;
  }

  return null;
}
 
Example 11
Source File: ResteasyGitLabClientBuilder.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private GitLabClient buildClient(String url, String apiToken, ProxyConfiguration httpProxyConfig, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) {
    ResteasyClientBuilder builder = new ResteasyClientBuilder();

    if (ignoreCertificateErrors) {
        builder.hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.ANY);
        builder.disableTrustManager();
    }

    if (httpProxyConfig != null) {
        Proxy proxy = httpProxyConfig.createProxy(getHost(url));
        if (proxy.type() == HTTP) {
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            builder.defaultProxy(address.getHostString().replaceFirst("^.*://", ""),
                address.getPort(),
                address.getHostName().startsWith("https") ? "https" : "http",
                httpProxyConfig.getUserName(),
                httpProxyConfig.getPassword());
        }
    }

    GitLabApiProxy apiProxy = builder
        .connectionPoolSize(60)
        .maxPooledPerRoute(30)
        .establishConnectionTimeout(connectionTimeout, TimeUnit.SECONDS)
        .socketTimeout(readTimeout, TimeUnit.SECONDS)
        .register(new JacksonJsonProvider())
        .register(new JacksonConfig())
        .register(new ApiHeaderTokenFilter(apiToken))
        .register(new LoggingFilter())
        .register(new RemoveAcceptEncodingFilter())
        .register(new JaxrsFormProvider())
        .build().target(url)
        .proxyBuilder(apiProxyClass)
        .classloader(apiProxyClass.getClassLoader())
        .build();

    return new ResteasyGitLabClient(url, apiProxy, mergeRequestIdProvider);
}
 
Example 12
Source File: HttpAuthenticator.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
public Credential authenticateProxy(Proxy proxy, URL url, List<Challenge> challenges) throws IOException {
    for (Challenge challenge : challenges) {
        if (!"Basic".equals(challenge.getScheme())) {
            continue;
        }

        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.PROXY);
        if (auth != null) {
            return Credential.basic(auth.getUserName(), new String(auth.getPassword()));
        }
    }
    return null;
}
 
Example 13
Source File: PreemptiveAuthHttpClientConnection.java    From git-client-plugin with MIT License 5 votes vote down vote up
private static void configureProxy(final HttpClientBuilder builder, final Proxy proxy) {
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        final SocketAddress socketAddress = proxy.address();
        if (socketAddress instanceof InetSocketAddress) {
            final InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
            final String proxyHost = inetSocketAddress.getHostName();
            final int proxyPort = inetSocketAddress.getPort();
            final HttpHost httpHost = new HttpHost(proxyHost, proxyPort);
            builder.setProxy(httpHost);
        }
    }
}
 
Example 14
Source File: ProxySettings.java    From OCR-Equation-Solver with MIT License 4 votes vote down vote up
public synchronized String[] getProxyHostAndPort(String url) {

        int port = 0;
        String host = null;

        if (useProxy == PROXY_AUTOMATIC) {
            ProxySelector ps = ProxySelector.getDefault(); // Will get MyProxySelector.
            try {
                URI uri = new URI(url);
                List<Proxy> proxyList = ps.select(uri);
                int len = proxyList.size();
                for (int i = 0; i < len; i++) {
                    Proxy p = (Proxy) proxyList.get (i);
                    InetSocketAddress addr = (InetSocketAddress) p.address();
                    if (addr != null) {
                        host = addr.getHostName();
                        port = addr.getPort();
                        break;
                    }
                }
            } catch (Exception e) {
                // TODO: Handle?
            }
        } else if (useProxy == PROXY_MANUAL) {
            String protocol;
            int colonPos = url.indexOf(':');
            if (colonPos != -1) {
                protocol = url.substring(0, colonPos).toLowerCase();
            } else {
                // Shouldn't happen, but might as well do something and let it fail later.
                protocol = "http";
            }
            if (protocol.equals("http")) {
                host = httpProxyHost;
                port = httpProxyPort;
            }
            // Don't handle directly Socks calls.
        }

        return new String[]{host, String.valueOf(port)};
    }
 
Example 15
Source File: RSSocketFactory.java    From Game with GNU General Public License v3.0 4 votes vote down vote up
private Socket open(Proxy proxy) throws IOException {
	try {
		if (proxy.type() != Type.DIRECT) {
			SocketAddress var3 = proxy.address();
			if (var3 instanceof InetSocketAddress) {
				InetSocketAddress var4 = (InetSocketAddress) var3;
				if (proxy.type() == Type.HTTP) {
					String var16 = null;

					try {
						Class<?> var6 = Class.forName("sun.net.www.protocol.http.AuthenticationInfo");
						Method var7 = var6.getDeclaredMethod("getProxyAuth",
							String.class, Integer.TYPE);
						var7.setAccessible(true);
						Object var8 = var7.invoke(null,
							var4.getHostName(), valueOf(var4.getPort()));
						if (null != var8) {
							Method var9 = var6.getDeclaredMethod("supportsPreemptiveAuthorization");
							var9.setAccessible(true);
							if ((Boolean) var9.invoke(var8, new Object[0])) {
								Method var10 = var6.getDeclaredMethod("getHeaderName");
								var10.setAccessible(true);
								Method var11 = var6.getDeclaredMethod("getHeaderValue",
									URL.class, String.class);
								var11.setAccessible(true);
								String var12 = (String) var10.invoke(var8, new Object[0]);
								String var13 = (String) var11.invoke(var8,
									new Object[]{new URL("https://" + this.socketHost + "/"), "https"});
								var16 = var12 + ": " + var13;
							}
						}
					} catch (Exception ignored) {
					}

					return this.openConnect(var4.getPort(), 1514, var16, var4.getHostName());
				} else if (proxy.type() != Type.SOCKS) {
					return null;
				} else {
					Socket var5 = new Socket(proxy);
					var5.connect(new InetSocketAddress(this.socketHost, this.socketPort));
					return var5;
				}
			} else {
				return null;
			}
		} else {
			return this.openRaw();
		}
	} catch (RuntimeException var15) {
		throw GenUtil.makeThrowable(var15,
			"gb.F(" + (proxy != null ? "{...}" : "null") + ',' + "dummy" + ')');
	}
}
 
Example 16
Source File: ApplicationProxy.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private ApplicationProxy(Proxy proxy) {
    super(proxy.type(), proxy.address());
}
 
Example 17
Source File: ApplicationProxy.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private ApplicationProxy(Proxy proxy) {
    super(proxy.type(), proxy.address());
}
 
Example 18
Source File: ApplicationProxy.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private ApplicationProxy(Proxy proxy) {
    super(proxy.type(), proxy.address());
}
 
Example 19
Source File: ApplicationProxy.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private ApplicationProxy(Proxy proxy) {
    super(proxy.type(), proxy.address());
}
 
Example 20
Source File: ApplicationProxy.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private ApplicationProxy(Proxy proxy) {
    super(proxy.type(), proxy.address());
}