Initialize the context with the given {@link io.micronaut.context.annotation.Context} scope beans.

@param contextScopeBeans The context scope beans
@param processedBeans    The beans that require {@link ExecutableMethodProcessor} handling
976553
protected void initializeContext(
            @Nonnull List<BeanDefinitionReference> contextScopeBeans,
            @Nonnull List<BeanDefinitionReference> processedBeans) {

        if (CollectionUtils.isNotEmpty(contextScopeBeans)) {
            final Collection<BeanDefinition> contextBeans = new ArrayList<>();

            for (BeanDefinitionReference contextScopeBean : contextScopeBeans) {
                try {
                    loadContextScopeBean(contextScopeBean, contextBeans::add);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeBean.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            filterProxiedTypes((Collection) contextBeans, true, false);
            filterReplacedBeans((Collection) contextBeans);

            for (BeanDefinition contextScopeDefinition: contextBeans) {
                try {
                    loadContextScopeBean(contextScopeDefinition);
                } catch (Throwable e) {
                    throw new BeanInstantiationException("Bean definition [" + contextScopeDefinition.getName() + "] could not be loaded: " + e.getMessage(), e);
                }
            }
            contextBeans.clear();
        }

        if (!processedBeans.isEmpty()) {

            @SuppressWarnings("unchecked") Stream<BeanDefinitionMethodReference<?, ?>> methodStream = processedBeans
                    .stream()
                    // is the bean reference enabled
                    .filter(ref -> ref.isEnabled(this))
                    // ok - continue and load it
                    .map((Function<BeanDefinitionReference, BeanDefinition<?>>) reference -> {
                        try {
                            return reference.load(this);
                        } catch (Exception e) {
                            throw new BeanInstantiationException("Bean definition [" + reference.getName() + "] could not be loaded: " + e.getMessage(), e);
                        }
                    })
                    // is the bean itself enabled
                    .filter(bean -> bean.isEnabled(this))
                    // ok continue and get all of the ExecutableMethod references
                    .flatMap(beanDefinition ->
                            beanDefinition.getExecutableMethods()
                                    .parallelStream()
                                    .map((Function<ExecutableMethod<?, ?>, BeanDefinitionMethodReference<?, ?>>) executableMethod ->
                                            BeanDefinitionMethodReference.of((BeanDefinition) beanDefinition, executableMethod)
                                    )
                    );

            // group the method references by annotation type such that we have a map of Annotation -> MethodReference
            // ie. Class<Scheduled> -> @Scheduled void someAnnotation()
            Map<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> byAnnotation = methodStream
                    .collect(
                            Collectors.groupingBy((Function<ExecutableMethod<?, ?>, Class<? extends Annotation>>) executableMethod ->
                                    executableMethod.getAnnotationTypeByStereotype(Executable.class)
                                            .orElseThrow(() ->
                                                    new IllegalStateException("BeanDefinition.requiresMethodProcessing() returned true but method has no @Executable definition. This should never happen. Please report an issue.")
                                            )));

            // Find ExecutableMethodProcessor for each annotation and process the BeanDefinitionMethodReference
            for (Map.Entry<Class<? extends Annotation>, List<BeanDefinitionMethodReference<?, ?>>> entry : byAnnotation.entrySet()) {
                Class<? extends Annotation> annotationType = entry.getKey();
                streamOfType(ExecutableMethodProcessor.class, Qualifiers.byTypeArguments(annotationType))
                        .forEach(processor -> {
                            for (BeanDefinitionMethodReference<?, ?> method : entry.getValue()) {

                                BeanDefinition<?> beanDefinition = method.getBeanDefinition();

                                // Only process the method if the the annotation is not declared at the class level
                                // If declared at the class level it will already have been processed by AnnotationProcessorListener
                                if (!beanDefinition.hasStereotype(annotationType)) {
                                    //noinspection unchecked
                                    if (method.hasDeclaredStereotype(Parallel.class)) {
                                        ForkJoinPool.commonPool().execute(() -> {
                                            try {
                                                processor.process(beanDefinition, method);
                                            } catch (Throwable e) {
                                                if (LOG.isErrorEnabled()) {
                                                    LOG.error("Error processing bean method " + beanDefinition + "." + method + " with processor (" + processor + "): " + e.getMessage(), e);
                                                }
                                                Boolean shutdownOnError = method.getValue(Parallel.class, "shutdownOnError", Boolean.class).orElse(true);
                                                if (shutdownOnError) {
                                                    stop();
                                                }
                                            }
                                        });
                                    } else {
                                        processor.process(beanDefinition, method);
                                    }
                                }
                            }

                            if (processor instanceof Completable) {
                                ((Completable) processor).onComplete();
                            }

                        });
            }
        }

        final Runnable runnable = () ->
                beanDefinitionsClasses.removeIf((BeanDefinitionReference beanDefinitionReference) ->
                        !beanDefinitionReference.isEnabled(this));
        if (ClassLoadingReporter.isReportingEnabled()) {
            // do this in a blocking manner so that reporting is immediately aware of missing classes
            runnable.run();
        } else {
            // proactively remove bean definitions that are not enabled
            new Thread(runnable).start();
        }

    }
584517
@Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        propertyProvider = new PropertyProvider(applicationContext);
        conversionService = DefaultConversionService.getSharedInstance();
        wireParams(this);
        afterInitialized();
    }
194182
public void afterPropertiesSet() {

		ApplicationContext context = this.context;

		if (context == null) {
			throw new IllegalStateException("ApplicationContext not set!");
		}

		Class<?> type = this.type;

		if (type == null) {
			throw new IllegalStateException("No type configured!");
		}

		this.targetSource = new BeansOfTypeTargetSource(context, type, false, exclusions);
	}
1053306
protected void execute(InputStream input, OutputStream output, C context) throws IOException {
        final ApplicationContext applicationContext = buildApplicationContext(context);
        if (context == null) {
            context = (C) applicationContext;
        }

        final Environment env = startEnvironment(applicationContext);
        final String functionName = resolveFunctionName(env);

        if (functionName == null) {
            throw new InvocationException("No Function name configured. Set 'micronaut.function.name' in your Function configuration");
        }

        LocalFunctionRegistry localFunctionRegistry = applicationContext.getBean(LocalFunctionRegistry.class);
        ExecutableMethod<Object, Object> method = resolveFunction(localFunctionRegistry, functionName);
        Class<?> returnJavaType = method.getReturnType().getType();
        if (ClassLoadingReporter.isReportingEnabled()) {
            ClassLoadingReporter.reportBeanPresent(returnJavaType);
        }

        Argument[] requiredArguments = method.getArguments();
        int argCount = requiredArguments.length;
        Object result;
        Qualifier<Object> qualifier = Qualifiers.byName(functionName);
        Class<Object> functionType = method.getDeclaringType();
        BeanDefinition<Object> beanDefinition = applicationContext.getBeanDefinition(functionType, qualifier);
        Object bean = applicationContext.getBean(functionType, qualifier);
        List<Argument<?>> typeArguments = beanDefinition.getTypeArguments();

        try {
            switch (argCount) {
                case 0:
                    result = method.invoke(bean);
                    break;
                case 1:

                    Argument arg = requiredArguments[0];
                    if (!typeArguments.isEmpty()) {
                        arg = Argument.of(typeArguments.get(0).getType(), arg.getName());
                    }
                    Object value = decodeInputArgument(env, localFunctionRegistry, arg, input);
                    result = method.invoke(bean, value);
                    break;
                case 2:
                    Argument firstArgument = requiredArguments[0];
                    Argument secondArgument = requiredArguments[1];

                    if (!typeArguments.isEmpty()) {
                        firstArgument = Argument.of(typeArguments.get(0).getType(), firstArgument.getName());
                    }

                    Object first = decodeInputArgument(env, localFunctionRegistry, firstArgument, input);
                    Object second = decodeContext(env, secondArgument, context);
                    result = method.invoke(bean, first, second);
                    break;
                default:
                    throw new InvocationException("Function [" + functionName + "] cannot be made executable.");
            }
            if (result != null) {
                encode(env, localFunctionRegistry, returnJavaType, result, output);
            }
        } finally {
            closeApplicationContext();
        }
    }
120742
@Override
    public void init(final String scope) throws InitializationException, InterruptedException {
        try {
            init(ScopeProcessor.generateScope(scope));
        } catch (CouldNotPerformException | NullPointerException ex) {
            throw new InitializationException(this, ex);
        }
    }
531144
@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		try {
			HashSet<Class<?>> registeredTypes = new HashSet<>();

			// Get Service Broker
			ServiceBroker broker = applicationContext.getBean(ServiceBroker.class);

			// Find Services in Spring Application Context
			Map<String, Service> serviceMap = applicationContext.getBeansOfType(Service.class);
			if (serviceMap != null && !serviceMap.isEmpty()) {
				String name;
				for (Map.Entry<String, Service> service : serviceMap.entrySet()) {

					// Register Service in Broker
					name = service.getKey();
					registeredTypes.add(service.getClass());
					if (name != null && name.startsWith("$")) {
						broker.createService(name, service.getValue());
						logger.info("Service \"" + name + "\" registered.");
					} else {
						Service instance = service.getValue();
						broker.createService(instance);
						logger.info("Service \"" + instance.getName() + "\" registered.");
					}
				}
			}

			// Add new Services
			if (packagesToScan != null && packagesToScan.length > 0) {
				DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext
						.getAutowireCapableBeanFactory();
				for (String packageName : packagesToScan) {
					if (!packageName.isEmpty()) {
						LinkedList<String> classNames = scan(packageName);
						for (String className : classNames) {
							if (className.indexOf('$') > -1) {
								continue;
							}
							className = packageName + '.' + className;
							Class<?> type = Class.forName(className);
							if (Service.class.isAssignableFrom(type)) {

								// Check type
								if (!registeredTypes.add(type)) {
									continue;
								}

								// Register Service in Spring
								String name = nameOf(type, false);
								BeanDefinition definition = BeanDefinitionBuilder.genericBeanDefinition(type)
										.setScope(BeanDefinition.SCOPE_SINGLETON)
										.setAutowireMode(DefaultListableBeanFactory.AUTOWIRE_BY_TYPE).setLazyInit(false)
										.getBeanDefinition();
								beanFactory.registerBeanDefinition(name, definition);
								Service service = (Service) beanFactory.createBean(type);

								// Register Service in Broker
								broker.createService(service);

								// Log
								logger.info("Service \"" + name + "\" registered.");
							}
						}
					}
				}
			}
		} catch (Exception cause) {
			throw new FatalBeanException("Unable to define Moleculer Service!", cause);
		}
	}
955421
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
		if (this.beanNameGenerator != null) {
			context.getBeanFactory().registerSingleton(
					AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
					this.beanNameGenerator);
		}
		if (this.resourceLoader != null) {
			if (context instanceof GenericApplicationContext) {
				((GenericApplicationContext) context)
						.setResourceLoader(this.resourceLoader);
			}
			if (context instanceof DefaultResourceLoader) {
				((DefaultResourceLoader) context)
						.setClassLoader(this.resourceLoader.getClassLoader());
			}
		}
		if (this.addConversionService) {
			context.getBeanFactory().setConversionService(
					ApplicationConversionService.getSharedInstance());
		}
	}
1173258
public void processStartOfScope(Scope scopeStarting, Iterable<Object> handlerInstances) throws Exception {
        for (Object handler : handlerInstances) {
            Handler handlerAnnotation = handler.getClass().getAnnotation(Handler.class);
            Scope handlerScope = handlerAnnotation.scope();

            injectResourceFieldsForScope(scopeStarting, handler, handlerScope, handlerInstances);
            runLifecycleMethods(handler, handlerScope, scopeStarting, false);
        }    
    }
1141806
@Override
    public void contextInitialized(ServletContextEvent event) {
        try {
            initEurekaEnvironment();
            initEurekaServerContext();

            ServletContext sc = event.getServletContext();
            sc.setAttribute(EurekaServerContext.class.getName(), serverContext);
        } catch (Throwable e) {
            logger.error("Cannot bootstrap eureka server :", e);
            throw new RuntimeException("Cannot bootstrap eureka server :", e);
        }
    }
800185
public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,
            Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {
        for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {
            initializer.invoke(instance, null, manager, creationalContext, CreationException.class);
        }
    }
1173920
@Override
    public void initialize(BeanContext context) {
        Resource resource = ConsoleUtil.getConsoleResource(context);
        initialize(context, ResourceHandle.use(resource));
    }
1171755
@Override
    public final void contextInitialized(final ServletContextEvent sce) {
        if (persistenceEnabled) {
            // Load ec2 instances
            AbstractMockEc2Instance[] instanceArray = (AbstractMockEc2Instance[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.EC2);
            if (null != instanceArray) {
                MockEc2Controller.getInstance()
                        .restoreAllMockEc2Instances(Arrays.asList(instanceArray));
            }

         // Load Vpc
            MockVpc[] vpcArray = (MockVpc[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.VPC);
            if (null != vpcArray) {
                MockVpcController.getInstance()
                        .restoreAllMockVpc(Arrays.asList(vpcArray));
            }

            // Load Volume
            MockVolume[] volumeArray = (MockVolume[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.VOLUME);
            if (null != volumeArray) {
                MockVolumeController.getInstance()
                        .restoreAllMockVolume(Arrays.asList(volumeArray));
            }

            // Load Tags
            MockTags[] tagsArray = (MockTags[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.TAGS);
            if (null != tagsArray) {
                MockTagsController.getInstance()
                        .restoreAllMockTags(Arrays.asList(tagsArray));
            }

            // Load Subnet
            MockSubnet[] subnetArray = (MockSubnet[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.SUBNET);
            if (null != subnetArray) {
                MockSubnetController.getInstance()
                        .restoreAllMockSubnet(Arrays.asList(subnetArray));
            }

            // Load RouteTable
            MockRouteTable[] routetableArray = (MockRouteTable[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.ROUTETABLE);
            if (null != routetableArray) {
                MockRouteTableController.getInstance()
                        .restoreAllMockRouteTable(Arrays.asList(routetableArray));
            }

            // Load Internet Gateway
            MockInternetGateway[] internetgatewayArray = (MockInternetGateway[]) PersistenceUtils
                    .loadAll(PersistenceStoreType.INTERNETGATEWAY);
            if (null != internetgatewayArray) {
                MockInternetGatewayController.getInstance()
                        .restoreAllInternetGateway(Arrays.asList(internetgatewayArray));
            }
        }

        // start a timer for cleaning up terminated instances
        MockEc2Controller.getInstance()
                .cleanupTerminatedInstances(cleanupTerminatedInstancesPeriod);

        log.info("aws-mock started.");
    }
1147772
public final void contextInitialized(final ServletContextEvent sce) {
		try {
			// Get the configuration
			final ParalleljConfiguration configuration = (ParalleljConfiguration) ConfigurationService
					.getConfigurationService().getConfigurationManager()
					.get(ParalleljConfigurationManager.class).getConfiguration();

			// Initialize the launcher
			Launcher.getLauncher();

			// Initialize a TcpIpServer
			if (configuration.getServers() != null
					&& configuration.getServers().getTelnet() != null) {
				this.tcpIpServer = new TcpIpServer(configuration.getServers()
						.getTelnet().getHost(), configuration.getServers()
						.getTelnet().getPort(), new TcpIpHandlerAdapter());
				// Try to start the TciIpServer
				if (this.tcpIpServer != null) {
					try {
						this.tcpIpServer.start();
					} catch (IOException e) {
						LaunchingMessageKind.ETCPIP0001.format(e);
					}
				}
			}

			// Initialize a JmxServer
			// and register all defined Program as MBeans
			if (configuration.getServers() != null
					&& configuration.getServers().getJmx() != null) {
				this.jmxServer = new JmxServer(configuration.getServers()
						.getJmx().getHost(), configuration.getServers()
						.getJmx().getPort());
				// Try to start the JmxServer
				if (this.jmxServer != null) {
					try {
						this.jmxServer.start();
					} catch (IOException e) {
						LaunchingMessageKind.EJMX0001.format(e);
					}
				}
			}

			// Initialize a SshServer
			if (configuration.getServers() != null
					&& configuration.getServers().getSsh() != null) {

				this.sshServer = new SshServer(configuration.getServers()
						.getSsh().getPort());

				// Try to start SshServer
				if (this.sshServer != null) {
					try {
						sshServer.start();
					} catch (IOException e) {
						LaunchingMessageKind.ESSH0001.format(e);
					}
				}
			}
			
		} catch (LaunchException e) {
			LaunchingMessageKind.EWLAUNCH0001.format(e);
		}
	}
601914
@Override
	public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
		if (bean instanceof Properties && bean != getPrefixedProperties() && getProcessOtherProperties()) {
			final Properties props = (Properties) bean;
			final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(placeholderPrefix, placeholderSuffix,
					valueSeparator, ignoreUnresolvablePlaceholders);
			final PrefixedProperties clone = getPrefixedProperties().clone();
			clone.putAll(props);
			final Properties beanProperty = (Properties) bean;
			for (final Object key : beanProperty.keySet()) {
				if (key instanceof String) {
					final String stringKey = (String) key;
					props.setProperty(stringKey,
							helper.replacePlaceholders(beanProperty.getProperty(stringKey), clone));
				}
			}
		}
		return bean;
	}
925388
public static void init( ServletContext servletContext )
    {
        PageFlowFactoriesConfig factoriesBean = ConfigUtil.getConfig().getPageFlowFactories();
        FlowControllerFactory factory = null;

        if ( factoriesBean != null )
        {
            PageFlowFactoryConfig fcFactoryBean = factoriesBean.getPageFlowFactory();
            factory = ( FlowControllerFactory ) FactoryUtils.getFactory( servletContext, fcFactoryBean, FlowControllerFactory.class );
        }

        if ( factory == null )
            factory = new FlowControllerFactory();

        factory.reinit( servletContext );

        servletContext.setAttribute( CONTEXT_ATTR, factory );
    }
1240544
public void initialize(HttpContext context)
    {
        SessionManager sessionManager=getSessionManager();
        

        if (_httpContext!=null&& _httpContext!=context)
            throw new IllegalStateException("Can't initialize handler for different context");
        _httpContext=context;
        
        sessionManager.initialize(this);
    }
1122091
@SuppressWarnings("unchecked")
    <T> void processBean(@Observes ProcessBean<T> processBean) {
        Bean<T> bean = processBean.getBean();
        for (Type type : bean.getTypes()) {
            if (!(type instanceof Class<?>)) {
                continue;
            }

            // Check if the bean is an RedisURI.
            if (RedisURI.class.isAssignableFrom((Class<?>) type)) {
                Set<Annotation> qualifiers = LettuceSets.newHashSet(bean.getQualifiers());
                if (bean.isAlternative() || !redisUris.containsKey(qualifiers)) {
                    LOGGER.debug(String.format("Discovered '%s' with qualifiers %s.", RedisURI.class.getName(), qualifiers));
                    redisUris.put(qualifiers, (Bean<RedisURI>) bean);
                }
            }

            if (ClientResources.class.isAssignableFrom((Class<?>) type)) {
                Set<Annotation> qualifiers = LettuceSets.newHashSet(bean.getQualifiers());
                if (bean.isAlternative() || !clientResources.containsKey(qualifiers)) {
                    LOGGER.debug(String.format("Discovered '%s' with qualifiers %s.", ClientResources.class.getName(),
                            qualifiers));
                    clientResources.put(qualifiers, (Bean<ClientResources>) bean);
                }
            }
        }
    }