Exemplo n.º 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;
  }
 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();
   }
 }
Exemplo n.º 3
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;
    }
  // 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;
    }
  }
Exemplo n.º 5
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;
  }
Exemplo n.º 6
0
  /** 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;
  }
Exemplo n.º 7
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;
  }
Exemplo n.º 8
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;
 }
Exemplo n.º 9
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 = "";
   }
 }
Exemplo n.º 10
0
 @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);
 }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
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;
 }
 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;
 }
Exemplo n.º 14
0
 public boolean connect() {
   ExpCoordinator.printer.print("NCCPConnection.connect", 3);
   if (host.length() == 0) {
     ExpCoordinator.printer.print("NCCPConnection.connect host is not set", 6);
     return false;
   }
   if (proxy == null && nonProxy == null) {
     ExpCoordinator.printer.print("NCCPConnection.connect proxy null");
     return false;
   }
   if (ExpCoordinator.isSPPMon()) return (connectSPPMon());
   if (state == ConnectionEvent.CONNECTION_CLOSED || state == ConnectionEvent.CONNECTION_FAILED) {
     state = ConnectionEvent.CONNECTION_PENDING;
     if (proxy != null) {
       proxy.openConnection(this);
     }
   }
   /*
   if (nonProxy != null && proxy == null)
   {
   	return (nonProxy.connect());
   }
   */
   return true;
 }
Exemplo n.º 15
0
 public void write(ONL.Writer wrtr) throws java.io.IOException {
   wrtr.writeString(host);
   wrtr.writeInt(port);
   short cid = 0;
   if (proxy != null) cid = proxy.getConnectionID(this);
   wrtr.writeShort(cid);
 }
 /** 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();
 }
Exemplo n.º 17
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");
   }
 }
Exemplo n.º 18
0
  private synchronized Socket getOrCreateSocket(boolean resend) throws NetworkIOException {
    if (reconnectPolicy.shouldReconnect()) {
      logger.debug("Reconnecting due to reconnectPolicy dictating it");
      UILogger.getInstance().add("Reconnecting due to reconnectPolicy dictating it");
      Utilities.close(socket);
      socket = null;
    }

    if (socket == null || socket.isClosed()) {
      try {
        if (proxy == null) {
          socket = factory.createSocket(host, port);
          logger.debug("Connected new socket {}", socket);
          UILogger.getInstance().add("Connected new socket" + socket.toString());
        } else if (proxy.type() == Proxy.Type.HTTP) {
          TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
          socket =
              tunnelBuilder.build(
                  (SSLSocketFactory) factory, proxy, proxyUsername, proxyPassword, host, port);
          logger.debug("Connected new socket through http tunnel {}", socket);
          UILogger.getInstance()
              .add("Connected new socket through http tunnel " + socket.toString());
        } else {
          boolean success = false;
          Socket proxySocket = null;
          try {
            proxySocket = new Socket(proxy);
            proxySocket.connect(new InetSocketAddress(host, port), connectTimeout);
            socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
            success = true;
          } finally {
            if (!success) {
              Utilities.close(proxySocket);
            }
          }
          logger.debug("Connected new socket through socks tunnel {}", socket);
          UILogger.getInstance()
              .add("Connected new socket through socks tunnel " + socket.toString());
        }

        socket.setSoTimeout(readTimeout);
        socket.setKeepAlive(true);

        if (errorDetection) {
          monitorSocket(socket);
        }

        reconnectPolicy.reconnected();
        logger.debug("Made a new connection to APNS");
        UILogger.getInstance().add("Made a new connection to APNS");
      } catch (IOException e) {
        logger.error("Couldn't connect to APNS server", e);
        UILogger.getInstance().add("Couldn't connect to APNS server" + e.toString());
        // indicate to clients whether this is a resend or initial send
        throw new NetworkIOException(e, resend);
      }
    }
    return socket;
  }
Exemplo n.º 19
0
 public static void downloadToFile(final Proxy proxy, final URL url, final File file)
     throws IOException {
   if (proxy != Proxy.NO_PROXY && proxy.type() != Proxy.Type.DIRECT) {
     downloadUsingProxy(proxy, url, file);
   } else {
     FileUtils.copyURLToFile(url, file, 10000, 5000);
   }
 }
Exemplo n.º 20
0
 public void read(ONL.Reader rdr) throws java.io.IOException {
   setHost(new String(rdr.readString()));
   setPort(rdr.readInt());
   short cid = (short) rdr.readShort();
   ExpCoordinator.print(
       new String("NCCPConnection.read host:" + getHost() + " port:" + getPort() + " cid:" + cid),
       5);
   if (proxy != null) proxy.setConnectionID(this, cid);
 }
Exemplo n.º 21
0
 @Override
 public int hashCode() {
   int result = 17;
   result = 31 * result + uriHost.hashCode();
   result = 31 * result + uriPort;
   result = 31 * result + (proxy != null ? proxy.hashCode() : 0);
   result = 31 * result + (requiresTunnel ? 1 : 0);
   return result;
 }
Exemplo n.º 22
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;
  }
Exemplo n.º 23
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;
 }
Exemplo n.º 24
0
 /** Returns connected socket to be used for this HTTP connection. */
 protected HttpConnection getHTTPConnection(Proxy proxy) throws IOException {
   HttpConnection connection;
   if (proxy == null || proxy.type() == Proxy.Type.DIRECT) {
     this.proxy = null; // not using proxy
     connection = HttpConnectionManager.getDefault().getConnection(uri, getConnectTimeout());
   } else {
     connection =
         HttpConnectionManager.getDefault().getConnection(uri, proxy, getConnectTimeout());
   }
   return connection;
 }
 @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");
 }
Exemplo n.º 26
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;
  }
Exemplo n.º 27
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)};
  }
Exemplo n.º 28
0
 public void setConnectionID(short cid) {
   ExpCoordinator.print(
       new String(
           "NCCPConnection.setConnectionID host:"
               + getHost()
               + " port:"
               + getPort()
               + " cid:"
               + cid),
       5);
   if (proxy != null) proxy.setConnectionID(this, cid);
 }
 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;
 }
Exemplo n.º 30
0
 public void sendMessage(NCCP.Message msg) {
   if (isClosed() || isFailed()) connect();
   if (isConnected()) {
     ExpCoordinator.printer.print("NCCPConnection::sendMessage", 5);
     if (proxy != null) proxy.sendMessage(msg, this);
     else {
       if (nonProxy != null) nonProxy.sendMessage(msg);
     }
   } else // still can't connect
   {
     pendingMessages.add(msg);
   }
 }