コード例 #1
1
  private HttpClient getClient() {
    if (client == null) {
      HttpClientBuilder clientBuilder = HttpClients.custom();
      RequestConfig.Builder configBuilder = RequestConfig.custom();
      if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        isUsingProxy = true;
        InetSocketAddress adr = (InetSocketAddress) proxy.address();
        clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
      }
      if (timeout != null) {
        configBuilder.setConnectTimeout(timeout.intValue());
      }
      if (readTimeout != null) {
        configBuilder.setSocketTimeout(readTimeout.intValue());
      }
      if (followRedirects != null) {
        configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
      }
      if (hostnameverifier != null) {
        SSLConnectionSocketFactory sslConnectionFactory =
            new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier);
        clientBuilder.setSSLSocketFactory(sslConnectionFactory);
        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .build();
        clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
      }
      clientBuilder.setDefaultRequestConfig(configBuilder.build());
      client = clientBuilder.build();
    }

    return client;
  }
コード例 #2
0
  public static boolean lowLevelPingHost(Proxy proxy) {
    int exitValue;
    Runtime runtime = Runtime.getRuntime();
    Process proc;

    String cmdline = null;
    String proxyAddress = null;

    try {
      InetSocketAddress proxySocketAddress = (InetSocketAddress) proxy.address();
      proxyAddress = proxySocketAddress.getAddress().getHostAddress();
    } catch (Exception e) {
      APL.getEventReport()
          .send(
              new Exception(
                  "ProxyUtils.lowLevelPingHost() Exception calling getAddress().getHostAddress() on proxySocketAddress : ",
                  e));
    }

    if (proxyAddress == null) {
      try {
        InetSocketAddress proxySocketAddress = (InetSocketAddress) proxy.address();
        proxyAddress = proxySocketAddress.toString();
      } catch (Exception e) {
        APL.getEventReport()
            .send(
                new Exception(
                    "ProxyUtils.lowLevelPingHost() Exception calling toString() on proxySocketAddress",
                    e));
      }
    }

    if (proxyAddress != null) {
      cmdline = "ping -c 1 -w 1 " + proxyAddress;

      try {
        proc = runtime.exec(cmdline);
        proc.waitFor();
        exitValue = proc.exitValue();

        LogWrapper.d(TAG, "Ping exit value: " + exitValue);

        if (exitValue == 0) {
          return true;
        } else {
          return false;
        }
      } catch (IOException e) {
        APL.getEventReport().send(new Exception("ProxyUtils.lowLevelPingHost() IOException", e));
      } catch (InterruptedException e) {
        APL.getEventReport()
            .send(new Exception("ProxyUtils.lowLevelPingHost() InterruptedException", e));
      }
    }

    return false;
  }
コード例 #3
0
 public void setProxy(final Proxy proxy) {
   final String DELIM = "|";
   if (proxy != Proxy.NO_PROXY && proxy.type() != Proxy.Type.DIRECT) {
     final StringBuffer sb = new StringBuffer();
     sb.append(proxy.type().toString()).append(DELIM);
     sb.append(Integer.toString(((InetSocketAddress) proxy.address()).getPort())).append(DELIM);
     sb.append(proxy.address().toString());
     proxySettings = sb.toString();
   } else {
     proxySettings = "";
   }
 }
コード例 #4
0
 private void resetNextInetSocketAddress(Proxy paramProxy) throws IOException {
   this.inetSocketAddresses = new ArrayList();
   if ((paramProxy.type() == Proxy.Type.DIRECT) || (paramProxy.type() == Proxy.Type.SOCKS)) {
     paramProxy = this.address.getUriHost();
   }
   Object localObject;
   for (int i = this.address.getUriPort();
       (i < 1) || (i > 65535);
       i = ((InetSocketAddress) localObject).getPort()) {
     throw new SocketException("No route to " + paramProxy + ":" + i + "; port is out of range");
     paramProxy = paramProxy.address();
     if (!(paramProxy instanceof InetSocketAddress)) {
       throw new IllegalArgumentException(
           "Proxy.address() is not an InetSocketAddress: " + paramProxy.getClass());
     }
     localObject = (InetSocketAddress) paramProxy;
     paramProxy = getHostString((InetSocketAddress) localObject);
   }
   paramProxy = this.address.getDns().lookup(paramProxy);
   int j = 0;
   int k = paramProxy.size();
   while (j < k) {
     localObject = (InetAddress) paramProxy.get(j);
     this.inetSocketAddresses.add(new InetSocketAddress((InetAddress) localObject, i));
     j += 1;
   }
   this.nextInetSocketAddressIndex = 0;
 }
コード例 #5
0
 public Request authenticateProxy(Proxy paramProxy, Response paramResponse) {
   List localList = paramResponse.challenges();
   paramResponse = paramResponse.request();
   URL localURL = paramResponse.url();
   int i = 0;
   int j = localList.size();
   while (i < j) {
     Object localObject = (Challenge) localList.get(i);
     if ("Basic".equalsIgnoreCase(((Challenge) localObject).getScheme())) {
       InetSocketAddress localInetSocketAddress = (InetSocketAddress) paramProxy.address();
       localObject =
           java.net.Authenticator.requestPasswordAuthentication(
               localInetSocketAddress.getHostName(),
               getConnectToInetAddress(paramProxy, localURL),
               localInetSocketAddress.getPort(),
               localURL.getProtocol(),
               ((Challenge) localObject).getRealm(),
               ((Challenge) localObject).getScheme(),
               localURL,
               Authenticator.RequestorType.PROXY);
       if (localObject != null) {
         paramProxy =
             Credentials.basic(
                 ((PasswordAuthentication) localObject).getUserName(),
                 new String(((PasswordAuthentication) localObject).getPassword()));
         return paramResponse.newBuilder().header("Proxy-Authorization", paramProxy).build();
       }
     }
     i += 1;
   }
   return null;
 }
 /** Gets the SOCKS proxy server port. */
 private int socksGetServerPort() {
   // get socks server port from proxy. It is unnecessary to check
   // "socksProxyPort" property, since proxy setting should only be
   // determined by ProxySelector.
   InetSocketAddress addr = (InetSocketAddress) proxy.address();
   return addr.getPort();
 }
コード例 #7
0
ファイル: RouteSelector.java プロジェクト: deveshmittal/hike
  /** Prepares the socket addresses to attempt for the current proxy or host. */
  private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
    // Clear the addresses. Necessary if getAllByName() below throws!
    inetSocketAddresses = new ArrayList<InetSocketAddress>();

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

    // Try each address for best behavior in mixed IPv4/IPv6 environments.
    for (InetAddress inetAddress : network.resolveInetAddresses(socketHost)) {
      inetSocketAddresses.add(new InetSocketAddress(inetAddress, socketPort));
    }
    nextInetSocketAddressIndex = 0;
  }
コード例 #8
0
 /*
  * Enabled aggressive block sorting
  */
 @Override
 public Request authenticateProxy(Proxy object, Response object2) throws IOException {
   List<Challenge> list = object2.challenges();
   object2 = object2.request();
   URL uRL = object2.url();
   int n2 = 0;
   int n3 = list.size();
   while (n2 < n3) {
     InetSocketAddress inetSocketAddress;
     Object object3 = list.get(n2);
     if ("Basic".equalsIgnoreCase(object3.getScheme())
         && (object3 =
                 java.net.Authenticator.requestPasswordAuthentication(
                     (inetSocketAddress = (InetSocketAddress) object.address()).getHostName(),
                     this.getConnectToInetAddress((Proxy) object, uRL),
                     inetSocketAddress.getPort(),
                     uRL.getProtocol(),
                     object3.getRealm(),
                     object3.getScheme(),
                     uRL,
                     Authenticator.RequestorType.PROXY))
             != null) {
       object = Credentials.basic(object3.getUserName(), new String(object3.getPassword()));
       return object2.newBuilder().header("Proxy-Authorization", (String) object).build();
     }
     ++n2;
   }
   return null;
 }
コード例 #9
0
 public static HttpURLConnection getConnection(String urlStr) throws IOException {
   URL url = new URL(urlStr);
   NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
   if (null == activeNetworkInfo) {
     Log.w(TAG, "No active network available!");
     return null;
   }
   Proxy p = getProxy();
   String extra = activeNetworkInfo.getExtraInfo();
   // chinese mobile network
   if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE && p != null) {
     // cmwap, uniwap, 3gwap
     if (extra != null
         && (extra.startsWith("cmwap")
             || extra.startsWith("uniwap")
             || extra.startsWith("3gwap"))) {
       HttpURLConnection conn =
           (HttpURLConnection)
               new URL("http://" + p.address().toString() + url.getPath()).openConnection();
       conn.setRequestProperty(
           "X-Online-Host", url.getHost() + ":" + (url.getPort() == -1 ? "80" : url.getPort()));
       return conn;
     }
   }
   if (null != p) {
     // through proxy
     return (HttpURLConnection) url.openConnection(p);
   } else {
     return (HttpURLConnection) url.openConnection();
   }
 }
コード例 #10
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;
  }
コード例 #11
0
  // 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;
    }
  }
コード例 #12
0
 @Override
 public final Permission getPermission() throws IOException {
   String hostName = getURL().getHost();
   int hostPort = Util.getEffectivePort(getURL());
   if (usingProxy()) {
     InetSocketAddress proxyAddress = (InetSocketAddress) requestedProxy.address();
     hostName = proxyAddress.getHostName();
     hostPort = proxyAddress.getPort();
   }
   return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
 }
コード例 #13
0
 /**
  * Get the hostname of the connection machine. This is either the name given in the URL or the
  * name of the proxy server.
  */
 private String getHostName() {
   if (hostName == null) {
     // the value was not set yet
     if (proxy != null) {
       hostName = ((InetSocketAddress) proxy.address()).getHostName();
     } else {
       hostName = url.getHost();
     }
   }
   return hostName;
 }
コード例 #14
0
 /**
  * Get the InetAddress of the connection machine. This is either the address given in the URL or
  * the address of the proxy server.
  */
 private InetAddress getHostAddress() throws IOException {
   if (hostAddress == null) {
     // the value was not set yet
     if (proxy != null && proxy.type() != Proxy.Type.DIRECT) {
       hostAddress = ((InetSocketAddress) proxy.address()).getAddress();
     } else {
       hostAddress = InetAddress.getByName(url.getHost());
     }
   }
   return hostAddress;
 }
コード例 #15
0
  public static boolean standardAPIPingHost(Proxy proxy) {
    try {
      InetSocketAddress proxySocketAddress = (InetSocketAddress) proxy.address();
      return InetAddress.getByName(proxySocketAddress.toString().split(":")[0]).isReachable(100000);
      //			return proxySocketAddress.getAddress().isReachable(100000);
    } catch (Exception e) {
      APL.getEventReport().send(new Exception("ProxyUtils.standardAPIPingHost() Exception", e));
    }

    return false;
  }
コード例 #16
0
ファイル: OkApacheClient.java プロジェクト: dyglcc/mmwd
 @Override
 public Object getParameter(String name) {
   if (name.equals(ConnRouteParams.DEFAULT_PROXY)) {
     Proxy proxy = client.getProxy();
     if (proxy == null) {
       return null;
     }
     InetSocketAddress address = (InetSocketAddress) proxy.address();
     return new HttpHost(address.getHostName(), address.getPort());
   }
   throw new IllegalArgumentException(name);
 }
コード例 #17
0
 /**
  * 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;
 }
  /** Gets the InetAddress of the SOCKS proxy server. */
  private InetAddress socksGetServerAddress() throws UnknownHostException {
    String proxyName;
    // get socks server address from proxy. It is unnecessary to check
    // "socksProxyHost" property, since all proxy setting should be
    // determined by ProxySelector.
    InetSocketAddress addr = (InetSocketAddress) proxy.address();
    proxyName = addr.getHostName();
    if (null == proxyName) {
      proxyName = addr.getAddress().getHostAddress();
    }

    InetAddress anAddr = netImpl.getHostByName(proxyName, NetUtil.preferIPv6Addresses());
    return anAddr;
  }
コード例 #19
0
 /**
  * Get the connection port. This is either the URL's port or the proxy port if a proxy port has
  * been set.
  */
 private int getHostPort() {
   if (hostPort < 0) {
     // the value was not set yet
     if (proxy != null) {
       hostPort = ((InetSocketAddress) proxy.address()).getPort();
     } else {
       hostPort = url.getPort();
     }
     if (hostPort < 0) {
       hostPort = defaultPort;
     }
   }
   return hostPort;
 }
コード例 #20
0
    /**
     * @param requiresTunnel true if the HTTP connection needs to tunnel one protocol over another,
     *     such as when using HTTPS through an HTTP proxy. When doing so, we must avoid buffering
     *     bytes intended for the higher-level protocol.
     */
    public Address(URI uri, Proxy proxy, boolean requiresTunnel) {
      this.proxy = proxy;
      this.requiresTunnel = requiresTunnel;
      this.uriHost = uri.getHost();
      this.uriPort = uri.getEffectivePort();

      SocketAddress proxyAddress = proxy.address();
      if (!(proxyAddress instanceof InetSocketAddress)) {
        throw new IllegalArgumentException(
            "Proxy.address() is not an InetSocketAddress: " + proxyAddress.getClass());
      }
      InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
      this.socketHost = proxySocketAddress.getHostName();
      this.socketPort = proxySocketAddress.getPort();
    }
コード例 #21
0
ファイル: EC2Cloud.java プロジェクト: ryanaslett/ec2-plugin
 /**
  * * Connect to an EC2 instance.
  *
  * @return {@link AmazonEC2} client
  */
 public static synchronized AmazonEC2 connect(
     AWSCredentialsProvider credentialsProvider, URL endpoint) {
   awsCredentialsProvider = credentialsProvider;
   ClientConfiguration config = new ClientConfiguration();
   config.setMaxErrorRetry(16); // Default retry limit (3) is low and often
   // cause problems. Raise it a bit.
   // See: https://issues.jenkins-ci.org/browse/JENKINS-26800
   config.setSignerOverride("QueryStringSignerType");
   ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
   Proxy proxy =
       proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
   if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
     InetSocketAddress address = (InetSocketAddress) proxy.address();
     config.setProxyHost(address.getHostName());
     config.setProxyPort(address.getPort());
     if (null != proxyConfig.getUserName()) {
       config.setProxyUsername(proxyConfig.getUserName());
       config.setProxyPassword(proxyConfig.getPassword());
     }
   }
   AmazonEC2 client = new AmazonEC2Client(credentialsProvider, config);
   client.setEndpoint(endpoint.toString());
   return client;
 }
コード例 #22
0
ファイル: GameRunner2.java プロジェクト: nanounanue/TripleA
 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");
   }
 }
コード例 #23
0
ファイル: HttpAuthenticator.java プロジェクト: MeetMe/okhttp
  /**
   * Returns the authorization credentials that may satisfy the challenge. Returns null if a
   * challenge header was not provided or if credentials were not available.
   */
  private static String getCredentials(
      RawHeaders responseHeaders, String challengeHeader, Proxy proxy, URL url) throws IOException {
    List<Challenge> challenges = parseChallenges(responseHeaders, challengeHeader);
    if (challenges.isEmpty()) {
      return null;
    }

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

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

    return null;
  }
コード例 #24
0
  @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());
    }
  }
コード例 #25
0
  private ConnectivitySettings proxyToCs(Proxy proxy, URI uri) {
    ConnectivitySettings cs = new ConnectivitySettings();
    InetSocketAddress isa = (InetSocketAddress) proxy.address();
    switch (proxy.type()) {
      case HTTP:
        setupProxy(cs, ConnectivitySettings.CONNECTION_VIA_HTTPS, isa);
        break;
      case SOCKS:
        setupProxy(cs, ConnectivitySettings.CONNECTION_VIA_SOCKS, isa);
        break;
      default:
    }

    String prosyUser = NetworkSettings.getAuthenticationUsername(uri);
    if (prosyUser != null && !prosyUser.isEmpty()) {
      cs.setProxyUsername(prosyUser);
      cs.setProxyPassword(Keyring.read(NetworkSettings.getKeyForAuthenticationPassword(uri)));
    }
    return cs;
  }
コード例 #26
0
ファイル: ProxySettings.java プロジェクト: belfero/viajenda
  // 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)};
  }
コード例 #27
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$
     }
   }
 }
コード例 #28
0
ファイル: RouteSelector.java プロジェクト: Gongcong/okhttp
  /** Resets {@link #nextInetSocketAddress} to the first option. */
  private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
    socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!

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

    // Try each address for best behavior in mixed IPv4/IPv6 environments.
    socketAddresses = dns.getAllByName(socketHost);
    nextSocketAddressIndex = 0;
  }
コード例 #29
0
  public static void putProxyIntoServersFile(
      final File configDir, final String host, final Proxy proxyInfo) {
    final IdeaSVNConfigFile configFile =
        new IdeaSVNConfigFile(new File(configDir, SERVERS_FILE_NAME));
    configFile.updateGroups();

    String groupName = SvnAuthenticationManager.getGroupForHost(host, configFile);

    if (StringUtil.isEmptyOrSpaces(groupName)) {
      groupName = host;
      final Map<String, ProxyGroup> groups = configFile.getAllGroups();
      while (StringUtil.isEmptyOrSpaces(groupName) || groups.containsKey(groupName)) {
        groupName += "1";
      }
    }

    final HashMap<String, String> map = new HashMap<String, String>();
    final InetSocketAddress address = ((InetSocketAddress) proxyInfo.address());
    map.put(SvnAuthenticationManager.HTTP_PROXY_HOST, address.getHostName());
    map.put(SvnAuthenticationManager.HTTP_PROXY_PORT, String.valueOf(address.getPort()));
    configFile.addGroup(groupName, host + "*", map);
    configFile.save();
  }
コード例 #30
0
 private InetAddress getConnectToInetAddress(Proxy paramProxy, URL paramURL) {
   if ((paramProxy != null) && (paramProxy.type() != Proxy.Type.DIRECT)) {
     return ((InetSocketAddress) paramProxy.address()).getAddress();
   }
   return InetAddress.getByName(paramURL.getHost());
 }