@Override
  public List<Proxy> select(URI uri) {
    String url = uri.toString().replace("www", "");
    if (!uri.getScheme().startsWith("http") && Bukkit.isPrimaryThread()) {
      Exception stackTraceCreator = new Exception();
      StackTraceElement[] stackTrace = stackTraceCreator.getStackTrace();

      // remove the parts from LagMonitor
      StackTraceElement[] copyOfRange = Arrays.copyOfRange(stackTrace, 1, stackTrace.length);
      Entry<Plugin, StackTraceElement> foundPlugin = PluginUtil.findPlugin(copyOfRange);

      PluginViolation violation = new PluginViolation(url);
      if (foundPlugin != null) {
        String pluginName = foundPlugin.getKey().getName();
        violation = new PluginViolation(pluginName, foundPlugin.getValue(), url);

        if (!violatedPlugins.add(violation.getPluginName())
            && plugin.getConfig().getBoolean("oncePerPlugin")) {
          return oldProxySelector == null
              ? Lists.newArrayList(Proxy.NO_PROXY)
              : oldProxySelector.select(uri);
        }
      }

      if (!violations.add(violation)) {
        return oldProxySelector == null
            ? Lists.newArrayList(Proxy.NO_PROXY)
            : oldProxySelector.select(uri);
      }

      plugin
          .getLogger()
          .log(
              Level.WARNING,
              "Plugin {0} is performing a blocking action to {1} on the main thread"
                  + " This could be a performance hit."
                  + " Report it to the plugin author",
              new Object[] {violation.getPluginName(), url});

      if (plugin.getConfig().getBoolean("hideStacktrace")) {
        if (foundPlugin != null) {
          StackTraceElement source = foundPlugin.getValue();
          plugin
              .getLogger()
              .log(
                  Level.WARNING,
                  "Source: {0}, method {1}, line {2}",
                  new Object[] {
                    source.getClassName(), source.getMethodName(), source.getLineNumber()
                  });
        }
      } else {
        plugin.getLogger().log(Level.WARNING, "", stackTraceCreator);
      }
    }

    return oldProxySelector == null
        ? Lists.newArrayList(Proxy.NO_PROXY)
        : oldProxySelector.select(uri);
  }
示例#2
0
  /** Get or create the http client to be used to fetch all the map data. */
  public HttpClient getHttpClient(URI uri) {
    MultiThreadedHttpConnectionManager connectionManager = getConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);

    // httpclient is a bit pesky about loading everything in memory...
    // disabling the warnings.
    Logger.getLogger(HttpMethodBase.class).setLevel(Level.ERROR);

    // configure proxies for URI
    ProxySelector selector = ProxySelector.getDefault();

    List<Proxy> proxyList = selector.select(uri);
    Proxy proxy = proxyList.get(0);

    if (!proxy.equals(Proxy.NO_PROXY)) {
      InetSocketAddress socketAddress = (InetSocketAddress) proxy.address();
      String hostName = socketAddress.getHostName();
      int port = socketAddress.getPort();

      httpClient.getHostConfiguration().setProxy(hostName, port);
    }

    for (SecurityStrategy sec : security)
      if (sec.matches(uri)) {
        sec.configure(uri, httpClient);
        break;
      }
    return httpClient;
  }
  // Result host and port are returned in a string in the format host:port
  public static String[] getProxyForURL(String target) {
    String[] proxyInfo = new String[0];
    List<String> proxies = new ArrayList<String>();
    URI uri = null;
    try {
      ProxySelector defaultProxySelector = ProxySelector.getDefault();
      uri = new URI(target);
      List<Proxy> proxyList = defaultProxySelector.select(uri);

      Proxy proxy = proxyList.get(0);
      if (proxy.equals(Proxy.NO_PROXY)) {
        System.out.println("DalvikProxySelector.getProxyForURL(): No proxy found");
        return null;
      }
      SocketAddress address = proxy.address();
      InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
      String host = inetSocketAddress.getHostName();
      int port = inetSocketAddress.getPort();
      if (host == null) {
        System.out.println("DalvikProxySelector.getProxyForURL(): No proxy found");
        return null;
      }

      proxies.add(host); // even index, host
      proxies.add(Integer.toString(port)); // odd index, port

      System.out.println("DalvikProxySelector.getProxyForURL(): host=" + host + " port=" + port);
      return proxies.toArray(new String[0]);
    } catch (Exception e) {
      System.out.println(
          "DalvikProxySelector.getProxyForURL(): exception(ignored): " + e.toString());
      return null;
    }
  }
  /** Tests select(URI) NO_PROXY */
  @Test
  public void testSelect_Direct() {
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    List<Proxy> list = ps.select(testHttpUri);
    assertEquals(list.get(0), Proxy.NO_PROXY);
  }
示例#5
0
 /**
  * Gets proxy list according to the URI by system ProxySelector.
  *
  * @param uri
  * @return a list of proxy for the URI. Returns null if no proxy is available.
  */
 public static List<Proxy> getProxyList(URI uri) {
   // use system default selector to get proxy list
   ProxySelector selector = ProxySelector.getDefault();
   if (null == selector) {
     return null;
   }
   return selector.select(uri);
 }
  @Before
  public void init() {
    MyProxySelector ps = new MyProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Injector injector = Guice.createInjector();
    documentService = injector.getInstance(DocumentService.class);
  }
  @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());
    }
  }
 /**
  * Establishes the connection to the remote HTTP server
  *
  * <p>Any methods that requires a valid connection to the resource will call this method
  * implicitly. After the connection is established, <code>connected</code> is set to true.
  *
  * @see #connected
  * @see java.io.IOException
  * @see URLStreamHandler
  */
 @Override
 public void connect() throws IOException {
   if (connected) {
     return;
   }
   if (getFromCache()) {
     return;
   }
   try {
     uri = url.toURI();
   } catch (URISyntaxException e1) {
     // ignore
   }
   // socket to be used for connection
   connection = null;
   // try to determine: to use the proxy or not
   if (proxy != null) {
     // try to make the connection to the proxy
     // specified in constructor.
     // IOException will be thrown in the case of failure
     connection = getHTTPConnection(proxy);
   } else {
     // Use system-wide ProxySelect to select proxy list,
     // then try to connect via elements in the proxy list.
     ProxySelector selector = ProxySelector.getDefault();
     List<Proxy> proxyList = selector.select(uri);
     if (proxyList != null) {
       for (Proxy selectedProxy : proxyList) {
         if (selectedProxy.type() == Proxy.Type.DIRECT) {
           // the same as NO_PROXY
           continue;
         }
         try {
           connection = getHTTPConnection(selectedProxy);
           proxy = selectedProxy;
           break; // connected
         } catch (IOException e) {
           // failed to connect, tell it to the selector
           selector.connectFailed(uri, selectedProxy.address(), e);
         }
       }
     }
   }
   if (connection == null) {
     // make direct connection
     connection = getHTTPConnection(null);
   }
   connection.setSoTimeout(getReadTimeout());
   setUpTransportIO(connection);
   connected = true;
 }
示例#9
0
 public static void init(
     ProxyInfo defaultProxy,
     Set<String> exclude,
     Set<UrlProxyInfo> include,
     boolean isLogEnabled) {
   sLogEnabled = isLogEnabled;
   if (exclude != null) {
     sExcludeSet = exclude;
   }
   if (include != null) {
     sIncludeSet = include;
   }
   sDefaultProxy = defaultProxy;
   ProxySelector.setDefault(new EasyProxySelector(ProxySelector.getDefault()));
 }
 /**
  * *********************************************************************** Test method
  *
  * @throws ProxyException on proxy detection error.
  * @throws URISyntaxException on invalid URL syntax.
  *     **********************************************************************
  */
 @Test
 public void testManualFtp() throws ProxyException, URISyntaxException {
   System.setProperty(
       OsxProxySearchStrategy.OVERRIDE_SETTINGS_FILE,
       "test"
           + File.separator
           + "data"
           + File.separator
           + "osx"
           + File.separator
           + "osx_manual.plist");
   ProxySelector ps = new OsxProxySearchStrategy().getProxySelector();
   List<Proxy> result = ps.select(TestUtil.FTP_TEST_URI);
   assertEquals(TestUtil.FTP_TEST_PROXY, result.get(0));
 }
示例#11
0
文件: IO.java 项目: kdchamil/ASTomEE
  public static String readFileAsString(final URI uri) throws IOException {
    final StringBuilder builder = new StringBuilder("");
    for (final Proxy proxy : ProxySelector.getDefault().select(uri)) {
      final InputStream is;

      try {
        final URLConnection urlConnection = uri.toURL().openConnection(proxy);
        urlConnection.setConnectTimeout(MAX_TIMEOUT);
        is = urlConnection.getInputStream();
      } catch (IOException e) {
        continue;
      }

      String line;
      try {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        while ((line = reader.readLine()) != null) {
          builder.append(line);
        }
      } finally {
        close(is);
      }
    }

    return builder.toString();
  }
示例#12
0
 /**
  * Returns a shallow copy of this OkHttpClient that uses the system-wide default for each field
  * that hasn't been explicitly configured.
  */
 OkHttpClient copyWithDefaults() {
   OkHttpClient result = clone();
   if (result.proxySelector == null) {
     result.proxySelector = ProxySelector.getDefault();
   }
   if (result.cookieHandler == null) {
     result.cookieHandler = CookieHandler.getDefault();
   }
   if (result.cache == null && result.cacheAdapter == null) {
     // TODO: drop support for the default response cache.
     ResponseCache defaultCache = ResponseCache.getDefault();
     result.cacheAdapter = defaultCache != null ? new CacheAdapter(defaultCache) : null;
   }
   if (result.socketFactory == null) {
     result.socketFactory = SocketFactory.getDefault();
   }
   if (result.sslSocketFactory == null) {
     result.sslSocketFactory = getDefaultSSLSocketFactory();
   }
   if (result.hostnameVerifier == null) {
     result.hostnameVerifier = OkHostnameVerifier.INSTANCE;
   }
   if (result.authenticator == null) {
     result.authenticator = AuthenticatorAdapter.INSTANCE;
   }
   if (result.connectionPool == null) {
     result.connectionPool = ConnectionPool.getDefault();
   }
   if (result.protocols == null) {
     result.protocols = Util.immutableList(Protocol.HTTP_2, Protocol.SPDY_3, Protocol.HTTP_1_1);
   }
   return result;
 }
  /** Tests select(URI) HTTS */
  @Test
  public void testSelect_HTTPS() throws UnknownHostException {
    System.getProperties().put(HTTPS_PROXY_HOST, "127.0.0.1");
    System.getProperties().put(HTTPS_PROXY_PORT, "8888");

    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    List<Proxy> list = ps.select(testHttpsUri);
    assertEquals(
        list.get(0),
        new Proxy(Type.HTTP, new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 8888)));

    System.getProperties().remove(HTTPS_PROXY_HOST);
    System.getProperties().remove(HTTPS_PROXY_PORT);
  }
  @Override
  public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient
        .getParams()
        .setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner =
        new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
      httpClient
          .getCredentialsProvider()
          .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    }

    return httpClient;
  }
示例#15
0
    /**
     * Setup proxy based on JAVA_OPTS if necessary
     */
    static boolean isProxyValid() {
        //Setting up proxy if necessary
        System.setProperty("java.net.useSystemProxies","true");
        List<Proxy> proxies;
        try {
            proxies = ProxySelector.getDefault().select(new URI("http://www.google.com"));
        } catch ( URISyntaxException e) {
            log.error("Failed to create URI." + e);
            return false;
        }
        for (Proxy proxy : proxies) {
            if (proxy.type() == Proxy.Type.DIRECT) {
                log.info("Proxy is DIRECT CONNECTION");
                return true;
            }
            
            log.info("Proxy setting: host=" + System.getProperty("http.proxyHost") +
                      "port=" + System.getProperty("http.proxyPort") +
                      "user="******"http.proxyUser") +
                      "password="******"http.proxyPassword"));

            if (System.getProperty("http.proxyHost") != null &&
                System.getProperty("http.proxyPort") != null &&
                System.getProperty("http.proxyUser") != null ) return true;
            log.error("Proxy is incorrect: host=" + System.getProperty("http.proxyHost") +
                      "port=" + System.getProperty("http.proxyPort") +
                      "user="******"http.proxyUser") +
                      "password="******"http.proxyPassword"));
            return false;
        }
        return false;
    }
  private HttpClient newHttpClient(String sslProtocol, HttpRequest request) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, httpTimeoutsProvider.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(params, httpTimeoutsProvider.getSocketTimeout());

    // AG-1059: Need to follow redirects to ensure that if the host app is setup with Apache and
    // mod_jk we can still
    // fetch internal gadgets.
    if (request.getFollowRedirects()) {
      params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
      params.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);
    }
    params.setParameter(
        ClientPNames.DEFAULT_HEADERS,
        ImmutableSet.of(new BasicHeader("Accept-Encoding", "gzip, deflate")));
    DefaultHttpClient client = new DefaultHttpClient(params);
    // AG-1044: Need to use the JVM's default proxy configuration for requests.
    ProxySelectorRoutePlanner routePlanner =
        new ProxySelectorRoutePlanner(
            client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);

    client.addResponseInterceptor(new GzipDeflatingInterceptor());
    client
        .getConnectionManager()
        .getSchemeRegistry()
        .register(new Scheme("https", new CustomSSLSocketFactory(sslProtocol), 443));
    return client;
  }
 /**
  * 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 {
     server = new TestServer(80, getFile("pac42.js").getParentFile()); // $NON-NLS-1$
     final ProxySelector selector = new CoreNetProxySelector();
     final List<Proxy> proxies = selector.select(new URI("http://www.eclipse.org")); // $NON-NLS-1$
     assertEquals(2, proxies.size());
     assertEquals(
         "idproxy", ((InetSocketAddress) proxies.get(0).address()).getHostName()); // $NON-NLS-1$
     assertEquals(3128, ((InetSocketAddress) proxies.get(0).address()).getPort());
   } catch (final Throwable e) {
     fail();
   } finally {
     server.stop();
   }
 }
示例#18
0
 private static void setToUseSystemProxies() {
   final String JAVA_NET_USESYSTEMPROXIES = "java.net.useSystemProxies";
   System.setProperty(JAVA_NET_USESYSTEMPROXIES, "true");
   List<Proxy> proxyList = null;
   try {
     final ProxySelector def = ProxySelector.getDefault();
     if (def != null) {
       proxyList = def.select(new URI("http://sourceforge.net/"));
       ProxySelector.setDefault(null);
       if (proxyList != null && !proxyList.isEmpty()) {
         final Proxy proxy = proxyList.get(0);
         final InetSocketAddress address = (InetSocketAddress) proxy.address();
         if (address != null) {
           final String host = address.getHostName();
           final int port = address.getPort();
           System.setProperty(HTTP_PROXYHOST, host);
           System.setProperty(HTTP_PROXYPORT, Integer.toString(port));
           System.setProperty(PROXY_HOST, host);
           System.setProperty(PROXY_PORT, Integer.toString(port));
         } else {
           System.clearProperty(HTTP_PROXYHOST);
           System.clearProperty(HTTP_PROXYPORT);
           System.clearProperty(PROXY_HOST);
           System.clearProperty(PROXY_PORT);
         }
       }
     } else {
       final String host = System.getProperty(PROXY_HOST);
       final String port = System.getProperty(PROXY_PORT);
       if (host == null) System.clearProperty(HTTP_PROXYHOST);
       else System.setProperty(HTTP_PROXYHOST, host);
       if (port == null) System.clearProperty(HTTP_PROXYPORT);
       else {
         try {
           Integer.parseInt(port);
           System.setProperty(HTTP_PROXYPORT, port);
         } catch (final NumberFormatException nfe) {
           // nothing
         }
       }
     }
   } catch (final Exception e) {
     e.printStackTrace();
   } finally {
     System.setProperty(JAVA_NET_USESYSTEMPROXIES, "false");
   }
 }
示例#19
0
  private void setupProxy(final BundleContext context) {
    final ServiceReference proxy;

    proxy = context.getServiceReference(IProxyService.class.getName());
    if (proxy != null) {
      ProxySelector.setDefault(new EclipseProxySelector((IProxyService) context.getService(proxy)));
      Authenticator.setDefault(new EclipseAuthenticator((IProxyService) context.getService(proxy)));
    }
  }
示例#20
0
 @Override
 public List<Proxy> select(URI uri) {
   if (HTTP.equalsIgnoreCase(uri.getScheme()) || SOCKS.equalsIgnoreCase(uri.getScheme())) {
     if (isInExcludedSet(uri.toASCIIString())) {
       if (isLogEnabled()) {
         Log.d(TAG, "Found in excludedSet. Returning default proxy for url : " + uri);
       }
       if (sDefaultProxy == null) {
         return mDefaultProxySelector.select(uri);
       }
       return Arrays.asList(
           new Proxy(
               Proxy.Type.HTTP,
               new InetSocketAddress(sDefaultProxy.getHost(), sDefaultProxy.getPort())));
     }
     ProxyInfo proxyForUrl = getProxyForUrl(uri.toASCIIString());
     if (proxyForUrl != null) {
       if (isLogEnabled()) {
         Log.d(
             TAG,
             "Found in includeSet. Returning proxy ("
                 + proxyForUrl.getHost()
                 + ", "
                 + proxyForUrl.getPort()
                 + ") for url : "
                 + uri);
       }
       return Arrays.asList(
           new Proxy(
               Proxy.Type.HTTP,
               new InetSocketAddress(proxyForUrl.getHost(), proxyForUrl.getPort())));
     }
   }
   if (isLogEnabled()) {
     Log.d(TAG, "Not found anywhere. Returning default proxy (which is none generally).");
   }
   if (sDefaultProxy == null) {
     return mDefaultProxySelector.select(uri);
   }
   return Arrays.asList(
       new Proxy(
           Proxy.Type.HTTP,
           new InetSocketAddress(sDefaultProxy.getHost(), sDefaultProxy.getPort())));
 }
  @Before
  public void setup() {
    requestManager = new EtsyRequestManager(apiKey, apiSecret, callback, scope);

    DefaultHttpClient client = new DefaultHttpClient();
    HttpRoutePlanner routePlanner =
        new ProxySelectorRoutePlanner(
            client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);
  }
示例#22
0
 /** Resets {@link #nextProxy} to the first option. */
 private void resetNextProxy(URI uri, Proxy proxy) {
   this.hasNextProxy = true; // This includes NO_PROXY!
   if (proxy != null) {
     this.userSpecifiedProxy = proxy;
   } else {
     List<Proxy> proxyList = proxySelector.select(uri);
     if (proxyList != null) {
       this.proxySelectorProxies = proxyList.iterator();
     }
   }
 }
示例#23
0
  // Decide what proxy, if any, to use for a request. Manual settings take precedence,
  // then we fall back to using system settings (e.g., Internet Explorer settings on Windows)
  // as handled by the ProxySelector class introduced in Java 1.5.
  //
  // Public so that it can be called from Mathematica.
  //
  public synchronized String[] getProxyHostAndPort(String url) {

    int port = 0;
    String host = null;

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

    return new String[] {host, String.valueOf(port)};
  }
示例#24
0
 TransportHttp(final Repository local, final URIish uri) throws NotSupportedException {
   super(local, uri);
   try {
     String uriString = uri.toString();
     if (!uriString.endsWith("/")) uriString += "/";
     baseUrl = new URL(uriString);
     objectsUrl = new URL(baseUrl, "objects/");
   } catch (MalformedURLException e) {
     throw new NotSupportedException("Invalid URL " + uri, e);
   }
   proxySelector = ProxySelector.getDefault();
 }
示例#25
0
 /**
  * Establishes the connection to the resource specified by this <code>URL</code>
  *
  * @see #connected
  * @see java.io.IOException
  * @see URLStreamHandler
  */
 @Override
 public void connect() throws IOException {
   // Use system-wide ProxySelect to select proxy list,
   // then try to connect via elements in the proxy list.
   List<Proxy> proxyList = null;
   if (null != proxy) {
     proxyList = new ArrayList<Proxy>(1);
     proxyList.add(proxy);
   } else {
     proxyList = NetUtil.getProxyList(uri);
   }
   if (null == proxyList) {
     currentProxy = null;
     connectInternal();
   } else {
     ProxySelector selector = ProxySelector.getDefault();
     Iterator<Proxy> iter = proxyList.iterator();
     boolean connectOK = false;
     String failureReason = ""; // $NON-NLS-1$
     while (iter.hasNext() && !connectOK) {
       currentProxy = iter.next();
       try {
         connectInternal();
         connectOK = true;
       } catch (IOException ioe) {
         failureReason = ioe.getLocalizedMessage();
         // If connect failed, callback "connectFailed"
         // should be invoked.
         if (null != selector && Proxy.NO_PROXY != currentProxy) {
           selector.connectFailed(uri, currentProxy.address(), ioe);
         }
       }
     }
     if (!connectOK) {
       // K0097=Unable to connect to server\: {0}
       throw new IOException(Msg.getString("K0097", failureReason)); // $NON-NLS-1$
     }
   }
 }
示例#26
0
  // @Test(groups = "standalone")
  public void testUseProxySelector()
      throws IOException, ExecutionException, TimeoutException, InterruptedException {
    ProxySelector originalProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(
        new ProxySelector() {
          public List<Proxy> select(URI uri) {
            if (uri.getHost().equals("127.0.0.1")) {
              return Arrays.asList(
                  new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port1)));
            } else {
              return Arrays.asList(Proxy.NO_PROXY);
            }
          }

          public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {}
        });

    try (AsyncHttpClient client = asyncHttpClient(config().setUseProxySelector(true))) {
      String proxifiedTarget = "http://127.0.0.1:1234/";
      Future<Response> f = client.prepareGet(proxifiedTarget).execute();
      Response resp = f.get(3, TimeUnit.SECONDS);
      assertNotNull(resp);
      assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
      assertEquals(resp.getHeader("target"), "/");

      String nonProxifiedTarget = "http://localhost:1234/";
      f = client.prepareGet(nonProxifiedTarget).execute();
      try {
        f.get(3, TimeUnit.SECONDS);
        fail("should not be able to connect");
      } catch (ExecutionException e) {
        // ok, no proxy used
      }
    } finally {
      // FIXME not threadsafe
      ProxySelector.setDefault(originalProxySelector);
    }
  }
示例#27
0
 public static InputStream inputStreamTryingProxies(final URI source) throws Exception {
   final URL url = source.toURL();
   for (final Proxy proxy : ProxySelector.getDefault().select(source)) {
     // try to connect
     try {
       final URLConnection urlConnection = url.openConnection(proxy);
       urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
       return new BufferedInputStream(urlConnection.getInputStream());
     } catch (final IOException e) {
       // ignored
     }
   }
   return null;
 }
示例#28
0
 private Address newAddress(String name) {
   return new Address(
       name,
       1,
       Dns.SYSTEM,
       SocketFactory.getDefault(),
       null,
       null,
       null,
       new RecordingOkAuthenticator("password"),
       null,
       Collections.<Protocol>emptyList(),
       Collections.<ConnectionSpec>emptyList(),
       ProxySelector.getDefault());
 }
  private Socket createSocket(URI uri, InetSocketAddress address, int timeout) throws IOException {
    List<Proxy> proxies = ProxySelector.getDefault().select(uri);
    IOException lastFailure = null;
    for (Proxy proxy : proxies) {
      ConnectivitySettings cs = proxyToCs(proxy, uri);
      try {
        Socket s = createSocket(cs, address, timeout);
        lastKnownSettings.put(address, cs);
        return s;
      } catch (IOException e) {
        lastFailure = e;
      }
    }

    throw lastFailure;
  }
 /** {@inheritDoc} */
 @Override
 public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
   if (uri == null || sa == null || ioe == null) {
     throw new IllegalArgumentException("Arguments can not be null.");
   }
   final ProxyDecorator p = proxies.get(sa);
   if (p != null) {
     if (p.failed() >= 3) {
       proxies.remove(sa);
     }
   } else {
     if (defaultSelector != null) {
       defaultSelector.connectFailed(uri, sa, ioe);
     }
   }
 }