Inject instances to the microservices instance. either Microservices or ServiceProxy. Scan all
local service instances and inject a service proxy.

@param microservices microservices instance
@param services services set
@return microservices instance
481551
public static Microservices inject(Microservices microservices, Collection<Object> services) {
    services.forEach(
        service ->
            Arrays.stream(service.getClass().getDeclaredFields())
                .forEach(field -> injectField(microservices, field, service)));
    services.forEach(service -> processAfterConstruct(microservices, service));
    return microservices;
  }
682581
public static void main(String[] args) throws InterruptedException {
    Microservices ms1 =
        Microservices.builder()
            .discovery(ScalecubeServiceDiscovery::new)
            .transport(ServiceTransports::rsocketServiceTransport)
            .defaultErrorMapper(new ServiceAProviderErrorMapper()) // default mapper for whole node
            .services(
                ServiceInfo.fromServiceInstance(new ServiceAImpl())
                    .errorMapper(new ServiceAProviderErrorMapper()) // mapper per service instance
                    .build())
            .startAwait();

    System.err.println("ms1 started: " + ms1.serviceAddress());

    Microservices ms2 =
        Microservices.builder()
            .discovery(serviceEndpoint -> serviceDiscovery(serviceEndpoint, ms1))
            .transport(ServiceTransports::rsocketServiceTransport)
            .services(
                call -> {
                  ServiceA serviceA =
                      call.errorMapper(
                              new ServiceAClientErrorMapper()) // service client error mapper
                          .api(ServiceA.class);

                  ServiceB serviceB = new ServiceBImpl(serviceA);

                  return Collections.singleton(ServiceInfo.fromServiceInstance(serviceB).build());
                })
            .startAwait();

    System.err.println("ms2 started: " + ms2.serviceAddress());

    ms2.call()
        .api(ServiceB.class)
        .doAnotherStuff(0)
        .subscribe(
            System.out::println,
            th ->
                System.err.println(
                    "No service client mapper is defined for ServiceB, "
                        + "so default scalecube mapper is used! -> "
                        + th),
            () -> System.out.println("Completed!"));

    Thread.currentThread().join();
  }
972979
private function overrideServices(ContainerBuilder $container, array $services)
    {
        $serviceConfig = array(
            'auth_handler' => 'ma27_api_key_authentication.auth_handler',
            'key_factory'  => 'ma27_api_key_authentication.key_factory',
        );

        foreach ($serviceConfig as $configIndex => $replaceableServiceId) {
            if (!isset($services[$configIndex]) || null === $serviceId = $services[$configIndex]) {
                continue;
            }

            $container->removeDefinition($replaceableServiceId);
            $container->setAlias($replaceableServiceId, new Alias($serviceId));
        }
    }
1006511
protected function getServiceProxy(string $service): LocatorProxyInterface
    {
        return new LocatorProxy(
            $this->coreNamespaces,
            $this->projectNamespaces,
            ucfirst($service)
        );
    }
43897
@SuppressWarnings( "unchecked" )
    public <T> T getService( final Class<T> serviceType,
                             final long timeoutInMillis )
    {
        return (T) Proxy.newProxyInstance(
            getClass().getClassLoader(),
            new Class<?>[]{ serviceType },
            new InvocationHandler()
            {
                /**
                 * {@inheritDoc}
                 * Delegates the call to remote bundle context.
                 */
                public Object invoke( final Object proxy,
                                      final Method method,
                                      final Object[] params )
                    throws Throwable
                {
                    try
                    {
                        return getRemoteBundleContext().remoteCall(
                            method.getDeclaringClass(),
                            method.getName(),
                            method.getParameterTypes(),
                            timeoutInMillis,
                            params
                        );
                    }
                    catch( InvocationTargetException e )
                    {
                        throw e.getCause();
                    }
                    catch( RemoteException e )
                    {
                        throw new TestContainerException( "Remote exception", e );
                    }
                    catch( Exception e )
                    {
                        throw new TestContainerException( "Invocation exception", e );
                    }
                }
            }
        );
    }
1288160
@SuppressWarnings("unchecked")
    public static <T> Set<T> getServices(Class<T> serviceInterface) {
        synchronized(servicesCache) {
            if (servicesCache.containsKey(serviceInterface)) {
                return (Set<T>) servicesCache.get(serviceInterface);
            }
    
            Set<T> services = new LinkedHashSet<>();
            try {
                for (T service : ServiceLoader.load(serviceInterface)) {
                    services.add(service);
                }
            } catch (ServiceConfigurationError sce) {
                // No services found - don't check again.
            }
            servicesCache.put(serviceInterface, services);
            return services;
        }
    }
1292529
static Set<String> serviceNames(Service<HttpRequest, HttpResponse> service) {
        if (thriftServiceClass == null || entriesMethod == null || interfacesMethod == null) {
            return ImmutableSet.of();
        }
        return service.as(thriftServiceClass)
                      .map(s -> {
                          @SuppressWarnings("unchecked")
                          final Map<String, ?> entries = (Map<String, ?>) invokeMethod(entriesMethod, s);
                          assert entries != null;
                          return toServiceName(entries.values());
                      })
                      .orElse(ImmutableSet.of());
    }
1360158
@Override
    public InjectionBinding<JMSConnectionFactoryDefinition> createInjectionBinding(JMSConnectionFactoryDefinition annotation, Class<?> instanceClass, Member member, String jndiName) throws InjectionException {
        InjectionBinding<JMSConnectionFactoryDefinition> injectionBinding =
                        new JMSConnectionFactoryDefinitionInjectionBinding(jndiName, ivNameSpaceConfig);
        injectionBinding.merge(annotation, instanceClass, null);
        return injectionBinding;
    }
173978
public void setServices(List<ServiceInfo> services) {
        if (services == null || services.size() == 0) {
            throw new IllegalArgumentException("services is empty!");
        }
        this.services = services;
        serviceReset = true;
    }
1368834
private ServiceRegistration<?> registerMBeanService(String jmsResourceName, BundleContext bundleContext) {
        Dictionary<String, String> props = new Hashtable<String, String>();
        props.put(KEY_SERVICE_VENDOR, "IBM");

        JmsServiceProviderMBeanImpl jmsProviderMBean = new JmsServiceProviderMBeanImpl(getServerName(), KEY_JMS2_PROVIDER);
        props.put(KEY_JMX_OBJECTNAME, jmsProviderMBean.getobjectName());

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "JmsQueueMBeanImpl=" + jmsProviderMBean.getobjectName() + " props=" + props);
        }
        return bundleContext.registerService(JmsServiceProviderMBeanImpl.class, jmsProviderMBean, props);
    }
1258431
@Override
	public Promise waitForServices(long timeoutMillis, Collection<String> services) {
		if (services == null || services.isEmpty() || isServicesOnline(services)) {
			return Promise.resolve();
		}
		Promise promise = new Promise();
		long timeoutAt;
		if (timeoutMillis > 0) {
			timeoutAt = System.currentTimeMillis() + timeoutMillis;
		} else {
			timeoutAt = 0;
		}
		ServiceListener listener = new ServiceListener(promise, timeoutAt, services);
		synchronized (serviceListeners) {
			serviceListeners.addLast(listener);
			if (servicesOnlineTimer == null) {
				servicesOnlineTimer = scheduler.scheduleWithFixedDelay(this::checkServicesOnline, 1, 1,
						TimeUnit.SECONDS);
			}
		}
		return promise;
	}
578365
public static List<Service> getServices(List<ServiceId> ids) {
        ProviderList list = Providers.getProviderList();
        return list.getServices(ids);
    }
1122423
private Class<?> retrieveRealServiceClass(Object service) {
        Class<?> serviceClass = service.getClass();
        Method realTypeMethod = null;
        try {
            realTypeMethod = serviceClass.getMethod("getRealUnproxiedType");
        } catch (NoSuchMethodException e) {
            // no problem this method does not have to exist
        }
        if (realTypeMethod != null) {
            try {
                serviceClass = (Class<?>) realTypeMethod.invoke(service);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return serviceClass;
    }
466612
public void setServices(java.util.Collection<String> services) {
        if (services == null) {
            this.services = null;
            return;
        }

        this.services = new java.util.ArrayList<String>(services);
    }
809822
private <T extends OrchidService> void initializeService(Class<T> serviceClass, T service) {
        services.put(serviceClass, service);
    }
1062339
public Client createWithValues(Object... varValues) {
        serviceFactory.setBus(getBus());
        checkResources(false);
        ClassResourceInfo cri = null;
        try {
            Endpoint ep = createEndpoint();
            if (getServiceClass() != null) {
                for (ClassResourceInfo info : serviceFactory.getClassResourceInfo()) {
                    if (info.getServiceClass().isAssignableFrom(getServiceClass())
                        || getServiceClass().isAssignableFrom(info.getServiceClass())) {
                        cri = info;
                        break;
                    }
                }
                if (cri == null) {
                    // can not happen in the reality
                    throw new RuntimeException("Service class " + getServiceClass().getName()
                                               + " is not recognized");
                }
            } else {
                cri = serviceFactory.getClassResourceInfo().get(0);
            }

            boolean isRoot = cri.getURITemplate() != null;
            ClientProxyImpl proxyImpl = null;
            ClientState actualState = getActualState();
            proxyImpl = createClientProxy(cri, isRoot, actualState, varValues);
            initClient(proxyImpl, ep, actualState == null);

            final Class<?> serviceClass = cri.getServiceClass();
            ClassLoader theLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {

                @Override
                public ClassLoader run() {
                    return proxyLoader == null ? serviceClass.getClassLoader() : proxyLoader;
                }
            });
            Class<?>[] ifaces = new Class[]{Client.class, InvocationHandlerAware.class, cri.getServiceClass()};
            Client actualClient = (Client)ProxyHelper.getProxy(theLoader, ifaces, proxyImpl);
            proxyImpl.setProxyClient(actualClient);
            notifyLifecycleManager(actualClient);
            this.getServiceFactory().sendEvent(FactoryBeanListener.Event.CLIENT_CREATED, actualClient, ep);
            return actualClient;
        } catch (IllegalArgumentException ex) {
            String message = ex.getLocalizedMessage();
            if (cri != null) {
                String expected = cri.getServiceClass().getSimpleName();
                if ((expected + " is not an interface").equals(message)) {
                    message += "; make sure CGLIB is on the classpath";
                }
            }
            LOG.severe(ex.getClass().getName() + " : " + message);
            throw ex;
        } catch (Exception ex) {
            LOG.severe(ex.getClass().getName() + " : " + ex.getLocalizedMessage());
            throw new RuntimeException(ex);
        }

    }
415933
public GrpcServerBuilder addService(GrpcService serviceDefinition) {
    ServerServiceDefinition service = serviceDefinition.getServiceDefinition();
    if (SecurityUtils.isAuthenticationEnabled(mConfiguration)
        && serviceDefinition.isAuthenticated()) {
      // Intercept the service with authenticated user injector.
      service = ServerInterceptors.intercept(service,
          new AuthenticatedUserInjector(mAuthenticationServer));
    }
    mNettyServerBuilder = mNettyServerBuilder.addService(service);
    return this;
  }