Returns a wrapped instance of {@link HttpClientConnectionManager}
to capture the necessary performance metrics.

@param orig the target instance to be wrapped
343511
public static HttpClientConnectionManager wrap
    (HttpClientConnectionManager orig) {
        if (orig instanceof Wrapped)
            throw new IllegalArgumentException();
        final Class<?>[] interfaces;
        if (orig instanceof ConnPoolControl) {
            interfaces = new Class<?>[]{
                    HttpClientConnectionManager.class,
                    ConnPoolControl.class,
                    Wrapped.class
            };
        } else {
            interfaces = new Class<?>[]{
                    HttpClientConnectionManager.class,
                    Wrapped.class
            };
        }
        return (HttpClientConnectionManager) Proxy.newProxyInstance(
                // https://github.com/aws/aws-sdk-java/pull/48#issuecomment-29454423
                ClientConnectionManagerFactory.class.getClassLoader(),
                interfaces,
                new Handler(orig));
    }
276768
protected void defineProxyMethods(CtClass cc, CtClass orig) throws Exception {
//        cc.addMethod( CtMethod.make( "public void __setDispatcher( "+ DispatcherThread.class.getName()+" d ) { __target.__dispatcher(d); }", cc ) );
        CtMethod[] methods = getSortedPublicCtMethods(orig,false);

        for (int i = 0; i < methods.length; i++) {
            CtMethod method = methods[i];
            CtMethod originalMethod = method;
            if (method.getName().equals("getActor")) {
                ClassMap map = new ClassMap();
                map.put(Actor.class.getName(),Actor.class.getName());
                method = CtMethod.make( "public "+Actor.class.getName()+" getActor() { return __target; }", cc ) ;
            } else {
                ClassMap map = new ClassMap();
                map.fix(orig);
                map.fix(Actor.class.getName());
                method = new CtMethod(method, cc, map);
            }

            CtClass returnType = method.getReturnType();
            boolean isCallerSide = // don't touch
                    originalMethod.getAnnotation(CallerSideMethod.class) != null ||
                    (originalMethod.getName().equals("self"));// || originalMethod.getName().equals("future")); ??


            if ( isCallerSide ) {
                // verify callerside and inthread are not used
                Object[][] availableParameterAnnotations = originalMethod.getAvailableParameterAnnotations();
                CtClass[] parameterTypes = originalMethod.getParameterTypes();
                for (int j = 0; j < availableParameterAnnotations.length; j++) {
                    Object[] availableParameterAnnotation = availableParameterAnnotations[j];
                    if ( availableParameterAnnotation.length > 0 ) {
                        for (int k = 0; k < availableParameterAnnotation.length; k++) {
                            Object annot = availableParameterAnnotation[k];
                            if ( annot.toString().indexOf("kontraktor.annotations.InThread") > 0 ) {
                                throw new RuntimeException("cannot combine @CallerSide and @InThread, manually wrap callback using inThread(). method:"+originalMethod+" clz:"+orig);
                            }
                        }
                    }
                }
            }

            boolean allowed = //((method.getModifiers() & AccessFlag.ABSTRACT) == 0 ) &&
                    (method.getModifiers() & (AccessFlag.NATIVE|AccessFlag.FINAL|AccessFlag.STATIC)) == 0 &&
                    (method.getModifiers() & AccessFlag.PUBLIC) != 0 &&
                    !isCallerSide;
            // by default lock all method of object and actor
            allowed &= !originalMethod.getDeclaringClass().getName().equals(Object.class.getName()) &&
                       !originalMethod.getDeclaringClass().getName().equals(Actor.class.getName());

            // exceptions: async built-in actor methods that can be called
            if ( //originalMethod.getName().equals("executeInActorThread") || // needed again ! see spore
                // async methods at actor class. FIXME: add annotation
                 originalMethod.getName().equals("getSubMonitorables") ||
                 originalMethod.getName().equals("getReport") ||
                 originalMethod.getName().equals("askMsg") ||
                 originalMethod.getName().equals("tellMsg") ||
                 originalMethod.getName().equals("__unpublish") ||
                 originalMethod.getName().equals("__republished") ||
                 originalMethod.getName().equals("router$clientPing") ||
                 originalMethod.getName().equals("ping") ||
                 originalMethod.getName().equals("cyclic") ||
                 originalMethod.getName().equals("__submit") ||
                 originalMethod.getName().equals("execInThreadPool") ||
                 originalMethod.getName().equals("asyncstop") ||
                 originalMethod.getName().equals("receive") ||
                 originalMethod.getName().equals("complete") ||
                 originalMethod.getName().equals("close")
            )
            {
                allowed = true;
            }

            if (allowed) {
                boolean isVoid = returnType == CtPrimitiveType.voidType;
                boolean isCallbackCall = originalMethod.getAnnotation(AsCallback.class) != null;
                if (returnType != CtPrimitiveType.voidType && !returnType.getName().equals(IPromise.class.getName()) ) {
                    throw new RuntimeException("only void methods or methods returning IPromise allowed problematic method:"+originalMethod );
                }
                String conversion = "";
                Object[][] availableParameterAnnotations = originalMethod.getAvailableParameterAnnotations();
                CtClass[] parameterTypes = originalMethod.getParameterTypes();
                for (int j = 0; j < availableParameterAnnotations.length; j++) {
                    Object[] availableParameterAnnotation = availableParameterAnnotations[j];
                    if ( availableParameterAnnotation.length > 0 ) {
                        for (int k = 0; k < availableParameterAnnotation.length; k++) {
                            Object annot = availableParameterAnnotation[k];
                            if ( annot.toString().indexOf("kontraktor.annotations.InThread") > 0 ) {
                                if ( parameterTypes[j].getName().equals(Callback.class.getName()) ) {
                                    Log.Info(this,"InThread unnecessary when using built in Callback class. method:"+originalMethod+" clz:"+orig);
                                    continue;
                                }
                                if ( ! parameterTypes[j].isInterface() )
                                    throw new RuntimeException("@InThread can be used on interfaces only");
                                String an = Actor.class.getName();
                                conversion += an+" sender=("+an+")sender.get();";
                                conversion += "if ( sender != null ) { args[" + j + "] = sender.__scheduler.inThread(sender.__self, args[" + j + "]); }";
                                break;
                            }
                        }
                    }
                }
                String call = "__target.__enqueueCall( this, \""+method.getName()+"\", args, "+isCallbackCall+" );";
                if ( ! isVoid ) {
                    call = "return ("+originalMethod.getReturnType().getName()+") (Object)"+call;
                }
                String body = "{ Object args[] = $args;" +
                        conversion +
                        call+
                    "}";
                method.setBody(body);
                cc.addMethod(method);
            } else if ( (method.getModifiers() & (AccessFlag.NATIVE|AccessFlag.FINAL|AccessFlag.STATIC)) == 0 )
            {
                if (isCallerSide || method.getName().equals("toString") || method.getName().equals("__stopImpl") ) {
                } else if (
                    ! method.getName().equals("getActor") &&
                    ! method.getName().equals("delayed") &&
                    ! method.getName().equals("execInThreadPool")
                )
                {
                    method.setBody("throw new RuntimeException(\"can only call public methods on actor ref. method:'"+method.getName()+"\");");
                    cc.addMethod(method);
                } else {
                    cc.addMethod(method);
                }
            }
        }

//        methods = getSortedNonPublicCtMethods(orig);
//
//        for (int i = 0; i < methods.length; i++) {
//            CtMethod method = methods[i];
//            CtMethod originalMethod = method;
//            if (method.getName().equals("getActor")) {
//                ClassMap then = new ClassMap();
//                then.put(Actor.class.getName(),Actor.class.getName());
//                method = CtMethod.make( "public "+Actor.class.getName()+" getActor() { return __target; }", cc ) ;
//            } else {
//                ClassMap then = new ClassMap();
//                then.fix(orig);
//                method = new CtMethod(method, cc, then);
//            }
//
//            CtClass returnType = method.getReturnType();
//            // by default ignore all method of object and actor
//            boolean isObjectOrActor = !originalMethod.getDeclaringClass().getName().equals(Object.class.getName()) &&
//                    !originalMethod.getDeclaringClass().getName().equals(Actor.class.getName());
//
//            if (! isObjectOrActor &&
//                (method.getModifiers() & (AccessFlag.NATIVE|AccessFlag.FINAL|AccessFlag.STATIC)) == 0 )
//            {
//                method.setBody("throw new RuntimeException(\"can only call public methods on actor ref\");");
//                cc.addMethod(method);
//            }
//        }
    }
746831
public static TcpClient<ByteBuf, ByteBuf> newClient(ConnectionProviderFactory<ByteBuf, ByteBuf> providerFactory,
                                                        Observable<Host> hostStream) {
        return TcpClientImpl.create(providerFactory, hostStream);
    }
372488
public <T> HttpClientRequest.Builder<T> perform(final String methodName, final URI uri, final HttpClientResponseHandler<T> httpHandler) {
        final HttpClientMethod method;
        try {
            method = HttpClientMethod.valueOf(methodName.toUpperCase(Locale.ENGLISH));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Unknown HTTP method type " + methodName, e);
        }

        return new HttpClientRequest.Builder<T>(httpClientFactory, method, uri, httpHandler);
    }
660524
public static void copyProperties(Object dest, Object orig){
		try {
			if (orig != null && dest != null){
				BeanUtils.copyProperties(dest, orig);

				PropertyUtils putils = new PropertyUtils();
	            PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig);

				for (PropertyDescriptor origDescriptor : origDescriptors) {
					String name = origDescriptor.getName();
					if ("class".equals(name)) {
						continue; // No point in trying to set an object's class
					}

					Class propertyType = origDescriptor.getPropertyType();
					if (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType)))
						continue;

					if (!putils.isReadable(orig, name)) { //because of bad convention
						Method m = orig.getClass().getMethod("is" + name.substring(0, 1).toUpperCase() + name.substring(1), (Class<?>[]) null);
						Object value = m.invoke(orig, (Object[]) null);

						if (putils.isWriteable(dest, name)) {
							BeanUtilsBean.getInstance().copyProperty(dest, name, value);
						}
					}

				}
			}
		} catch (Exception e) {
			throw new DJException("Could not copy properties for shared object: " + orig +", message: " + e.getMessage(),e);
		}
	}
1110650
public static HttpClient getNewHttpClient(String uri, ClientConnectionManager connectionManager) {
        try {

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            final DefaultHttpClient result = new DefaultHttpClient(
                    connectionManager, params);
            configureProxy(uri, result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new DefaultHttpClient();
        }
    }
391539
public static RedissonClient create(Config config) {
        Redisson redisson = new Redisson(config);
        if (config.isReferenceEnabled()) {
            redisson.enableRedissonReferenceSupport();
        }
        return redisson;
    }
1045540
public SipServletRequest createRequest(SipServletRequest origRequest) {
        final SipServletRequestImpl newSipServletRequest = (SipServletRequestImpl) sipFactoryImpl.createRequest(origRequest, false);
        final SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest;

        final MobicentsSipSession originalSession = origRequestImpl.getSipSession();
        final MobicentsSipSession session = newSipServletRequest.getSipSession();
        // B2buaHelperTest.testLinkSipSessions101 assumes the sessions shouldn't be linked together
//		sessionMap.put(originalSession.getKey(), session.getKey());
//		sessionMap.put(session.getKey(), originalSession.getKey());
//		dumpLinkedSessions();

//		linkedRequestMap.put(newSipServletRequest, origRequestImpl);
//		linkedRequestMap.put(origRequestImpl, newSipServletRequest);
        session.setB2buaHelper(this);
        originalSession.setB2buaHelper(this);
        setOriginalRequest(session, newSipServletRequest);
        dumpAppSession(session);
        return newSipServletRequest;
    }
954859
public static HttpClient<ByteBuf, ByteBuf> newClient(ConnectionProviderFactory<ByteBuf, ByteBuf> providerFactory,
                                                         Observable<Host> hostStream) {
        return HttpClientImpl.create(providerFactory, hostStream);
    }
413237
async def _request_mock(self, orig_self: ClientSession,
                            method: str, url: 'Union[URL, str]',
                            *args: Tuple,
                            **kwargs: Dict) -> 'ClientResponse':
        """"""
        url = normalize_url(merge_params(url, kwargs.get('params')))
        url_str = str(url)
        for prefix in self._passthrough:
            if url_str.startswith(prefix):
                return (await self.patcher.temp_original(
                    orig_self, method, url, *args, **kwargs
                ))

        response = await self.match(method, url, **kwargs)
        if response is None:
            raise ClientConnectionError(
                'Connection refused: {} {}'.format(method, url)
            )
        self._responses.append(response)
        key = (method, url)
        self.requests.setdefault(key, [])
        self.requests[key].append(RequestCall(args, kwargs))
        return response
451728
@SuppressWarnings("deprecation")
  public static DefaultHttpClient getClientThatAllowAnyHTTPS(ThreadSafeClientConnManager cm) {

    final TrustManager easyTrustManager = new X509TrustManager() {


      public void checkClientTrusted(X509Certificate[] xcs, String string)
          throws CertificateException {}

      public void checkServerTrusted(X509Certificate[] xcs, String string)
          throws CertificateException {}

      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
    };
    final X509HostnameVerifier easyVerifier = new X509HostnameVerifier() {

      public boolean verify(String string, SSLSession ssls) {
        return true;
      }

      public void verify(String string, SSLSocket ssls) throws IOException {}

      public void verify(String string, String[] strings, String[] strings1) throws SSLException {}

      public void verify(String string, X509Certificate xc) throws SSLException {}

    };

    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("TLS");
      ctx.init(null, new TrustManager[] {easyTrustManager}, null);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    } catch (KeyManagementException e) {
      throw new RuntimeException(e);
    }

    final SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(easyVerifier);
    cm.getSchemeRegistry().register(new Scheme(HTTPS, ssf, HTTPS_PORT));

    return new DefaultHttpClient(cm);


  }
1280698
protected static HttpClient httpClient() throws Exception {
    return HttpClients.custom()
        .setHostnameVerifier(new AllowAllHostnameVerifier())
        .setSslcontext(SSLContexts.custom()
            .loadTrustMaterial(null, new TrustStrategy() {
              @Override
              public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
              }
            })
            .build())
        .build();
  }
522007
public Client<? extends Options, ? extends OptionsBuilder, ? extends RequestBuilder> newClient() {
        if (clientClassName == null) {
            return new DefaultClient();
        } else {
            try {
                return (Client) Thread.currentThread().getContextClassLoader().loadClass(clientClassName).newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
1024279
public CloseableHttpClient getHttpClient() {
    try {
      URI crxUri = new URI(props.getPackageManagerUrl());

      final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort());
      final Credentials credentials = new UsernamePasswordCredentials(props.getUserId(), props.getPassword());
      final CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(authScope, credentials);

      HttpClientBuilder httpClientBuilder = HttpClients.custom()
          .setDefaultCredentialsProvider(credsProvider)
          .addInterceptorFirst(new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
              // enable preemptive authentication
              AuthState authState = (AuthState)context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
              authState.update(new BasicScheme(), credentials);
            }
          })
          .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
              // keep reusing connections to a minimum - may conflict when instance is restarting and responds in unexpected manner
              return 1;
            }
          });

      // timeout settings
      httpClientBuilder.setDefaultRequestConfig(HttpClientUtil.buildRequestConfig(props));

      // relaxed SSL check
      if (props.isRelaxedSSLCheck()) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        httpClientBuilder.setSSLSocketFactory(sslsf);
      }

      // proxy support
      Proxy proxy = getProxyForUrl(props.getPackageManagerUrl());
      if (proxy != null) {
        httpClientBuilder.setProxy(new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol()));
        if (proxy.useAuthentication()) {
          AuthScope proxyAuthScope = new AuthScope(proxy.getHost(), proxy.getPort());
          Credentials proxyCredentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
          credsProvider.setCredentials(proxyAuthScope, proxyCredentials);
        }
      }

      return httpClientBuilder.build();
    }
    catch (URISyntaxException ex) {
      throw new PackageManagerException("Invalid url: " + props.getPackageManagerUrl(), ex);
    }
    catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) {
      throw new PackageManagerException("Could not set relaxedSSLCheck", ex);
    }
  }
1085670
public static function parseLabels(&$data, $orig = null)
    {
        $str = '';
        while (mb_orig_strlen($data) > 0) {
            $l = ord($data[0]);

            if ($l >= 192) {
                $pos = Binary::bytes2int(chr($l - 192) . mb_orig_substr($data, 1, 1));
                $data = mb_orig_substr($data, 2);
                $ref = mb_orig_substr($orig, $pos);
                return $str . Binary::parseLabels($ref, $orig);
            }

            $p = mb_orig_substr($data, 1, $l);
            $str .= $p . (($l !== 0) ? '.' : '');
            $data = mb_orig_substr($data, $l + 1);
            if ($l === 0) {
                break;
            }
        }
        return $str;
    }
1034342
public ApiClient setHttpClient(OkHttpClient newHttpClient) {
        if (!httpClient.equals(newHttpClient)) {
            newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());
            httpClient.networkInterceptors().clear();
            newHttpClient.interceptors().addAll(httpClient.interceptors());
            httpClient.interceptors().clear();
            this.httpClient = newHttpClient;
        }
        return this;
    }
36574
@SuppressWarnings("unchecked")
    @Override
    protected InvocationCallback<Object> checkAsyncCallback(OperationResourceInfo ori,
                                                            Map<String, Object> reqContext,
                                                            Message outMessage) {
        InvocationCallback<Object> callback = outMessage.getContent(InvocationCallback.class);
        if (callback == null && CompletionStage.class.equals(ori.getMethodToInvoke().getReturnType())) {
            callback = NO_OP_CALLBACK;
            outMessage.setContent(InvocationCallback.class, callback);
        }
        return callback;
    }