Java Examples for java.net.Proxy
The following java examples will help you to understand the usage of java.net.Proxy. These source code samples are taken from different open source projects.
Example 1
| Project: android-sdk-sources-for-api-level-23-master File: ProxyInfo.java View source code |
/**
* @hide
*/
public java.net.Proxy makeProxy() {
java.net.Proxy proxy = java.net.Proxy.NO_PROXY;
if (mHost != null) {
try {
InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort);
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress);
} catch (IllegalArgumentException e) {
}
}
return proxy;
}Example 2
| Project: ARTPart-master File: ProxyTest.java View source code |
/**
* java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
*/
public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_Normal() {
// test HTTP type proxy
Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
assertEquals(Proxy.Type.HTTP, proxy.type());
assertEquals(address, proxy.address());
// test SOCKS type proxy
proxy = new Proxy(Proxy.Type.SOCKS, address);
assertEquals(Proxy.Type.SOCKS, proxy.type());
assertEquals(address, proxy.address());
// test DIRECT type proxy
proxy = Proxy.NO_PROXY;
assertEquals(Proxy.Type.DIRECT, proxy.type());
assertNull(proxy.address());
}Example 3
| Project: jInstagram-master File: RequestTest.java View source code |
/**
* Run the void addBody(HttpURLConnection,byte[]) method test.
*
* @throws Exception
*
*
*/
@Test
public void testAddBody_1() throws Exception {
Request fixture = new Request(Verbs.DELETE, "");
fixture.setConnectionKeepAlive(true);
fixture.setCharset("UTF-8");
fixture.addPayload("Dummy payload");
fixture.setConnection(mockHttpConnection);
fixture.setProxy(proxy);
byte[] content = "Dummy Payload".getBytes();
HttpURLConnection mockConn = Mockito.mock(HttpURLConnection.class);
OutputStream mockOut = Mockito.mock(OutputStream.class);
Mockito.when(mockConn.getOutputStream()).thenReturn(mockOut);
System.out.println(mockConn);
fixture.addBody(mockConn, content);
// add additional test code here
// An unexpected exception was thrown in user code while executing this
// test:
// java.lang.IllegalArgumentException: type DIRECT is not compatible
// with address 0.0.0.0/0.0.0.0:1
// at java.net.Proxy.<init>(Proxy.java:95)
}Example 4
| Project: android_libcore-master File: ExcludedProxyTest.java View source code |
/**
* @tests java.net.HttpURLConnection#usingProxy()
*/
@TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Tests Proxy functionality. Indirect test.", method = "Proxy", args = { java.net.Proxy.Type.class, java.net.SocketAddress.class })
@BrokenTest("the host address isn't working anymore")
public void test_usingProxy() throws Exception {
try {
System.setProperty("http.proxyHost", Support_Configuration.ProxyServerTestHost);
URL u1 = new URL("http://" + Support_Configuration.HomeAddress);
URLConnection conn1 = u1.openConnection();
conn1.getInputStream();
boolean exception = false;
try {
System.setProperty("http.proxyPort", "81");
URL u3 = new URL("http://" + Support_Configuration.InetTestAddress);
URLConnection conn3 = u3.openConnection();
conn3.getInputStream();
fail("Should throw IOException");
} catch (IOException e) {
}
System.setProperty("http.proxyPort", "80");
URL u2 = new URL("http://" + Support_Configuration.ProxyServerTestHost + "/cgi-bin/test.pl");
java.net.HttpURLConnection conn2 = (java.net.HttpURLConnection) u2.openConnection();
conn2.setDoOutput(true);
conn2.setRequestMethod("POST");
OutputStream out2 = conn2.getOutputStream();
String posted2 = "this is a test";
out2.write(posted2.getBytes());
out2.close();
conn2.getResponseCode();
InputStream is2 = conn2.getInputStream();
String response2 = "";
byte[] b2 = new byte[1024];
int count2 = 0;
while ((count2 = is2.read(b2)) > 0) response2 += new String(b2, 0, count2);
assertTrue("Response to POST method invalid", response2.equals(posted2));
String posted4 = "just a test";
URL u4 = new URL("http://" + Support_Configuration.ProxyServerTestHost + "/cgi-bin/test.pl");
java.net.HttpURLConnection conn4 = (java.net.HttpURLConnection) u4.openConnection();
conn4.setDoOutput(true);
conn4.setRequestMethod("POST");
conn4.setRequestProperty("Content-length", String.valueOf(posted4.length()));
OutputStream out = conn4.getOutputStream();
out.write(posted4.getBytes());
out.close();
conn4.getResponseCode();
InputStream is = conn4.getInputStream();
String response = "";
byte[] b4 = new byte[1024];
int count = 0;
while ((count = is.read(b4)) > 0) response += new String(b4, 0, count);
assertTrue("Response to POST method invalid", response.equals(posted4));
} finally {
System.setProperties(null);
}
}Example 5
| Project: aether-core-master File: JreProxySelector.java View source code |
public Proxy getProxy(RemoteRepository repository) { List<java.net.Proxy> proxies = null; try { URI uri = new URI(repository.getUrl()).parseServerAuthority(); proxies = java.net.ProxySelector.getDefault().select(uri); } catch (Exception e) { } if (proxies != null) { for (java.net.Proxy proxy : proxies) { if (java.net.Proxy.Type.DIRECT.equals(proxy.type())) { break; } if (java.net.Proxy.Type.HTTP.equals(proxy.type()) && isValid(proxy.address())) { InetSocketAddress addr = (InetSocketAddress) proxy.address(); return new Proxy(Proxy.TYPE_HTTP, addr.getHostName(), addr.getPort(), JreProxyAuthentication.INSTANCE); } } } return null; }
Example 6
| Project: KinanCity-master File: HttpProxy.java View source code |
@Override
public OkHttpClient getClient() {
Builder clientBuilder = new OkHttpClient.Builder();
// HTTP Proxy
clientBuilder.proxy(new Proxy(Type.HTTP, new InetSocketAddress(host, port)));
// Authentication
if (StringUtils.isNotEmpty(login)) {
clientBuilder.proxyAuthenticator(new ProxyBasicAuthenticator(login, pass));
}
return clientBuilder.build();
}Example 7
| Project: ceylon-module-resolver-master File: CallbackTestCase.java View source code |
protected void doTest(ArtifactContext context, TestArtifactCallback callback) throws Exception {
String repoURL = "http://jboss-as7-modules-repository.googlecode.com/svn/trunk/ceylon";
try {
new URL(repoURL).openStream();
} catch (Exception e) {
log.error(String.format("Cannot connect to repo %s - %s", repoURL, e));
return;
}
RepositoryManagerBuilder builder = getRepositoryManagerBuilder(false, 60000, java.net.Proxy.NO_PROXY);
RemoteContentStore rcs = new RemoteContentStore(repoURL, log, false, 60000, java.net.Proxy.NO_PROXY);
CmrRepository repo = new DefaultRepository(rcs.createRoot());
RepositoryManager manager = builder.addRepository(repo).buildRepository();
try {
File file = manager.getArtifact(context);
Assert.assertNotNull(file);
Assert.assertTrue(callback.size > 0);
Assert.assertEquals(callback.size, callback.current);
} catch (Exception re) {
Assert.assertNotNull(callback.ts);
Assert.assertNotNull(callback.err);
Assert.assertEquals(callback.ts, callback.err.getMessage());
} finally {
manager.removeArtifact(name, version);
// test if remove really works
testSearchResults("com.redhat.fizbiz", ModuleQuery.Type.JVM, new ModuleSearchResult.ModuleDetails[0]);
}
}Example 8
| Project: ceylon-common-master File: ProxyTool.java View source code |
public static void main(String[] args) throws Exception {
if (args.length != 3) {
usage("Wrong number of arguments");
}
String mode = args[0];
File configFile = new File(args[1]);
if (!configFile.exists()) {
usage("Config file doesn't exist");
return;
}
final URL url;
try {
url = new URL(args[2]);
} catch (MalformedURLException e) {
usage("Malformed URL");
return;
}
CeylonConfig config = CeylonConfigFinder.loadConfigFromFile(configFile);
Authentication auth = Authentication.fromConfig(config);
Proxy proxy = Proxies.withConfig(config).getProxy();
final URLConnection conn;
switch(mode) {
case "proxy":
java.net.Proxy netProxy = auth.getProxy();
if (netProxy != null) {
conn = url.openConnection(netProxy);
} else {
conn = url.openConnection();
}
break;
case "install":
auth.installProxy();
conn = url.openConnection();
break;
default:
throw new RuntimeException("Unsupported mode");
}
InputStream in = conn.getInputStream();
try {
int ch = in.read();
while (ch != -1) {
System.out.append((char) ch);
ch = in.read();
}
} finally {
in.close();
}
}Example 9
| Project: mockserver-master File: HttpProxy.java View source code |
private static ProxySelector createProxySelector(final String host, final int port) {
return new ProxySelector() {
@Override
public List<java.net.Proxy> select(URI uri) {
return Arrays.asList(new java.net.Proxy(java.net.Proxy.Type.SOCKS, new InetSocketAddress(host, port)));
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
logger.error("Connection could not be established to proxy at socket [" + sa + "]", ioe);
}
};
}Example 10
| Project: android_frameworks_base-master File: ProxyInfo.java View source code |
/**
* @hide
*/
public java.net.Proxy makeProxy() {
java.net.Proxy proxy = java.net.Proxy.NO_PROXY;
if (mHost != null) {
try {
InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort);
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress);
} catch (IllegalArgumentException e) {
}
}
return proxy;
}Example 11
| Project: egdownloader-master File: HttpsUtils.java View source code |
private static HttpsURLConnection getHttpsConnection(String urlStr, Proxy proxy) throws IOException, NoSuchAlgorithmException, KeyManagementException {
URL url = new URL(urlStr);
HttpsURLConnection conn = null;
if (proxy != null) {
conn = (HttpsURLConnection) url.openConnection(proxy);
} else {
conn = (HttpsURLConnection) url.openConnection();
}
// ä¸?验è¯?æœ?务器主机å??å’Œè¯?书
conn.setHostnameVerifier(new IgnoreHostnameVerifier());
TrustManager[] tm = { new X509TrustManager4Portal() };
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, null);
SSLSocketFactory ssf = sslContext.getSocketFactory();
conn.setSSLSocketFactory(ssf);
return conn;
}Example 12
| Project: platform_frameworks_base-master File: ProxyInfo.java View source code |
/**
* @hide
*/
public java.net.Proxy makeProxy() {
java.net.Proxy proxy = java.net.Proxy.NO_PROXY;
if (mHost != null) {
try {
InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort);
proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress);
} catch (IllegalArgumentException e) {
}
}
return proxy;
}Example 13
| Project: hplookball-master File: HttpUrlDownloader.java View source code |
@Override
protected Void doInBackground(final Void... params) {
try {
InputStream is = null;
String thisUrl = url;
HttpURLConnection urlConnection = null;
while (true) {
final URL u = new URL(thisUrl);
//urlConnection = (HttpURLConnection)u.openConnection();
if (SharedPreferencesMgr.getInt("is_maa", 0) == 1) {
if (Proxy.getAddress() != null) {
String host = Proxy.getAddress().getHost();
int port = Proxy.getAddress().getPort();
java.net.Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(host, port));
urlConnection = (HttpURLConnection) u.openConnection(proxy);
} else {
urlConnection = (HttpURLConnection) u.openConnection();
}
} else {
urlConnection = (HttpURLConnection) u.openConnection();
}
urlConnection.setInstanceFollowRedirects(true);
if (mRequestPropertiesCallback != null) {
final ArrayList<NameValuePair> props = mRequestPropertiesCallback.getHeadersForRequest(context, url);
if (props != null) {
for (final NameValuePair pair : props) {
urlConnection.addRequestProperty(pair.getName(), pair.getValue());
}
}
}
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_MOVED_TEMP && urlConnection.getResponseCode() != HttpURLConnection.HTTP_MOVED_PERM)
break;
thisUrl = urlConnection.getHeaderField("Location");
}
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
UrlImageViewHelper.clog("Response Code: " + urlConnection.getResponseCode());
return null;
}
is = urlConnection.getInputStream();
callback.onDownloadComplete(HttpUrlDownloader.this, is, null);
return null;
} catch (final Throwable e) {
e.printStackTrace();
return null;
}
}Example 14
| Project: spring-framework-master File: ProxyFactoryBeanTests.java View source code |
@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 15
| Project: DownloadPlus-master File: ConnectionProxy.java View source code |
/* HTTP(S) proxy with authentication */
public static void setHTTPProxy(String host, int port, final String username, final String passwd) {
proxyHTTP = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(username, passwd.toCharArray()));
}
};
Authenticator.setDefault(auth);
}Example 16
| Project: MineClipse-Project-master File: Snippet.java View source code |
public static void main(String[] args) {
try {
System.setProperty("java.net.useSystemProxies", "true");
List l = ProxySelector.getDefault().select(new URI("http://www.yahoo.com/"));
for (Iterator iter = l.iterator(); iter.hasNext(); ) {
Proxy proxy = (Proxy) iter.next();
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 17
| Project: Mineshafter-Launcher-master File: InterceptHttpsHandler.java View source code |
@Override
protected URLConnection openConnection(URL url, Proxy p) throws IOException {
Handler handler = null;
for (Handler h : handlers) {
if (h.canHandle(url)) {
handler = h;
break;
}
}
System.out.println("Should handle? " + url.toString() + " " + (handler != null));
if (handler != null) {
return new URLConnectionAdapter(url, handler);
} else {
return super.openConnection(url, p);
}
}Example 18
| Project: android-sdk-master File: ProxyConfiguration.java View source code |
Authenticator authenticator() {
return new Authenticator() {
@Override
public okhttp3.Request authenticate(Route route, okhttp3.Response response) throws IOException {
String credential = Credentials.basic(user, password);
return response.request().newBuilder().header("Proxy-Authorization", credential).header("Proxy-Connection", "Keep-Alive").build();
}
};
}Example 19
| Project: gizmo-master File: MySelector.java View source code |
@Override public List<Proxy> select(URI uri) { ArrayList<Proxy> al = new ArrayList<Proxy>(); if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { al.add(new Proxy(Type.HTTP, new InetSocketAddress("localhost", 8080))); } else { al.add(Proxy.NO_PROXY); } return al; }
Example 20
| Project: selenese-runner-java-master File: WebResourcesTest.java View source code |
// proxy access.
@Ignore
@Test
public void testWebProxyResources() throws IOException {
String baseURL = wsr.getBaseURL();
String expect = IOUtils.toString(getClass().getResource("/htdocs/index.html"), StandardCharsets.UTF_8);
int proxyPort = wpr.getPort();
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyPort));
URL url = new URL(baseURL);
URLConnection conn = url.openConnection(proxy);
Object content = conn.getContent();
String actualProxy = IOUtils.toString((InputStream) content, StandardCharsets.UTF_8);
assertThat(actualProxy, is(expect));
assertThat(wpr.getCount(), is(1));
}Example 21
| Project: android-15-master File: Proxy.java View source code |
/**
* Return the proxy object to be used for the URL given as parameter.
* @param ctx A Context used to get the settings for the proxy host.
* @param url A URL to be accessed. Used to evaluate exclusion list.
* @return Proxy (java.net) object containing the host name. If the
* user did not set a hostname it returns the default host.
* A null value means that no host is to be used.
* {@hide}
*/
public static final java.net.Proxy getProxy(Context ctx, String url) {
String host = "";
if (url != null) {
URI uri = URI.create(url);
host = uri.getHost();
}
if (!isLocalHost(host)) {
if (sConnectivityManager == null) {
sConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (sConnectivityManager == null)
return java.net.Proxy.NO_PROXY;
ProxyProperties proxyProperties = sConnectivityManager.getProxy();
if (proxyProperties != null) {
if (!proxyProperties.isExcluded(host)) {
return proxyProperties.makeProxy();
}
}
}
return java.net.Proxy.NO_PROXY;
}Example 22
| Project: android-proxy-master File: ProxyProperties.java View source code |
public java.net.Proxy makeProxy() { java.net.Proxy proxy = java.net.Proxy.NO_PROXY; if (mHost != null) { try { InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort); proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress); } catch (IllegalArgumentException e) { } } return proxy; }
Example 23
| Project: android-smsmms-master File: ProxyProperties.java View source code |
public java.net.Proxy makeProxy() { java.net.Proxy proxy = java.net.Proxy.NO_PROXY; if (mHost != null) { try { InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort); proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress); } catch (IllegalArgumentException e) { } } return proxy; }
Example 24
| Project: cnAndroidDocs-master File: Proxy.java View source code |
/**
* Return the proxy object to be used for the URL given as parameter.
* @param ctx A Context used to get the settings for the proxy host.
* @param url A URL to be accessed. Used to evaluate exclusion list.
* @return Proxy (java.net) object containing the host name. If the
* user did not set a hostname it returns the default host.
* A null value means that no host is to be used.
* {@hide}
*/
public static final java.net.Proxy getProxy(Context ctx, String url) {
String host = "";
if (url != null) {
URI uri = URI.create(url);
host = uri.getHost();
}
if (!isLocalHost(host)) {
if (sConnectivityManager == null) {
sConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (sConnectivityManager == null)
return java.net.Proxy.NO_PROXY;
ProxyProperties proxyProperties = sConnectivityManager.getProxy();
if (proxyProperties != null) {
if (!proxyProperties.isExcluded(host)) {
return proxyProperties.makeProxy();
}
}
}
return java.net.Proxy.NO_PROXY;
}Example 25
| Project: frameworks_base_disabled-master File: Proxy.java View source code |
/**
* Return the proxy object to be used for the URL given as parameter.
* @param ctx A Context used to get the settings for the proxy host.
* @param url A URL to be accessed. Used to evaluate exclusion list.
* @return Proxy (java.net) object containing the host name. If the
* user did not set a hostname it returns the default host.
* A null value means that no host is to be used.
* {@hide}
*/
public static final java.net.Proxy getProxy(Context ctx, String url) {
String host = "";
if (url != null) {
URI uri = URI.create(url);
host = uri.getHost();
}
if (!isLocalHost(host)) {
if (sConnectivityManager == null) {
sConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (sConnectivityManager == null)
return java.net.Proxy.NO_PROXY;
ProxyProperties proxyProperties = sConnectivityManager.getProxy();
if (proxyProperties != null) {
if (!proxyProperties.isExcluded(host)) {
return proxyProperties.makeProxy();
}
}
}
return java.net.Proxy.NO_PROXY;
}Example 26
| Project: property-db-master File: Proxy.java View source code |
/**
* Return the proxy object to be used for the URL given as parameter.
* @param ctx A Context used to get the settings for the proxy host.
* @param url A URL to be accessed. Used to evaluate exclusion list.
* @return Proxy (java.net) object containing the host name. If the
* user did not set a hostname it returns the default host.
* A null value means that no host is to be used.
* {@hide}
*/
public static final java.net.Proxy getProxy(Context ctx, String url) {
String host = "";
if (url != null) {
URI uri = URI.create(url);
host = uri.getHost();
}
if (!isLocalHost(host)) {
if (sConnectivityManager == null) {
sConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (sConnectivityManager == null)
return java.net.Proxy.NO_PROXY;
ProxyProperties proxyProperties = sConnectivityManager.getProxy();
if (proxyProperties != null) {
if (!proxyProperties.isExcluded(host)) {
return proxyProperties.makeProxy();
}
}
}
return java.net.Proxy.NO_PROXY;
}Example 27
| Project: qksms-master File: ProxyProperties.java View source code |
public java.net.Proxy makeProxy() { java.net.Proxy proxy = java.net.Proxy.NO_PROXY; if (mHost != null) { try { InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort); proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress); } catch (IllegalArgumentException e) { } } return proxy; }
Example 28
| Project: XobotOS-master File: Proxy.java View source code |
/**
* Return the proxy object to be used for the URL given as parameter.
* @param ctx A Context used to get the settings for the proxy host.
* @param url A URL to be accessed. Used to evaluate exclusion list.
* @return Proxy (java.net) object containing the host name. If the
* user did not set a hostname it returns the default host.
* A null value means that no host is to be used.
* {@hide}
*/
public static final java.net.Proxy getProxy(Context ctx, String url) {
String host = "";
if (url != null) {
URI uri = URI.create(url);
host = uri.getHost();
}
if (!isLocalHost(host)) {
if (sConnectivityManager == null) {
sConnectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (sConnectivityManager == null)
return java.net.Proxy.NO_PROXY;
ProxyProperties proxyProperties = sConnectivityManager.getProxy();
if (proxyProperties != null) {
if (!proxyProperties.isExcluded(host)) {
return proxyProperties.makeProxy();
}
}
}
return java.net.Proxy.NO_PROXY;
}Example 29
| Project: aether-connector-okhttp-master File: OkHttpAetherClient.java View source code |
private Request authenticateProxy(Proxy proxy, okhttp3.Response response) throws IOException { Request req = response.request(); if (req.header("Proxy-Authorization") == null && config.getProxy() != null && config.getProxy().getAuthentication() != null) { String value = toHeaderValue(config.getProxy().getAuthentication()); boolean tunneled = req.isHttps() && proxy.type() == Type.HTTP; if (!tunneled) { // start including proxy-auth on each request headers.put("Proxy-Authorization", value); } return req.newBuilder().header("Proxy-Authorization", value).build(); } return null; }
Example 30
| Project: dropwizard-experiment-master File: WebDriverFactory.java View source code |
/**
* Use the system proxy (i.e. Charles) if one is running.
* This does not seem to happen automatically, even though it does happen automatically when running the browser normally.
*
* @param caps The capabilities to modify
*/
private static void withSystemProxy(DesiredCapabilities caps) {
List<Proxy> proxies = ProxySelector.getDefault().select(URI.create("http://www.google.com"));
java.net.Proxy proxy = proxies.get(0);
if (proxy.type() == java.net.Proxy.Type.HTTP) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
if ("127.0.0.1".equals(address.getHostString())) {
log.info("Detected local proxy on port {}, using for WebDriver-controlled browser.", address.getPort());
caps.setCapability(CapabilityType.PROXY, new org.openqa.selenium.Proxy().setHttpProxy("localhost:" + address.getPort()));
}
}
}Example 31
| Project: package-drone-master File: Helper.java View source code |
private static Proxy getProxy(final String url) { final ProxySelector ps = ProxySelector.getDefault(); if (ps == null) { logger.debug("No proxy selector found"); return null; } final List<java.net.Proxy> proxies = ps.select(URI.create(url)); for (final java.net.Proxy proxy : proxies) { if (proxy.type() != Type.HTTP) { logger.debug("Unsupported proxy type: {}", proxy.type()); continue; } final SocketAddress addr = proxy.address(); logger.debug("Proxy address: {}", addr); if (!(addr instanceof InetSocketAddress)) { logger.debug("Unsupported proxy address type: {}", addr.getClass()); continue; } final InetSocketAddress inetAddr = (InetSocketAddress) addr; return new Proxy(Proxy.TYPE_HTTP, inetAddr.getHostString(), inetAddr.getPort()); } logger.debug("No proxy found"); return null; }
Example 32
| Project: cyrille-leclerc-master File: ConfigurableProxySelectorTest.java View source code |
@Test
public void testSetProxiesHostPortByHostName() throws Exception {
String hostName = "myHost";
String proxyHost = "myProxyServer";
int proxyPort = 8080;
ConfigurableProxySelector configurableProxySelector = new ConfigurableProxySelector();
Map<String, Proxy> expected = new HashMap<String, Proxy>();
Proxy expectedProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
expected.put(hostName, expectedProxy);
Map<String, String> proxiesHostPortByHostName = new HashMap<String, String>();
proxiesHostPortByHostName.put(hostName, proxyHost + ":" + proxyPort);
configurableProxySelector.setProxiesHostPortByHostName(proxiesHostPortByHostName);
Map<String, Proxy> actual = configurableProxySelector.proxiesByHostName;
assertEquals(expected, actual);
}Example 33
| Project: FML-master File: Yggdrasil.java View source code |
public static void login(Map<String, String> args) {
if (!args.containsKey("--username") || !args.containsKey("--password"))
return;
YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1").createUserAuthentication(Agent.MINECRAFT);
auth.setUsername(args.get("--username"));
auth.setPassword(args.remove("--password"));
try {
auth.logIn();
} catch (AuthenticationException e) {
LogManager.getLogger("FMLTWEAK").error("-- Login failed! " + e.getMessage());
Throwables.propagate(e);
return;
}
args.put("--username", auth.getSelectedProfile().getName());
args.put("--uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
args.put("--accessToken", auth.getAuthenticatedToken());
args.put("--userProperties", auth.getUserProperties().toString());
}Example 34
| Project: jenkins-csvexporter-master File: HttpConnectionRetriever.java View source code |
public HttpURLConnection getConnection(String httpURL) throws IOException {
URL url = new URL(httpURL);
HttpURLConnection httpURLConnection;
if (isShouldUseProxy(httpURL)) {
int intHttpProxyPort = 0;
try {
intHttpProxyPort = Integer.parseInt(httpProxyPort);
} catch (NumberFormatException ne) {
}
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, intHttpProxyPort));
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
} else {
httpURLConnection = (HttpURLConnection) url.openConnection();
}
return httpURLConnection;
}Example 35
| Project: MinecraftForkage-master File: Yggdrasil.java View source code |
public static void login(Map<String, String> args) {
if (!args.containsKey("--username") || !args.containsKey("--password"))
return;
YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1").createUserAuthentication(Agent.MINECRAFT);
auth.setUsername(args.get("--username"));
auth.setPassword(args.remove("--password"));
try {
auth.logIn();
} catch (AuthenticationException e) {
LogManager.getLogger("FMLTWEAK").error("-- Login failed! " + e.getMessage());
Throwables.propagate(e);
return;
}
args.put("--username", auth.getSelectedProfile().getName());
args.put("--uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
args.put("--accessToken", auth.getAuthenticatedToken());
args.put("--userProperties", auth.getUserProperties().toString());
}Example 36
| Project: MusicUU-master File: BaseApplication.java View source code |
@Override
public void onCreate() {
super.onCreate();
CrashReport.initCrashReport(getApplicationContext(), "900055380", false);
File file = new File(Constants.lyricPath);
if (!file.exists()) {
file.mkdirs();
}
NoHttp.initialize(this, new NoHttp.Config().setConnectTimeout(30000).setReadTimeout(30000).setNetworkExecutor(new OkHttpNetworkExecutor()));
FileDownloader.init(getApplicationContext(), new DownloadMgrInitialParams.InitCustomMaker().connectionCreator(new FileDownloadUrlConnection.Creator(new FileDownloadUrlConnection.Configuration().connectTimeout(15_000).readTimeout(15_000).proxy(Proxy.NO_PROXY))));
FileDownloader.setGlobalPost2UIInterval(1000);
}Example 37
| Project: psicquic-master File: DetectProxy.java View source code |
private void loadProxy() {
String proxyHost = System.getProperty("http.proxyHost", null);
String proxyPort = System.getProperty("http.proxyPort", null);
if (proxyHost != null) {
try {
if (proxyPort != null && proxyPort.length() > 0) {
int port = Integer.parseInt(proxyPort);
SocketAddress address = new InetSocketAddress(proxyHost, port);
setProxy(new Proxy(Proxy.Type.HTTP, address));
}
} catch (Exception e) {
DetectProxy.log.error("Cannot create proxy using port " + proxyPort);
}
}
}Example 38
| Project: WildAnimalsPlus-1.7.10-master File: Yggdrasil.java View source code |
public static void login(Map<String, String> args) {
if (!args.containsKey("--username") || !args.containsKey("--password"))
return;
YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1").createUserAuthentication(Agent.MINECRAFT);
auth.setUsername(args.get("--username"));
auth.setPassword(args.remove("--password"));
try {
auth.logIn();
} catch (AuthenticationException e) {
LogManager.getLogger("FMLTWEAK").error("-- Login failed! " + e.getMessage());
Throwables.propagate(e);
return;
}
args.put("--username", auth.getSelectedProfile().getName());
args.put("--uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
args.put("--accessToken", auth.getAuthenticatedToken());
args.put("--userProperties", auth.getUserProperties().toString());
}Example 39
| Project: hale-master File: ClientProxyUtil.java View source code |
/**
* Set-up the given HTTP client to use the given proxy
*
* @param builder the HTTP client builder
* @param proxy the proxy
* @return the client builder adapted with the proxy settings
*/
public static HttpClientBuilder applyProxy(HttpClientBuilder builder, Proxy proxy) {
ProxyUtil.init();
// check if proxy shall be used
if (proxy != null && proxy.type() == Type.HTTP) {
InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
// set the proxy
HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
builder = builder.setProxy(proxyHost);
//$NON-NLS-1$
String user = System.getProperty("http.proxyUser");
//$NON-NLS-1$
String password = System.getProperty("http.proxyPassword");
boolean useProxyAuth = user != null && !user.isEmpty();
if (useProxyAuth) {
// set the proxy credentials
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyAddress.getHostName(), proxyAddress.getPort()), createCredentials(user, password));
builder = builder.setDefaultCredentialsProvider(credsProvider).setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
}
_log.trace(//$NON-NLS-1$ //$NON-NLS-2$
"Set proxy to " + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + //$NON-NLS-1$ //$NON-NLS-2$
((useProxyAuth) ? (" as user " + user) : ("")));
}
return builder;
}Example 40
| Project: maven-confluence-plugin-master File: ProxyTest.java View source code |
@Test
public void parseTest() {
System.setProperty("http.proxyHost", "myproxy");
System.setProperty("http.proxyPort", "80");
System.setProperty("http.nonProxyHosts", "127.0.0.1|localhost|*.company.com");
{
final List<Proxy> proxyList = ProxySelector.getDefault().select(URI.create("http://localhost:8080/confluence/xmlrpc"));
Assert.assertThat(proxyList.isEmpty(), Is.is(false));
Assert.assertThat(proxyList.size(), Is.is(1));
final Proxy p = proxyList.get(0);
System.out.printf("type=[%s] address=[%s]\n", p.type(), p.address());
Assert.assertThat(p.type(), Is.is(Type.DIRECT));
Assert.assertThat(p.address(), IsNull.nullValue());
}
{
final List<Proxy> proxyList = ProxySelector.getDefault().select(URI.create("http://my.company.com:8033/confluence/xmlrpc"));
Assert.assertThat(proxyList.isEmpty(), Is.is(false));
Assert.assertThat(proxyList.size(), Is.is(1));
final Proxy p = proxyList.get(0);
System.out.printf("type=[%s] address=[%s]\n", p.type(), p.address());
Assert.assertThat(p.type(), Is.is(Type.DIRECT));
Assert.assertThat(p.address(), IsNull.nullValue());
}
{
final List<Proxy> proxyList = ProxySelector.getDefault().select(URI.create("http://www.google.com/confluence/xmlrpc"));
Assert.assertThat(proxyList.isEmpty(), Is.is(false));
Assert.assertThat(proxyList.size(), Is.is(1));
final Proxy p = proxyList.get(0);
System.out.printf("type=[%s] address=[%s]\n", p.type(), p.address());
Assert.assertThat(p.type(), Is.is(Type.HTTP));
Assert.assertThat(p.address(), IsNull.notNullValue());
}
}Example 41
| Project: mylyn.tasks-master File: TaskRepositoryLocation.java View source code |
@Override
public Proxy getProxyForHost(String host, String proxyType) {
if (!taskRepository.isDefaultProxyEnabled()) {
String proxyHost = taskRepository.getProperty(TaskRepository.PROXY_HOSTNAME);
String proxyPort = taskRepository.getProperty(TaskRepository.PROXY_PORT);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort != null) {
try {
int proxyPortNum = Integer.parseInt(proxyPort);
AuthenticationCredentials credentials = taskRepository.getCredentials(AuthenticationType.PROXY);
return WebUtil.createProxy(proxyHost, proxyPortNum, credentials);
} catch (NumberFormatException e) {
StatusHandler.log(new RepositoryStatus(taskRepository, IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, 0, "Error occured while configuring proxy. Invalid port \"" + proxyPort + "\" specified.", e));
}
}
}
return WebUtil.getProxy(host, proxyType);
}Example 42
| Project: org.eclipse.mylyn.tasks-master File: TaskRepositoryLocation.java View source code |
@Override
public Proxy getProxyForHost(String host, String proxyType) {
if (!taskRepository.isDefaultProxyEnabled()) {
String proxyHost = taskRepository.getProperty(TaskRepository.PROXY_HOSTNAME);
String proxyPort = taskRepository.getProperty(TaskRepository.PROXY_PORT);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort != null) {
try {
int proxyPortNum = Integer.parseInt(proxyPort);
AuthenticationCredentials credentials = taskRepository.getCredentials(AuthenticationType.PROXY);
return WebUtil.createProxy(proxyHost, proxyPortNum, credentials);
} catch (NumberFormatException e) {
StatusHandler.log(new RepositoryStatus(taskRepository, IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, 0, "Error occured while configuring proxy. Invalid port \"" + proxyPort + "\" specified.", e));
}
}
}
return WebUtil.getProxy(host, proxyType);
}Example 43
| Project: Tank-master File: Main.java View source code |
public void start() {
try {
application.startSession(this);
logger.setUseParentHandlers(false);
Handler ch = new ConsoleHandler();
ch.setFormatter(new TextFormatter());
logger.addHandler(ch);
InetSocketAddress listen;
try {
listen = new InetSocketAddress("localhost", port);
} catch (NumberFormatException nfe) {
usage();
return;
}
String proxy = "DIRECT";
final ProxySelector ps = getProxySelector(proxy);
DefaultHttpRequestHandler drh = new DefaultHttpRequestHandler() {
@Override
protected HttpClient createClient() {
HttpClient client = super.createClient();
client.setProxySelector(ps);
client.setSoTimeout(20000);
return client;
}
};
ServerGroup sg = new ServerGroup();
sg.addServer(listen);
drh.setServerGroup(sg);
HttpRequestHandler rh = drh;
rh = new LoggingHttpRequestHandler(rh);
BufferedMessageInterceptor bmi = new BufferedMessageInterceptor() {
@Override
public Action directResponse(RequestHeader request, MutableResponseHeader response) {
// + "===========");
return Action.BUFFER;
}
@Override
public Action directRequest(MutableRequestHeader request) {
// + "===========");
return Action.BUFFER;
}
};
rh = new BufferingHttpRequestHandler(rh, bmi, 1024 * 1024, application);
HttpProxyConnectionHandler hpch = new HttpProxyConnectionHandler(rh);
SSLContextSelector cp = getSSLContextSelector();
TargetedConnectionHandler tch = new SSLConnectionHandler(cp, true, hpch);
tch = new LoopAvoidingTargetedConnectionHandler(sg, tch);
hpch.setConnectHandler(tch);
TargetedConnectionHandler socks = new SocksConnectionHandler(tch, true);
p = new Proxy(listen, socks, null);
p.setSocketTimeout(90000);
p.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 44
| Project: OWASP-Proxy-master File: DefaultHttpProxyTest.java View source code |
@Test
public void testRun() throws Exception {
Proxy proxy = new Proxy(listen, ch, null);
proxy.start();
java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("localhost", 9998));
try {
URL url = new URL("http://localhost:9999/");
URLConnection uc = url.openConnection(p);
uc.connect();
InputStream is = uc.getInputStream();
byte buff[] = new byte[1024];
int got;
while ((got = is.read(buff)) > 0) {
logger.finer(AsciiString.create(buff, 0, got));
}
is.close();
uc = url.openConnection(p);
uc.setRequestProperty("Content-Length", "15");
uc.setDoOutput(true);
uc.connect();
OutputStream os = uc.getOutputStream();
os.write("123456789012345".getBytes());
os.close();
is = uc.getInputStream();
while ((got = is.read(buff)) > 0) {
logger.finer(AsciiString.create(buff, 0, got));
}
is.close();
// request.setPort(999);
// request.setMessage("POST / HTTP/1.0\r\nContent-Length: 15\r\n\r\n123456789012345".getBytes());
// // c =
// client.fetchResponse(request);
// // System.out.write(c.getResponse().getMessage());
} finally {
proxy.stop();
}
}Example 45
| Project: sshj-master File: SocketClient.java View source code |
/**
* Connect to a host via a proxy.
* @param hostname The host name to connect to.
* @param port The port to connect to.
* @param proxy The proxy to connect via.
* @deprecated This method will be removed after v0.12.0. If you want to connect via a proxy, you can do this by injecting a {@link javax.net.SocketFactory}
* into the SocketClient. The SocketFactory should create sockets using the {@link java.net.Socket#Socket(java.net.Proxy)} constructor.
*/
@Deprecated
public void connect(String hostname, int port, Proxy proxy) throws IOException {
this.hostname = hostname;
if (JavaVersion.isJava7OrEarlier() && proxy.type() == Proxy.Type.HTTP) {
// Java7 and earlier have no support for HTTP Connect proxies, return our custom socket.
socket = new Jdk7HttpProxySocket(proxy);
} else {
socket = new Socket(proxy);
}
socket.connect(new InetSocketAddress(hostname, port), connectTimeout);
onConnect();
}Example 46
| Project: cismet-gui-commons-master File: FTPAccessHandler.java View source code |
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected FTPClient getConfiguredFTPClient() {
if (LOG.isDebugEnabled()) {
// NOI18N
LOG.debug("getConfiguredFTPClient");
}
final FTPClient client = new FTPClient();
final FTPClientConfig config = new FTPClientConfig();
if (proxy != null) {
// proxy needs authentication
if ((proxy.getUsername() != null) && (proxy.getPassword() != null)) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
final PasswordAuthentication p = new PasswordAuthentication(proxy.getUsername(), proxy.getPassword().toCharArray());
return p;
}
});
}
final java.net.Proxy proxyfo = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(this.proxy.getHost(), this.proxy.getPort()));
client.setProxy(proxyfo);
}
client.configure(config);
return client;
}Example 47
| Project: pentaho-reporting-master File: FirewallingProxySelector.java View source code |
/**
* Selects all the applicable proxies based on the protocol to access the resource with and a destination address to
* access the resource at. The format of the URI is defined as follow: <UL> <LI>http URI for http connections</LI>
* <LI>https URI for https connections <LI>ftp URI for ftp connections</LI> <LI><code>socket://host:port</code><br>
* for tcp client sockets connections</LI> </UL>
*
* @param uri The URI that a connection is required to
* @return a List of Proxies. Each element in the the List is of type {@link java.net.Proxy Proxy}; when no proxy is
* available, the list will contain one element of type {@link java.net.Proxy Proxy} that represents a direct
* connection.
* @throws IllegalArgumentException if either argument is null
*/
public List<Proxy> select(final URI uri) {
if (WorkspaceSettings.getInstance().isOfflineMode()) {
if (LOCALHOST.equalsIgnoreCase(uri.getHost())) {
return selectDefault(uri);
}
if (LOCALHOST_IP.equalsIgnoreCase(uri.getHost())) {
return selectDefault(uri);
}
if (LOCALHOST_LOCALDOMAIN.equalsIgnoreCase(uri.getHost())) {
return selectDefault(uri);
}
throw new IllegalArgumentException(UtilMessages.getInstance().getString("FirewallingProxySelector.FilterMessage"));
}
return selectDefault(uri);
}Example 48
| Project: aws-toolkit-eclipse-master File: CheckIpUtil.java View source code |
/**
* Creates a Proxy to use when opening a URLConnection, otherwise, it
* returns <code>Proxy.NO_PROXY</code>.
*
* @return A proxy configured with the settings the user has entered in
* Eclipse; otherwise, returns <code>Proxy.NO_PROXY</code>.
*/
private static Proxy createProxy() {
IProxyService proxyService = AwsToolkitCore.getDefault().getProxyService();
if (proxyService.isProxiesEnabled()) {
IProxyData[] proxyData = proxyService.select(URI.create(CHECKIP_URL));
if (proxyData.length > 0) {
// NOTE: For proxy authentication support in this class, we should switch
// to HttpClient since java.net.Proxy doesn't allow you to configure
// per-instance auth settings, and instead, we'd have to use
// java.net.Authenticator#setDefault to set JVM-wide auth settings.
InetSocketAddress proxyAddress = new InetSocketAddress(proxyData[0].getHost(), proxyData[0].getPort());
return new Proxy(Proxy.Type.HTTP, proxyAddress);
}
}
return Proxy.NO_PROXY;
}Example 49
| Project: chbosync4android-master File: ProxyFactory.java View source code |
//---------- Private fields
//---------- Constructor
//---------- Public properties
//---------- Public methods
/**
* Create the right {@link java.net.Proxy} based on {@link ProxyConfig} values
* @param proxyConfig
* @return
*/
public static Proxy createProxyInstance(ProxyConfig proxyConfig) {
if (null == proxyConfig || proxyConfig.getType() == ProxyConfig.TYPE_DIRECT)
return null;
Proxy.Type proxyType = Proxy.Type.DIRECT;
switch(proxyConfig.getType()) {
case ProxyConfig.TYPE_HTTP:
proxyType = Proxy.Type.HTTP;
break;
case ProxyConfig.TYPE_SOCKS:
proxyType = Proxy.Type.SOCKS;
break;
default:
break;
}
Proxy proxy = new Proxy(proxyType, InetSocketAddress.createUnresolved(proxyConfig.getAddress(), proxyConfig.getPort()));
return proxy;
}Example 50
| Project: ftpapi-master File: Download.java View source code |
/**
* @param args
* command line arguments.
* @throws InstantiationException
* propogated
* @throws ClassNotFoundException
* propogated
* @throws IllegalAccessException
* propogated
* @throws FTPException
* propogated
* @throws ConnectionException
* propogated
*/
public static void main(String[] args) throws InstantiationException, ClassNotFoundException, IllegalAccessException, FTPException, ConnectionException {
// Determine the FTPClient implementation that you would like to use.
// For most FTP servers, the DefaultFTPClient should work.
String className = "com.myjavaworld.ftp.DefaultFTPClient";
// Use reflection to find the class and obtain an instance of the class.
FTPClient client = (FTPClient) Class.forName(className).newInstance();
// Determine the directory list parser that we would like to use in this
// session. For most FTP servers, the default implementatiom should work
// fine.
ListParser parser = (ListParser) Class.forName("com.myjavaworld.ftp.DefaultListParser").newInstance();
// Set the list parser to use with the FTP client.
client.setListParser(parser);
client.setProxy(new Proxy(Type.SOCKS, new InetSocketAddress("localhost", 1080)));
client.setPassive(true);
// Connect to the FTP server.
System.out.println("Connecting...");
client.connect("ftp.netscape.com");
System.out.println("Connected. ");
// Login to the FTP server.
System.out.println("Logging in...");
client.login("anonymous", "you@yourcompany.com");
System.out.println("Logged in. ");
// Download a file
RemoteFile source = parser.createRemoteFile("/pub/netscape9/en-US/9.0/windows/win32/netscape-navigator-9.0.exe", false);
File destination = new File("/temp/netscape-navigator-9.0.exe");
System.out.println("Downloading: " + source);
client.download(source, destination, FTPConstants.TYPE_BINARY, false);
System.out.println("Done. ");
// Disconnect from the FTP server.
System.out.println("Disconnecting...");
client.disconnect();
System.out.println("Disconnected. ");
}Example 51
| Project: funambol-client-sdk-master File: ProxyFactory.java View source code |
//---------- Private fields
//---------- Constructor
//---------- Public properties
//---------- Public methods
/**
* Create the right {@link java.net.Proxy} based on {@link ProxyConfig} values
* @param proxyConfig
* @return
*/
public static Proxy createProxyInstance(ProxyConfig proxyConfig) {
if (null == proxyConfig || proxyConfig.getType() == ProxyConfig.TYPE_DIRECT)
return null;
Proxy.Type proxyType = Proxy.Type.DIRECT;
switch(proxyConfig.getType()) {
case ProxyConfig.TYPE_HTTP:
proxyType = Proxy.Type.HTTP;
break;
case ProxyConfig.TYPE_SOCKS:
proxyType = Proxy.Type.SOCKS;
break;
default:
break;
}
Proxy proxy = new Proxy(proxyType, InetSocketAddress.createUnresolved(proxyConfig.getAddress(), proxyConfig.getPort()));
return proxy;
}Example 52
| Project: keystone-master File: ClientFactory.java View source code |
private static void addProxy(ClientConfig cc, Config config) {
if (config.getProxy() != null) {
HttpUrlConnectorProvider cp = new HttpUrlConnectorProvider();
cc.connectorProvider(cp);
final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(config.getProxy().getRawHost(), config.getProxy().getPort()));
cp.connectionFactory(new ConnectionFactory() {
@Override
public HttpURLConnection getConnection(URL url) throws IOException {
return (HttpURLConnection) url.openConnection(proxy);
}
});
}
}Example 53
| Project: neutron-master File: ClientFactory.java View source code |
private static void addProxy(ClientConfig cc, Config config) {
if (config.getProxy() != null) {
HttpUrlConnectorProvider cp = new HttpUrlConnectorProvider();
cc.connectorProvider(cp);
final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(config.getProxy().getRawHost(), config.getProxy().getPort()));
cp.connectionFactory(new ConnectionFactory() {
@Override
public HttpURLConnection getConnection(URL url) throws IOException {
return (HttpURLConnection) url.openConnection(proxy);
}
});
}
}Example 54
| Project: open-keychain-master File: OkHttpKeybaseClient.java View source code |
@Override
public Response getUrlResponse(URL url, Proxy proxy, boolean isKeybase) throws IOException {
OkHttpClient client;
try {
if (proxy != null) {
client = OkHttpClientFactory.getClientPinnedIfAvailable(url, proxy);
} else {
client = OkHttpClientFactory.getSimpleClient();
}
} catch (TlsCertificatePinning.TlsCertificatePinningException e) {
Log.e(Constants.TAG, "TlsHelper failed", e);
throw new IOException("TlsHelper failed");
}
Request request = new Request.Builder().url(url).build();
okhttp3.Response okResponse = client.newCall(request).execute();
return new Response(okResponse.body().byteStream(), okResponse.code(), okResponse.message(), okResponse.headers().toMultimap());
}Example 55
| Project: openstack4j-master File: ClientFactory.java View source code |
private static void addProxy(ClientConfig cc, Config config) {
if (config.getProxy() != null) {
HttpUrlConnectorProvider cp = new HttpUrlConnectorProvider();
cc.connectorProvider(cp);
final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(config.getProxy().getRawHost(), config.getProxy().getPort()));
cp.connectionFactory(new ConnectionFactory() {
@Override
public HttpURLConnection getConnection(URL url) throws IOException {
return (HttpURLConnection) url.openConnection(proxy);
}
});
}
}Example 56
| Project: polycasso-master File: URLFetcher.java View source code |
/**
* retrieve arbitrary data found at a specific url - either http or file urls for http requests, sets the user-agent to mozilla to avoid sites being cranky
* about a java sniffer
*
* @param url
* the url to retrieve
* @param proxyHost
* the host to use for the proxy
* @param proxyPort
* the port to use for the proxy
* @return a byte array of the content
*
* @throws IOException
* the site fails to respond
*/
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
HttpURLConnection con = null;
InputStream is = null;
try {
URL u = new URL(url);
if (url.startsWith("file://")) {
is = new BufferedInputStream(u.openStream());
} else {
Proxy proxy;
if (proxyHost != null) {
proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
} else {
proxy = Proxy.NO_PROXY;
}
con = (HttpURLConnection) u.openConnection(proxy);
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
con.addRequestProperty("Accept-Charset", "UTF-8");
con.addRequestProperty("Accept-Language", "en-US,en");
con.addRequestProperty("Accept", "text/html,image/*");
con.setDoInput(true);
con.setDoOutput(false);
con.connect();
is = new BufferedInputStream(con.getInputStream());
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(is, baos);
return baos.toByteArray();
} catch (MalformedURLException e) {
if (url.startsWith("data:")) {
int commaPos = url.indexOf(",");
if (commaPos < 0) {
throw new IOException("Poorly formatted data url");
}
String prefix = url.substring("data:".length(), commaPos);
String[] attributes = prefix.trim().split(";");
if (attributes.length < 0) {
throw new IOException("Data url doesn't specify mime type");
}
String data = url.substring(commaPos + 1);
switch(attributes[0]) {
case "image/jpeg":
case "image/png":
case "image/gif":
return Base64.getDecoder().decode(data);
default:
throw new IOException("Unsupported data url mimetype: " + attributes[0]);
}
} else {
throw e;
}
} finally {
IOUtils.closeQuietly(is);
if (con != null) {
con.disconnect();
}
}
}Example 57
| Project: riena-master File: CoreNetProxySelectorTest.java View source code |
/**
* To run this test it is necessary that "http://localhost/pac42.js" is
* entered in the "automatic configuration script" of the "internet options"
* dialog.
*
* @throws URISyntaxException
* @throws IOException
*/
public void testPac() {
TestServer server = null;
try {
//$NON-NLS-1$
server = new TestServer(80, getFile("pac42.js").getParentFile());
final ProxySelector selector = new CoreNetProxySelector();
//$NON-NLS-1$
final List<Proxy> proxies = selector.select(new URI("http://www.eclipse.org"));
assertEquals(2, proxies.size());
//$NON-NLS-1$
assertEquals("idproxy", ((InetSocketAddress) proxies.get(0).address()).getHostName());
assertEquals(3128, ((InetSocketAddress) proxies.get(0).address()).getPort());
} catch (final Throwable e) {
fail();
} finally {
server.stop();
}
}Example 58
| Project: AndroidVideoCache-master File: ProxySelectorTest.java View source code |
// https://github.com/danikula/AndroidVideoCache/issues/28
@Test
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 59
| Project: bitmask_android-master File: ProxyDetection.java View source code |
static SocketAddress detectProxy(VpnProfile vp) {
// Construct a new url with https as protocol
try {
URL url = new URL(String.format("https://%s:%s", vp.mServerName, vp.mServerPort));
Proxy proxy = getFirstProxy(url);
if (proxy == null)
return null;
SocketAddress addr = proxy.address();
if (addr instanceof InetSocketAddress) {
return addr;
}
} catch (MalformedURLException e) {
VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage());
} catch (URISyntaxException e) {
VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage());
}
return null;
}Example 60
| Project: bugvm-master File: HttpsHandler.java View source code |
@Override
protected OkHttpClient newOkHttpClient(Proxy proxy) {
OkHttpClient client = super.newOkHttpClient(proxy);
client.setTransports(ENABLED_TRANSPORTS);
HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
// default verifier.
if (!(verifier instanceof DefaultHostnameVerifier)) {
client.setHostnameVerifier(verifier);
}
return client;
}Example 61
| Project: eclipse-integration-cloudfoundry-master File: CloudFoundryTestUtil.java View source code |
/** * @param host * @param proxyType * @return proxy or null if it cannot be resolved */ public static Proxy getProxy(String host, String proxyType) { Proxy foundProxy = null; try { URI uri = new URI(proxyType, "//" + host, null); List<Proxy> proxies = ProxySelector.getDefault().select(uri); if (proxies != null) { for (Proxy proxy : proxies) { if (proxy != Proxy.NO_PROXY) { foundProxy = proxy; break; } } } } catch (URISyntaxException e) { } return foundProxy; }
Example 62
| Project: enzymeportal-master File: SiteMapServlet.java View source code |
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sitemaps = request.getParameter("sitemaps");
response.setContentType("text/xml");
LOGGER.info("Getting URL connection to sitemap...");
//.getWebApplicationContext(getServletContext());
WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
// ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
//FilesConfig sitemapConfig = (FilesConfig) context.getBean("sitemapConfig");
sitemapConfig = (FilesConfig) context.getBean(FilesConfig.class);
String output = String.format("%s/%s", sitemapConfig.getSitemapUrl(), sitemaps);
URL url = new URL(output);
LOGGER.info("Connecting to sitemap...");
URLConnection con = url.openConnection(java.net.Proxy.NO_PROXY);
LOGGER.info("Connected to sitemap...");
InputStream inputStream = con.getInputStream();
int r = -1;
LOGGER.debug("Starting to read sitemap...");
while ((r = inputStream.read()) != -1) {
response.getOutputStream().write(r);
}
try {
response.getOutputStream().flush();
response.flushBuffer();
LOGGER.debug("... Read and served");
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}Example 63
| Project: hideninja_core_openvpn_for_android-master File: ProxyDetection.java View source code |
static SocketAddress detectProxy(VpnProfile vp) {
// Construct a new url with https as protocol
try {
URL url = new URL(String.format("https://%s:%s", vp.mServerName, vp.mServerPort));
Proxy proxy = getFirstProxy(url);
if (proxy == null)
return null;
SocketAddress addr = proxy.address();
if (addr instanceof InetSocketAddress) {
return addr;
}
} catch (MalformedURLException e) {
VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage());
} catch (URISyntaxException e) {
VpnStatus.logError(R.string.getproxy_error, e.getLocalizedMessage());
}
return null;
}Example 64
| Project: hifivetools-master File: URLConnectionImplEx.java View source code |
/**
* {@inheritDoc}
*
* @see com.htmlhifive.tools.wizard.download.IConnectMethod#setProxy(org.eclipse.core.net.proxy.IProxyService)
*/
@Override
public void setProxy(IProxyService proxyService) {
// プãƒã‚ã‚·è¨å®š.
IProxyData[] proxyDataForHost = proxyService.select(URI.create(urlStr));
for (IProxyData data : proxyDataForHost) {
if (data.getHost() != null) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(data.getHost(), data.getPort()));
if (data.getUserId() != null) {
proxyAuthorization = "Basic " + new String(Base64.encodeBase64(new StringBuilder(data.getUserId()).append(":").append(data.getPassword()).toString().getBytes()));
}
}
}
}Example 65
| Project: intellij-community-master File: SocksProxyData.java View source code |
public Socket connect() throws IOException {
final InetSocketAddress proxyAddr = new InetSocketAddress(mySettings.getProxyHostName(), mySettings.getProxyPort());
final Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
final Socket socket = new Socket(proxy);
final InetSocketAddress realAddress = new InetSocketAddress(mySettings.getHostName(), mySettings.getPort());
socket.connect(realAddress, mySettings.getConnectionTimeout());
socket.setSoTimeout(0);
return socket;
}Example 66
| Project: jcodec-master File: HttpUtils.java View source code |
public static HttpClient getHttpClient(String trackUrl) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
try {
for (Proxy proxy : ProxySelector.getDefault().select(new URI(trackUrl))) {
if (proxy == proxy.NO_PROXY)
continue;
InetSocketAddress address = (InetSocketAddress) proxy.address();
HttpHost httpHost = new HttpHost(address.getAddress().getHostAddress(), address.getPort());
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpHost);
System.out.println("Using proxy server: " + address.getHostName() + ":" + address.getPort());
break;
}
} catch (URISyntaxException e) {
throw new IOException(e);
}
return client;
}Example 67
| Project: jdk7u-jdk-master File: B6563259.java View source code |
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 68
| Project: kappaeg-master File: Toolbox.java View source code |
public static String fullURL(String anyURL) throws IOException {
URL url = new URL(anyURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
httpURLConnection.setInstanceFollowRedirects(false);
String finalURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return finalURL;
}Example 69
| Project: lets-the-right-one-in-master File: ApiAuthenticator.java View source code |
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
Log.d(TAG, "Calling ApiAuthenticator.authenticate");
// Do not try to authenticate oauth related paths
if (response.request().uri().getPath().startsWith("/oauth"))
return null;
Account account = AuthUtils.getActiveAccount(appContext, accountType);
if (account == null) {
failAuth();
return null;
}
String oldToken = accountManager.peekAuthToken(account, authtokenType);
if (oldToken != null) {
Log.d(TAG, "Invalidating auth token.");
accountManager.invalidateAuthToken(accountType, oldToken);
}
try {
Log.d(TAG, "calling accountManager.blockingGetAuthToken");
String token = accountManager.blockingGetAuthToken(account, authtokenType, false);
if (token == null) {
accountManager.removeAccount(account, null, null, null);
failAuth();
return null;
} else {
return response.request().newBuilder().header("Authorization", "Bearer " + token).build();
}
} catch (Exception e) {
Log.e(TAG, "Failed to retrieve auth token.", e);
}
return null;
}Example 70
| Project: ManagedRuntimeInitiative-master File: B6563259.java View source code |
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 71
| Project: MCFreedomLauncher-master File: Util.java View source code |
public static String performPost(URL url, String parameters, Proxy proxy, String contentType, boolean returnErrorPage) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
byte[] paramAsBytes = parameters.getBytes(Charset.forName("UTF-8"));
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
connection.setRequestProperty("Content-Length", "" + paramAsBytes.length);
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.write(paramAsBytes);
writer.flush();
writer.close();
InputStream stream;
try {
stream = connection.getInputStream();
} catch (IOException e) {
if (returnErrorPage) {
stream = connection.getErrorStream();
if (stream == null)
throw e;
} else {
throw e;
}
}
return IOUtils.toString(stream);
}Example 72
| Project: ntlm-proxy-master File: ProxyTest.java View source code |
private static void enableSystemProxy(final URI uri) {
Proxy proxy = CompoundProxySelectorFactory.getProxySelector().select(uri).get(0);
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.setProperty("http.proxyHost", "");
System.setProperty("http.proxyPort", "");
} else {
System.setProperty("http.proxyHost", addr.getHostName());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
}
}Example 73
| Project: okhttp-utils-master File: RequestLine.java View source code |
/**
* Returns the request status line, like "GET / HTTP/1.1". This is exposed to the application by
* {@link HttpURLConnection#getHeaderFields}, so it needs to be set even if the transport is
* SPDY.
*/
static String get(Request request, Proxy.Type proxyType) {
StringBuilder result = new StringBuilder();
result.append(request.method());
result.append(' ');
if (includeAuthorityInRequestLine(request, proxyType)) {
result.append(request.url());
} else {
result.append(requestPath(request.url()));
}
result.append(" HTTP/1.1");
return result.toString();
}Example 74
| Project: openjdk-master File: B6563259.java View source code |
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 75
| Project: openjdk8-jdk-master File: B6563259.java View source code |
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 76
| Project: Orlib-master File: SocksHttpClient.java View source code |
private static ClientConnectionManager initConnectionManager(String proxyHost, int proxyPort) throws UnknownHostException {
if (ccm == null) {
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", SocksSocketFactory.getSocketFactory(proxyHost, proxyPort), 80));
supportedSchemes.register(new Scheme("https", ModSSLSocketFactory.getSocketFactory(Proxy.Type.SOCKS, proxyHost, proxyPort), 443));
ccm = new MyThreadSafeClientConnManager(initParams(), supportedSchemes);
}
return ccm;
}Example 77
| Project: proxy-vole-master File: PacProxySelectorTest.java View source code |
/*************************************************************************
* Test method
*
* @throws ProxyException
* on proxy detection error.
* @throws MalformedURLException
* on URL erros
************************************************************************/
@Test
public void testScriptExecution2() throws ProxyException, MalformedURLException {
PacProxySelector pacProxySelector = new PacProxySelector(new UrlPacScriptSource(toUrl("test2.pac")));
List<Proxy> result = pacProxySelector.select(TestUtil.HTTP_TEST_URI);
assertEquals(Proxy.NO_PROXY, result.get(0));
result = pacProxySelector.select(TestUtil.HTTPS_TEST_URI);
assertEquals(Proxy.NO_PROXY, result.get(0));
}Example 78
| Project: robovm-master File: HttpsHandler.java View source code |
@Override
protected OkHttpClient newOkHttpClient(Proxy proxy) {
OkHttpClient client = super.newOkHttpClient(proxy);
client.setTransports(ENABLED_TRANSPORTS);
HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
// default verifier.
if (!(verifier instanceof DefaultHostnameVerifier)) {
client.setHostnameVerifier(verifier);
}
return client;
}Example 79
| Project: sdk-core-java-master File: GoogleAppEngineHttpConnection.java View source code |
@Override
public void createAndconfigureHttpConnection(HttpConfiguration clientConfiguration) throws IOException {
this.config = clientConfiguration;
URL url = new URL(this.config.getEndPointUrl());
// Google App Engine does not support the
// javax.net.ssl.HttpsURLConnection class.
// However, one can use use URL.openConnection() with a https:// URL and
// it will
// return an HttpURLConnection that is capable of retrieving HTTPS data.
// see
// https://groups.google.com/forum/?fromgroups#!topic/google-appengine-java/ZEskGLwyE_0
// Google App Engine does not require any proxy settings so we can skip
// that configuration entirely.
// Other Google issues that can be starred to add better support:
// http://code.google.com/p/googleappengine/issues/detail?id=1036
this.connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
this.connection.setDoInput(true);
this.connection.setDoOutput(true);
this.connection.setRequestMethod(config.getHttpMethod());
this.connection.setConnectTimeout(this.config.getConnectionTimeout());
this.connection.setReadTimeout(this.config.getReadTimeout());
}Example 80
| Project: SE252-JAN2015-master File: functions.java View source code |
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
/* for proxy.
InputStream is = null;
String proxyHost = System.getProperty("https.proxyHost");
int proxyPort = Integer.parseInt(System.getProperty("https.proxyPort"));
if(proxyHost.trim().equals(""))
is = new URL(url).openStream();
else
{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
is = new URL(url).openStream();
}
*/
System.setProperty("http.proxyHost", "proxy.iisc.ernet.in");
System.setProperty("http.proxyPort", "3128");
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}Example 81
| Project: seed-master File: SeedProxySelector.java View source code |
@Override public List<Proxy> select(URI uri) { if (uri == null) { throw new IllegalArgumentException("URI can't be null."); } String protocol = uri.getScheme(); if (isNotExcluded(uri) && ("http".equalsIgnoreCase(protocol))) { return Lists.newArrayList(httpProxy); } else if (isNotExcluded(uri) && ("https".equalsIgnoreCase(protocol))) { return Lists.newArrayList(httpsProxy); } else if (defaultProxySelector != null) { return defaultProxySelector.select(uri); } else { return Lists.newArrayList(Proxy.NO_PROXY); } }
Example 82
| Project: slack4gerrit-master File: Connector.java View source code |
public static void main(String[] args) throws Exception {
Properties parameters = new Properties();
parameters.load(new FileReader(DEFAULT_PROPERTIES_FILE));
if (!parameters.containsKey(Constants.GERRIT_URL)) {
throw new IllegalArgumentException("missing property '" + Constants.GERRIT_URL + "' in " + DEFAULT_PROPERTIES_FILE);
}
if (!parameters.containsKey(Constants.CHANGE_INFO_FORMATTER_CLASS)) {
throw new IllegalArgumentException("missing property '" + Constants.CHANGE_INFO_FORMATTER_CLASS + "' in " + DEFAULT_PROPERTIES_FILE);
}
injector = Guice.createInjector(new BaseModule(parameters));
SlackSession session;
if (parameters.containsKey(Constants.PROXY_HOST)) {
String proxyURL = parameters.getProperty(Constants.PROXY_HOST);
int proxyPort = Integer.parseInt(parameters.getProperty(Constants.PROXY_PORT, "80"));
session = SlackSessionFactory.createWebSocketSlackSession(parameters.getProperty(Constants.BOT_TOKEN), Proxy.Type.HTTP, proxyURL, proxyPort);
} else {
session = SlackSessionFactory.createWebSocketSlackSession(parameters.getProperty(Constants.BOT_TOKEN));
}
ReviewRequestService reviewRequestService = Connector.injector.getProvider(ReviewRequestService.class).get();
GerritChangeInfoService gerritChangeInfoService = Connector.injector.getProvider(GerritChangeInfoService.class).get();
session.addMessagePostedListener(new ReviewMessageListener());
scheduledExecutor.scheduleAtFixedRate(new ReviewRequestCleanupTask(reviewRequestService, gerritChangeInfoService, session), 1, 5, TimeUnit.MINUTES);
session.connect();
Thread.sleep(Long.MAX_VALUE);
}Example 83
| Project: spring-roo-custom-master File: ProxyConfigurationCommands.java View source code |
@CliCommand(value = "proxy configuration", help = "Shows the proxy server configuration")
public String proxyConfiguration() throws MalformedURLException {
final Proxy p = proxyService.setupProxy(new URL("http://www.springsource.org/roo"));
final StringBuilder sb = new StringBuilder();
if (p == null) {
sb.append(" *** Your system has no proxy setup ***").append(LINE_SEPARATOR);
sb.append("http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html offers useful information.").append(LINE_SEPARATOR);
sb.append("For most people, simply edit /etc/java-6-openjdk/net.properties (or equivalent) and set the").append(LINE_SEPARATOR);
sb.append("java.net.useSystemProxies=true property to use your operating system-defined proxy settings.");
} else {
sb.append("Proxy to use: ").append(p);
}
return sb.toString();
}Example 84
| Project: spring-security-oauth-master File: OAuthOverHttpURLStreamHandler.java View source code |
@Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
HttpURLConnection connection = (HttpURLConnection) super.openConnection(url, proxy);
connection.setRequestMethod(this.httpMethod);
if (resourceDetails.isAcceptsAuthorizationHeader()) {
String authHeader = support.getAuthorizationHeader(resourceDetails, accessToken, url, httpMethod, additionalParameters);
connection.setRequestProperty("Authorization", authHeader);
}
return connection;
}Example 85
| Project: stackify-api-java-master File: HttpProxy.java View source code |
/** * @return Proxy from system settings */ public static Proxy fromSystemProperties() { try { String proxyHost = System.getProperty("https.proxyHost"); String proxyPort = System.getProperty("https.proxyPort"); if ((proxyHost != null) && (!proxyHost.isEmpty())) { if ((proxyPort != null) && (!proxyPort.isEmpty())) { return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))); } } } catch (Throwable t) { LOGGER.info("Unable to read HTTP proxy information from system properties", t); } return Proxy.NO_PROXY; }
Example 86
| Project: SwipeCardsView-master File: RequestLine.java View source code |
/**
* Returns the request status line, like "GET / HTTP/1.1". This is exposed
* to the application by {@link HttpURLConnection#getHeaderFields}, so it
* needs to be set even if the transport is SPDY.
*/
static String get(Request request, Proxy.Type proxyType) {
StringBuilder result = new StringBuilder();
result.append(request.method());
result.append(' ');
if (includeAuthorityInRequestLine(request, proxyType)) {
result.append(request.url());
} else {
result.append(requestPath(request.url()));
}
result.append(" HTTP/1.1");
return result.toString();
}Example 87
| Project: TNTRun-master File: VersionChecker.java View source code |
public static byte[] get(URL url) {
try {
HttpURLConnection c = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
c.setRequestMethod("GET");
c.setRequestProperty("Host", url.getHost());
BufferedInputStream in = new BufferedInputStream(c.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
Streams.pipeStreams(in, out);
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
Bukkit.getLogger().log(Level.WARNING, "[TNTRun] An error was occured while checking version! Please report this here: https://www.spigotmc.org/threads/tntrun.67418/");
}
return null;
}Example 88
| Project: moxie-master File: BuildConfig.java View source code |
public java.net.Proxy getProxy(String repositoryId, String url) { if (proxies.size() == 0) { return java.net.Proxy.NO_PROXY; } for (Proxy proxy : proxies) { if (proxy.active && proxy.matches(repositoryId, url)) { return new java.net.Proxy(java.net.Proxy.Type.HTTP, proxy.getSocketAddress()); } } return java.net.Proxy.NO_PROXY; }
Example 89
| Project: Simutalk2-master File: HttpUtils.java View source code |
/**
* ¸ù¾ÝURL»ñÈ¡·þÎñÆ÷µÄ·µ»Ø×Ö·û´®,²¢±£´æÔÚ±¾µØ»º´æÖÐ
*
* @author haitian
*/
public static byte[] getServerString(Context context, String aurl, boolean flag) {
byte[] ret = null;
URL url = null;
HttpURLConnection cn = null;
ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
int BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
LogInfo.LogOut("request: " + aurl);
if (!URLUtil.isHttpUrl(aurl)) {
return ret;
}
try {
url = new URL(aurl);
String proxyHost = android.net.Proxy.getDefaultHost();
if (isWifi(context)) {
cn = (HttpURLConnection) url.openConnection();
} else {
if (proxyHost != null) {
java.net.Proxy p = new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(android.net.Proxy.getDefaultHost(), android.net.Proxy.getDefaultPort()));
cn = (HttpURLConnection) url.openConnection(p);
} else {
cn = (HttpURLConnection) url.openConnection();
}
}
cn.setRequestProperty("Accept", "*/*");
cn.setRequestProperty("Accept-Language", "zh-cn");
cn.setRequestProperty("Accept-Encoding", "");
cn.setAllowUserInteraction(false);
cn.setConnectTimeout(NetDefine.HTTP_CONNECT_TIMEOUT);
cn.setReadTimeout(NetDefine.HTTP_READ_TIMEOUT);
cn.setRequestMethod("GET");
cn.setDoInput(true);
cn.connect();
InputStream is = cn.getInputStream();
int nRead = 0;
while ((nRead = is.read(buf, 0, BUFFER_SIZE)) != -1) {
if (nRead > 0) {
out.write(buf, 0, nRead);
}
}
out.flush();
// ÓеÄandroidÊÖ»úÖ§³Ö´ËÖÖÌæ»»·½Ê½
ret = out.toByteArray();
if (flag) {
saveVoiceData(downId, ret, fileType);
}
} catch (Exception e) {
e.printStackTrace();
LogInfo.LogOut("dataException:" + e.getMessage());
} finally {
if (cn != null) {
cn.disconnect();
}
cn = null;
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
out = null;
}
return ret;
}Example 90
| Project: auto-master File: TypeSimplifierTest.java View source code |
@Test
public void testImportsForPlainTypes() {
Set<TypeMirror> types = typeMirrorSet(typeUtils.getPrimitiveType(TypeKind.INT), typeMirrorOf(java.lang.String.class), typeMirrorOf(java.net.Proxy.class), typeMirrorOf(java.net.Proxy.Type.class), typeMirrorOf(java.util.regex.Pattern.class), typeMirrorOf(javax.management.MBeanServer.class));
List<String> expectedImports = ImmutableList.of("java.net.Proxy", "java.util.regex.Pattern", "javax.management.MBeanServer");
TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, "foo.bar", types, baseWithoutContainedTypes());
assertThat(typeSimplifier.typesToImport()).containsExactlyElementsIn(expectedImports).inOrder();
assertThat(typeSimplifier.simplify(typeMirrorOf(java.net.Proxy.class))).isEqualTo("Proxy");
assertThat(typeSimplifier.simplify(typeMirrorOf(java.net.Proxy.Type.class))).isEqualTo("Proxy.Type");
}Example 91
| Project: bazel-master File: ProxyHelper.java View source code |
/**
* This method takes a String for the resource being requested and sets up a proxy to make
* the request if HTTP_PROXY and/or HTTPS_PROXY environment variables are set.
*
* @param requestedUrl remote resource that may need to be retrieved through a proxy
*/
public Proxy createProxyIfNeeded(URL requestedUrl) throws IOException {
String proxyAddress = null;
if (HttpUtils.isProtocol(requestedUrl, "https")) {
proxyAddress = env.get("https_proxy");
if (Strings.isNullOrEmpty(proxyAddress)) {
proxyAddress = env.get("HTTPS_PROXY");
}
} else if (HttpUtils.isProtocol(requestedUrl, "http")) {
proxyAddress = env.get("http_proxy");
if (Strings.isNullOrEmpty(proxyAddress)) {
proxyAddress = env.get("HTTP_PROXY");
}
}
return createProxy(proxyAddress);
}Example 92
| Project: commons-master File: UrlResolverUtil.java View source code |
/**
* Returns the URL that {@code url} lands on, which will be the result of a 3xx redirect,
* or {@code url} if the url does not redirect using an HTTP 3xx response code. If there is a
* non-2xx or 3xx HTTP response code null is returned.
*
* @param url The URL to follow.
* @return The redirected URL, or {@code url} if {@code url} returns a 2XX response, otherwise
* null
* @throws java.io.IOException If an error occurs while trying to follow the url.
*/
String getEffectiveUrl(String url, @Nullable ProxyConfig proxyConfig) throws IOException {
Preconditions.checkNotNull(url);
// Don't follow https.
if (url.startsWith("https://")) {
url = url.replace("https://", "http://");
} else if (!url.startsWith("http://")) {
url = "http://" + url;
}
URL urlObj = new URL(url);
HttpURLConnection con;
if (proxyConfig != null) {
Proxy proxy = new Proxy(Type.HTTP, proxyConfig.getProxyAddress());
con = (HttpURLConnection) urlObj.openConnection(proxy);
ProxyAuthorizer.adapt(proxyConfig).authorize(con);
} else {
con = (HttpURLConnection) urlObj.openConnection();
}
try {
// TODO(John Sirois): several commonly tweeted hosts 406 or 400 on HEADs and only work with GETs
// fix the call chain to be able to specify retry-with-GET
con.setRequestMethod("HEAD");
con.setUseCaches(true);
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setInstanceFollowRedirects(false);
// I hate to have to do this, but some URL shorteners don't respond otherwise.
con.setRequestProperty("User-Agent", urlToUserAgent.apply(urlObj));
try {
con.connect();
} catch (StringIndexOutOfBoundsException e) {
LOG.info("Got StringIndexOutOfBoundsException when fetching headers for " + url);
return null;
}
int responseCode = con.getResponseCode();
switch(responseCode / 100) {
case 2:
return url;
case 3:
String location = con.getHeaderField("Location");
if (location == null) {
if (responseCode != 304) /* not modified */
{
LOG.info(String.format("[%d] Location header was null for URL: %s", responseCode, url));
}
return url;
}
// is relative, so we need to check.
try {
String domain = UrlHelper.getDomainChecked(location);
if (domain == null || domain.isEmpty()) {
// This is a relative URI.
location = "http://" + UrlHelper.getDomain(url) + location;
}
} catch (URISyntaxException e) {
LOG.info("location contained an invalid URI: " + location);
}
return location;
default:
LOG.info("Failed to resolve url: " + url + " with: " + responseCode + " -> " + con.getResponseMessage());
return null;
}
} finally {
con.disconnect();
}
}Example 93
| Project: commons-old-master File: UrlResolverUtil.java View source code |
/**
* Returns the URL that {@code url} lands on, which will be the result of a 3xx redirect,
* or {@code url} if the url does not redirect using an HTTP 3xx response code. If there is a
* non-2xx or 3xx HTTP response code null is returned.
*
* @param url The URL to follow.
* @return The redirected URL, or {@code url} if {@code url} returns a 2XX response, otherwise
* null
* @throws java.io.IOException If an error occurs while trying to follow the url.
*/
String getEffectiveUrl(String url, @Nullable ProxyConfig proxyConfig) throws IOException {
Preconditions.checkNotNull(url);
// Don't follow https.
if (url.startsWith("https://")) {
url = url.replace("https://", "http://");
} else if (!url.startsWith("http://")) {
url = "http://" + url;
}
URL urlObj = new URL(url);
HttpURLConnection con;
if (proxyConfig != null) {
Proxy proxy = new Proxy(Type.HTTP, proxyConfig.getProxyAddress());
con = (HttpURLConnection) urlObj.openConnection(proxy);
ProxyAuthorizer.adapt(proxyConfig).authorize(con);
} else {
con = (HttpURLConnection) urlObj.openConnection();
}
try {
// TODO(John Sirois): several commonly tweeted hosts 406 or 400 on HEADs and only work with GETs
// fix the call chain to be able to specify retry-with-GET
con.setRequestMethod("HEAD");
con.setUseCaches(true);
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setInstanceFollowRedirects(false);
// I hate to have to do this, but some URL shorteners don't respond otherwise.
con.setRequestProperty("User-Agent", urlToUserAgent.apply(urlObj));
try {
con.connect();
} catch (StringIndexOutOfBoundsException e) {
LOG.info("Got StringIndexOutOfBoundsException when fetching headers for " + url);
return null;
}
int responseCode = con.getResponseCode();
switch(responseCode / 100) {
case 2:
return url;
case 3:
String location = con.getHeaderField("Location");
if (location == null) {
if (responseCode != 304) /* not modified */
{
LOG.info(String.format("[%d] Location header was null for URL: %s", responseCode, url));
}
return url;
}
// is relative, so we need to check.
try {
String domain = UrlHelper.getDomainChecked(location);
if (domain == null || domain.isEmpty()) {
// This is a relative URI.
location = "http://" + UrlHelper.getDomain(url) + location;
}
} catch (URISyntaxException e) {
LOG.info("location contained an invalid URI: " + location);
}
return location;
default:
LOG.info("Failed to resolve url: " + url + " with: " + responseCode + " -> " + con.getResponseMessage());
return null;
}
} finally {
con.disconnect();
}
}Example 94
| Project: Correct-master File: ProxyHelper.java View source code |
/**
* This method takes a String for the resource being requested and sets up a proxy to make
* the request if HTTP_PROXY and/or HTTPS_PROXY environment variables are set.
*
* @param requestedUrl remote resource that may need to be retrieved through a proxy
*/
public Proxy createProxyIfNeeded(URL requestedUrl) throws IOException {
String proxyAddress = null;
if (HttpUtils.isProtocol(requestedUrl, "https")) {
proxyAddress = env.get("https_proxy");
if (Strings.isNullOrEmpty(proxyAddress)) {
proxyAddress = env.get("HTTPS_PROXY");
}
} else if (HttpUtils.isProtocol(requestedUrl, "http")) {
proxyAddress = env.get("http_proxy");
if (Strings.isNullOrEmpty(proxyAddress)) {
proxyAddress = env.get("HTTP_PROXY");
}
}
return createProxy(proxyAddress);
}Example 95
| Project: generators-master File: TypeSimplifierTest.java View source code |
@Test
public void testImportsForPlainTypes() {
Set<TypeMirror> types = typeMirrorSet(typeUtils.getPrimitiveType(TypeKind.INT), typeMirrorOf(java.lang.String.class), typeMirrorOf(java.net.Proxy.class), typeMirrorOf(java.net.Proxy.Type.class), typeMirrorOf(java.util.regex.Pattern.class), typeMirrorOf(javax.management.MBeanServer.class));
List<String> expectedImports = ImmutableList.of("java.net.Proxy", "java.util.regex.Pattern", "javax.management.MBeanServer");
TypeSimplifier typeSimplifier = new TypeSimplifier(typeUtils, "foo.bar", types, baseWithoutContainedTypes());
assertThat(typeSimplifier.typesToImport()).containsExactlyElementsIn(expectedImports).inOrder();
assertThat(typeSimplifier.simplify(typeMirrorOf(java.net.Proxy.class))).isEqualTo("Proxy");
assertThat(typeSimplifier.simplify(typeMirrorOf(java.net.Proxy.Type.class))).isEqualTo("Proxy.Type");
}Example 96
| Project: jmxtrans2-master File: LibratoWriterFactory.java View source code |
@Nonnull
@Override
public BatchingOutputWriter<HttpOutputWriter<LibratoWriter>> create(@Nonnull Map<String, String> settings) {
int batchSize = getInt(settings, "batchSize", 100);
URL url = parseUrl(getString(settings, "libratoUrl", "https://metrics-api.librato.com/v1/metrics"));
int timeoutInMillis = getInt(settings, "timeoutInMillis", 1000);
Proxy proxy = getProxy(settings);
// FIXME: correct handling of source should be implemented after #60 is done.
String source = "hostname";
String username = getString(settings, "username", null);
String token = getString(settings, "token", null);
HttpOutputWriter.Builder<LibratoWriter> httpOutputWriter = builder(url, loadAppInfo(), new LibratoWriter(new JsonFactory(), source)).withContentType("application/json; charset=utf-8").withTimeout(timeoutInMillis, MILLISECONDS);
if (username != null && !username.isEmpty()) {
httpOutputWriter.withAuthentication(username, token);
}
if (proxy != null) {
httpOutputWriter.withProxy(proxy);
}
return new BatchingOutputWriter<>(batchSize, httpOutputWriter.build());
}Example 97
| Project: jruby-maven-plugins-master File: MavenGemWagon.java View source code |
@Override
public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
Resource resource = inputData.getResource();
try {
if (proxy != Proxy.NO_PROXY) {
warn("proxy support is not implemented - ignoring proxy settings");
}
URLConnection urlConnection = newConnection(resource.getName());
InputStream is = urlConnection.getInputStream();
inputData.setInputStream(is);
resource.setLastModified(urlConnection.getLastModified());
resource.setContentLength(urlConnection.getContentLength());
} catch (MalformedURLException e) {
throw new TransferFailedException("Invalid repository URL: " + e.getMessage(), e);
} catch (FileNotFoundException e) {
throw new ResourceDoesNotExistException("Unable to locate resource in repository", e);
} catch (IOException e) {
throw new TransferFailedException("Error transferring file: " + e.getMessage(), e);
}
}Example 98
| Project: legacy-jclouds-master File: ProxyForURITest.java View source code |
@Test
public void testDontUseProxyForSockets() throws Exception {
ProxyConfig config = new MyProxyConfig(false, Proxy.Type.HTTP, hostAndPort, creds);
ProxyForURI proxy = new ProxyForURI(config);
Field useProxyForSockets = proxy.getClass().getDeclaredField("useProxyForSockets");
useProxyForSockets.setAccessible(true);
useProxyForSockets.setBoolean(proxy, false);
URI uri = new URI("socket://ssh.example.com:22");
assertEquals(proxy.apply(uri), Proxy.NO_PROXY);
}Example 99
| Project: org-tools-master File: IOToolBox.java View source code |
public static Proxy determineProxy(URL url) throws URISyntaxException { IProxyService proxyService = PlatformUtilsPlugin.getDefault().getProxyService(); IProxyData[] proxyData = proxyService.select(url.toURI()); Proxy proxy = Proxy.NO_PROXY; if (proxyData != null && proxyData.length > 0) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyData[0].getHost(), proxyData[0].getPort())); } return proxy; }
Example 100
| Project: Spoutcraft-master File: Main.java View source code |
public static void main(String[] par0ArrayOfStr) {
System.setProperty("java.net.preferIPv4Stack", "true");
OptionParser var1 = new OptionParser();
var1.allowsUnrecognizedOptions();
var1.accepts("demo");
var1.accepts("fullscreen");
ArgumentAcceptingOptionSpec var2 = var1.accepts("server").withRequiredArg();
ArgumentAcceptingOptionSpec var3 = var1.accepts("port").withRequiredArg().ofType(Integer.class).defaultsTo(Integer.valueOf(25565), new Integer[0]);
ArgumentAcceptingOptionSpec var4 = var1.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File("."), new File[0]);
ArgumentAcceptingOptionSpec var5 = var1.accepts("assetsDir").withRequiredArg().ofType(File.class);
ArgumentAcceptingOptionSpec var6 = var1.accepts("resourcePackDir").withRequiredArg().ofType(File.class);
ArgumentAcceptingOptionSpec var7 = var1.accepts("proxyHost").withRequiredArg();
ArgumentAcceptingOptionSpec var8 = var1.accepts("proxyPort").withRequiredArg().defaultsTo("8080", new String[0]).ofType(Integer.class);
ArgumentAcceptingOptionSpec var9 = var1.accepts("proxyUser").withRequiredArg();
ArgumentAcceptingOptionSpec var10 = var1.accepts("proxyPass").withRequiredArg();
ArgumentAcceptingOptionSpec var11 = var1.accepts("username").withRequiredArg().defaultsTo("Player" + Minecraft.getSystemTime() % 1000L, new String[0]);
ArgumentAcceptingOptionSpec var12 = var1.accepts("session").withRequiredArg().defaultsTo("Invalid Session ID", new String[0]);
ArgumentAcceptingOptionSpec var13 = var1.accepts("version").withRequiredArg().required();
ArgumentAcceptingOptionSpec var14 = var1.accepts("width").withRequiredArg().ofType(Integer.class).defaultsTo(Integer.valueOf(854), new Integer[0]);
ArgumentAcceptingOptionSpec var15 = var1.accepts("height").withRequiredArg().ofType(Integer.class).defaultsTo(Integer.valueOf(480), new Integer[0]);
NonOptionArgumentSpec var16 = var1.nonOptions();
OptionSet var17 = var1.parse(par0ArrayOfStr);
List var18 = var17.valuesOf(var16);
String var19 = (String) var17.valueOf(var7);
Proxy var20 = Proxy.NO_PROXY;
if (var19 != null) {
try {
var20 = new Proxy(Type.SOCKS, new InetSocketAddress(var19, ((Integer) var17.valueOf(var8)).intValue()));
} catch (Exception var34) {
;
}
}
String var21 = (String) var17.valueOf(var9);
String var22 = (String) var17.valueOf(var10);
if (!var20.equals(Proxy.NO_PROXY) && func_110121_a(var21) && func_110121_a(var22)) {
Authenticator.setDefault(new MainProxyAuthenticator(var21, var22));
}
int var23 = ((Integer) var17.valueOf(var14)).intValue();
int var24 = ((Integer) var17.valueOf(var15)).intValue();
boolean var25 = var17.has("fullscreen");
boolean var26 = var17.has("demo");
String var27 = (String) var17.valueOf(var13);
File var28 = (File) var17.valueOf(var4);
File var29 = var17.has(var5) ? (File) var17.valueOf(var5) : new File(var28, "assets/");
File var30 = var17.has(var6) ? (File) var17.valueOf(var6) : new File(var28, "resourcepacks/");
Session var31 = new Session((String) var11.value(var17), (String) var12.value(var17));
Minecraft var32 = new Minecraft(var31, var23, var24, var25, var26, var28, var29, var30, var20, var27);
String var33 = (String) var17.valueOf(var2);
if (var33 != null) {
var32.setServer(var33, ((Integer) var17.valueOf(var3)).intValue());
}
Runtime.getRuntime().addShutdownHook(new MainShutdownHook());
if (!var18.isEmpty()) {
System.out.println("Completely ignored arguments: " + var18);
}
Thread.currentThread().setName("Minecraft main thread");
DownloadAssets.importOldConfig();
var32.run();
}Example 101
| Project: test-master File: ProxyHelper.java View source code |
/**
* This method takes a String for the resource being requested and sets up a proxy to make
* the request if HTTP_PROXY and/or HTTPS_PROXY environment variables are set.
*
* @param requestedUrl remote resource that may need to be retrieved through a proxy
*/
public Proxy createProxyIfNeeded(URL requestedUrl) throws IOException {
String proxyAddress = null;
if (HttpUtils.isProtocol(requestedUrl, "https")) {
proxyAddress = env.get("https_proxy");
if (Strings.isNullOrEmpty(proxyAddress)) {
proxyAddress = env.get("HTTPS_PROXY");
}
} else if (HttpUtils.isProtocol(requestedUrl, "http")) {
proxyAddress = env.get("http_proxy");
if (Strings.isNullOrEmpty(proxyAddress)) {
proxyAddress = env.get("HTTP_PROXY");
}
}
return createProxy(proxyAddress);
}