Java Code Examples for javax.enterprise.inject.Instance#get()

The following examples show how to use javax.enterprise.inject.Instance#get() . 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: ConfiguredChannelFactory.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
ConfiguredChannelFactory(@Any Instance<IncomingConnectorFactory> incomingConnectorFactories,
        @Any Instance<OutgoingConnectorFactory> outgoingConnectorFactories,
        Instance<Config> config, @Any Instance<ChannelRegistry> registry,
        BeanManager beanManager, boolean logConnectors) {
    this.registry = registry.get();
    if (config.isUnsatisfied()) {
        this.incomingConnectorFactories = null;
        this.outgoingConnectorFactories = null;
        this.config = null;
    } else {
        this.incomingConnectorFactories = incomingConnectorFactories;
        this.outgoingConnectorFactories = outgoingConnectorFactories;
        if (logConnectors) {
            log.foundIncomingConnectors(getConnectors(beanManager, IncomingConnectorFactory.class));
            log.foundOutgoingConnectors(getConnectors(beanManager, OutgoingConnectorFactory.class));
        }
        //TODO Should we try to merge all the config?
        // For now take the first one.
        this.config = config.stream().findFirst()
                .orElseThrow(() -> ex.illegalStateRetieveConfig());
    }
}
 
Example 2
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on a request scoped bean, then verify a contextualized callable
 * has the state propagated to it when ran on the same thread.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDITCCtxPropagate() throws Exception {
    ThreadContext defaultTC = ThreadContext.builder()
                                           .propagated(ThreadContext.CDI)
                                           .cleared(ThreadContext.ALL_REMAINING)
                                           .unchanged()
                                           .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    RequestScopedBean requestBean = selectedInstance.get();
    requestBean.setState("testCDIContextPropagate-STATE2");
    Callable<String> getState = defaultTC.contextualCallable(() -> {
        String state = requestBean.getState();
        return state;
    });
    assertEquals(getState.call(), "testCDIContextPropagate-STATE2");
}
 
Example 3
Source File: CDIContextTest.java    From microprofile-context-propagation with Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on a request scoped bean, then verify a contextualized callable
 * has the state cleared from it when ran on the same thread.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDITCCtxClear() throws Exception {
    ThreadContext clearAllCtx = ThreadContext.builder()
                    .propagated() // propagate nothing
                    .cleared(ThreadContext.ALL_REMAINING)
                    .unchanged()
                    .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    RequestScopedBean requestBean = selectedInstance.get();
    requestBean.setState("testCDIThreadCtxClear-STATE1");
    Callable<String> getState = clearAllCtx.contextualCallable(() -> {
        String state = requestBean.getState();
        return state;
    });
    assertEquals(getState.call(), "UNINITIALIZED");
}
 
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: VertxRequestHandler.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public VertxRequestHandler(Vertx vertx,
        BeanContainer beanContainer,
        ObjectMapper mapper,
        FunqyKnativeEventsConfig config,
        FunctionInvoker defaultInvoker,
        Map<String, FunctionInvoker> typeTriggers,
        Executor executor) {
    this.defaultInvoker = defaultInvoker;
    this.vertx = vertx;
    this.beanContainer = beanContainer;
    this.executor = executor;
    this.mapper = mapper;
    this.typeTriggers = typeTriggers;
    Instance<CurrentIdentityAssociation> association = CDI.current().select(CurrentIdentityAssociation.class);
    this.association = association.isResolvable() ? association.get() : null;
    Instance<IdentityProviderManager> identityProviderManager = CDI.current().select(IdentityProviderManager.class);
    this.currentVertxRequest = CDI.current().select(CurrentVertxRequest.class).get();

}
 
Example 6
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 7
Source File: ExecutionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Inject
public ExecutionHolder(Instance<Vertx> instanceOfVertx) {
    if (instanceOfVertx == null || instanceOfVertx.isUnsatisfied()) {
        internalVertxInstance = true;
        this.vertx = Vertx.vertx();
        log.vertXInstanceCreated();
    } else {
        this.vertx = instanceOfVertx.get();
    }
}
 
Example 8
Source File: AlternativePriorityAnnotationTest.java    From quarkus with 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 9
Source File: SmallRyeGraphQLRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public Handler<RoutingContext> executionHandler(boolean allowGet) {
    Instance<CurrentIdentityAssociation> identityAssociations = CDI.current()
            .select(CurrentIdentityAssociation.class);
    CurrentIdentityAssociation association;
    if (identityAssociations.isResolvable()) {
        association = identityAssociations.get();
    } else {
        association = null;
    }
    return new SmallRyeGraphQLExecutionHandler(allowGet, association);
}
 
Example 10
Source File: DefaultPicocliCommandLineFactory.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public CommandLine create() {
    String topCommandName = picocliConfiguration.topCommand.orElse(null);
    if (topCommandName != null) {
        Instance<Object> namedTopCommand = topCommand.select(NamedLiteral.of(topCommandName));
        if (namedTopCommand.isResolvable()) {
            return new CommandLine(namedTopCommand.get(), picocliFactory);
        }
        return new CommandLine(classForName(topCommandName), picocliFactory);
    }
    return new CommandLine(topCommand.get(), picocliFactory);
}
 
Example 11
Source File: AppInitializer.java    From oxTrust with MIT License 5 votes vote down vote up
protected void recreatePersistanceEntryManagerImpl(Instance<PersistenceEntryManager> instance,
		String persistenceEntryManagerName, Annotation... qualifiers) {
	// Get existing application scoped instance
	PersistenceEntryManager oldLdapEntryManager = CdiUtil.getContextBean(beanManager, PersistenceEntryManager.class,
			persistenceEntryManagerName, qualifiers);

	// Close existing connections
	closePersistenceEntryManager(oldLdapEntryManager, persistenceEntryManagerName);

	// Force to create new bean
	PersistenceEntryManager ldapEntryManager = instance.get();
	instance.destroy(ldapEntryManager);
	log.info("Recreated instance {}: {} with operation service: {}", persistenceEntryManagerName, ldapEntryManager,
			ldapEntryManager.getOperationService());
}
 
Example 12
Source File: AppInitializer.java    From oxAuth with MIT License 5 votes vote down vote up
protected void recreatePersistanceEntryManagerImpl(Instance<PersistenceEntryManager> instance,
		String persistenceEntryManagerName, Annotation... qualifiers) {
	// Get existing application scoped instance
	PersistenceEntryManager oldPersistenceEntryManager = CdiUtil.getContextBean(beanManager,
			PersistenceEntryManager.class, persistenceEntryManagerName);

	// Close existing connections
	closePersistenceEntryManager(oldPersistenceEntryManager, persistenceEntryManagerName);

	// Force to create new bean
	PersistenceEntryManager persistenceEntryManager = instance.get();
	instance.destroy(persistenceEntryManager);
	log.info("Recreated instance {}: {} with operation service: {}", persistenceEntryManagerName,
			persistenceEntryManager, persistenceEntryManager.getOperationService());
}
 
Example 13
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 14
Source File: VertxClientCertificateLookup.java    From keycloak with 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 15
Source File: MetricDecorator.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Inject
private void setMetricRegistry(Instance<MetricRegistry> registryInstance) {
    if (registryInstance.isResolvable()) {
        registry = registryInstance.get();
    }
}
 
Example 16
Source File: PackageValidator.java    From microprofile-starter with Apache License 2.0 3 votes vote down vote up
/**
 * Retrieve the single CDI instance which has the classType in the bean definition. It throws the standard CDI exceptions
 * in case when there are no or multiple beans which are a candidate for the type.
 *
 * @param classType a {@link java.lang.Class} representing the required type
 * @param <T>       Generic Type argument
 * @return CDI instance matching the class type and qualifiers (if specified).
 * @throws javax.enterprise.inject.AmbiguousResolutionException When more then 1 bean is found in the match
 * @throws UnsatisfiedResolutionException                       When no bean is found in the match.
 */
public static <T> T retrieveInstance(Class<T> classType) {
    Instance<T> instance = CDI.current().select(classType);
    if (instance.isUnsatisfied()) {
        throw new UnsatisfiedResolutionException(String.format("No bean found for class %s", classType.getName()));
    }
    return instance.get();
}