public void validate(@Observes AfterDeploymentValidation add, BeanManager bm) { List<String> deploymentProblems = new ArrayList<>(); Config config = ConfigProvider.getConfig(); for (InjectionPoint injectionPoint : injectionPoints) { Type type = injectionPoint.getType(); ConfigProperty configProperty = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class); if (type instanceof Class) { String key = getConfigKey(injectionPoint, configProperty); if (!config.getOptionalValue(key, (Class)type).isPresent()) { String defaultValue = configProperty.defaultValue(); if (defaultValue == null || defaultValue.equals(ConfigProperty.UNCONFIGURED_VALUE)) { deploymentProblems.add("No Config Value exists for " + key); } } } } if (!deploymentProblems.isEmpty()) { add.addDeploymentProblem(new DeploymentException("Error while validating Configuration\n" + String.join("\n", deploymentProblems))); } }
@Test @SuppressWarnings({ "unchecked", "rawtypes" }) public void initialiseContexts() { final WebSocketContext webSocketContext = mock(WebSocketContext.class); ReflectionUtil.set(this.extension, "webSocketContext", webSocketContext); final AfterDeploymentValidation afterDeploymentValidation = mock(AfterDeploymentValidation.class); final Bean<?> bean = mock(Bean.class); when(this.beanManager.getBeans(WebSocketSessionHolder.class)).thenReturn(Collections.singleton(bean)); when(this.beanManager.resolve(any(Set.class))).thenReturn(bean); final CreationalContext creationalContext = mock(CreationalContext.class); when(this.beanManager.createCreationalContext(bean)).thenReturn(creationalContext); final WebSocketSessionHolder webSocketSessionHolder = mock(WebSocketSessionHolder.class); when(this.beanManager.getReference(bean, WebSocketSessionHolder.class, creationalContext)).thenReturn(webSocketSessionHolder); this.extension.initialiseContexts(afterDeploymentValidation, this.beanManager); verify(this.beanManager).getBeans(WebSocketSessionHolder.class); verify(this.beanManager).resolve(any(Set.class)); verify(this.beanManager).createCreationalContext(bean); verify(this.beanManager).getReference(bean, WebSocketSessionHolder.class, creationalContext); verify(webSocketContext).init(webSocketSessionHolder); verifyNoMoreInteractions(webSocketContext, afterDeploymentValidation, bean, creationalContext, webSocketSessionHolder); }
/** * Instantiates <em>unmanaged instances</em> of HealthCheckProcedure and * handle manually their CDI creation lifecycle. * Add them to the {@link Monitor}. */ private void afterDeploymentValidation(@Observes final AfterDeploymentValidation abd, BeanManager beanManager) { try { for (AnnotatedType delegate : delegates) { Unmanaged<HealthCheck> unmanagedHealthCheck = new Unmanaged<HealthCheck>(beanManager, delegate.getJavaClass()); Unmanaged.UnmanagedInstance<HealthCheck> healthCheckInstance = unmanagedHealthCheck.newInstance(); HealthCheck healthCheck = healthCheckInstance.produce().inject().postConstruct().get(); healthChecks.add(healthCheck); healthCheckInstances.add(healthCheckInstance); monitor.registerHealthBean(healthCheck); log.info(">> Added health bean impl " + healthCheck); } // we don't need the references anymore delegates.clear(); } catch (Exception e) { throw new RuntimeException("Failed to register health bean", e); } }
void registerMetrics(@Observes AfterDeploymentValidation adv, BeanManager manager) { // Produce and register custom metrics MetricRegistry registry = getReference(manager, MetricRegistry.class); MetricName name = getReference(manager, MetricName.class); for (Map.Entry<Bean<?>, AnnotatedMember<?>> bean : metrics.entrySet()) { if (// skip non @Default beans !bean.getKey().getQualifiers().contains(DEFAULT) // skip producer methods with injection point metadata || hasInjectionPointMetadata(bean.getValue())) { continue; } String metricName = name.of(bean.getValue()); registry.register(metricName, getReference(manager, bean.getValue().getBaseType(), bean.getKey())); } // Let's clear the collected metric producers metrics.clear(); }
public void validate(@Observes AfterDeploymentValidation add) { List<String> deploymentProblems = new ArrayList<>(); config = ConfigProvider.getConfig(); for (InjectionPoint injectionPoint : injectionPoints) { Type type = injectionPoint.getType(); ConfigProperty configProperty = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class); if (type instanceof Class) { // a direct injection of a ConfigProperty // that means a Converter must exist. String key = ConfigInjectionBean.getConfigKey(injectionPoint, configProperty); if (!config.getOptionalValue(key, (Class) type).isPresent()) { deploymentProblems.add("No Config Value exists for " + key); } } } if (!deploymentProblems.isEmpty()) { add.addDeploymentProblem(new DeploymentException("Error while validating Configuration\n" + String.join("\n", deploymentProblems))); } }
private boolean addRouteToContext(Bean<?> routeBean, Bean<?> contextBean, BeanManager manager, AfterDeploymentValidation adv) { try { CamelContext context = getReference(manager, CamelContext.class, contextBean); try { Object route = getReference(manager, Object.class, routeBean); if (route instanceof RoutesBuilder) { context.addRoutes((RoutesBuilder) route); } else if (route instanceof RouteContainer) { context.addRouteDefinitions(((RouteContainer) route).getRoutes()); } else { throw new IllegalArgumentException( "Invalid routes type [" + routeBean.getBeanClass().getName() + "], " + "must be either of type RoutesBuilder or RouteContainer!"); } return true; } catch (Exception cause) { adv.addDeploymentProblem( new InjectionException( "Error adding routes of type [" + routeBean.getBeanClass().getName() + "] " + "to Camel context [" + context.getName() + "]", cause)); } } catch (Exception exception) { adv.addDeploymentProblem(exception); } return false; }
private boolean addRouteToContext(Bean<?> routeBean, Bean<?> contextBean, BeanManager manager, AfterDeploymentValidation adv) { try { CamelContext context = getReference(manager, CamelContext.class, contextBean); try { Object route = getReference(manager, Object.class, routeBean); if (route instanceof RoutesBuilder) context.addRoutes((RoutesBuilder) route); else if (route instanceof RouteContainer) context.addRouteDefinitions(((RouteContainer) route).getRoutes()); else throw new IllegalArgumentException( "Invalid routes type [" + routeBean.getBeanClass().getName() + "], " + "must be either of type RoutesBuilder or RouteContainer!"); return true; } catch (Exception cause) { adv.addDeploymentProblem( new DeploymentException("Error adding routes of type [" + routeBean.getBeanClass().getName() + "] " + "to Camel context [" + context.getName() + "]", cause)); } } catch (Exception exception) { adv.addDeploymentProblem(exception); } return false; }
private void configuration(@Observes AfterDeploymentValidation adv, BeanManager manager) { // Fire configuration event manager.fireEvent(configuration); configuration.unmodifiable(); // Produce and register custom metrics MetricRegistry registry = getReference(manager, MetricRegistry.class); MetricName name = getReference(manager, MetricName.class); for (Map.Entry<Bean<?>, AnnotatedMember<?>> bean : metrics.entrySet()) { // TODO: add MetricSet metrics into the metric registry if (bean.getKey().getTypes().contains(MetricSet.class) // skip non @Default beans || !bean.getKey().getQualifiers().contains(DEFAULT) // skip producer methods with injection point || hasInjectionPoints(bean.getValue())) continue; registry.register(name.of(bean.getValue()), (Metric) getReference(manager, bean.getValue().getBaseType(), bean.getKey())); } // Let's clear the collected metric producers metrics.clear(); }
protected void processConfigurationValidation(AfterDeploymentValidation adv) { for (ConfigValidator configValidator : ServiceUtils.loadServiceImplementations(ConfigValidator.class)) { Set<String> violations = configValidator.processValidation(); if (violations == null) { continue; } for (String violation : violations) { adv.addDeploymentProblem(new IllegalStateException(violation)); } } }
/** * Instantiates <em>unmanaged instances</em> of HealthCheckProcedure and * handle manually their CDI creation lifecycle. * Add them to the {@link HealthMonitor}. */ private void afterDeploymentValidation(@Observes final AfterDeploymentValidation avd, BeanManager bm) { for (AnnotatedType delegate : delegates) { try { Unmanaged<HealthCheck> unmanagedHealthCheck = new Unmanaged<HealthCheck>(bm, delegate.getJavaClass()); UnmanagedInstance<HealthCheck> healthCheckInstance = unmanagedHealthCheck.newInstance(); HealthCheck healthCheck = healthCheckInstance.produce().inject().postConstruct().get(); healthChecks.add(healthCheck); healthCheckInstances.add(healthCheckInstance); healthMonitor.addHealthCheck(healthCheck); } catch (Exception e) { throw new RuntimeException("Failed to register health bean", e); } } }
/** * <p>Initializes all beans found and saved in the {@link #collect(ProcessBean) collect} method. This enables eager loading of annotated beans on application (CDI) startup.</p> * * @param event CDI event that is triggered after CDI deployment. When this is triggered, the eager beans are instantiate. * @param beanManager The CDI bean manager that contains and manages all CDI beans. */ public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) { for (Bean<?> bean : eagerBeansList) { // note: toString() is important to instantiate the bean beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString(); } }
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { try { LOGGER.info("Initializing flowable-cdi."); // initialize the process engine ProcessEngine processEngine = lookupProcessEngine(beanManager); // deploy the processes if engine was set up correctly deployProcesses(processEngine); } catch (Exception e) { // interpret engine initialization problems as definition errors event.addDeploymentProblem(e); } }
public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) { for (Bean<?> bean : eagerBeansList) { // note: toString() is important to instantiate the bean // // I found through testing that managed beans will get instantiated without the toString call; however, // @PostConstruct methods in producer beans do not get called without the toString call. I have also // noticed that with the toString call managed beans are instantiated twice. We may need modify this // method to ensure we do not have the two constructor calls. It is not an immediate concern though since // this is being introduced specifically for https://issues.jboss.org/browse/HWKMETRICS-23. beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString(); } }
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { try { logger.info("Initializing activiti-cdi."); // initialize the process engine initializeProcessEngine(beanManager); // deploy the processes if engine was set up correctly deployProcesses(); } catch (Exception e) { // interpret engine initialization problems as definition errors event.addDeploymentProblem(e); } }
public void afterDeploymentValidation(final @Observes AfterDeploymentValidation event, final BeanManager manager) { if (CDI_METHOD.equalsIgnoreCase(START_METHOD)) { //Force execution of Bootstrap bean's @PostConstruct methods first runPostConstruct(manager, startupBootstrapBeans); //Followed by execution of remaining Eager bean's @PostConstruct methods runPostConstruct(manager, startupEagerBeans); } }
/** * Method that must be called after all events are generated and the CDI context is ready to * start processing beans. It registers the global scope service beans. This is done here, * because only now we know that the container is ready to start processing requests. * * @param val The validation event * @param manager The bean manager * @param <T> The type of the bean */ @SuppressWarnings("unchecked") public <T> void finish(@Observes AfterDeploymentValidation val, BeanManager manager) { exportedBeans.entrySet().stream().forEach((e) -> { Bean<T> bean = (Bean<T>) e.getKey(); CreationalContext<T> cc = manager.createCreationalContext(bean); T instance = bean.create(cc); e.setValue(BeanExporter.registerService(context, bean, instance)); }); }
public void finish(@Observes AfterDeploymentValidation event, BeanManager beanManager) { for (Bean<?> bean : theseBeans) { Object obj = beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)); // Since the object returned may be a proxy, force loading of the bean. obj.toString(); } }
void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) { for (Bean<?> bean : startupBeans) { // the call to toString() is a cheat to force the bean to be // initialized manager.getReference(bean, bean.getBeanClass(), manager.createCreationalContext(bean)).toString(); } }
@SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) { for (Bean<?> bean : autoloadBeanList) { if (loaded.contains(bean)) { continue; } // note: toString() is important to instantiate the bean beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString(); loaded.add(bean); } }
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { Set<Bean<?>> beans = beanManager.getBeans(Object.class, new AnnotationLiteral<Startup>() { }); for (Bean<?> bean : beans) { beanManager.getReference(bean, bean.getTypes().iterator().next(), beanManager.createCreationalContext(bean)).toString(); } }
/** * After the bean container has validated the deployment from its point of view, * do some checking from the portlet point of view. Activate the portlet deployment * by passing in a bean manager in order to create the required portlet bean instances. * * @param adv * @param bm * @throws InvalidAnnotationException */ void afterDeploymentValidation(@Observes AfterDeploymentValidation adv, BeanManager bm) throws InvalidAnnotationException { // Done processing the annotations, so put the resulting configuration in an // application scoped bean to pass it to the servlet LOG.trace("Now attempting to get the AnnotatedConfigBean ..."); Set<Bean<?>> beans = bm.getBeans(AnnotatedConfigBean.class); @SuppressWarnings("unchecked") Bean<AnnotatedConfigBean> bean = (Bean<AnnotatedConfigBean>) bm.resolve(beans); if (bean != null) { LOG.trace("Got AnnotatedConfigBean bean: " + bean.getBeanClass().getCanonicalName()); try { CreationalContext<AnnotatedConfigBean> cc = bm.createCreationalContext(bean); acb = (AnnotatedConfigBean) bm.getReference(bean, AnnotatedConfigBean.class, cc); LOG.trace("Got AnnotatedConfigBean instance."); acb.setMethodStore(ams); acb.setSummary(summary); acb.setStateScopedConfig(par.getStateScopedConfig()); acb.setSessionScopedConfig(par.getSessionScopedConfig()); } catch (Exception e) { StringBuilder txt = new StringBuilder(128); txt.append("Exception getting AnnotatedConfigBean bean instance: "); txt.append(e.toString()); LOG.warn(txt.toString()); } } else { LOG.warn("AnnotatedConfigBean bean was null."); } LOG.info("Portlet CDI Extension complete. Config bean: " + acb); }
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { try { logger.info("Initializing activiti-cdi."); // initialize the process engine ProcessEngine processEngine = lookupProcessEngine(beanManager); // deploy the processes if engine was set up correctly deployProcesses(processEngine); } catch (Exception e) { // interpret engine initialization problems as definition errors event.addDeploymentProblem(e); } }
void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager manager) { for (Bean<?> bean : startupBeans) { System.out.println("CDI: Starting "+bean.getName()); // the call to toString() is a cheat to force the bean to be initialized manager.getReference(bean, bean.getBeanClass(), manager.createCreationalContext(bean)).toString(); } }
public void cleanupFinalBeanManagers(final @Observes AfterDeploymentValidation adv) { if (!CDI_1_1_AVAILABLE) { for (final BeanManagerInfo bmi : bmpSingleton.bmInfos.values()) { bmi.finalBm = null; } } }
/** * The event type of the third event fired by the container after it has * validated that there are no deployment problems and before creating * contexts or processing requests. * Initialize all Beans annotated with {@link Startup}. */ <T> void AfterDeploymentValidation(@Observes AfterDeploymentValidation afterDeployment, BeanManager bm) { this.log.info("AfterDeploymentValidation Event was received"); for (Bean<?> bean : this.startupBeans) { Object o = bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean)); o.toString(); // Init bean } }
/** * Eagerly loads the Event Dispatcher. * * @param event AfterBeanDiscovery event. * @param eventDispatcher Event Dispatcher to eagerly load. */ void afterAfterDeploymentValidation(@Observes AfterDeploymentValidation event, WebSocketListenerRegister listenerRegister, WebSocketConfig config) { for(Object listenerCandidate : listenerCandidates) { listenerRegister.registerListener(listenerCandidate); } for(EndpointConfigImpl servletConfig : servletConfigs) { if(servletConfig.getName() != null) { config.registerEndpointConfig(servletConfig); } } }
@SuppressWarnings("UnusedDeclaration") public void buildViewConfig(@Observes AfterDeploymentValidation adv) { if (!isActivated) { return; } //needed to transform the metadata-tree during the bootstrapping process transformMetaDataTree(); this.transformed = true; }
/** * By cleaning the final BeanManager map after the deployment gets validated, premature loading of information from * JNDI is prevented in cases where the container might not be fully setup yet. * * This might happen if the BeanManagerProvider is used in an extension during CDI bootstrap. This should be * generally avoided. Instead, an injected BeanManager should be used in Extensions and propagated using setters. * * In EARs with multiple webapps, each WAR might get a different Extension. This depends on the container used. */ public void cleanupFinalBeanManagers(@Observes AfterDeploymentValidation adv) { for (BeanManagerInfo bmi : bmpSingleton.bmInfos.values()) { bmi.finalBm = null; bmi.booted = true; /*possible issue with >weld< based servers: if #getBeanManager gets called in a custom AfterDeploymentValidation observer >after< this observer, the wrong bean-manager might get stored (not deterministic due to the unspecified order of observers). finally a bean-manager for a single bda will be stored and returned (which isn't the bm exposed via jndi).*/ } }
/** * Verifies all injection points for every handler are valid. * * @param afterDeploymentValidation Lifecycle event * @param bm BeanManager instance */ @SuppressWarnings("UnusedDeclaration") public void verifyInjectionPoints(@Observes final AfterDeploymentValidation afterDeploymentValidation, final BeanManager bm) { if (!isActivated) { return; } for (Map.Entry<Type, Collection<HandlerMethod<? extends Throwable>>> entry : allHandlers.entrySet()) { for (HandlerMethod<? extends Throwable> handler : entry.getValue()) { for (InjectionPoint ip : ((HandlerMethodImpl<? extends Throwable>) handler).getInjectionPoints(bm)) { try { bm.validate(ip); } catch (InjectionException e) { afterDeploymentValidation.addDeploymentProblem(e); } } } } }
/** * We can only initialize our contexts in AfterDeploymentValidation because * getBeans must not be invoked earlier than this phase to reduce randomness * caused by Beans no being fully registered yet. */ public void initializeDeltaSpikeContexts(@Observes AfterDeploymentValidation adv, BeanManager beanManager) { if (!isActivated) { return; } WindowBeanHolder windowBeanHolder = BeanProvider.getContextualReference(beanManager, WindowBeanHolder.class, false); WindowIdHolder windowIdHolder = BeanProvider.getContextualReference(beanManager, WindowIdHolder.class, false); windowContext.init(windowBeanHolder, windowIdHolder); ConversationBeanHolder conversationBeanHolder = BeanProvider.getContextualReference(beanManager, ConversationBeanHolder.class, false); conversationContext.init(conversationBeanHolder); ViewAccessBeanHolder viewAccessBeanHolder = BeanProvider.getContextualReference(beanManager, ViewAccessBeanHolder.class, false); ViewAccessBeanAccessHistory viewAccessBeanAccessHistory = BeanProvider.getContextualReference(beanManager, ViewAccessBeanAccessHistory.class, false); ViewAccessViewHistory viewAccessViewHistory = BeanProvider.getContextualReference(beanManager, ViewAccessViewHistory.class, false); viewAccessScopedContext.init(viewAccessBeanHolder, viewAccessBeanAccessHistory, viewAccessViewHistory); }
void afterDeploymentValidation(@Observes AfterDeploymentValidation adv) { logger.info("finished the scanning process"); afterDeploymentValidation++; }
public void afterDeployment(@Observes AfterDeploymentValidation afterDeploymentValidation) { REGISTRY.process(discoveredTypes); }
void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { this.beanManager = beanManager; }
public void registerConsumersAfterDeploymentValidation(@Observes AfterDeploymentValidation afterDeploymentValidation, BeanManager beanManager) { if (vertx != null) { registerConsumers(vertx, BeanManagerProxy.unwrap(beanManager).event()); } asyncReferenceQualifiers.clear(); }
public void afterDeploymentValidation(@Observes AfterDeploymentValidation event, BeanManager beanManager) { }
void logLifecycleEvent(@Observes AfterDeploymentValidation event) { LOGGER.info("AfterDeploymentValidation"); }
public void startWebTier(@Observes AfterDeploymentValidation adv) { StartWebServer startWebServer = CDI.current().select(StartWebServer.class).get(); startWebServer.start(); }
public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) { for (Bean<?> bean : eagerBeansList) { beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString(); } }
private void end(@Observes final AfterDeploymentValidation ignored , final BeanManager manager) { final Bean<?> bean = manager.resolve(manager.getBeans(Marker.class)); assertNotNull(manager.getReference(bean, Marker.class, manager.createCreationalContext(bean))); CALLED.set(true); }