当前位置: 首页>>代码示例>>Java>>正文


Java CDI类代码示例

本文整理汇总了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;
}
 
开发者ID:PaperCutSoftware,项目名称:dust-api,代码行数:21,代码来源:AuthenticatorFeature.java

示例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);

    }
 
开发者ID:Emerjoin,项目名称:Hi-Framework,代码行数:20,代码来源:HTMLizer.java

示例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);
}
 
开发者ID:eclipse,项目名称:microprofile-jwt-auth,代码行数:26,代码来源:TokenValidationTest.java

示例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);
   		}		
       }
}
 
开发者ID:FroMage,项目名称:redpipe,代码行数:24,代码来源:CdiPlugin.java

示例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);
}
 
开发者ID:Juraji,项目名称:Biliomi,代码行数:19,代码来源:SystemBoot.java

示例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);
}
 
开发者ID:Juraji,项目名称:Biliomi,代码行数:19,代码来源:SystemBoot.java

示例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;
}
 
开发者ID:katharsis-project,项目名称:katharsis-framework,代码行数:17,代码来源:CdiServiceDiscovery.java

示例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();
}
 
开发者ID:eclipse,项目名称:yasson,代码行数:24,代码来源:JsonbComponentInstanceCreatorFactory.java

示例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();
}
 
开发者ID:backpaper0,项目名称:sealion,代码行数:18,代码来源:PermissionProvider.java

示例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);
    }

}
 
开发者ID:rdebusscher,项目名称:octopus-jsr375,代码行数:24,代码来源:SamRegistrationInstaller.java

示例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();
}
 
开发者ID:rdebusscher,项目名称:octopus-jsr375,代码行数:25,代码来源:BasicAuthenticationMechanism.java

示例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);
	}
}
 
开发者ID:kamaladafrica,项目名称:axon-cdi-quickstart,代码行数:19,代码来源:Main.java

示例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()));
				}
			}
		}
	};
}
 
开发者ID:sebfz1,项目名称:wicket-quickstart-cdi-async,代码行数:24,代码来源:WorkflowBean.java

示例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));
}
 
开发者ID:progolden,项目名称:vraptor-boilerplate,代码行数:20,代码来源:UserSession.java


注:本文中的javax.enterprise.inject.spi.CDI类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。