當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。