本文整理汇总了Java中javax.enterprise.inject.spi.CDI类的典型用法代码示例。如果您正苦于以下问题:Java CDI类的具体用法?Java CDI怎么用?Java CDI使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CDI类属于javax.enterprise.inject.spi包,在下文中一共展示了CDI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: configure
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Override
public boolean configure(final FeatureContext featureContext) {
final UserRepository userRepo = CDI.current().select(UserRepository.class).get();
final Authenticator<String, User> authenticator = new GoogleAuthenticator(
authConfig.getClientId(), userRepo, authConfig.getHostedDomain()
);
final Authenticator<String, User> cachingAuthenticator = new CachingAuthenticator<>(
metricRegistry, authenticator, authConfig.getAuthenticationCachePolicy()
);
featureContext.register(new AuthDynamicFeature(
new OAuthCredentialAuthFilter.Builder<User>()
.setAuthenticator(cachingAuthenticator)
.setPrefix("Bearer")
.buildAuthFilter()));
featureContext.register(new AuthValueFactoryProvider.Binder<>(User.class));
return true;
}
示例2: testProducer
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Test
public void testProducer() {
logger.info("starting producer spi test");
CDI<Object> cdi = current();
BeanManager beanManager = cdi.select(BeanManager.class).get();
AnnotatedField<? super AnotherFactory> field = this
.<AnotherFactory, AnnotatedField<AnotherFactory>>getAnnotatedMember(AnotherFactory.class, "jessie",
beanManager);
Bean<AnotherFactory> declaringBean = cast(beanManager.resolve(beanManager.getBeans(AnotherFactory.class)));
ProducerFactory<AnotherFactory> producerFactory = beanManager.getProducerFactory(field, declaringBean);
Producer<Toy> producer = cast(producerFactory.createProducer(null));
assertNotNull(producer);
assertTrue(producer.getInjectionPoints().isEmpty());
Toy jessie = producer.produce(beanManager.<Toy>createCreationalContext(null));
assertEquals("Jessie", jessie.getName());
}
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:18,代码来源:InjectSPITestCase.java
示例3: getAppData
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
private String getAppData(){
activeUser = CDI.current().select(ActiveUser.class).get();
CharSequence http = "http://";
CharSequence https = "https://";
AppContext appContext = CDI.current().select(AppContext.class).get();
Gson gson = new Gson();
Map map = new HashMap();
map.put("base_url", requestContext.getBaseURL());
map.put("base64_url", new BASE64Encoder().encode(requestContext.getBaseURL().getBytes()));
map.put("simple_base_url", requestContext.getBaseURL().replace(http,"").replace(https,""));
map.put("deployId",appContext.getDeployId());
map.put("deployMode",appContext.getDeployMode().toString());
map.put("csrfToken",activeUser.getCsrfToken());
return gson.toJson(map);
}
示例4: loadTokenParser
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@BeforeClass(alwaysRun=true)
public static void loadTokenParser() throws Exception {
System.out.printf("TokenValidationTest.initClass\n");
publicKey = TokenUtils.readPublicKey("/publicKey.pem");
if(publicKey == null) {
throw new IllegalStateException("Failed to load /publicKey.pem resource");
}
// Load the ITokenParser via the ServiceLoader
ServiceLoader<ITokenParser> serviceLoader = ServiceLoader.load(ITokenParser.class);
if(serviceLoader.iterator().hasNext() == false) {
// Try to obtain ITokenParser via CDI
tokenParser = CDI.current().select(ITokenParser.class).get();
if(tokenParser == null) {
throw new IllegalStateException(String.format("An %s service provider or producer is required", ITokenParser.class.getName()));
}
}
else {
tokenParser = serviceLoader.iterator().next();
if (tokenParser == null) {
throw new IllegalStateException(String.format("Service provider for %s produced a null parser", ITokenParser.class.getName()));
}
}
System.out.printf("Using ITokenParser: %s\n", tokenParser);
}
示例5: aroundRequest
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Override
public void aroundRequest(HttpRequest req, RunnableWithException<IOException> continuation) throws IOException {
BoundRequestContext cdiContext = CDI.current().select(BoundRequestContext.class).get();
Map<String,Object> contextMap = new HashMap<String,Object>();
cdiContext.associate(contextMap);
cdiContext.activate();
try {
// FIXME: associate CDI thread context on thread change, like Resteasy context?
continuation.run();
}finally {
if(req.getAsyncContext().isSuspended()) {
req.getAsyncContext().getAsyncResponse().register((CompletionCallback)(t) -> {
cdiContext.invalidate();
cdiContext.deactivate();
cdiContext.dissociate(contextMap);
});
}else {
cdiContext.invalidate();
cdiContext.deactivate();
cdiContext.dissociate(contextMap);
}
}
}
示例6: runInstallTasks
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
private void runInstallTasks() {
logger.info("Running installation tasks...");
List<Class<? extends SetupTask>> setupTasksClasses = findSetupTasksAndPrioritize();
setupTasksClasses.forEach(setupTaskClass -> {
SetupTask setupTask = CDI.current().select(setupTaskClass).get();
try {
logger.info("Installation task: {}", setupTask.getDisplayName());
setupTask.install();
} catch (Exception e) {
logger.error("Error while running installation task: {}", setupTask.getDisplayName(), e);
} finally {
CDI.current().destroy(setupTask);
}
});
logger.info("Installation tasks completed, do not forget to change biliomi.core.updateMode to {}", UpdateModeType.OFF);
}
示例7: runUpdateTasks
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
private void runUpdateTasks() {
logger.info("Running update tasks...");
List<Class<? extends SetupTask>> setupTasksClasses = findSetupTasksAndPrioritize();
setupTasksClasses.forEach(setupTaskClass -> {
SetupTask setupTask = CDI.current().select(setupTaskClass).get();
try {
logger.info("Update task: {}", setupTask.getDisplayName());
setupTask.update();
} catch (Exception e) {
logger.error("Error while running update task: {}", setupTask.getDisplayName(), e);
} finally {
CDI.current().destroy(setupTask);
}
});
logger.info("Update tasks completed, do not forget to change biliomi.core.updateMode to {}\n", UpdateModeType.OFF);
}
示例8: getInstancesByAnnotation
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
BeanManager beanManager = CDI.current().getBeanManager();
Set<Bean<?>> beans = beanManager.getBeans(Object.class);
List<Object> list = new ArrayList<>();
for (Bean<?> bean : beans) {
Class<?> beanClass = bean.getBeanClass();
Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
if (annotation.isPresent()) {
CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
Object object = beanManager.getReference(bean, beanClass, creationalContext);
list.add(object);
}
}
return list;
}
示例9: getComponentInstanceCreator
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
/**
* First check a CDI provider, if available use those.
* Try to lookup in a JNDI if no provider is registered.
* If one of the above is found {@link BeanManagerInstanceCreator} is returned,
* or {@link DefaultConstructorCreator} otherwise.
* @return Component instance creator, either CDI or default constructor.
*/
public static JsonbComponentInstanceCreator getComponentInstanceCreator() {
try {
return new BeanManagerInstanceCreator(CDI.current().getBeanManager());
} catch (Throwable e) {
log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_NO_PROVIDER));
try {
InitialContext context = new InitialContext();
final BeanManager lookup = (BeanManager) context.lookup(BEAN_MANAGER_NAME);
return new BeanManagerInstanceCreator(lookup);
} catch (NamingException e1) {
log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_JNDI, BEAN_MANAGER_NAME, e1.getExplanation()));
}
}
log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_USING_DEFAULT));
return new DefaultConstructorCreator();
}
示例10: filter
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Instance<Object> instance = CDI.current();
User user = instance.select(User.class).get();
List<AccountRole> roles = user.getAccountRoles();
if (Arrays.stream(permissions.roles()).anyMatch(roles::contains)) {
return;
}
Permission permission = instance.select(permissions.value()).get();
if (permission.test(requestContext)) {
return;
}
throw new ForbiddenException();
}
示例11: onStartup
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
// Obtain a reference to the CdiExtension that was used to see if
// there's an enabled bean
CdiExtension cdiExtension = CDI.current().select(CdiExtension.class).get();
if (cdiExtension.isHttpAuthenticationMechanismFound()) {
// A SAM must be registered at this point, since the programmatically added
// Listener is for some reason restricted (not allow) from calling
// getVirtualServerName. At this point we're still allowed to call this.
// TODO: Ask the Servlet EG to address this? Is there any ground for this restriction???
registerServerAuthModule(new HttpBridgeServerAuthModule(), ctx);
// Add a listener so we can process the context destroyed event, which is needed
// to de-register the SAM correctly.
ctx.addListener(this);
}
}
示例12: validateRequest
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
@Override
public AuthStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMsgContext) throws AuthException {
String[] credentials = getCredentials(request);
if (!isEmpty(credentials)) {
IdentityStore identityStore = CDI.current().select(IdentityStore.class).get();
CredentialValidationResult result = identityStore.validate(
new UsernamePasswordCredential(credentials[0], new Password(credentials[1])));
if (result.getStatus() == VALID) {
return httpMsgContext.notifyContainerAboutLogin(
result.getCallerName(), result.getCallerGroups());
}
}
if (httpMsgContext.isProtected()) {
response.setHeader("WWW-Authenticate", basicHeaderValue);
return httpMsgContext.responseUnAuthorized();
}
return httpMsgContext.doNothing();
}
示例13: main
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
final CdiContainer container = CdiContainerLoader.getCdiContainer();
try {
container.boot();
ContextControl contextControl = container.getContextControl();
contextControl.startContext(ApplicationScoped.class);
Quickstart quickstart = CDI.current().select(Quickstart.class).get();
quickstart.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
container.shutdown();
System.out.println("Shutting down...");
System.exit(0);
}
}
示例14: newWorkflowRunnable
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
private Runnable newWorkflowRunnable(final IWorkflowListener listener)
{
return new Runnable() {
@Override
public void run()
{
LOG.info("Workflow started... {}", CDI.current());
for (IWorkflowStep step : newWorkflowSteps(listener))
{
try
{
step.run(); /* sync */
}
catch (WorkflowException e)
{
listener.onException(String.format(EXCEPTION_PATTERN, "Workflow", e.getMessage()));
}
}
}
};
}
示例15: login
import javax.enterprise.inject.spi.CDI; //导入依赖的package包/类
public void login(UserAccessToken token) {
this.logout();
this.accessToken = token;
UserBS bs = CDI.current().select(UserBS.class).get();
// TODO Recuperar as permissões de fato.
List<UserPermission> perms = null;
if (GeneralUtils.isEmpty(perms)) {
this.permissions = new ArrayList<String>();
} else {
this.permissions = new ArrayList<String>(perms.size());
for (UserPermission perm : perms) {
this.permissions.add(perm.getPermission());
}
}
this.accessLevel = token.getUser().getAccessLevel();
this.loginEvent.fire(new AuthEvent(this.accessToken));
}