javax.enterprise.inject.spi.CDI Java Examples

The following examples show how to use javax.enterprise.inject.spi.CDI. 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: QuarkusSmallRyeTracingDynamicFeature.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public QuarkusSmallRyeTracingDynamicFeature() {
    Config config = ConfigProvider.getConfig();
    Optional<String> skipPattern = config.getOptionalValue("mp.opentracing.server.skip-pattern", String.class);
    Optional<String> operationNameProvider = config.getOptionalValue("mp.opentracing.server.operation-name-provider",
            String.class);

    ServerTracingDynamicFeature.Builder builder = new ServerTracingDynamicFeature.Builder(
            CDI.current().select(Tracer.class).get())
                    .withOperationNameProvider(OperationNameProvider.ClassNameOperationName.newBuilder())
                    .withTraceSerialization(false);
    if (skipPattern.isPresent()) {
        builder.withSkipPattern(skipPattern.get());
    }
    if (operationNameProvider.isPresent()) {
        if ("http-path".equalsIgnoreCase(operationNameProvider.get())) {
            builder.withOperationNameProvider(OperationNameProvider.WildcardOperationName.newBuilder());
        } else if (!"class-method".equalsIgnoreCase(operationNameProvider.get())) {
            logger.warn("Provided operation name does not match http-path or class-method. Using default class-method.");
        }
    }
    this.delegate = builder.build();
}
 
Example #2
Source File: CDIInstanceManager.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
public void newInstance(final Object o) throws IllegalAccessException, InvocationTargetException, NamingException {
    if (WebBeansConfigurationListener.class.isInstance(o) || o.getClass().getName().startsWith("org.apache.catalina.servlets.")) {
        return;
    }

    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(o.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(o, creationalContext);
    try {
        injectionTarget.postConstruct(o);
    } catch (final RuntimeException e) {
        creationalContext.release();
        throw e;
    }
    destroyables.put(o, () -> {
        try {
            injectionTarget.preDestroy(o);
        } finally {
            creationalContext.release();
        }
    });
}
 
Example #3
Source File: VertxRequestHandler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public VertxRequestHandler(Vertx vertx,
        BeanContainer beanContainer,
        String rootPath,
        Executor executor) {
    this.vertx = vertx;
    this.beanContainer = beanContainer;
    // make sure rootPath ends with "/" for easy parsing
    if (rootPath == null) {
        this.rootPath = "/";
    } else if (!rootPath.endsWith("/")) {
        this.rootPath = rootPath + "/";
    } else {
        this.rootPath = rootPath;
    }

    this.executor = executor;
    Instance<CurrentIdentityAssociation> association = CDI.current().select(CurrentIdentityAssociation.class);
    this.association = association.isResolvable() ? association.get() : null;
    currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get();
}
 
Example #4
Source File: VertxRequestHandler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public VertxRequestHandler(Vertx vertx,
        BeanContainer beanContainer,
        ResteasyDeployment deployment,
        String rootPath,
        BufferAllocator allocator, Executor executor, long readTimeout) {
    this.vertx = vertx;
    this.beanContainer = beanContainer;
    this.dispatcher = new RequestDispatcher((SynchronousDispatcher) deployment.getDispatcher(),
            deployment.getProviderFactory(), null, Thread.currentThread().getContextClassLoader());
    this.rootPath = rootPath;
    this.allocator = allocator;
    this.executor = executor;
    this.readTimeout = readTimeout;
    Instance<CurrentIdentityAssociation> association = CDI.current().select(CurrentIdentityAssociation.class);
    this.association = association.isResolvable() ? association.get() : null;
    currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get();
}
 
Example #5
Source File: GameRound.java    From liberty-bikes with Eclipse Public License 1.0 6 votes vote down vote up
private void updatePlayerStats() {
    if (gameState != State.FINISHED)
        throw new IllegalStateException("Cannot update player stats while game is still running.");

    PlayerService playerSvc = CDI.current().select(PlayerService.class, RestClient.LITERAL).get();
    int rank = 1;
    for (Player p : playerRanks) {
        log("Player " + p.name + " came in place " + rank);
        if (p.isRealPlayer()) {
            String jwt = createJWT();
            String authHeader = "Bearer " + jwt;
            playerSvc.recordGame(p.id, rank, authHeader);
        }
        rank++;
    }
}
 
Example #6
Source File: InjectRule.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            CreationalContext<?> creationalContext = null;
            try {
                creationalContext = Injector.inject(instance);
                Injector.injectConfig(CDI.current().select(Meecrowave.Builder.class).get(), instance);
                base.evaluate();
            } finally {
                if (creationalContext != null) {
                    creationalContext.release();
                }
            }
        }
    };
}
 
Example #7
Source File: URLServiceConfigSource.java    From microprofile1.4-samples with MIT License 6 votes vote down vote up
@Override
public String getValue(String propertyName) {
    if (propertyName.equals(HelloService.class.getName() +  "/mp-rest/url")) {

        try {
            HttpServletRequest request = CDI.current().select(HttpServletRequest.class).get();

            StringBuffer url = request.getRequestURL();
            String uri = request.getRequestURI();

            return url.substring(0, url.length() - uri.length() + request.getContextPath().length()) + "/";
        } catch (Exception e) {
            // Ignore, thrown when the key is requested ahead of a request
        }
    }

    return null;
}
 
Example #8
Source File: URLServiceConfigSource.java    From microprofile1.4-samples with MIT License 6 votes vote down vote up
@Override
public String getValue(String propertyName) {
    if (propertyName.equals(HelloService.class.getName() +  "/mp-rest/url")) {

        try {
            HttpServletRequest request = CDI.current().select(HttpServletRequest.class).get();

            StringBuffer url = request.getRequestURL();
            String uri = request.getRequestURI();

            return url.substring(0, url.length() - uri.length() + request.getContextPath().length()) + "/";
        } catch (Exception e) {
            // Ignore, thrown when the key is requested ahead of a request
        }
    }

    return null;
}
 
Example #9
Source File: CdiServiceDiscovery.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public BeanManager getBeanManager() {
	if (beanManager != null) {
		return beanManager;
	} else if (cdiAvailable != Boolean.FALSE) {
		try {
			CDI<Object> current = CDI.current();
			cdiAvailable = Boolean.TRUE;
			return current.getBeanManager();
		} catch (IllegalStateException e) {
			LOGGER.error("CDI context not available, CdiServiceDiscovery will not be used");
			LOGGER.debug("CDI.current() failed", e);
			cdiAvailable = Boolean.FALSE;
			return null;
		}
	}
	return null;
}
 
Example #10
Source File: BValInterceptor.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void initClassConfig(Class<?> targetClass) {
    if (classConfiguration == null) {
        synchronized (this) {
            if (classConfiguration == null) {
                final AnnotatedType<?> annotatedType = CDI.current().getBeanManager()
                        .createAnnotatedType(targetClass);

                if (annotatedType.isAnnotationPresent(ValidateOnExecution.class)) {
                    // implicit does not apply at the class level:
                    classConfiguration = ExecutableTypes.interpret(
                            removeFrom(Arrays.asList(annotatedType.getAnnotation(ValidateOnExecution.class).type()),
                                    ExecutableType.IMPLICIT));
                } else {
                    classConfiguration = globalConfiguration.getGlobalExecutableTypes();
                }
            }
        }
    }
}
 
Example #11
Source File: WeldContainer.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Initialize the container.
 *
 * @param context the container context.
 */
@Override
public void initialize(ContainerContext context) {
    try {
        CDI.setCDIProvider(new WeldProvider());
    } catch (IllegalStateException ise) {
    }
    try {
        WeldManager manager = context.getManager();
        WeldCDI cdi = new WeldCDI();
        cdi.setWeldManager(manager);
        WeldProvider.setCDI(cdi);
        InitialContext initialContext = new InitialContext();
        initialContext.rebind("java:comp/BeanManager", manager);
    } catch (NamingException ne) {
        throw new RuntimeException(ne);
    }
}
 
Example #12
Source File: JTACDITest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
private void verifyNoTransaction() {
    try {
        TransactionManager transactionManager = CDI.current().select(TransactionManager.class).get();

        try {
            if (transactionManager.getTransaction() != null) {
                Assert.fail("transaction still active");
            }
        }
        catch (SystemException e) {
            Assert.fail("Could verify that no transaction is associated", e);
        }
    }
    catch (Exception ignore) {
        // the implementation does not expose a JTA TM as a CDI bean
    }
}
 
Example #13
Source File: CdiPlugin.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Completable deployToResteasy(VertxResteasyDeployment deployment) {
	ResteasyCdiExtension cdiExtension = CDI.current().select(ResteasyCdiExtension.class).get();
	deployment.setActualResourceClasses(cdiExtension.getResources());
	deployment.setInjectorFactoryClass(CdiInjectorFactory.class.getName());
	deployment.getActualProviderClasses().addAll(cdiExtension.getProviders());
	return Completable.complete();
}
 
Example #14
Source File: Injector.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public static CreationalContext<?> inject(final Object testInstance) {
    if (testInstance == null) {
        return null;
    }
    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(testInstance.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<?> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(testInstance, creationalContext);
    return creationalContext;
}
 
Example #15
Source File: JTAConnectionHolder.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private DataSource resolveDataSource(String dataSourceName) {
    if ("".equals(dataSourceName)) { //default datasource
        return CDI.current().select(DataSource.class).get();
    } else {
        return datasources.select(DataSource.class, new RiderPUAnnotation(dataSourceName)).get();
    }
}
 
Example #16
Source File: CXFWebservicePublisher.java    From kumuluzee with MIT License 5 votes vote down vote up
private Object getBean(Class<?> clazz, boolean cdiPresent) {
    //cdi
    if (cdiPresent) {
        return CDI.current().select(clazz).get();
    }

    //pojo instance
    try {
        return clazz.getConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new RuntimeException("Unable to instantiate bean from " + clazz, e);
    }

}
 
Example #17
Source File: LoggerFactory.java    From microprofile-sandbox with Apache License 2.0 5 votes vote down vote up
private static LoggerFactoryProvider initFactory() {
  try {
    return CDI.current().select(LoggerFactoryProvider.class).get();
  } catch (Throwable t) {
    // no factory
  }
  return NOOPFACTORY;
}
 
Example #18
Source File: TheServerAuthModule.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void cdi(final MessageInfo messageInfo, final String msg) throws AuthException {
    final HttpServletRequest request = HttpServletRequest.class.cast(messageInfo.getRequestMessage());
    final HttpServletResponse response = HttpServletResponse.class.cast(messageInfo.getResponseMessage());
    if (request.getParameter("bean") != null) {
        final TheBean cdiBean = CDI.current().select(TheBean.class).get();
        cdiBean.set(msg);
        try {
            response.getWriter().write(String.valueOf(request.getAttribute("cdi")));
        } catch (final IOException e) {
            throw new AuthException(e.getMessage());
        }
    }
}
 
Example #19
Source File: RestClientRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public BeanContainerListener hackAroundExtension() {
    return new BeanContainerListener() {
        @Override
        public void created(BeanContainer container) {
            try {
                Field f = RestClientExtension.class.getDeclaredField("manager");
                f.setAccessible(true);
                f.set(null, CDI.current().getBeanManager());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #20
Source File: IdentityStoreLoginHandler.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public AuthenticatedIdentity login(HttpServletRequest request, String username, String password) {

    CredentialValidationResult result = CDI.current()
       .select(IdentityStoreHandler.class)
       .get()
       .validate(new UsernamePasswordCredential(username, new Password(password)));

    if (result.getStatus() == VALID) {
        return new DefaultAuthenticatedIdentity(result.getCallerPrincipal(), result.getCallerGroups());
    }
    
    return null;
}
 
Example #21
Source File: Meecrowave.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public <T> AutoCloseable inject(final T instance) {
    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(instance.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(instance, creationalContext);
    return creationalContext::release;
}
 
Example #22
Source File: JWTProcessorConverter.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Override
public JWTProcessor convert(String s) {
    try {
        Class<JWTProcessor> aClass = (Class<JWTProcessor>)Class.forName(s);
        return CDI.current().select(aClass).get();
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("No class "+s,e);
    }
}
 
Example #23
Source File: MeecrowaveTest.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private void assertClasspath(final Meecrowave meecrowave) throws MalformedURLException {
    assertEquals(CDI.current().select(Configuration.class).get(), meecrowave.getConfiguration()); // not symmetric cause of proxy!
    assertEquals("simplefalse", slurp(new URL("http://localhost:" + meecrowave.getConfiguration().getHttpPort() + "/api/test")));
    assertEquals("simplefiltertrue", slurp(new URL("http://localhost:" + meecrowave.getConfiguration().getHttpPort() + "/filter")));
    assertEquals(
            "sci:" + Bounced.class.getName() + Endpoint.class.getName() + InterfaceApi.class.getName() + RsApp.class.getName() + TestJsonEndpoint.class.getName(),
            slurp(new URL("http://localhost:" + meecrowave.getConfiguration().getHttpPort() + "/sci")));
}
 
Example #24
Source File: QuarkusJaxRsMetricsFilter.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) {
    Long start = System.nanoTime();
    final Class<?> resourceClass = resourceInfo.getResourceClass();
    final Method resourceMethod = resourceInfo.getResourceMethod();
    /*
     * The reason for using a Vert.x handler instead of ContainerResponseFilter is that
     * RESTEasy does not call the response filter for requests that ended up with an unmapped exception.
     * This way we can capture these responses as well and update the metrics accordingly.
     */
    RoutingContext routingContext = CDI.current().select(CurrentVertxRequest.class).get().getCurrent();
    routingContext.addBodyEndHandler(
            event -> finishRequest(start, resourceClass, resourceMethod));
}
 
Example #25
Source File: ComponentServerConfiguration.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private void doActivateDebugMode(final ClassLoader loader, final Class<?> feature)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException,
        java.lang.reflect.InvocationTargetException, NoSuchMethodException {
    final Class<?> bus = loader.loadClass("org.apache.cxf.Bus");
    final Object instance = feature.getConstructor().newInstance();
    final Object busInstance = CDI.current().select(bus).get();
    feature.getMethod("initialize", bus).invoke(instance, busInstance);
    log.info("Activated debug mode - will log requests/responses");
}
 
Example #26
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void lazyInit() {
    Instance<EntityManagerFactory> instance = CDI.current().select(EntityManagerFactory.class);

    if (!instance.isResolvable()) {
        throw new RuntimeException("Failed to resolve " + EntityManagerFactory.class + " from Quarkus runtime");
    }

    emf = instance.get();

    try (Connection connection = getConnection()) {
        if (jtaEnabled) {
            KeycloakModelUtils.suspendJtaTransaction(factory, () -> {
                KeycloakSession session = factory.create();
                try {
                    migration(getSchema(), connection, session);
                } finally {
                    session.close();
                }
            });
        } else {
            KeycloakModelUtils.runJobInTransaction(factory, session -> {
                migration(getSchema(), connection, session);
            });
        }
        prepareOperationalInfo(connection);
    } catch (SQLException cause) {
        throw new RuntimeException("Failed to migrate model", cause);
    }
}
 
Example #27
Source File: WeldSecurityService.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Principal getPrincipal() {
    Instance<SecurityContext> securityServiceInstance =  CDI.current().select(SecurityContext.class);
    if (securityServiceInstance.isResolvable()) {
        return securityServiceInstance.get().getCallerPrincipal();
    }
    
    return null;
}
 
Example #28
Source File: PingCDIBean.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
public int getBeanMangerViaCDICurrent() throws Exception {
    BeanManager beanManager = CDI.current().getBeanManager();
    Set<Bean<?>> beans = beanManager.getBeans(Object.class);
    
    if (beans.size() > 0) {
        return ++getBeanManagerHitCountSPI;
    }
    return 0;

}
 
Example #29
Source File: CdiPlugin.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Completable init() {
	return Completable.defer(() -> {
		// Setup the Vertx-CDI integration
		VertxExtension vertxExtension = CDI.current().select(VertxExtension.class).get();
		BeanManager beanManager = CDI.current().getBeanManager();
		// has to be done in a blocking thread
		Vertx vertx = AppGlobals.get().getVertx();
		return vertx.rxExecuteBlocking(future -> {
			vertxExtension.registerConsumers(vertx.getDelegate(), BeanManagerProxy.unwrap(beanManager).event());
			future.complete();
		}).ignoreElement();
	});
}
 
Example #30
Source File: HttpSecurityRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Handler<RoutingContext> permissionCheckHandler() {
    return new Handler<RoutingContext>() {
        volatile HttpAuthorizer authorizer;

        @Override
        public void handle(RoutingContext event) {
            if (authorizer == null) {
                authorizer = CDI.current().select(HttpAuthorizer.class).get();
            }
            authorizer.checkPermission(event);
        }
    };
}