javax.enterprise.context.ApplicationScoped Java Examples

The following examples show how to use javax.enterprise.context.ApplicationScoped. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StreamsRegistryConfiguration.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@Produces
@ApplicationScoped
@Current
public AsyncBiFunctionService<String, Long, Str.Data> waitForDataUpdateService(
    StreamsProperties properties,
    KafkaStreams streams,
    HostInfo storageLocalHost,
    LocalService<AsyncBiFunctionService.WithSerdes<String, Long, Str.Data>> localWaitForDataUpdateService
) {
    return new DistributedAsyncBiFunctionService<>(
        streams,
        storageLocalHost,
        properties.getStorageStoreName(),
        localWaitForDataUpdateService,
        new DefaultGrpcChannelProvider()
    );
}
 
Example #2
Source File: KafkaRegistryConfiguration.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
@Produces
@ApplicationScoped
public CloseableSupplier<Boolean> livenessCheck(
    @RegistryProperties(
            value = {"registry.kafka.common", "registry.kafka.liveness-check"},
            empties = {"ssl.endpoint.identification.algorithm="}
    ) Properties properties
) {
    AdminClient admin = AdminClient.create(properties);
    return new CloseableSupplier<Boolean>() {
        @Override
        public void close() {
            admin.close();
        }

        @Override
        public Boolean get() {
            return (admin.listTopics() != null);
        }
    };
}
 
Example #3
Source File: DefaultConfigTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Produces
@ApplicationScoped
@Named("default-kafka-broker")
public Map<String, Object> createKafkaRuntimeConfig() {
    Map<String, Object> properties = new HashMap<>();

    StreamSupport
            .stream(config.getPropertyNames().spliterator(), false)
            .map(String::toLowerCase)
            .filter(name -> name.startsWith("kafka"))
            .distinct()
            .sorted()
            .forEach(name -> {
                final String key = name.substring("kafka".length() + 1).toLowerCase().replaceAll("[^a-z0-9.]", ".");
                final String value = config.getOptionalValue(name, String.class).orElse("");
                properties.put(key, value);
            });

    return properties;
}
 
Example #4
Source File: CdiBeanProducer.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
@Produces
@ApplicationScoped
@CDIBean.Priority3Executor
public Executor createPriority3Executor(@CDIBean.PriorityContext ThreadContext ctx) {
    int originalPriority = Thread.currentThread().getPriority();
    try {
        Thread.currentThread().setPriority(3);
        Label.set("do-not-propagate-this-label");
        Buffer.set(new StringBuffer("do-not-propagate-this-buffer"));

        return ctx.currentContextExecutor();
    } finally {
        // restore previous values
        Buffer.set(null);
        Label.set(null);
        Thread.currentThread().setPriority(originalPriority);
    }
}
 
Example #5
Source File: VertxProducer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Undeploy verticles backed by contextual instances of {@link ApplicationScoped} beans before the application context is
 * destroyed. Otherwise Vertx may attempt to stop the verticles after the CDI container is shut down.
 * 
 * @param event
 * @param beanManager
 */
void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event,
        BeanManager beanManager, io.vertx.mutiny.core.Vertx mutiny) {
    // Only beans with the AbstractVerticle in the set of bean types are considered - we need a deployment id 
    Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE);
    Context applicationContext = beanManager.getContext(ApplicationScoped.class);
    for (Bean<?> bean : beans) {
        if (ApplicationScoped.class.equals(bean.getScope())) {
            // Only beans with @ApplicationScoped are considered
            Object instance = applicationContext.get(bean);
            if (instance != null) {
                // Only existing instances are considered
                try {
                    AbstractVerticle verticle = (AbstractVerticle) instance;
                    mutiny.undeploy(verticle.deploymentID()).await().indefinitely();
                    LOGGER.debugf("Undeployed verticle: %s", instance.getClass());
                } catch (Exception e) {
                    // In theory, a user can undeploy the verticle manually
                    LOGGER.debugf("Unable to undeploy verticle %s: %s", instance.getClass(), e.toString());
                }
            }
        }
    }
}
 
Example #6
Source File: KafkaRuntimeConfigProducer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Produces
@DefaultBean
@ApplicationScoped
@Named("default-kafka-broker")
public Map<String, Object> createKafkaRuntimeConfig() {
    Map<String, Object> properties = new HashMap<>();
    final Config config = ConfigProvider.getConfig();

    StreamSupport
            .stream(config.getPropertyNames().spliterator(), false)
            .map(String::toLowerCase)
            .filter(name -> name.startsWith(configPrefix))
            .distinct()
            .sorted()
            .forEach(name -> {
                final String key = name.substring(configPrefix.length() + 1).toLowerCase().replaceAll("[^a-z0-9.]", ".");
                final String value = config.getOptionalValue(name, String.class).orElse("");
                properties.put(key, value);
            });

    return properties;
}
 
Example #7
Source File: StartupBuildSteps.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
AnnotationsTransformerBuildItem annotationTransformer(CustomScopeAnnotationsBuildItem customScopes) {
    return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {

        @Override
        public boolean appliesTo(org.jboss.jandex.AnnotationTarget.Kind kind) {
            return kind == org.jboss.jandex.AnnotationTarget.Kind.CLASS;
        }

        @Override
        public void transform(TransformationContext context) {
            if (context.isClass() && !customScopes.isScopeDeclaredOn(context.getTarget().asClass())) {
                // Class with no built-in scope annotation but with @Scheduled method
                if (Annotations.contains(context.getTarget().asClass().classAnnotations(), STARTUP_NAME)) {
                    LOGGER.debugf("Found @Startup on a class %s with no scope annotations - adding @ApplicationScoped",
                            context.getTarget());
                    context.transform().add(ApplicationScoped.class).done();
                }
            }
        }
    });
}
 
Example #8
Source File: BeanDefiningAnnotationStereotypeTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static Consumer<BuildChainBuilder> buildCustomizer() {
    return new Consumer<BuildChainBuilder>() {

        @Override
        public void accept(BuildChainBuilder builder) {
            builder.addBuildStep(new BuildStep() {

                @Override
                public void execute(BuildContext context) {
                    context.produce(new BeanDefiningAnnotationBuildItem(DotName.createSimple(MakeItBean.class.getName()),
                            DotName.createSimple(ApplicationScoped.class.getName())));
                }
            }).produces(BeanDefiningAnnotationBuildItem.class).build();
        }
    };
}
 
Example #9
Source File: H2DatabaseServiceInitializer.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(@Observes @Initialized(ApplicationScoped.class) Object event) throws Exception {
    log.info("Starting H2 ...");
    H2DatabaseService tmp = new H2DatabaseService();
    tmp.start();
    service = tmp;
}
 
Example #10
Source File: ArtemisJmsProducer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
@DefaultBean
public ConnectionFactory connectionFactory() {
    return new ActiveMQJMSConnectionFactory(config.url,
            config.username.orElse(null), config.password.orElse(null));
}
 
Example #11
Source File: StreamsRegistryConfiguration.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
public StreamsProperties streamsProperties(
    @RegistryProperties(
            value = {"registry.streams.common", "registry.streams.topology"},
            empties = {"ssl.endpoint.identification.algorithm="}
    ) Properties properties
) {
    return new StreamsPropertiesImpl(properties);
}
 
Example #12
Source File: ReactiveEngineProvider.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
/**
 * @return the reactive stream engine. It uses {@link ServiceLoader#load(Class)} to find an implementation from the
 *         Classpath.
 * @throws IllegalStateException if no implementations are found.
 */
@Produces
@ApplicationScoped
public ReactiveStreamsEngine getEngine() {
    Iterator<ReactiveStreamsEngine> iterator = ServiceLoader.load(ReactiveStreamsEngine.class).iterator();
    if (iterator.hasNext()) {
        return iterator.next();
    }
    throw new IllegalStateException("No implementation of the "
            + ReactiveStreamsEngine.class.getName() + " found in the Classpath");
}
 
Example #13
Source File: StreamsServiceInitializer.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(@Observes @Initialized(ApplicationScoped.class) Object event) throws Exception {
    Properties properties = new Properties();
    properties.put(
            CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG,
            System.getProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
    );
    properties.put("connections.max.idle.ms", 10000);
    properties.put("request.timeout.ms", 5000);
    try (AdminClient client = AdminClient.create(properties)) {
        ListTopicsResult topics = client.listTopics();
        Set<String> names = topics.names().get();
        log.info("Kafka is running - {} ...", names);
    }
}
 
Example #14
Source File: KafkaRegistryConfiguration.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
public ProducerActions<Long, StorageSnapshot> snapshotProducer(
    @RegistryProperties(
            value = {"registry.kafka.common", "registry.kafka.snapshot-producer"},
            empties = {"ssl.endpoint.identification.algorithm="}
    ) Properties properties
) {
    return new AsyncProducer<>(
        properties,
        Serdes.Long().serializer(),
        new StorageSnapshotSerde()
    );
}
 
Example #15
Source File: KafkaRegistryConfiguration.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
public ProducerActions<Cmmn.UUID, Str.StorageValue> storageProducer(
    @RegistryProperties(
            value = {"registry.kafka.common", "registry.kafka.storage-producer"},
            empties = {"ssl.endpoint.identification.algorithm="}
    ) Properties properties
) {
    return new AsyncProducer<>(
        properties,
        ProtoSerde.parsedWith(Cmmn.UUID.parser()),
        ProtoSerde.parsedWith(Str.StorageValue.parser())
    );
}
 
Example #16
Source File: UndertowBuildStep.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
@Record(STATIC_INIT)
SyntheticBeanBuildItem servletContextBean(
        UndertowDeploymentRecorder recorder) {
    return SyntheticBeanBuildItem.configure(ServletContext.class).scope(ApplicationScoped.class)
            .supplier(recorder.servletContextSupplier()).done();
}
 
Example #17
Source File: AxonConfiguration.java    From cdi with Apache License 2.0 5 votes vote down vote up
/**
 * Produces JPA token store.
 *
 * @return token store.
 */
@Produces
@ApplicationScoped
public TokenStore tokenStore(EntityManagerProvider entityManagerProvider,
        Serializer serializer) {
    return new JpaTokenStore(entityManagerProvider, serializer);
}
 
Example #18
Source File: WorkerPoolRegistry.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public void terminate(
        @Observes(notifyObserver = Reception.IF_EXISTS) @Priority(100) @BeforeDestroyed(ApplicationScoped.class) Object event) {
    if (!workerExecutors.isEmpty()) {
        for (WorkerExecutor executor : workerExecutors.values()) {
            executor.close();
        }
    }
}
 
Example #19
Source File: ProducerBean.java    From microprofile-context-propagation with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
@MPConfigBean.Max5Queue
protected ManagedExecutor createExecutor() {
    // rely on MP Config for defaults of maxAsync=1, cleared=Remaining
    return ManagedExecutor.builder()
            .maxQueued(5)
            .propagated()
            .build();
}
 
Example #20
Source File: AxonConfiguration.java    From cdi with Apache License 2.0 5 votes vote down vote up
/**
 * Produces the entity manager provider.
 *
 * @return entity manager provider.
 */
@Produces
@ApplicationScoped
public EntityManagerProvider entityManagerProvider(
        EntityManager entityManager) {
    return new SimpleEntityManagerProvider(entityManager);
}
 
Example #21
Source File: QuartzScheduler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Need to gracefully shutdown the scheduler making sure that all triggers have been
 * released before datasource shutdown.
 *
 * @param event ignored
 */
void destroy(@BeforeDestroyed(ApplicationScoped.class) Object event) { //
    if (scheduler != null) {
        try {
            scheduler.shutdown(true); // gracefully shutdown
        } catch (SchedulerException e) {
            LOGGER.warnf("Unable to gracefully shutdown the scheduler", e);
        }
    }
}
 
Example #22
Source File: QuarkusWorkerPoolRegistry.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void terminate(
        @Observes(notifyObserver = Reception.IF_EXISTS) @Priority(100) @BeforeDestroyed(ApplicationScoped.class) Object event) {
    if (!workerExecutors.isEmpty()) {
        for (WorkerExecutor executor : workerExecutors.values()) {
            executor.close();
        }
    }
}
 
Example #23
Source File: AlternativePriorityAnnotationTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
@AlternativePriority(1000)
@Alternative
public TheUltimateImpl createUltimateImpl() {
    return new TheUltimateImpl();
}
 
Example #24
Source File: ProducerClientProxyTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
FunctionChild produceSupplier() {
    return new FunctionChild() {

    };
}
 
Example #25
Source File: SameDescriptorDifferentReturnTypeMethodTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
Loop produce() {
    return new Loop() {

        @Override
        public Integer next() {
            return 9;
        }
    };
}
 
Example #26
Source File: AxonConfiguration.java    From cdi with Apache License 2.0 5 votes vote down vote up
/**
 * Produces the entity manager.
 *
 * @return entity manager.
 */
@Produces
@ApplicationScoped
public EntityManager entityManager() {
    try {
        return (EntityManager) new InitialContext().lookup("java:comp/env/accounts/entitymanager");
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Failed to look up entity manager.", ex);
    }

    return null;
}
 
Example #27
Source File: AppConfiguration.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
@Current
public SearchClient searchClient(@RegistryProperties("registry.search-index") Properties properties) {
    return SearchClient.create(properties);
}
 
Example #28
Source File: S3ClientProducer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
public S3AsyncClient asyncClient() {
    asyncClient = asyncConfiguredBuilder.build();
    return asyncClient;
}
 
Example #29
Source File: SnsClientProducer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
public SnsAsyncClient asyncClient() {
    asyncClient = asyncConfiguredBuilder.build();
    return asyncClient;
}
 
Example #30
Source File: ActivitiServices.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Produces
@Named
@ApplicationScoped
public TaskService taskService() {
  return processEngine().getTaskService();
}