Get a Proxy, using the given provider

@param provider provider to use
@param test whether to test the proxy
@return used proxy
@throws IOException I/O Error
540242
public static Proxy getProxy(final IProxyProvider provider, final boolean test) throws IOException {
    LOGGER.info("Getting proxy...");

    List<Proxy> proxies = provider.getProxies(-1, false, true);
    LOGGER.info("Total Proxies: " + proxies.size());

    final CountDownLatch countDown = new CountDownLatch(proxies.size());
    final AtomicReference<Proxy> useProxy = new AtomicReference<>();
    
    int threadCount = proxies.size() > 10 ? 10 : proxies.size();
    if (threadCount <= 0) {
      threadCount = 1;
    }
    
    final ExecutorService testService = Executors.newFixedThreadPool(threadCount);

    for (final Proxy proxy : proxies) {

      Thread validate = new Thread() {
        @Override
        public void run() {
          try {

            if (test) {
              
              if (proxy.isBlackListed()) {
                return;
              }
              
              proxy.updateStatus();
              if (!proxy.isOnline()) {
                return;
              }

              proxy.updateAnonymity();
              if (!proxy.isAnonymous()) {
                return;
              }
            }

            if (useProxy.get() == null) {
              LOGGER.info("Using Proxy: " + proxy.toString());
              useProxy.set(proxy);

              // count to 0
              while (countDown.getCount() > 0) {
                countDown.countDown();
              }

            }

          } catch (Exception e) {
            LOGGER.info("Proxy validation returned error: " + e.getClass().getName() + " - " + e.getMessage());
          } finally {
            countDown.countDown();
          }
        }
      };
      testService.submit(validate);

    }

    try {
      countDown.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    testService.shutdownNow();

    if (useProxy.get() == null) {
      //if null, use another provider
      return getProxy(test);
    }
    
    return useProxy.get();

  }
1237268
@SuppressWarnings("unchecked") // safe since the proxy implements type
  private <T> T createFakeResource(Class<T> type, final String name) {
    return (T) Proxy.newProxyInstance(
        FakeClientBundleProvider.class.getClassLoader(),
        new Class<?>[] {type},
        new InvocationHandler() {
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            Class<?> returnType = method.getReturnType();
            if (returnType == String.class) {
              return name;
            } else if (returnType == SafeHtml.class) {
              return SafeHtmlUtils.fromTrustedString(name);
            } else if (returnType == SafeUri.class) {
              return UriUtils.fromTrustedString(name);
            } else if (returnType == boolean.class) {
              return false;
            } else if (returnType == int.class) {
              return 0;
            } else if (method.getParameterTypes()[0] == ResourceCallback.class) {
              // Read the underlying resource type out of the generic parameter
              // in the method's argument
              Class<?> resourceType = 
                  (Class<?>) 
                  ((ParameterizedType) args[0].getClass().getGenericInterfaces()[0])
                  .getActualTypeArguments()[0];
              ((ResourceCallback<ResourcePrototype>) args[0]).onSuccess(
                  (ResourcePrototype) createFakeResource(resourceType, name));
              return null;
            } else {
              throw new IllegalArgumentException(
                  "Unexpected return type for method " + method.getName());
            }
          }
        });
  }
513207
public static <V extends VersionedProtocol> V getProxy(Class<V> protocol, InetSocketAddress addr,
			SocketFactory factory) throws IOException {

		@SuppressWarnings("unchecked")
		V proxy = (V) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(addr, factory));

		return proxy;
	}
1372314
public void setProxy(Proxy proxy) {
        if (config.delivery instanceof HttpDelivery) {
            ((HttpDelivery) config.delivery).setProxy(proxy);
        }
        if (config.sessionDelivery instanceof HttpDelivery) {
            ((HttpDelivery) config.sessionDelivery).setProxy(proxy);
        }
    }
424010
public static HOTPProvider instantiateProvider(boolean allowTestProvider) {
        HOTPProvider resultProvider = null;
        ServiceLoader<HOTPProvider> loader = ServiceLoader.load(HOTPProvider.class);
        Iterator<HOTPProvider> iterator = loader.iterator();
        if (iterator.hasNext()) {
            while (iterator.hasNext()) {
                HOTPProvider provider = iterator.next();
                if (!"com.payneteasy.superfly.spring.TestHOTPProvider".equals(provider.getClass().getName())
                        || allowTestProvider) {
                    resultProvider = provider;
                    break;
                }
            }
        }
        return resultProvider;
    }
507418
private HttpURLConnection connect(URL url) throws IOException {
        LOGGER.debug("Searching Artifactory url {}", url);

        // Determine if we need to use a proxy. The rules:
        // 1) If the proxy is set, AND the setting is set to true, use the proxy
        // 2) Otherwise, don't use the proxy (either the proxy isn't configured,
        // or proxy is specifically set to false)
        final URLConnectionFactory factory = new URLConnectionFactory(settings);
        final HttpURLConnection conn = factory.createHttpURLConnection(url, useProxy);
        conn.setDoOutput(true);

        conn.addRequestProperty("X-Result-Detail", "info");

        final String username = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME);
        final String apiToken = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN);
        if (username != null && apiToken != null) {
            final String userpassword = username + ":" + apiToken;
            final String encodedAuthorization = Base64.getEncoder().encodeToString(userpassword.getBytes(StandardCharsets.UTF_8));
            conn.addRequestProperty("Authorization", "Basic " + encodedAuthorization);
        } else {
            final String bearerToken = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_BEARER_TOKEN);
            if (bearerToken != null) {
                conn.addRequestProperty("Authorization", "Bearer " + bearerToken);
            }
        }

        conn.connect();
        return conn;
    }
749981
def proxy(ctx, bind, port):
    
    app = web.Application()
    app.on_startup.append(startup_proxy)
    app.on_cleanup.append(cleanup_proxy)

    app.router.add_route("GET", r'/stream/{path:.*$}', websocket_handler)
    app.router.add_route("GET", r'/wsproxy/{path:.*$}', websocket_handler)
    app.router.add_route('*', r'/{path:.*$}', web_handler)
    if getattr(ctx.args, 'testing', False):
        return app
    web.run_app(app, host=bind, port=port)
581675
public static <T> T newProxyInstance(final Class<?>[] interfaceClasses, final InvocationHandler h) {
        return (T) Proxy.newProxyInstance(N.class.getClassLoader(), interfaceClasses, h);
    }
249059
public static <T> Provider<T> guicify(javax.inject.Provider<T> provider) {
    if (provider instanceof Provider) {
      return (Provider<T>) provider;
    }

    final javax.inject.Provider<T> delegate = checkNotNull(provider, "provider");

    // Ensure that we inject all injection points from the delegate provider.
    Set<InjectionPoint> injectionPoints =
        InjectionPoint.forInstanceMethodsAndFields(provider.getClass());
    if (injectionPoints.isEmpty()) {
      return new GuicifiedProvider<T>(delegate);
    } else {
      Set<Dependency<?>> mutableDeps = Sets.newHashSet();
      for (InjectionPoint ip : injectionPoints) {
        mutableDeps.addAll(ip.getDependencies());
      }
      final Set<Dependency<?>> dependencies = ImmutableSet.copyOf(mutableDeps);
      return new GuicifiedProviderWithDependencies<T>(dependencies, delegate);
    }
  }
423264
public static <T> T proxy(T target, Class<? extends Aspect> aspectClass){
		return ProxyFactory.createProxy(target, aspectClass);
	}
353499
@SuppressWarnings("unchecked")
    private Class<? extends T> generateProxyClass() throws IOException {
        if (ViewProxy.class.isAssignableFrom(mBaseClass)) {
            return mBaseClass;
        }

        Class<? extends T> proxyClass = (Class) sGeneratedProxyClasses.get(mBaseClass);
        if (proxyClass != null &&
                (proxyClass.getClassLoader() == mParentClassLoader ||
                 proxyClass.getClassLoader().getParent() == mParentClassLoader)) {
            // Cache hit; return immediately.
            return proxyClass;
        }

        proxyClass = (Class<? extends T>) findProxyViewClass(mContext, mBaseClass.getName());
        if (proxyClass != null) {
            // This app ships with the build-time proxy.
            sGeneratedProxyClasses.put(mBaseClass, proxyClass);
            return proxyClass;
        }

        try {
            Class.forName("com.google.dexmaker.DexMaker");
            return DexProxyBuilder.generateProxyClass(mContext, mBaseClass);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
1242724
public static MethodInvokeProxy proxyByName(Object target,String methodName,Object ...args)
	{
		Method m=findMethodByName(target, methodName);
		if(m!=null)
		{
			return new MethodInvokeProxy(target, m, args);
		}
		return null;
	}
809914
function Proxy(host, port, user, pass) {
  if (!(this instanceof Proxy))
    return new Proxy(host, port, user, pass);

  EventEmitter.call(this);

  assert(typeof host === 'string');
  assert(typeof port === 'number');

  this.socket = null;
  this.host = host;
  this.port = port;
  this.username = user || null;
  this.password = pass || null;
  this.bytesWritten = 0;
  this.bytesRead = 0;
  this.remoteAddress = null;
  this.remotePort = 0;
  this.ops = [];
}
1238021
public void addProxy(String protocol, String host, int port, String username, String password,
                       int socketTimeout, int connectTimeout, int connectionRequestTimeout) {
    Proxy proxy = new Proxy(protocol, host, port, username, password, socketTimeout, connectTimeout, connectionRequestTimeout);
    proxies.add(proxy);
  }
859427
public Proxy setHost( String host )
    {
        if ( this.host.equals( host ) || ( host == null && this.host.length() <= 0 ) )
        {
            return this;
        }
        return new Proxy( type, host, port, auth );
    }
1306486
public static void proxy(Method method, InvocationHandler invocationHandler) {
		assertInvocationHandlerNotNull(invocationHandler);
		MockRepository.putMethodProxy(method, invocationHandler);
	}
318453
protected Proxy getProxy(final Settings settings, final String serverId, final String host) {
		if (settings == null)
			return null;
		List<Proxy> proxies = settings.getProxies();
		if (proxies == null || proxies.isEmpty())
			return null;

		// search id match first
		if ( serverId != null && !serverId.isEmpty() ) {
			for (Proxy proxy : proxies) {
				if ( proxy.isActive() ) {
					final String proxyId = proxy.getId();
					if ( proxyId != null && !proxyId.isEmpty() ) {
						if ( proxyId.equalsIgnoreCase(serverId) ) {
							if ( ( "http".equalsIgnoreCase( proxy.getProtocol() ) || "https".equalsIgnoreCase( proxy.getProtocol() ) ) ) {
								if ( matchNonProxy( proxy, host ) )
									return null;
								else
									return proxy;
							}
						}
					}
				}
			}
		}

		// search active proxy
		for (Proxy proxy : proxies)
			if ( proxy.isActive() &&
					( "http".equalsIgnoreCase( proxy.getProtocol() ) || "https".equalsIgnoreCase( proxy.getProtocol() ) )
					)
			{
				if ( matchNonProxy( proxy, host ) )
					return null;
				else
					return proxy;
			}

		return null;
	}