javax.enterprise.inject.Instance Java Examples
The following examples show how to use
javax.enterprise.inject.Instance.
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: smallrye-jwt Author: smallrye File: SmallRyeJWTAuthCDIExtension.java License: Apache License 2.0 | 6 votes |
public static boolean isHttpAuthMechanismEnabled() { boolean enabled = false; if (isEESecurityAvailable()) { Instance<JWTHttpAuthenticationMechanism> instance; try { instance = CDI.current().select(JWTHttpAuthenticationMechanism.class); enabled = instance.isResolvable(); } catch (@SuppressWarnings("unused") Exception e) { //Ignore exceptions, consider HTTP authentication mechanism to be disabled } } return enabled; }
Example #2
Source Project: pnc Author: project-ncl File: BuildSchedulerFactory.java License: Apache License 2.0 | 6 votes |
@Inject public BuildSchedulerFactory(Instance<BuildScheduler> availableSchedulers, Configuration configuration) throws CoreException { AtomicReference<String> schedulerId = new AtomicReference<>(null); try { schedulerId.set( configuration.getModuleConfig(new PncConfigProvider<>(SystemConfig.class)).getBuildSchedulerId()); } catch (ConfigurationParseException e) { logger.warn("Unable parse config. Using default scheduler"); schedulerId.set(DEFAULT_SCHEDULER_ID); } availableSchedulers.forEach(scheduler -> setMatchingScheduler(scheduler, schedulerId.get())); if (configuredBuildScheduler == null) { throw new CoreException( "Cannot get BuildScheduler, check configurations and make sure a scheduler with configured id is available for injection. configured id: " + schedulerId); } }
Example #3
Source Project: deltaspike Author: apache File: JsfRequestLifecycleBroadcaster.java License: Apache License 2.0 | 6 votes |
@Inject protected JsfRequestLifecycleBroadcaster(Instance<PhaseListener> phaseListenerInstance) { Class phaseListenerClass; for (PhaseListener currentPhaseListener : phaseListenerInstance) { phaseListenerClass = ProxyUtils.getUnproxiedClass(currentPhaseListener.getClass()); if (phaseListenerClass.isAnnotationPresent(JsfPhaseListener.class)) { if (Deactivatable.class.isAssignableFrom(phaseListenerClass) && !ClassDeactivationUtils.isActivated(phaseListenerClass)) { continue; } this.phaseListeners.add(currentPhaseListener); } } //higher ordinals first sortDescending(this.phaseListeners); }
Example #4
Source Project: microprofile-context-propagation Author: eclipse File: CDIContextTest.java License: Apache License 2.0 | 6 votes |
/** * Set some state on Request scoped bean and verify * the state is propagated to the thread where the other task runs. * * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done. * * @throws Exception indicates test failure */ @Test public void testCDIMECtxPropagatesRequestScopedBean() throws Exception { // check if given context is active, if it isn't test ends successfully try { bm.getContext(RequestScoped.class); } catch (ContextNotActiveException e) { return; } ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI) .cleared(ThreadContext.ALL_REMAINING) .build(); Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class); assertTrue(selectedInstance.isResolvable()); try { checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-REQUEST", propagateCDI, selectedInstance.get()); } finally { propagateCDI.shutdown(); } }
Example #5
Source Project: microprofile-context-propagation Author: eclipse File: CDIContextTest.java License: Apache License 2.0 | 6 votes |
/** * Set some state on Session scoped bean and verify * the state is propagated to the thread where the other task runs. * * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done. * * @throws Exception indicates test failure */ @Test public void testCDIMECtxPropagatesSessionScopedBean() throws Exception { // check if given context is active, if it isn't test ends successfully try { bm.getContext(SessionScoped.class); } catch (ContextNotActiveException e) { return; } ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI) .cleared(ThreadContext.ALL_REMAINING) .build(); Instance<SessionScopedBean> selectedInstance = instance.select(SessionScopedBean.class); assertTrue(selectedInstance.isResolvable()); try { checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-SESSION", propagateCDI, selectedInstance.get()); } finally { propagateCDI.shutdown(); } }
Example #6
Source Project: microprofile-context-propagation Author: eclipse File: CDIContextTest.java License: Apache License 2.0 | 6 votes |
/** * Set some state on Session scoped bean and verify * the state is cleared on the thread where the other task runs. * * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done. * * @throws Exception indicates test failure */ @Test public void testCDIMECtxClearsSessionScopedBeans() throws Exception { // check if given context is active, if it isn't test ends successfully try { bm.getContext(SessionScoped.class); } catch (ContextNotActiveException e) { return; } ManagedExecutor propagatedNone = ManagedExecutor.builder() .propagated() // none .cleared(ThreadContext.ALL_REMAINING) .build(); Instance<SessionScopedBean> selectedInstance = instance.select(SessionScopedBean.class); assertTrue(selectedInstance.isResolvable()); try { checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-SESSION", propagatedNone, selectedInstance.get()); } finally { propagatedNone.shutdown(); } }
Example #7
Source Project: microprofile-context-propagation Author: eclipse File: CDIContextTest.java License: Apache License 2.0 | 6 votes |
/** * Set some state on Conversation scoped bean and verify * the state is cleared on the thread where the other task runs. * * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done. * * @throws Exception indicates test failure */ @Test public void testCDIMECtxClearsConversationScopedBeans() throws Exception { // check if given context is active, if it isn't test ends successfully try { bm.getContext(ConversationScoped.class); } catch (ContextNotActiveException e) { return; } ManagedExecutor propagatedNone = ManagedExecutor.builder() .propagated() // none .cleared(ThreadContext.ALL_REMAINING) .build(); Instance<ConversationScopedBean> selectedInstance = instance.select(ConversationScopedBean.class); assertTrue(selectedInstance.isResolvable()); try { checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-CONVERSATION", propagatedNone, selectedInstance.get()); } finally { propagatedNone.shutdown(); } }
Example #8
Source Project: microprofile-context-propagation Author: eclipse File: CDIContextTest.java License: Apache License 2.0 | 6 votes |
/** * 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 #9
Source Project: quarkus Author: quarkusio File: DataSources.java License: Apache License 2.0 | 6 votes |
public DataSources(DataSourcesBuildTimeConfig dataSourcesBuildTimeConfig, DataSourcesRuntimeConfig dataSourcesRuntimeConfig, DataSourcesJdbcBuildTimeConfig dataSourcesJdbcBuildTimeConfig, DataSourcesJdbcRuntimeConfig dataSourcesJdbcRuntimeConfig, LegacyDataSourcesJdbcBuildTimeConfig legacyDataSourcesJdbcBuildTimeConfig, LegacyDataSourcesRuntimeConfig legacyDataSourcesRuntimeConfig, LegacyDataSourcesJdbcRuntimeConfig legacyDataSourcesJdbcRuntimeConfig, TransactionManager transactionManager, TransactionSynchronizationRegistry transactionSynchronizationRegistry, DataSourceSupport dataSourceSupport, @Any Instance<AgroalPoolInterceptor> agroalPoolInterceptors) { this.dataSourcesBuildTimeConfig = dataSourcesBuildTimeConfig; this.dataSourcesRuntimeConfig = dataSourcesRuntimeConfig; this.dataSourcesJdbcBuildTimeConfig = dataSourcesJdbcBuildTimeConfig; this.dataSourcesJdbcRuntimeConfig = dataSourcesJdbcRuntimeConfig; this.legacyDataSourcesJdbcBuildTimeConfig = legacyDataSourcesJdbcBuildTimeConfig; this.legacyDataSourcesRuntimeConfig = legacyDataSourcesRuntimeConfig; this.legacyDataSourcesJdbcRuntimeConfig = legacyDataSourcesJdbcRuntimeConfig; this.transactionManager = transactionManager; this.transactionSynchronizationRegistry = transactionSynchronizationRegistry; this.dataSourceSupport = dataSourceSupport; this.agroalPoolInterceptors = agroalPoolInterceptors; }
Example #10
Source Project: pnc Author: project-ncl File: AuthenticationProviderFactory.java License: Apache License 2.0 | 6 votes |
@Inject public AuthenticationProviderFactory( @AuthProvider Instance<AuthenticationProvider> providers, Configuration configuration) throws CoreException { AtomicReference<String> providerId = new AtomicReference<>(null); try { providerId.set( configuration.getModuleConfig(new PncConfigProvider<>(SystemConfig.class)) .getAuthenticationProviderId()); } catch (ConfigurationParseException e) { logger.warn("Unable parse config. Using default scheduler"); providerId.set(DEFAULT_AUTHENTICATION_PROVIDER_ID); } providers.forEach(provider -> setMatchingProvider(provider, providerId.get())); if (authenticationProvider == null) { throw new CoreException( "Cannot get AuthenticationProvider, check configurations and make sure a provider with configured id is available for injection. configured id: " + providerId); } }
Example #11
Source Project: quarkus Author: quarkusio File: VertxRequestHandler.java License: Apache License 2.0 | 6 votes |
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 #12
Source Project: quarkus Author: quarkusio File: VertxRequestHandler.java License: Apache License 2.0 | 6 votes |
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 #13
Source Project: oxAuth Author: GluuFederation File: CacheGrant.java License: MIT License | 6 votes |
public CIBAGrant asCibaGrant(Instance<AbstractAuthorizationGrant> grantInstance) { CIBAGrant grant = grantInstance.select(CIBAGrant.class).get(); grant.init(user, AuthorizationGrantType.CIBA, client, authenticationTime); grant.setScopes(scopes); grant.setGrantId(grantId); grant.setSessionDn(sessionDn); grant.setCodeChallenge(codeChallenge); grant.setCodeChallengeMethod(codeChallengeMethod); grant.setAcrValues(acrValues); grant.setNonce(nonce); grant.setClaims(claims); grant.setAuthReqId(authReqId); grant.setTokensDelivered(tokensDelivered); return grant; }
Example #14
Source Project: quarkus Author: quarkusio File: KafkaStreamsTopologyManager.java License: Apache License 2.0 | 6 votes |
@Inject public KafkaStreamsTopologyManager(Instance<Topology> topology, Instance<KafkaClientSupplier> kafkaClientSupplier, Instance<StateListener> stateListener, Instance<StateRestoreListener> globalStateRestoreListener) { // No producer for Topology -> nothing to do if (topology.isUnsatisfied()) { LOGGER.debug("No Topology producer; Kafka Streams will not be started"); this.executor = null; return; } this.executor = Executors.newSingleThreadExecutor(); this.topology = topology; this.kafkaClientSupplier = kafkaClientSupplier; this.stateListener = stateListener; this.globalStateRestoreListener = globalStateRestoreListener; }
Example #15
Source Project: oxAuth Author: GluuFederation File: CacheGrant.java License: MIT License | 6 votes |
public AuthorizationCodeGrant asCodeGrant(Instance<AbstractAuthorizationGrant> grantInstance) { AuthorizationCodeGrant grant = grantInstance.select(AuthorizationCodeGrant.class).get(); grant.init(user, client, authenticationTime); grant.setAuthorizationCode(new AuthorizationCode(authorizationCodeString, authorizationCodeCreationDate, authorizationCodeExpirationDate)); grant.setScopes(scopes); grant.setGrantId(grantId); grant.setSessionDn(sessionDn); grant.setCodeChallenge(codeChallenge); grant.setCodeChallengeMethod(codeChallengeMethod); grant.setAcrValues(acrValues); grant.setNonce(nonce); grant.setClaims(claims); return grant; }
Example #16
Source Project: joynr Author: bmwcarit File: DefaultJoynrRuntimeFactoryTest.java License: Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private Instance<String> createLocalDomainMock() { Instance<String> joynrLocalDomain = mock(Instance.class); when(joynrLocalDomain.get()).thenReturn(LOCAL_DOMAIN); when(joynrLocalDomain.isAmbiguous()).thenReturn(false); when(joynrLocalDomain.isUnsatisfied()).thenReturn(false); return joynrLocalDomain; }
Example #17
Source Project: kogito-runtimes Author: kiegroup File: VertxJobsService.java License: Apache License 2.0 | 5 votes |
@Inject public VertxJobsService(@ConfigProperty(name = "kogito.jobs-service.url") String jobServiceUrl, @ConfigProperty(name = "kogito.service.url") String callbackEndpoint, Vertx vertx, Instance<WebClient> providedWebClient) { super(jobServiceUrl, callbackEndpoint); this.vertx = vertx; this.providedWebClient = providedWebClient; }
Example #18
Source Project: vraptor4 Author: caelum File: GsonBuilderWrapper.java License: Apache License 2.0 | 5 votes |
@Inject public GsonBuilderWrapper(@Any Instance<JsonSerializer<?>> jsonSerializers, @Any Instance<JsonDeserializer<?>> jsonDeserializers, Serializee serializee, ReflectionProvider reflectionProvider) { this.jsonSerializers = jsonSerializers; this.jsonDeserializers = jsonDeserializers; this.serializee = serializee; ExclusionStrategy exclusion = new Exclusions(serializee, reflectionProvider); exclusions = singletonList(exclusion); }
Example #19
Source Project: smallrye-reactive-messaging Author: smallrye File: AmqpClientHelper.java License: Apache License 2.0 | 5 votes |
static AmqpClient createClientFromClientOptionsBean(Vertx vertx, Instance<AmqpClientOptions> instance, String optionsBeanName) { Instance<AmqpClientOptions> options = instance.select(NamedLiteral.of(optionsBeanName)); if (options.isUnsatisfied()) { throw ex.illegalStateFindingBean(AmqpClientOptions.class.getName(), optionsBeanName); } log.createClientFromBean(optionsBeanName); return AmqpClient.create(vertx, options.get()); }
Example #20
Source Project: smallrye-reactive-messaging Author: smallrye File: ExecutionHolder.java License: Apache License 2.0 | 5 votes |
@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 #21
Source Project: tomee Author: apache File: ServletContextInjectionTest.java License: Apache License 2.0 | 5 votes |
@Context public void setApplication(final Application application) { final Instance<Loader> loader = CDI.current().select(Loader.class); if (!loader.isUnsatisfied()) { loader.iterator().next().useServletContext(); } }
Example #22
Source Project: smallrye-config Author: smallrye File: ConfigInjectionBean.java License: Apache License 2.0 | 5 votes |
@Override public T create(CreationalContext<T> context) { InjectionPoint ip = (InjectionPoint) bm.getInjectableReference(new InjectionPointMetadataInjectionPoint(), context); Annotated annotated = ip.getAnnotated(); ConfigProperty configProperty = annotated.getAnnotation(ConfigProperty.class); String key = ConfigProducerUtil.getConfigKey(ip, configProperty); String defaultValue = configProperty.defaultValue(); if (annotated.getBaseType() instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) annotated.getBaseType(); Type rawType = paramType.getRawType(); // handle Provider<T> and Instance<T> if (rawType instanceof Class && (((Class<?>) rawType).isAssignableFrom(Provider.class) || ((Class<?>) rawType).isAssignableFrom(Instance.class)) && paramType.getActualTypeArguments().length == 1) { Class<?> paramTypeClass = (Class<?>) paramType.getActualTypeArguments()[0]; return (T) getConfig().getValue(key, paramTypeClass); } } else { Class annotatedTypeClass = (Class) annotated.getBaseType(); if (defaultValue == null || defaultValue.length() == 0) { return (T) getConfig().getValue(key, annotatedTypeClass); } else { Config config = getConfig(); Optional<T> optionalValue = config.getOptionalValue(key, annotatedTypeClass); if (optionalValue.isPresent()) { return optionalValue.get(); } else { return (T) ((SmallRyeConfig) config).convert(defaultValue, annotatedTypeClass); } } } throw InjectionMessages.msg.unhandledConfigProperty(); }
Example #23
Source Project: pnc Author: project-ncl File: MessageSenderProvider.java License: Apache License 2.0 | 5 votes |
@Inject public MessageSenderProvider(Instance<MessageSender> messageSenders, SystemConfig config) throws MessagingConfigurationException { this.messageSenders = messageSenders; this.config = config; this.messageSender = selectMessageSender(); }
Example #24
Source Project: javamoney-lib Author: JavaMoney File: CDIAccessor.java License: Apache License 2.0 | 5 votes |
public static <T> Instance<T> getInstances(Class<T> instanceType, Annotation... qualifiers) { try { //noinspection ConstantConditions return getInstance(Instance.class).get().select(instanceType, qualifiers); } catch (Exception e) { LOG.info("Failed to load instances from CDI.", e); return emptyInstance(); } }
Example #25
Source Project: quarkus Author: quarkusio File: InstanceBean.java License: Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public Instance<?> get(CreationalContext<Instance<?>> creationalContext) { // Obtain current IP to get the required type and qualifiers InjectionPoint ip = InjectionPointProvider.get(); InstanceImpl<Instance<?>> instance = new InstanceImpl<Instance<?>>((InjectableBean<?>) ip.getBean(), ip.getType(), ip.getQualifiers(), (CreationalContextImpl<?>) creationalContext, Collections.EMPTY_SET, ip.getMember(), 0); CreationalContextImpl.addDependencyToParent((InjectableBean<Instance<?>>) ip.getBean(), instance, creationalContext); return instance; }
Example #26
Source Project: vraptor4 Author: caelum File: XStreamBuilderImpl.java License: Apache License 2.0 | 5 votes |
public static XStreamBuilder cleanInstance(Converter...converters) { Instance<Converter> convertersInst = new MockInstanceImpl<>(converters); Instance<SingleValueConverter> singleValueConverters = new MockInstanceImpl<>(); XStreamConverters xStreamConverters = new XStreamConverters(convertersInst, singleValueConverters); return new XStreamBuilderImpl(xStreamConverters, new DefaultTypeNameExtractor(), new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider()); }
Example #27
Source Project: quarkus Author: quarkusio File: DisposerTest.java License: Apache License 2.0 | 5 votes |
void dipose(@Disposes Long value, @MyQualifier String injectedString, Instance<Pong> pongs) { assertNotNull(injectedString); DISPOSED.set(value); pongs.forEach(p -> { assertEquals("OK", p.id); }); }
Example #28
Source Project: keycloak Author: keycloak File: VertxClientCertificateLookup.java License: Apache License 2.0 | 5 votes |
@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 #29
Source Project: quarkus Author: quarkusio File: BuiltInBeansAreResolvableTest.java License: Apache License 2.0 | 5 votes |
@SuppressWarnings({ "serial", "unchecked", "rawtypes" }) @Test public void testEventBean() { // use dynamic resolution to test it Instance<Object> instance = Arc.container().beanManager().createInstance(); // event with no qualifier and raw type Instance<Event> rawNoQualifier = instance.select(Event.class); assertTrue(rawNoQualifier.isResolvable()); DummyBean.resetCounters(); rawNoQualifier.get().fire(new Payload()); assertEquals(1, DummyBean.noQualifiers); assertEquals(0, DummyBean.qualifierTimesTriggered); assertEquals(1, DummyBean.timesTriggered); // event with type and no qualifier Instance<Event<Payload>> typedEventNoQualifier = instance.select(new TypeLiteral<Event<Payload>>() { }); assertTrue(typedEventNoQualifier.isResolvable()); DummyBean.resetCounters(); typedEventNoQualifier.get().fire(new Payload()); assertEquals(1, DummyBean.noQualifiers); assertEquals(0, DummyBean.qualifierTimesTriggered); assertEquals(1, DummyBean.timesTriggered); // event with type and qualifier Instance<Event<Payload>> typedEventWithQualifier = instance.select(new TypeLiteral<Event<Payload>>() { }, new DummyQualifier.Literal()); assertTrue(typedEventWithQualifier.isResolvable()); DummyBean.resetCounters(); typedEventWithQualifier.get().fire(new Payload()); assertEquals(1, DummyBean.noQualifiers); assertEquals(1, DummyBean.qualifierTimesTriggered); assertEquals(1, DummyBean.timesTriggered); }
Example #30
Source Project: quarkus Author: quarkusio File: BeanManagerInstanceTest.java License: Apache License 2.0 | 5 votes |
@Test public void testGetEvent() { BeanManager beanManager = Arc.container() .beanManager(); Instance<FuuService> instance = beanManager.createInstance() .select(FuuService.class); assertTrue(instance.isResolvable()); assertEquals(10, instance.get().age); }