Wraps a driver object with a dynamic proxy that counts method calls and their durations.<p>

@param newDriverInstance the driver instance to wrap
@return the proxy
547216
private Object wrapDriverInProfilingProxy(Object newDriverInstance) {

        Class<?> cls = getDriverInterfaceForProxy(newDriverInstance);
        if (cls == null) {
            return newDriverInstance;
        }
        return Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(),
            new Class[] {cls},
            new CmsProfilingInvocationHandler(newDriverInstance, CmsDefaultProfilingHandler.INSTANCE));
    }
1070946
protected InternalDriver createDriver( SecurityPlan securityPlan, SessionFactory sessionFactory, MetricsProvider metricsProvider, Config config )
    {
        return new InternalDriver( securityPlan, sessionFactory, metricsProvider, config.logging() );
    }
1371255
protected Interceptor ensureInterceptor( String n )
    {
        Interceptor i = null;
        if ( _interceptors == null )
        {
            _interceptors = new HashMap<String,Interceptor>();
        }
        else
        {
            i = _interceptors.get( n );
        }

        if ( i == null )
        {
            try
            {
                i  = (Interceptor) getControlService( getControlBeanContext().getClassLoader().loadClass( n ), null );
            }
            catch ( Exception e )
            {
                // Couldn't instantiate the desired service; usually this is because the service interface itself
                // isn't present on this system at runtime (ClassNotFoundException), or if the container of the
                // control didn't registers the service.

                /* TODO log a message here to that effect, but just swallow the exception for now. */
            }
            finally
            {
                // We want to always return an interceptor, so if we can't get the one we want, we'll substitute
                // a "null" interceptor that does nothing.
                if ( i == null)
                    i = new NullInterceptor();

                _interceptors.put( n, i );
            }
        }
        return i;
    }
170333
function instantiateDrivers(config, defaultDriverInstance) {
    config.actionConfigs.forEach(action => {
            action.driverInstance=action.driver?action.driver():defaultDriverInstance;
    });
    return config;
}
1062203
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
    public <T> T create(final Class<T> service) {
        Utils.validateServiceInterface(service);
        if (validateEagerly) {
            eagerlyValidateMethods(service);
        }
        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[]{service},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object... args)
                            throws Throwable {
                        // If the method is a method from Object then defer to normal invocation.
                        if (method.getDeclaringClass() == Object.class) {
                            return method.invoke(this, args);
                        }
                        return loadMethodHandler(method).invoke(args);
                    }
                });
    }
501987
public static Function<Client<HttpRequest, HttpResponse>, HttpTracingClient> newDecorator(
            Tracing tracing,
            @Nullable String remoteServiceName) {
        ensureScopeUsesRequestContext(tracing);
        return delegate -> new HttpTracingClient(delegate, tracing, remoteServiceName);
    }
1304677
@Override
    public Object create(ActionParameter argument, Context context, ParameterFactories engine) {
        Object object = createNewInstance(argument.getRawType(), context, engine);

        for (Method method : argument.getRawType().getMethods()) {
            if (method.getName().startsWith(SETTER_PREFIX)) {
                if (method.getParameterTypes().length != 1) {
                    LOGGER.warn("The class {} has a setter method called {} but with too many parameters to be " +
                                    "injected with the 'BeanParameter' annotation", argument.getRawType().getName(),
                            method.getName());
                    continue;
                }

                // Only 1 parameter
                Annotation[] annotation = method.getParameterAnnotations()[0];
                Class<?> typesOfParameter = method.getParameterTypes()[0];
                Type genericTypeOfParameter = method.getGenericParameterTypes()[0];
                ActionParameter parameter = ActionParameter.from(method, annotation, typesOfParameter,
                        genericTypeOfParameter);
                // An exception is thrown if we can't build the parameter object.
                Object value = Bindings.create(parameter, context, engine);
                if (value != null) {
                    inject(object, method, value);
                }
            }
        }
        return object;
    }
317790
protected InternalDriver createRoutingDriver( SecurityPlan securityPlan, BoltServerAddress address, ConnectionPool connectionPool,
            EventExecutorGroup eventExecutorGroup, RoutingSettings routingSettings, RetryLogic retryLogic, MetricsProvider metricsProvider, Config config )
    {
        if ( !securityPlan.isRoutingCompatible() )
        {
            throw new IllegalArgumentException( "The chosen security plan is not compatible with a routing driver" );
        }
        ConnectionProvider connectionProvider = createLoadBalancer( address, connectionPool, eventExecutorGroup,
                config, routingSettings );
        SessionFactory sessionFactory = createSessionFactory( connectionProvider, retryLogic, config );
        InternalDriver driver = createDriver( securityPlan, sessionFactory, metricsProvider, config );
        Logger log = config.logging().getLog( Driver.class.getSimpleName() );
        log.info( "Routing driver instance %s created for server address %s", driver.hashCode(), address );
        return driver;
    }
979817
public CloseableHttpClient createHttpClient(final Consumer<HttpClientBuilder> customiser)
	{
		final HttpClientBuilder builder = HttpClientBuilder.create();

		// By default set long call timeouts
		{
			RequestConfig.Builder requestBuilder = RequestConfig.custom();

			requestBuilder.setConnectTimeout((int) connectionTimeout.getMilliseconds())
			              .setSocketTimeout((int) socketTimeout.getMilliseconds());

			builder.setDefaultRequestConfig(requestBuilder.build());
		}

		// Set the default keepalive setting
		if (noKeepalive)
			builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());

		// By default share the common connection provider
		builder.setConnectionManager(connectionManager);

		// By default use the JRE default route planner for proxies
		builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));

		// Allow customisation
		if (customiser != null)
			customiser.accept(builder);

		return builder.build();
	}
915216
public InvokeDynamicConstant addInvokeDynamicRef(BootstrapMethodAttribute attr,
                                                   String methodName,
                                                   String methodType,
                                                   String bootClass,
                                                   String bootMethod,
                                                   String bootType,
                                                   ConstantPoolEntry []cpEntries)
  {
    NameAndTypeConstant methodEntry = addNameAndType(methodName, methodType);

    MethodRefConstant bootMethodRef
        = addMethodRef(bootClass, bootMethod, bootType);

    MethodHandleConstant bootMethodHandle
      = addMethodHandle(MethodHandleType.INVOKE_STATIC,
                        bootMethodRef);

    int bootIndex = attr.addMethod(bootMethodHandle.getIndex(), cpEntries);

    InvokeDynamicConstant invokedynamicRef
      = new InvokeDynamicConstant(this,
                                  _entries.size(),
                                  attr,
                                  bootIndex,
                                  methodEntry.getIndex());

    addConstant(invokedynamicRef);

    return invokedynamicRef;
  }
695198
public static Driver loadDriver(final File jar) {
        try {
            return loadDriver(jar.toURI().toURL());
        } catch (java.net.MalformedURLException e) {
            throw new RuntimeException(e);
        } // end of catch
    }
188379
private ProxyInvocationHandler createProxyInvocationHandler(final ProxyCreatedCallback<T> callback) {
        if (buildCalled) {
            throw new JoynrIllegalStateException("Proxy builder was already used to build a proxy. Please create a new proxy builder for each proxy.");
        }
        buildCalled = true;

        StatelessAsyncCallback statelessAsyncCallback = null;
        if (statelessAsyncCallbackUseCase != null) {
            statelessAsyncCallback = statelessAsyncCallbackDirectory.get(statelessAsyncCallbackUseCase);
            if (statelessAsyncCallback == null) {
                throw new JoynrIllegalStateException("No stateless async callback found registered for use case "
                        + statelessAsyncCallbackUseCase);
            }
        }

        final ProxyInvocationHandler proxyInvocationHandler = proxyInvocationHandlerFactory.create(domains,
                                                                                                   interfaceName,
                                                                                                   proxyParticipantId,
                                                                                                   discoveryQos,
                                                                                                   messagingQos,
                                                                                                   shutdownNotifier,
                                                                                                   statelessAsyncCallback);

        // This order is necessary because the Arbitrator might return early
        // But if the listener is set after the ProxyInvocationHandler the
        // Arbitrator cannot return early
        arbitrator.setArbitrationListener(new ArbitrationCallback() {
            @Override
            public void onSuccess(ArbitrationResult arbitrationResult) {
                logger.debug("DISCOVERY proxy created for:{}", arbitrationResult.getDiscoveryEntries());
                proxyInvocationHandler.createConnector(arbitrationResult);
                callback.onProxyCreationFinished(proxy);
            }

            @Override
            public void onError(Throwable throwable) {
                JoynrRuntimeException reason;
                if (throwable instanceof JoynrRuntimeException) {
                    reason = (JoynrRuntimeException) throwable;
                } else {
                    reason = new JoynrRuntimeException(throwable);
                }
                proxyInvocationHandler.abort(reason);
                callback.onProxyCreationError(reason);
            }
        });

        return proxyInvocationHandler;
    }
984762
public static WrapperProxyState getWrapperProxyState(Object proxy)
    {
        // A business interface proxy.
        if (proxy instanceof BusinessLocalWrapperProxy)
        {
            return ((BusinessLocalWrapperProxy) proxy).ivState;
        }

        // An EJBLocalHome or EJBLocalObject proxy.
        if (proxy instanceof EJSLocalWrapperProxy)
        {
            return ((EJSLocalWrapperProxy) proxy).ivState;
        }

        // A no-interface view proxy.
        if (proxy instanceof LocalBeanWrapperProxy)
        {
            return EJSWrapperCommon.getLocalBeanWrapperProxyState((LocalBeanWrapperProxy) proxy);
        }

        if (proxy instanceof WrapperProxy)
        {
            // Something implemented WrapperProxy without updating this method.
            throw new IllegalStateException(Util.identity(proxy));
        }

        // The caller passed something that was not a WrapperProxy.
        throw new IllegalArgumentException(Util.identity(proxy));
    }
917372
@Override
    public WebDriver createInnerDriver(Map<String, String> options, DesiredCapabilities capabilities)
            throws Exception {
        ClientProperties properties = new ClientProperties(options);

        WebDriver wd = null;
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities);
        String browser = properties.getBrowser();

        if (properties.isUseGrid()) {
			if (browser.equalsIgnoreCase("chrome")) {		
				ChromeOptions chromeOptions = new ChromeOptions();
				chromeOptions=setChromeOptions(properties);
				
				capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
			}
            RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()),
                    capabilities);
            remoteWebDriver.setFileDetector(new LocalFileDetector());
            wd = remoteWebDriver;
        }else {
            if (browser == null || browser.equals("")) {
                throw new RuntimeException(
                        "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit.");
            } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore")
                    || browser.equalsIgnoreCase("*iexplore") || browser.equalsIgnoreCase("internet explore")) {
                String webdriverIEDriver = properties.getWebDriverIEDriver();

                if (webdriverIEDriver != null) {
                    System.setProperty("webdriver.ie.driver", webdriverIEDriver);
                }

                String browserVersion = properties.getBrowserVersion();

				if(properties.shouldIgnoreSecurityDomains()) {
					desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
				}
                if (browserVersion == null || browserVersion.equals("")) {
                    throw new RuntimeException(
                            "When using IE as the browser, please set 'browser.version' in client properties");
                } else {
                    if (browserVersion.startsWith("9")) {
                        desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
                        desiredCapabilities
                                .setCapability(
                                        InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                                        true);
                        wd = new InternetExplorerDriver(desiredCapabilities);
                    } else {
                        wd = new InternetExplorerDriver(desiredCapabilities);
                    }
                }
                
            } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) {
                final String webDriverGeckoDriver = properties.getWebDriverGeckoDriver();
                if(webDriverGeckoDriver != null){
                	System.setProperty("webdriver.gecko.driver", webDriverGeckoDriver);
                }
                final String ffProfileFolder = properties.getFirefoxProfileFolder();
                final String ffProfileFile = properties.getFirefoxProfileFile();
                final String path = properties.getBinaryPath();

                if (path != null) {
                    FirefoxBinary fireFox = getFFBinary(path);
                    FirefoxProfile ffp = null;

                    if (ffProfileFolder != null) {
                        ffp = new FirefoxProfile(new File(ffProfileFolder));
                    } else {
                        ffp = new FirefoxProfile();
                    }

                    if (ffProfileFile != null) {
                        addPreferences(ffp, ffProfileFile);
                    }

                    addPreferences(ffp);

                    List<String> ffExtensions = properties.getFirefoxExtensions();
                    if (ffExtensions != null && ffExtensions.size() > 0) {
                        addExtensionsToFirefoxProfile(ffp, ffExtensions);
                    }

                    wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities);
                } else {
                    wd = new FirefoxDriver(desiredCapabilities);
                }
            } else if (browser.equalsIgnoreCase("chrome")) {

                String webdriverChromeDriver = properties.getWebDriverChromeDriver();

                if (webdriverChromeDriver != null) {
                    System.setProperty("webdriver.chrome.driver", webdriverChromeDriver);
                }

				ChromeOptions chromeOptions = new ChromeOptions();
				chromeOptions=setChromeOptions(properties);

                desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);

                wd = new ChromeDriver(desiredCapabilities);
            } else if (browser.equalsIgnoreCase("safari")) {
                wd = new SafariDriver(desiredCapabilities);
            } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge")
            		|| browser.equalsIgnoreCase("edge")) {
                wd = new EdgeDriver(desiredCapabilities);
            } else if (browser.equalsIgnoreCase("htmlunit")) {
                desiredCapabilities.setBrowserName("htmlunit");
                wd = new HtmlUnitDriver(desiredCapabilities);
                ((HtmlUnitDriver) wd).setJavascriptEnabled(true);
            } else {
                throw new Exception("Unsupported browser type: " + browser
                        + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit.");
            }

            // move browser windows to specific position. It's useful for
            // debugging...
            final int browserInitPositionX = properties.getBrowserInitPositionX();
            final int browserInitPositionY = properties.getBrowserInitPositionY();
            if (browserInitPositionX != 0 || browserInitPositionY != 0) {
                wd.manage().window().setSize(new Dimension(1280, 1024));
                wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY));
            }
        }

        return wd;
    }
1295323
protected static <P extends AbstractEncoderProxy<T>, T> Object newInstance(
        final Class<P> proxyType, final Class<T> encoderType, final T encoder) {

        if (proxyType == null) {
            throw new NullPointerException("proxyType");
        }

        if (!StringEncoderProxy.class.isAssignableFrom(proxyType)) {
            throw new IllegalArgumentException(
                "proxyType(" + proxyType + ") is not assignable to "
                + StringEncoderProxy.class);
        }

        return newInstance(ENCODER.getClassLoader(), new Class<?>[]{ENCODER},
                           proxyType, encoderType, encoder);
    }
876762
private static Object makeClientWrapper(Class<?> clientType,String clientId,Class<? extends InvokeHandler> handlerClass){
        String clientName = clientType.getSimpleName();
        long id = WRAPPER_COUNTER.getAndIncrement();
        if(clientType==DCW.class){
            throw new IllegalArgumentException("not support generate wrapper for interface "+clientName);
        }
        if(!clientType.isInterface()){
            throw new IllegalArgumentException("only support interface to generate wrapper,but type "+clientName+" is not interface");
        }
        JavassistClassGenerator generator = JavassistClassGenerator.newInstance(clientType.getClassLoader());
        generator.addInterface(clientType.getName());
        generator.addInterface(DCW.class.getName());
        StringBuilder className = new StringBuilder();
        className.append(clientType.getSimpleName()).append("$DCW").append(id);
        generator.setClassName(className.toString());
        Method[] methods = clientType.getDeclaredMethods();
        StringBuilder methodCode = new StringBuilder();
        for(Method method:methods){
            methodCode.append("public ");
            Class<?> returnType = method.getReturnType();
            Class<?>[] argsTypes = method.getParameterTypes();
            if(returnType== Void.TYPE){
                methodCode.append("void ");
            }else{
                methodCode.append(returnType.getName()).append(" ");
            }
            methodCode.append(method.getName()).append("(");
            //append arguments
            if(argsTypes.length!=0){
                for(int i=0;i<argsTypes.length;i++){
                    methodCode.append(argsTypes[i].getName()).append(" arg").append(i).append(",");
                }
                methodCode.setLength(methodCode.length()-1);
            }
            Class<?>[] exceptionTypes = method.getExceptionTypes();
            methodCode.append(")");
            if(exceptionTypes.length!=0){
                methodCode.append("throws ");
                for(Class<?> exceptionType:exceptionTypes){
                    methodCode.append(exceptionType.getName()).append(",");
                }
                methodCode.setLength(methodCode.length()-1);
            }
            methodCode.append("{");
            methodCode.append("try{");
            //append method body
            //handle invoke before
            if(argsTypes.length==0){
                methodCode.append("invokeHandler.beforeInvoke(clientType,\"" + method.getName() + "\",null);");
            }else{
                methodCode.append("invokeHandler.beforeInvoke(clientType,\"" + method.getName() + "\",$args);");
            }
            //handle invoke complete
            if(returnType== Void.TYPE){
                methodCode.append("(($w)clientRef).").append(method.getName()).append("($$);");
                if(argsTypes.length==0){
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",null,null);");
                }else{
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",null,$args);");
                }
            }else{
                methodCode.append("Object result=(($w)clientRef).").append(method.getName()).append("($$);");
                if(argsTypes.length==0){
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",(Object)result,null);");
                }else{
                    methodCode.append("invokeHandler.completeInvoke(clientType,\"" + method.getName() + "\",(Object)result,$args);");
                }
                methodCode.append("return ($r)result;");
            }
            methodCode.append("}catch(Throwable t){");
            //handle invoke exception
            if(argsTypes.length==0){
                methodCode.append("invokeHandler.caughtException(clientType,\"" + method.getName() + "\",t,null);");
            }else{
                methodCode.append("invokeHandler.caughtException(clientType,\"" + method.getName() + "\",t,$args);");
            }

            methodCode.append("throw new ").append(InvokeTargetException.class.getName()).append("(clientType,\""+method.getName()+"\",t);");
            methodCode.append("}");
            methodCode.append("}");
            generator.addMethod(methodCode.toString());
            methodCode.setLength(0);
        }
        generator.addField("public static "+clientType.getName()+" clientRef;");
        generator.addField("public static "+InvokeHandler.class.getName()+" invokeHandler;");
        generator.addField("public static "+Class.class.getName()+" clientType;");
        Class<?> clazz = generator.toClass();
        try {
            ReferenceConfig config = new ReferenceConfig();
            config.setId(clientId);
            config.setCheck(false);
            config.setInterface(clientType.getName());
            clazz.getField("clientRef").set(null,config.get());
            if(!HANDLER_CACHE.containsKey(handlerClass)){
                HANDLER_CACHE.putIfAbsent(handlerClass,handlerClass.newInstance());
            }
            clazz.getField("invokeHandler").set(null,HANDLER_CACHE.get(handlerClass));
            clazz.getField("clientType").set(null,clientType);
            return clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }
642753
@Override
  public Transport newInstance(final String hostAddress,
                               final int port,
                               final EStage<TransportEvent> clientStage,
                               final EStage<TransportEvent> serverStage,
                               final int numberOfTries,
                               final int retryTimeout) {
    try {
      TcpPortProvider tcpPortProvider = Tang.Factory.getTang().newInjector().getInstance(TcpPortProvider.class);
      return newInstance(hostAddress, port, clientStage,
              serverStage, numberOfTries, retryTimeout, tcpPortProvider);
    } catch (final InjectionException e) {
      throw new RuntimeException(e);
    }
  }