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 Project: microprofile-context-propagation   Author: eclipse   File: JTACDITest.java    License: 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 #2
Source Project: tomee   Author: apache   File: BValInterceptor.java    License: 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 #3
Source Project: microprofile1.4-samples   Author: javaee-samples   File: URLServiceConfigSource.java    License: 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 #4
Source Project: microprofile1.4-samples   Author: javaee-samples   File: URLServiceConfigSource.java    License: 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 #5
Source Project: openwebbeans-meecrowave   Author: apache   File: InjectRule.java    License: 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 #6
Source Project: quarkus   Author: quarkusio   File: VertxRequestHandler.java    License: 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 #7
Source Project: quarkus   Author: quarkusio   File: QuarkusSmallRyeTracingDynamicFeature.java    License: 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 #8
Source Project: openwebbeans-meecrowave   Author: apache   File: CDIInstanceManager.java    License: 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 #9
Source Project: quarkus   Author: quarkusio   File: VertxRequestHandler.java    License: 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 #10
Source Project: piranha   Author: piranhacloud   File: WeldContainer.java    License: 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 #11
Source Project: crnk-framework   Author: crnk-project   File: CdiServiceDiscovery.java    License: 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 #12
Source Project: liberty-bikes   Author: OpenLiberty   File: GameRound.java    License: 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 #13
Source Project: hammock   Author: hammock-project   File: JettyWebServer.java    License: Apache License 2.0 5 votes vote down vote up
private static ServletContextListener getOrCreateListener(Class<? extends ServletContextListener> clazz) {
    try {
        return CDI.current().select(clazz).get();
    }
    catch (Exception e) {
        try {
            return clazz.newInstance();
        } catch (ReflectiveOperationException e1) {
            throw new RuntimeException("Unable to instantiate listener "+clazz+ " "
                    +e1.getMessage()+" "+e.getMessage(), e);
        }
    }
}
 
Example #14
Source Project: microprofile-context-propagation   Author: eclipse   File: JTACDITest.java    License: Apache License 2.0 5 votes vote down vote up
private UserTransaction getUserTransaction(String testName) {
    try {
        return CDI.current().select(UserTransaction.class).get();
    }
    catch (IllegalStateException x) {
        System.out.printf("Skipping test %s. UserTransaction is not available.%n", testName);
        return null;
    }
}
 
Example #15
Source Project: hammock   Author: hammock-project   File: HammockDataSource.java    License: Apache License 2.0 5 votes vote down vote up
private DataSource wrap(DataSource dataSource) {
    Instance<DataSourceWrapper> wrappers = CDI.current().select(DataSourceWrapper.class);
    for(DataSourceWrapper wrapper : wrappers) {
        dataSource = wrapper.wrap(name, dataSource);
    }
    return dataSource;
}
 
Example #16
Source Project: keycloak   Author: keycloak   File: VertxClientCertificateLookup.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(HttpRequest httpRequest) {
    Instance<RoutingContext> instances = CDI.current().select(RoutingContext.class);

    if (instances.isResolvable()) {
        RoutingContext context = instances.get();

        try {
            SSLSession sslSession = context.request().sslSession();
            
            if (sslSession == null) {
                return null;
            }
            
            X509Certificate[] certificates = (X509Certificate[]) sslSession.getPeerCertificates();

            if (logger.isTraceEnabled() && certificates != null) {
                for (X509Certificate cert : certificates) {
                    logger.tracef("Certificate's SubjectDN => \"%s\"", cert.getSubjectDN().getName());
                }
            }

            return certificates;
        } catch (SSLPeerUnverifiedException ignore) {
            // client not authenticated
        }
    }

    return null;
}
 
Example #17
Source Project: quarkus   Author: quarkusio   File: AlternativePriorityAnnotationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAnnotationWorks() {
    Instance<Object> instance = CDI.current().select(Object.class);
    assertTrue(instance.select(Foo.class).isResolvable());
    assertTrue(instance.select(AlternativeClassBean.class).isResolvable());
    assertTrue(instance.select(AlternativeProducerFieldBean.class).isResolvable());
    assertTrue(instance.select(AlternativeProducerMethodBean.class).isResolvable());
    assertTrue(instance.select(TheUltimateImpl.class).isResolvable());
    Instance<MyInterface> interfaceInstance = instance.select(MyInterface.class);
    assertTrue(interfaceInstance.isResolvable());
    MyInterface actualImpl = interfaceInstance.get();
    assertEquals(TheUltimateImpl.class.getSimpleName(), actualImpl.ping());
}
 
Example #18
Source Project: quarkus   Author: quarkusio   File: CDIProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProducer() throws IOException {
    Moo moo = CDI.current()
            .select(Moo.class)
            .get();
    assertEquals(10, moo.getVal());
}
 
Example #19
Source Project: quarkus   Author: quarkusio   File: CDIProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@AfterAll
public static void unset() {
    assertTrue(Moo.DESTROYED.get());
    try {
        Field providerField = CDI.class.getDeclaredField("configuredProvider");
        providerField.setAccessible(true);
        providerField.set(null, null);
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #20
Source Project: ozark   Author: mvc-spec   File: RedirectScopeContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the manager.
 *
 * @return the manager.
 */
public RedirectScopeManager getManager() {
    if (manager == null) {
        manager = CDI.current().select(RedirectScopeManager.class).get();
    }
    return manager;
}
 
Example #21
Source Project: quarkus   Author: quarkusio   File: ElytronRecorder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@linkplain SecurityDomain.Builder} for the given default {@linkplain SecurityRealm}.
 *
 * @param realmName - the default realm name
 * @param realm - the default SecurityRealm
 * @return a runtime value for the SecurityDomain.Builder
 * @throws Exception on any error
 */
public RuntimeValue<SecurityDomain.Builder> configureDomainBuilder(String realmName, RuntimeValue<SecurityRealm> realm)
        throws Exception {
    log.debugf("buildDomain, realm=%s", realm.getValue());

    SecurityDomain.Builder domain = SecurityDomain.builder()

            .addRealm(realmName, realm.getValue())

            .setRoleDecoder(new RoleDecoder() {
                @Override
                public Roles decodeRoles(AuthorizationIdentity authorizationIdentity) {
                    return CDI.current().select(DefaultRoleDecoder.class).get().decodeRoles(authorizationIdentity);
                }
            })
            .build()
            .setDefaultRealmName(realmName)
            .setPermissionMapper(new PermissionMapper() {
                @Override
                public PermissionVerifier mapPermissions(PermissionMappable permissionMappable, Roles roles) {
                    return new PermissionVerifier() {
                        @Override
                        public boolean implies(Permission permission) {
                            return true;
                        }
                    };
                }
            });

    return new RuntimeValue<>(domain);
}
 
Example #22
Source Project: openwebbeans-meecrowave   Author: apache   File: Injector.java    License: 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 #23
Source Project: keycloak   Author: keycloak   File: QuarkusJpaConnectionProviderFactory.java    License: 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 #24
Source Project: quarkus   Author: quarkusio   File: QuarkusJaxRsMetricsFilter.java    License: 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 Project: openwebbeans-meecrowave   Author: apache   File: MeecrowaveTest.java    License: 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 #26
Source Project: openwebbeans-meecrowave   Author: apache   File: Meecrowave.java    License: 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 #27
Source Project: quarkus   Author: quarkusio   File: HttpSecurityRecorder.java    License: 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);
        }
    };
}
 
Example #28
Source Project: quarkus   Author: quarkusio   File: RestClientRecorder.java    License: 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 #29
Source Project: database-rider   Author: database-rider   File: JTAConnectionHolder.java    License: 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 #30
Source Project: piranha   Author: piranhacloud   File: IdentityStoreLoginHandler.java    License: 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;
}