javax.enterprise.event.Observes Java Examples

The following examples show how to use javax.enterprise.event.Observes. 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: MetricCdiInjectionExtension.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private void addInterceptorBindings(@Observes BeforeBeanDiscovery bbd, BeanManager manager) {
    SmallRyeMetricsLogging.log.logSmallRyeMetricsVersion(getImplementationVersion().orElse("unknown"));

    String extensionName = MetricCdiInjectionExtension.class.getName();

    // It seems that fraction deployment module cannot be picked up as a CDI bean archive - see also SWARM-1725
    for (Class clazz : new Class[] {
            MetricProducer.class,
            MetricNameFactory.class,
            GaugeRegistrationInterceptor.class,
            MetricRegistries.class,

            MeteredInterceptor.class,
            CountedInterceptor.class,
            ConcurrentGaugeInterceptor.class,
            TimedInterceptor.class,
            SimplyTimedInterceptor.class,
            MetricsRequestHandler.class
    }) {
        bbd.addAnnotatedType(manager.createAnnotatedType(clazz), extensionName + "_" + clazz.getName());
    }
}
 
Example #2
Source File: ProviderExtensionSupport.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
/**
 * Collect the types of all {@linkplain Provider} injection points annotated with {@linkplain Claim}.
 *
 * @param pip - the injection point event information
 */
void processClaimProviderInjections(@Observes ProcessInjectionPoint<?, ? extends Provider> pip) {
    CDILogging.log.pip(pip.getInjectionPoint());
    final InjectionPoint ip = pip.getInjectionPoint();
    if (ip.getAnnotated().isAnnotationPresent(Claim.class)) {
        Claim claim = ip.getAnnotated().getAnnotation(Claim.class);
        if (claim.value().length() == 0 && claim.standard() == Claims.UNKNOWN) {
            pip.addDefinitionError(CDIMessages.msg.claimHasNoNameOrValidStandardEnumSetting(ip));
        }
        boolean usesEnum = claim.standard() != Claims.UNKNOWN;
        final String claimName = usesEnum ? claim.standard().name() : claim.value();
        CDILogging.log.checkingProviderClaim(claimName, ip);
        Type matchType = ip.getType();
        // The T from the Provider<T> injection site
        Type actualType = ((ParameterizedType) matchType).getActualTypeArguments()[0];
        // Don't add Optional or JsonValue as this is handled specially
        if (isOptional(actualType)) {
            // Validate that this is not an Optional<JsonValue>
            Type innerType = ((ParameterizedType) actualType).getActualTypeArguments()[0];
            if (!isJson(innerType)) {
                providerOptionalTypes.add(actualType);
                providerQualifiers.add(claim);
            }
        }
    }
}
 
Example #3
Source File: RedirectScopeManager.java    From krazo with Apache License 2.0 6 votes vote down vote up
/**
 * Upon detecting a redirect, either add cookie to response or re-write URL of new
 * location to co-relate next request.
 *
 * @param event the event.
 */
public void controllerRedirectEvent(@Observes ControllerRedirectEvent event) {
    if (request.getAttribute(SCOPE_ID) != null) {
        if (usingCookies()) {
            Cookie cookie = new Cookie(COOKIE_NAME, request.getAttribute(SCOPE_ID).toString());
            cookie.setPath(request.getContextPath());
            cookie.setMaxAge(600);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
        } else {
            final ContainerResponseContext crc = ((ControllerRedirectEventImpl) event).getContainerResponseContext();
            final UriBuilder builder = UriBuilder.fromUri(crc.getStringHeaders().getFirst(HttpHeaders.LOCATION));
            builder.queryParam(SCOPE_ID, request.getAttribute(SCOPE_ID).toString());
            crc.getHeaders().putSingle(HttpHeaders.LOCATION, builder.build());
        }
    }
}
 
Example #4
Source File: VertxGraphqlResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void setupRouter(@Observes Router router) {
    String schema = "type Query{hello: String}";

    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
            .build();

    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

    GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();

    router.route("/graphql").handler(ApolloWSHandler.create(graphQL));
    router.route("/graphql").handler(GraphQLHandler.create(graphQL));
}
 
Example #5
Source File: TransactionBeanWithEvents.java    From quarkus with Apache License 2.0 6 votes vote down vote up
void transactionScopePreDestroy(@Observes @BeforeDestroyed(TransactionScoped.class) final Object event,
        final BeanManager beanManager) throws SystemException {
    Transaction tx = tm.getTransaction();
    if (tx == null) {
        log.error("@BeforeDestroyed expects an active transaction");
        throw new IllegalStateException("@BeforeDestroyed expects an active transaction");
    }
    Context ctx;
    try {
        ctx = beanManager.getContext(TransactionScoped.class);
    } catch (Exception e) {
        log.error("Context on @Initialized is not available");
        throw e;
    }
    if (!ctx.isActive()) {
        log.error("Context on @BeforeDestroyed has to be active");
        throw new IllegalStateException("Context on @BeforeDestroyed has to be active");
    }
    if (!(event instanceof Transaction)) {
        log.error("@Intialized scope expects event payload being the " + Transaction.class.getName());
        throw new IllegalStateException("@Intialized scope expects event payload being the " + Transaction.class.getName());
    }

    beforeDestroyedCount++;
}
 
Example #6
Source File: JPADatabaseManager.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
void onStart(@Observes StartupEvent event) {

        log.info("JPA storage is starting...");

        dsUrl.ifPresent(x -> log.debug("Datasource URL: " + x));
        dsUrl.orElseThrow(() -> new IllegalStateException("Datasource URL missing!"));

        if (!dsUser.isPresent()) {
            log.warn("Datasource username is missing.");
        }
        if (!dsPassword.isPresent()) {
            log.warn("Datasource password is missing.");
        }
    }
 
Example #7
Source File: AxonCdiExtension.java    From cdi with Apache License 2.0 5 votes vote down vote up
<T> void processSagaStoreProducer(
        @Observes final ProcessProducer<T, SagaStore> processProducer) {
    logger.debug("Producer for saga store found: {}.", processProducer.getProducer());

    String sagaStoreName = CdiUtilities.extractBeanName(processProducer.getAnnotatedMember());

    this.sagaStoreProducerMap.put(sagaStoreName, processProducer.getProducer());
}
 
Example #8
Source File: SockJsExample.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
public void init(@Observes Router router) {
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
    sockJSHandler.bridge(new BridgeOptions(new JsonObject())
            .addOutboundPermitted(new PermittedOptions().setAddress("ticks")));
    router.route("/eventbus/*").handler(sockJSHandler);

    AtomicInteger counter = new AtomicInteger();
    vertx.setPeriodic(1000,
        ignored -> vertx.eventBus().publish("ticks", counter.getAndIncrement()));
}
 
Example #9
Source File: AxonCdiExtension.java    From cdi with Apache License 2.0 5 votes vote down vote up
<T> void processSagaConfigurationProducer(
        @Observes final ProcessProducer<T, SagaConfiguration<?>> processProducer) {
    logger.debug("Producer for saga configuration found: {}.",
            processProducer.getProducer());

    String sagaConfigurationName = CdiUtilities.extractBeanName(processProducer.getAnnotatedMember());

    sagaConfigurationProducerMap.put(sagaConfigurationName, processProducer.getProducer());
}
 
Example #10
Source File: H2DatabaseServiceInitializer.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void afterAll(@Observes @Destroyed(ApplicationScoped.class) Object event) {
    log.info("Stopping H2 ...");
    if (service != null) {
        service.stop();
    }
}
 
Example #11
Source File: VerticleClassnameHotReloadTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void init(@Observes Router router) throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    vertx.deployVerticle(MyVerticle.class.getName(),
            ar -> latch.countDown());
    router.get("/").handler(rc -> vertx.eventBus().<String> request("address", "",
            ar -> rc.response().end(ar.result().body())));
    latch.await();
}
 
Example #12
Source File: ShutdownTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void setup(@Observes Router router) {
    router.get("/shutdown").handler(new Handler<RoutingContext>() {
        @Override
        public void handle(RoutingContext routingContext) {
            routingContext.vertx().setTimer(HANDLER_WAIT_TIME, new Handler<Long>() {
                @Override
                public void handle(Long aLong) {
                    routingContext.response().end();
                }
            });
        }
    });
}
 
Example #13
Source File: ActivitiExtension.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void beforeShutdown(@Observes BeforeShutdown event) {
  if (processEngineLookup != null) {
    processEngineLookup.ungetProcessEngine();
    processEngineLookup = null;
  }
  logger.info("Shutting down activiti-cdi");
}
 
Example #14
Source File: TestEventListener.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void onStartActivityService1(@Observes @StartActivity("service1") BusinessProcessEvent businessProcessEvent) {    
	Integer loopCounter = (Integer) businessProcessEvent.getVariableScope().getVariable("loopCounter");
	if (loopCounter != null) {
		startActivityService1WithLoopCounter += 1;
	} else {
		startActivityService1WithoutLoopCounter += 1;
	}
}
 
Example #15
Source File: SslServerWithJksTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void register(@Observes Router router) {
    router.get("/ssl").handler(rc -> {
        Assertions.assertThat(rc.request().connection().isSsl()).isTrue();
        Assertions.assertThat(rc.request().isSSL()).isTrue();
        Assertions.assertThat(rc.request().connection().sslSession()).isNotNull();
        rc.response().end("ssl");
    });
}
 
Example #16
Source File: KafkaServiceInitializer.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 #17
Source File: LibraryResource.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Transactional
void onStart(@Observes StartupEvent ev) throws InterruptedException {
    // only reindex if we imported some content
    if (Book.count() > 0) {
        Search.session(em)
                .massIndexer()
                .startAndWait();
    }
}
 
Example #18
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 #19
Source File: RouterEventTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void observeRouter(@Observes Router router) {
    counter++;
    router.get("/boom").handler(ctx -> ctx.response().setStatusCode(200).end("ok"));
    Route post = router.post("/post");
    post.consumes("text/plain");
    post.handler(BodyHandler.create());
    post.handler(ctx -> ctx.response().end(Integer.toString(counter)));
}
 
Example #20
Source File: VertxInjectionTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void init(@Observes StartupEvent ev) {
    Assertions.assertNotNull(vertx);
    Assertions.assertNotNull(axle);
    Assertions.assertNotNull(rx);
    Assertions.assertNotNull(mutiny);
    ok = true;
}
 
Example #21
Source File: DisableHttpPortTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void register(@Observes Router router) {
    router.get("/ssl").handler(rc -> {
        Assertions.assertThat(rc.request().connection().isSsl()).isTrue();
        Assertions.assertThat(rc.request().isSSL()).isTrue();
        Assertions.assertThat(rc.request().connection().sslSession()).isNotNull();
        rc.response().end("ssl");
    });
}
 
Example #22
Source File: JPAConfig.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Need to shutdown all instances of Hibernate ORM before the actual destroy event,
 * as it might need to use the datasources during shutdown.
 *
 * @param event ignored
 */
void destroy(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event) {
    for (LazyPersistenceUnit factory : persistenceUnits.values()) {
        try {
            factory.close();
        } catch (Exception e) {
            LOGGER.warn("Unable to close the EntityManagerFactory: " + factory, e);
        }
    }
}
 
Example #23
Source File: AcademicFacadeImpl.java    From Java-EE-8-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@Statistical
public void requestTestReview (@Observes TestRevisionTO testRevisionTO) {
//public void requestTestReview (@ObservesAsync TestRevisionTO testRevisionTO) {  // the observer must be qualified as @ObservesAsync. It is new in JEE8...  
	System.out.println("matricula " + testRevisionTO.getEnrollment());
	LocalDateTime dateTime = scheduleTestReview (testRevisionTO);
	sendEmail (testRevisionTO, dateTime); // send an email with the schedule date for the test review:
}
 
Example #24
Source File: BeanRegisteringRoute.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void init(@Observes Router router) {
    router.route("/my-path").handler(rc -> rc.response().end("OK"));

    //ping only works on HTTP/2
    router.get("/ping").handler(rc -> {
        rc.request().connection().ping(Buffer.buffer(PING_DATA), new Handler<AsyncResult<Buffer>>() {
            @Override
            public void handle(AsyncResult<Buffer> event) {
                rc.response().end(event.result());
            }
        });
    });
}
 
Example #25
Source File: ActivitiExtension.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example #26
Source File: AxonCdiExtension.java    From cdi with Apache License 2.0 5 votes vote down vote up
<T> void processQueryBusProducer(
        @Observes final ProcessProducer<T, QueryBus> processProducer) {
    // TODO Handle multiple producer definitions.

    logger.debug("Producer for query bus found: {}.",
            processProducer.getProducer());

    this.queryBusProducer = processProducer.getProducer();
}
 
Example #27
Source File: SparkOperatorEntrypoint.java    From spark-operator with Apache License 2.0 5 votes vote down vote up
public void onStart(@Observes StartupEvent event) {
    log.info("onStart..");
    try {
        exposeMetrics();
    } catch (Exception e) {
        // ignore, not critical (service may have been already exposed)
        log.warn("Unable to expose the metrics, cause: {}", e.getMessage());
    }
}
 
Example #28
Source File: PathHandler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void setup(@Observes Router router) {
    router.route().handler(new Handler<RoutingContext>() {
        @Override
        public void handle(RoutingContext event) {
            QuarkusHttpUser user = (QuarkusHttpUser) event.user();
            StringBuilder ret = new StringBuilder();
            if (user != null) {
                ret.append(user.getSecurityIdentity().getPrincipal().getName());
            }
            ret.append(":");
            ret.append(event.normalisedPath());
            event.response().end(ret.toString());
        }
    });
}
 
Example #29
Source File: RefreshableScopeExtension.java    From datawave with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
void onRefresh(@Observes RefreshEvent event, BeanManager bm) {
    if (refreshableScopeContext != null) {
        log.debug("Invalidating beans created using the RefreshableScope scope.");
        refreshableScopeContext.invalidate();
    }
}
 
Example #30
Source File: MetricCdiInjectionExtension.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private <X> void applyMetricsBinding(@Observes @WithAnnotations({ Gauge.class }) ProcessAnnotatedType<X> pat) {
    Class<X> clazz = pat.getAnnotatedType().getJavaClass();
    Package pack = clazz.getPackage();
    if (pack == null || !pack.getName().equals(GaugeRegistrationInterceptor.class.getPackage().getName())) {
        if (!clazz.isInterface()) {
            AnnotatedTypeDecorator newPAT = new AnnotatedTypeDecorator<>(pat.getAnnotatedType(), METRICS_BINDING);
            pat.setAnnotatedType(newPAT);
        }
    }

}