/** * When the deployment is loaded register for recovery * * @param init a javax.servlet.ServletContext */ void enableRecovery(@Observes @Initialized(ApplicationScoped.class) Object init) { assert lraRecoveryModule == null; if (LRALogger.logger.isDebugEnabled()) LRALogger.logger.debugf("LRAServicve.enableRecovery%n"); lraRecoveryModule = new LRARecoveryModule(this); RecoveryManager.manager().addModule(lraRecoveryModule); Implementations.install(); lraRecoveryModule.getRecoveringLRAs(recoveringLRAs); for (Transaction transaction : recoveringLRAs.values()) transaction.getRecoveryCoordinatorUrls(participants); }
@Override public ScopeMetadata resolveScopeMetadata(final BeanDefinition definition) { if (definition instanceof AnnotatedBeanDefinition) { final AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) definition; final ScopeMetadata metadata = new ScopeMetadata(); final Set<String> annotationTypes = beanDefinition.getMetadata().getAnnotationTypes(); if (annotationTypes.contains(RequestScoped.class .getName())) { metadata.setScopeName("request"); metadata.setScopedProxyMode(ScopedProxyMode.TARGET_CLASS); } else if (annotationTypes .contains(ApplicationScoped.class.getName())) { metadata.setScopeName("singleton"); } else { return super.resolveScopeMetadata(definition); } return metadata; } else { return super.resolveScopeMetadata(definition); } }
private final void stopWatching(@Observes @BeforeDestroyed(ApplicationScoped.class) @Priority(LIBRARY_BEFORE) final Object event) throws Exception { final Closeable watch = this.watch; if (watch != null) { KubernetesClientException closeException = this.closeException; try { watch.close(); } catch (final Exception everything) { if (closeException != null) { closeException.addSuppressed(everything); throw closeException; } else { throw everything; } } if (closeException != null) { throw closeException; } } }
public void onTrigger(@Observes @Initialized(ApplicationScoped.class) Object test) { mes.submit(new Runnable() { @Override public void run() { try { while (true) { eventBus.fireAsync(new TickTock("tick-" + gen.nextInt(10), "tock-" + gen.nextInt(10))); System.out.println("Fired CDI event from thread " + Thread.currentThread().getName()); Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); } } }); System.out.println("Scheduler initialized"); }
void applyBeforeFeatureConfig(Class testClass) { CdiContainer container = CdiContainerLoader.getCdiContainer(); if (!isContainerStarted()) { container.boot(CdiTestSuiteRunner.getTestContainerConfig()); containerStarted = true; bootExternalContainers(testClass); } List<Class<? extends Annotation>> restrictedScopes = new ArrayList<Class<? extends Annotation>>(); //controlled by the container and not supported by weld: restrictedScopes.add(ApplicationScoped.class); restrictedScopes.add(Singleton.class); if (this.parent == null && this.testControl.getClass().equals(TestControlLiteral.class)) { //skip scope-handling if @TestControl isn't used explicitly on the test-class -> TODO re-visit it restrictedScopes.add(RequestScoped.class); restrictedScopes.add(SessionScoped.class); } this.previousProjectStage = ProjectStageProducer.getInstance().getProjectStage(); ProjectStageProducer.setProjectStage(this.projectStage); startScopes(container, testClass, null, restrictedScopes.toArray(new Class[restrictedScopes.size()])); }
public void onStartUp( @Observes @Initialized(ApplicationScoped.class) Object init, @DevMode boolean isDevMode, @BackEndProviders Set<BackendID> availableProviders) throws MTException { LOG.info("==================================="); LOG.info("==================================="); LOG.info("=== Machine Translation Service ==="); LOG.info("==================================="); LOG.info("==================================="); LOG.info("Build info: version-" + configurationService.getVersion() + " date-" + configurationService.getBuildDate()); if (isDevMode) { LOG.warn("THIS IS A DEV MODE BUILD. DO NOT USE IT FOR PRODUCTION"); } LOG.info("Available backend providers: {}", availableProviders); verifyCredentials(); }
@Produces @ApplicationScoped public EmbeddedCacheManager defaultClusteredCacheManager() { GlobalConfiguration g = new GlobalConfigurationBuilder() .clusteredDefault() .transport() .clusterName(MACHINE_TRANSLATIONS_CLUSTER) .globalJmxStatistics() .allowDuplicateDomains(true) .build(); Configuration cfg = new ConfigurationBuilder() .clustering() .cacheMode(CacheMode.DIST_ASYNC) .eviction() .strategy(EvictionStrategy.LRU) .type(EvictionType.COUNT).size(150) .transaction() .transactionMode(TransactionMode.TRANSACTIONAL) .lockingMode(LockingMode.PESSIMISTIC) .build(); return new DefaultCacheManager(g, cfg); }
@Produces @ApplicationScoped public JsonDataProvider produce(BeanManager beanManager) { ProbeExtension extension = beanManager.getExtension(ProbeExtension.class); if (extension == null) { throw new IllegalStateException("ProbeExtension not available"); } try { // Unfortunately, getJsonDataProvider() is package-private Method getProviderMethod = SecurityActions.getDeclaredMethod(ProbeExtension.class, "getJsonDataProvider"); if (getProviderMethod == null) { throw new IllegalStateException("ProbeExtension.getJsonDataProvider() method not found or inaccessible"); } SecurityActions.ensureAccessible(getProviderMethod); return (JsonDataProvider) getProviderMethod.invoke(extension); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException("Unable to get JsonDataProvider", e); } }
void processClaimValueInjections(@Observes ProcessInjectionPoint pip) { log.debugf("pipRaw: %s", pip.getInjectionPoint()); InjectionPoint ip = pip.getInjectionPoint(); if (ip.getAnnotated().isAnnotationPresent(Claim.class) && ip.getType() instanceof Class) { Class rawClass = (Class) ip.getType(); if (Modifier.isFinal(rawClass.getModifiers())) { Claim claim = ip.getAnnotated().getAnnotation(Claim.class); rawTypes.add(ip.getType()); rawTypeQualifiers.add(claim); log.debugf("+++ Added Claim raw type: %s", ip.getType()); Class declaringClass = ip.getMember().getDeclaringClass(); Annotation[] appScoped = declaringClass.getAnnotationsByType(ApplicationScoped.class); Annotation[] sessionScoped = declaringClass.getAnnotationsByType(SessionScoped.class); if ((appScoped != null && appScoped.length > 0) || (sessionScoped != null && sessionScoped.length > 0)) { String err = String.format("A raw type cannot be injected into application/session scope: IP=%s", ip); pip.addDefinitionError(new DeploymentException(err)); } } } }
@Override public void destroy() { if (isDestroyed()) { return; } isDestroyed = true; Destroyable.Util.tryDestroyAll(serviceById.values(), ApplicationScoped.class); Destroyable.Util.tryDestroyAll(dbHookers, ApplicationScoped.class); serviceById.clear(); serviceByClassField.clear(); fieldTypeMap.clear(); serviceByClass.clear(); updatePolicyByClassField.clear(); updatePolicyByClass.clear(); managedFieldByClass.clear(); managedFieldByClass2.clear(); setterByClass.clear(); dbHookers.clear(); app = null; }
/** * When the deployment is unloaded unregister for recovery * * @param init a javax.servlet.ServletContext */ void disableRecovery(@Observes @Destroyed(ApplicationScoped.class) Object init) { assert lraRecoveryModule != null; Implementations.uninstall(); RecoveryManager.manager().removeModule(lraRecoveryModule, false); lraRecoveryModule = null; if (LRALogger.logger.isDebugEnabled()) LRALogger.logger.debugf("LRAServicve.disableRecovery%n"); }
@Produces @ApplicationScoped public MetaModule createMetaModule() { MetaModuleConfig metaConfig = new MetaModuleConfig(); metaConfig.addMetaProvider(new ResourceMetaProvider()); MetaModule metaModule = MetaModule.createServerModule(metaConfig); return metaModule; }
@Produces @ApplicationScoped public Module createRepositoryModule() { SimpleModule module = new SimpleModule("mock"); module.addRepository(new ScheduleRepositoryImpl()); module.addRepository(new ProjectRepository()); module.addRepository(new TaskRepository()); module.addRepository(new ProjectToTaskRepository()); module.addRepository(new ScheduleToTaskRepository()); module.addRepository(new TaskSubtypeRepository()); module.addRepository(new TaskToProjectRepository()); module.addRepository(new TaskToScheduleRepo()); return module; }
static Bean<?> createIdSupplierBean() { return MockBean.<IdSupplier>builder() .types(IdSupplier.class) .scope(ApplicationScoped.class) .create(new CreateFunction<IdSupplier>() { @Override public IdSupplier create(CreationalContext<IdSupplier> creationalContext) { return new IdSupplier(UUID.randomUUID().toString()); } }).build(); }
static Bean<?> createIdSupplierBean() { return MockBean.<IdSupplier> builder() .types(IdSupplier.class) .scope(ApplicationScoped.class) .create(new CreateFunction<IdSupplier>() { @Override public IdSupplier create(CreationalContext<IdSupplier> creationalContext) { return new IdSupplier(UUID.randomUUID().toString()); } }).build(); }
/** * Activate and deactivate contexts for the given normal scopes for each test method execution. * <p> * {@link ApplicationScoped} is ignored as it is always active. * </p> * * @param normalScopes * @return self */ @SafeVarargs public final T activate(Class<? extends Annotation>... normalScopes) { for (Class<? extends Annotation> scope : normalScopes) { if (ApplicationScoped.class.equals(scope)) { continue; } if (!scope.isAnnotationPresent(NormalScope.class)) { throw new IllegalArgumentException("Only annotations annotated with @NormalScope are supported!"); } this.scopesToActivate.add(scope); } return self(); }
public void initVertx(@Observes @Initialized(ApplicationScoped.class) Object obj) { System.setProperty("vertx.disableDnsResolver", "true"); this.vertx = Vertx.vertx(); this.vertx.eventBus().registerDefaultCodec(ChatMessage.class, new ChatMessageCodec()); this.vertx.eventBus().registerDefaultCodec(PersonName.class, new PersonNameCodec()); this.vertx.eventBus().registerDefaultCodec(String[].class, new StringArrayCodec()); allDiscoveredVerticles.forEach(v -> { System.out.println("Found verticle "+v); vertx.deployVerticle(v); }); }
@Produces @RedisInstance @ApplicationScoped public RedisClient createRedisClient() { RedisOptions config = new RedisOptions().setHost("192.168.2.108"); //RedisOptions config = new RedisOptions().setHost("192.168.56.2"); return RedisClient.create(vertx, config); }
@Produces @ApplicationScoped public IVRouterService produceWebTarget() { return new ResteasyClientBuilder() .connectionPoolSize(100) .maxPooledPerRoute(20) .asyncExecutor(executor) .build() .target(CONFIG.getIvRouterBaseUrl()) .queryParam(IVRouterConfig.FORMAT, IVRouterConfig.REQUEST_FORMAT) .proxy(IVRouterService.class); }
@Deployment public static WebArchive createDeployment() { String url = SimpleGetApi.class.getName() + "/mp-rest/url=http://localhost:8080"; String url2 = MyAppScopedApi.class.getName() + "/mp-rest/url=http://localhost:8080"; String scope = SimpleGetApi.class.getName() + "/mp-rest/scope=" + ApplicationScoped.class.getName(); JavaArchive jar = ShrinkWrap.create(JavaArchive.class) .addClasses(SimpleGetApi.class, MyAppScopedApi.class) .addAsManifestResource(new StringAsset(url + "\n" + scope + "\n"+ url2), "microprofile-config.properties") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); return ShrinkWrap.create(WebArchive.class) .addAsLibrary(jar) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); }
public void addRegistryBean(@Observes AfterBeanDiscovery afterBeanDiscovery) { afterBeanDiscovery.addBean() .types(ReactorObserverRegistry.class) .produceWith((Function<Instance<Object>, Object>) f -> REGISTRY) .scope(ApplicationScoped.class); eventTypes.forEach(ip -> afterBeanDiscovery.addBean() .types(ip.getType()) .scope(Dependent.class) .produceWith((Function<Instance<Object>, Object>) inst -> { ParameterizedType type = (ParameterizedType) ip.getType(); Class<?> s = (Class<?>) type.getActualTypeArguments()[0]; Class<?> r = (Class<?>) type.getActualTypeArguments()[1]; return new ReactorEventImpl<>(s,r,ip.getQualifiers(),REGISTRY); })); }
@Produces @ApplicationScoped CamelContext createAndStartContext() throws Exception { DefaultCamelContext context = new DefaultCamelContext(); context.setName("camel-producer-method"); context.start(); return context; }
@ApplicationScoped @Produces public MongoDatabase getMongoDB() { MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray()); CodecRegistry codecRegistry = CodecRegistries.fromRegistries( CodecRegistries.fromProviders(new OtusCodecProvider()), MongoClient.getDefaultCodecRegistry()); MongoClientOptions options = MongoClientOptions.builder().codecRegistry(codecRegistry).build(); ServerAddress serverAddress = new ServerAddress(host, port); return new MongoClient(serverAddress, Arrays.asList(credential), options).getDatabase(database); }
@Produces @ApplicationScoped public Validator createValidator() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); return validator; }
@Produces @ApplicationScoped public MailerConfig getMailConfig() throws IOException { Properties props = new Properties(); props.load(this.getClass().getResourceAsStream("/mail.properties")); MailerConfig config = new MailerConfigImpl(props); assert(props.size() > 0); return config; }
@Lock(LockType.READ) @Produces @ApplicationScoped public JestClient produce() { LOGGER.log(Level.INFO, "Producing ElasticSearch rest client"); return client; }
@Produces @ApplicationScoped @Named("jpa") public JpaComponent jpaComponent(PlatformTransactionManager transactionManager, EntityManager entityManager) { JpaComponent component = new JpaComponent(); component.setTransactionManager(transactionManager); component.setEntityManagerFactory(entityManager.getEntityManagerFactory()); return component; }
public void addABean(@Observes AfterBeanDiscovery event) { // get an instance of BeanConfigurator event.addBean() // set the desired data .types(Greeter.class) .scope(ApplicationScoped.class) .addQualifier(Default.Literal.INSTANCE) //.addQualifier(Custom.CustomLiteral.INSTANCE); //finally, add a callback to tell CDI how to instantiate this bean .produceWith(obj -> new Greeter()); }
@Bean @ConditionalOnProperty(value = "jsf.scope-configurer.cdi.enabled", havingValue = "true", matchIfMissing = true) public static BeanFactoryPostProcessor cdiScopeAnnotationsConfigurer(Environment environment) { CustomScopeAnnotationConfigurer scopeAnnotationConfigurer = new CustomScopeAnnotationConfigurer(); scopeAnnotationConfigurer.setOrder(environment.getProperty("jsf.scope-configurer.cdi.order", Integer.class, Ordered.LOWEST_PRECEDENCE)); scopeAnnotationConfigurer.addMapping(RequestScoped.class, WebApplicationContext.SCOPE_REQUEST); scopeAnnotationConfigurer.addMapping(SessionScoped.class, WebApplicationContext.SCOPE_SESSION); scopeAnnotationConfigurer.addMapping(ConversationScoped.class, WebApplicationContext.SCOPE_SESSION); scopeAnnotationConfigurer.addMapping(ApplicationScoped.class, WebApplicationContext.SCOPE_APPLICATION); return scopeAnnotationConfigurer; }
public void onInitialized(@Observes @Initialized(ApplicationScoped.class) Object init) { beanManager.getBeans(Object.class, new AnnotationLiteral<Startup>() { }).forEach(bean -> { final CreationalContext<?> context = beanManager.createCreationalContext(bean); LOGGER.info("Force initializing {}...", beanManager.getReference(bean, bean.getBeanClass(), context).toString()); }); initialize(); }
public void registerBeansAfterBeanDiscovery(@Observes AfterBeanDiscovery event) { if (vertx == null) { // Do no register beans - no Vertx instance available during bootstrap return; } // Allow to inject Vertx used to deploy the WeldVerticle event.addBean().types(getBeanTypes(vertx.getClass(), Vertx.class)).addQualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE) .scope(ApplicationScoped.class).createWith(c -> vertx); // Allow to inject Context of the WeldVerticle event.addBean().types(getBeanTypes(context.getClass(), Context.class)).addQualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE) .scope(ApplicationScoped.class).createWith(c -> context); }
void start( @Observes @Initialized(ApplicationScoped.class) Object o ) { try { if( !scheduler.isStarted() ) { scheduler.start(); } } catch( SchedulerException ex ) { LOG.log( Level.SEVERE, "Failed to start scheduler", ex ); } }
@SuppressWarnings("unused") void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception { List<SimpleKey> configuredGroups = this.configView.simpleSubkeys(ROOT); for (SimpleKey groupName : configuredGroups) { Set<Bean<?>> groups = beanManager.getBeans(SocketBindingGroup.class, AnyLiteral.INSTANCE); AtomicBoolean producerRequired = new AtomicBoolean(false); if (groups .stream() .noneMatch(e -> e.getQualifiers() .stream() .anyMatch(anno -> anno instanceof Named && ((Named) anno).value().equals(groupName)))) { SocketBindingGroup group = new SocketBindingGroup(groupName.name(), null, "0"); applyConfiguration(group); if (producerRequired.get()) { CommonBean<SocketBindingGroup> interfaceBean = CommonBeanBuilder.newBuilder(SocketBindingGroup.class) .beanClass(SocketBindingGroupExtension.class) .scope(ApplicationScoped.class) .addQualifier(AnyLiteral.INSTANCE) .addQualifier(new NamedLiteral(group.name())) .createSupplier(() -> group) .addType(SocketBindingGroup.class) .addType(Object.class) .build(); abd.addBean(interfaceBean); } } } }
@SuppressWarnings("unused") void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception { List<SimpleKey> configuredInterfaces = this.configView.simpleSubkeys(ROOT); for (SimpleKey interfaceName : configuredInterfaces) { Set<Bean<?>> ifaces = beanManager.getBeans(Interface.class, AnyLiteral.INSTANCE); AtomicBoolean producerRequired = new AtomicBoolean(false); if (ifaces .stream() .noneMatch(e -> e.getQualifiers() .stream() .anyMatch(anno -> anno instanceof Named && ((Named) anno).value().equals(interfaceName + "-interface")))) { Interface iface = new Interface(interfaceName.name(), "0.0.0.0"); applyConfiguration(iface); if (producerRequired.get()) { CommonBean<Interface> interfaceBean = CommonBeanBuilder.newBuilder(Interface.class) .beanClass(InterfaceExtension.class) .scope(ApplicationScoped.class) .addQualifier(AnyLiteral.INSTANCE) .addQualifier(new NamedLiteral(interfaceName.name() + "-interface")) .createSupplier(() -> iface) .addType(Interface.class) .addType(Object.class) .build(); abd.addBean(interfaceBean); } } } }
@Produces @ApplicationScoped @Named("camelContext") CamelContext createDefaultContext() throws Exception { CamelContext camelContext = new DefaultCamelContext(); return camelContext; }
@Produces @ApplicationScoped @Named("myContext") CamelContext createMyCamelContext() throws Exception { CamelContext camelContext = new DefaultCamelContext(); return camelContext; }
@Produces @ApplicationScoped public ServletContainer createServletContainer() { final ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.register(HelloController.class); resourceConfig.property("javax.mvc.engine.ViewEngine.viewFolder", "META-INF/views/"); return new ServletContainer(resourceConfig); }
public void init(@Observes @Initialized(ApplicationScoped.class) Object doesntMatter) { this.cachingProvider = Caching.getCachingProvider(); this.cacheManager = cachingProvider.getCacheManager(); Configuration<String, String> configuration = getConfiguration(); this.store = this.cacheManager.getCache(CONFIGURATION, String.class, String.class); if (this.store == null) { this.store = this.cacheManager.createCache(CONFIGURATION, configuration); } for (Map<String, String> initial : initialValues) { this.store.putAll(initial); } }
@ApplicationScoped @Produces public RoleLookup<StarterRole> buildLookup() { // Make a typeSafe version of the roles. List<NamedApplicationRole> roles = new ArrayList<>(); for (StarterRole starterRole : StarterRole.values()) { roles.add(new NamedApplicationRole(starterRole.name())); } return new RoleLookup<>(roles, StarterRole.class); }
@Produces @ApplicationScoped @Named("properties") // "properties" component bean that Camel uses to lookup properties PropertiesComponent properties(PropertiesParser parser) { PropertiesComponent component = new PropertiesComponent(); // Use DeltaSpike as configuration source for Camel CDI component.setPropertiesParser(parser); return component; }