下面列出了怎么用javax.enterprise.inject.Instance的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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);
}
}
@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);
}
/**
* 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();
}
}
/**
* 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();
}
}
/**
* 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();
}
}
/**
* 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();
}
}
/**
* 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");
}
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;
}
@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);
}
}
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();
}
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();
}
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;
}
@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;
}
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;
}
@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;
}
@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;
}
@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);
}
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());
}
@Inject
public ExecutionHolder(Instance<Vertx> instanceOfVertx) {
if (instanceOfVertx == null || instanceOfVertx.isUnsatisfied()) {
internalVertxInstance = true;
this.vertx = Vertx.vertx();
log.vertXInstanceCreated();
} else {
this.vertx = instanceOfVertx.get();
}
}
@Context
public void setApplication(final Application application) {
final Instance<Loader> loader = CDI.current().select(Loader.class);
if (!loader.isUnsatisfied()) {
loader.iterator().next().useServletContext();
}
}
@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();
}
@Inject
public MessageSenderProvider(Instance<MessageSender> messageSenders, SystemConfig config)
throws MessagingConfigurationException {
this.messageSenders = messageSenders;
this.config = config;
this.messageSender = selectMessageSender();
}
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();
}
}
@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;
}
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());
}
void dipose(@Disposes Long value, @MyQualifier String injectedString, Instance<Pong> pongs) {
assertNotNull(injectedString);
DISPOSED.set(value);
pongs.forEach(p -> {
assertEquals("OK", p.id);
});
}
@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;
}
@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);
}
@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);
}