Java 类javax.enterprise.inject.Any 实例源码

项目:Camel    文件:CdiCamelFactory.java   
@Uri("")
@Produces
@Typed(MockEndpoint.class)
// Qualifiers are dynamically added in CdiCamelExtension
private static MockEndpoint mockEndpointFromUri(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) {
    Uri uri = getQualifierByType(ip, Uri.class).get();
    try {
        CamelContext context = uri.context().isEmpty()
            ? selectContext(ip, instance, extension)
            : selectContext(uri.context(), instance);
        return context.getEndpoint(uri.value(), MockEndpoint.class);
    } catch (Exception cause) {
        throw new InjectionException("Error injecting mock endpoint annotated with " + uri
            + " into " + ip, cause);
    }
}
项目:acmeair-modular    文件:ServiceLocator.java   
/**
 * Retrieves the services that are available for use with the description for each service. 
 * The Services are determined by looking up all of the implementations of the 
 * Customer Service interface that are using the  DataService qualifier annotation. 
 * The DataService annotation contains the service name and description information. 
 * @return Map containing a list of services available and a description of each one.
 */
public Map<String,String> getServices (){
    TreeMap<String,String> services = new TreeMap<String,String>();
    logger.fine("Getting CustomerService Impls");
    Set<Bean<?>> beans = beanManager.getBeans(CustomerService.class,new AnnotationLiteral<Any>() {
        private static final long serialVersionUID = 1L;});
    for (Bean<?> bean : beans) {            
        for (Annotation qualifer: bean.getQualifiers()){
            if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){
                DataService service = (DataService) qualifer;
                logger.fine("   name="+service.name()+" description="+service.description());
                services.put(service.name(), service.description());
            }
        }
    }       
    return services;
}
项目:weld-vertx    文件:AsyncReferenceImpl.java   
@Inject
public AsyncReferenceImpl(InjectionPoint injectionPoint, Vertx vertx, BeanManager beanManager, @Any WeldInstance<Object> instance) {
    this.isDone = new AtomicBoolean(false);
    this.future = new VertxCompletableFuture<>(vertx);
    this.instance = instance;

    ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType();
    Type requiredType = parameterizedType.getActualTypeArguments()[0];
    Annotation[] qualifiers = injectionPoint.getQualifiers().toArray(new Annotation[] {});

    // First check if there is a relevant async producer method available
    WeldInstance<Object> completionStage = instance.select(new ParameterizedTypeImpl(CompletionStage.class, requiredType), qualifiers);

    if (completionStage.isAmbiguous()) {
        failure(new AmbiguousResolutionException(
                "Ambiguous async producer methods for type " + requiredType + " with qualifiers " + injectionPoint.getQualifiers()));
    } else if (!completionStage.isUnsatisfied()) {
        // Use the produced CompletionStage
        initWithCompletionStage(completionStage.getHandler());
    } else {
        // Use Vertx worker thread
        initWithWorker(requiredType, qualifiers, vertx, beanManager);
    }
}
项目:switchyard    文件:ClientProxyBean.java   
/**
 * Public constructor.
 *
 * @param serviceName   The name of the ESB Service being proxied to.
 * @param proxyInterface The proxy Interface.
 * @param qualifiers     The CDI bean qualifiers.  Copied from the injection point.
 * @param beanDeploymentMetaData Deployment metadata.
 */
public ClientProxyBean(String serviceName, Class<?> proxyInterface, Set<Annotation> qualifiers, BeanDeploymentMetaData beanDeploymentMetaData) {
    this._serviceName = serviceName;
    this._serviceInterface = proxyInterface;

    if (qualifiers != null) {
        this._qualifiers = qualifiers;
    } else {
        this._qualifiers = new HashSet<Annotation>();
        this._qualifiers.add(new AnnotationLiteral<Default>() {
        });
        this._qualifiers.add(new AnnotationLiteral<Any>() {
        });
    }

    _proxyBean = Proxy.newProxyInstance(beanDeploymentMetaData.getDeploymentClassLoader(),
            new Class[]{_serviceInterface},
            new ClientProxyInvocationHandler(_serviceInterface));
}
项目:hawkular-metrics    文件:RESTMetrics.java   
public void initMetrics() throws IOException {
    String hostname = metricNameService.getHostName();

    Observable.from(beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {}))
            .map(Bean::getBeanClass)
            .filter(this::isRESTHandler)
            .flatMap(c -> Observable.from(c.getMethods()))
            .filter(this::isRESTHandlerMethod)
            .subscribe(
                    method -> {
                        HTTPMethod httpMethod = getHttpMethod(method);
                        String uri = getURI(method);
                        if (isWrite(method, uri)) {
                            register(RESTMetaData.forWrite(httpMethod, uri, hostname));
                        } else {
                            register(RESTMetaData.forRead(httpMethod, uri, hostname));
                        }
                    },
                    t -> logger.warn("Failed to register meta data for REST metrics", t),
                    () -> {}
            );
}
项目:camel-cdi    文件:RawEventEndpointTest.java   
@Test
public void sendMessageToProducer(@Uri("direct:produce") ProducerTemplate producer) throws InterruptedException {
    long random =  Math.round(Math.random() * Long.MAX_VALUE);

    produced.expectedMessageCount(1);
    produced.expectedBodiesReceived(random);
    produced.message(0).predicate(exchange -> {
        EventMetadata metadata = exchange.getIn().getHeader("metadata", EventMetadata.class);
        return metadata.getType().equals(Long.class) && metadata.getQualifiers().equals(new HashSet<>(Arrays.asList(new AnnotationLiteral<Any>() {}, new AnnotationLiteral<Default>() {})));
    });

    consumed.expectedMessageCount(1);
    consumed.expectedBodiesReceived(random);

    producer.sendBody(random);

    assertIsSatisfied(2L, TimeUnit.SECONDS, consumed, produced);
}
项目:marmotta    文件:StatisticsServiceImpl.java   
/**
 * Initialise all statistics modules that are found in the system
 * @param modules
 */
@Inject
protected void initModules(@Any Instance<StatisticsModule> modules) {
    log.info("Apache Marmotta StatisticsService starting up ...");

    this.modules = new LinkedHashMap<String,StatisticsModule>();

    for(StatisticsModule module : modules) {
        registerModule(module.getName(),module);
    }

    if(configurationService.getBooleanConfiguration("statistics.enabled",false)) {
        enableAll();
    } else {
        disableAll();
    }
}
项目:onlinepay    文件:InjectingConstraintValidatorFactory.java   
@SuppressWarnings("unchecked")
private static <T> T getBeanInstance(final Class<T> type) throws Exception {
    BeanManager beanManager = getBeanManager();

       final Set<Bean<?>> beans = beanManager.getBeans(Object.class,new AnnotationLiteral<Any>() {

        private static final long serialVersionUID = 3612602223649004820L;});

       for (Bean<?> iterateBean : beans) {
           if(iterateBean.getBeanClass().getName() == type.getName()){
            Bean<T> bean = (Bean<T>) iterateBean;
               final CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
               return (T) beanManager.getReference(bean, type,creationalContext);
           }
       }
       return null;
}
项目:clickpay    文件:InjectingConstraintValidatorFactory.java   
@SuppressWarnings("unchecked")
private static <T> T getBeanInstance(final Class<T> type) throws Exception {
    BeanManager beanManager = getBeanManager();

       final Set<Bean<?>> beans = beanManager.getBeans(Object.class,new AnnotationLiteral<Any>() {

        private static final long serialVersionUID = 3612602223649004820L;});

       for (Bean<?> iterateBean : beans) {
           if(iterateBean.getBeanClass().getName() == type.getName()){
            Bean<T> bean = (Bean<T>) iterateBean;
               final CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
               return (T) beanManager.getReference(bean, type,creationalContext);
           }
       }
       return null;
}
项目:kie-wb-common    文件:SessionPreviewImpl.java   
@Inject
public SessionPreviewImpl(final DefinitionManager definitionManager,
                          final ShapeManager shapeManager,
                          final TextPropertyProviderFactory textPropertyProviderFactory,
                          final CanvasCommandManager<AbstractCanvasHandler> canvasCommandManager,
                          final DefinitionUtils definitionUtils,
                          final GraphUtils graphUtils,
                          final @Any ManagedInstance<BaseCanvasHandler> canvasHandlerFactories,
                          final @Any ManagedInstance<CanvasCommandFactory> canvasCommandFactories,
                          final @MultipleSelection SelectionControl<AbstractCanvasHandler, ?> selectionControl,
                          final WidgetWrapperView view) {
    super(definitionManager,
          shapeManager,
          textPropertyProviderFactory,
          canvasCommandManager,
          definitionUtils,
          graphUtils,
          canvasHandlerFactories,
          canvasCommandFactories,
          selectionControl,
          view);
}
项目:kie-wb-common    文件:LRUBuilderCache.java   
@Inject
public LRUBuilderCache(final @Named("ioStrategy") IOService ioService,
                       final KieModuleService moduleService,
                       final ProjectImportsService importsService,
                       final @Any Instance<BuildValidationHelper> buildValidationHelperBeans,
                       final @Named("LRUModuleDependenciesClassLoaderCache") LRUModuleDependenciesClassLoaderCache dependenciesClassLoaderCache,
                       final @Named("LRUPomModelCache") LRUPomModelCache pomModelCache,
                       final PackageNameWhiteListService packageNameWhiteListService,
                       final @JavaSourceFilter Instance<Predicate<String>> classFilterBeans) {
    this.ioService = ioService;
    this.moduleService = moduleService;
    this.importsService = importsService;
    this.buildValidationHelperBeans = buildValidationHelperBeans;
    this.dependenciesClassLoaderCache = dependenciesClassLoaderCache;
    this.pomModelCache = pomModelCache;
    this.packageNameWhiteListService = (PackageNameWhiteListServiceImpl) packageNameWhiteListService;
    this.classFilterBeans = classFilterBeans;
}
项目:kie-wb-common    文件:ClientProjectSessionManager.java   
@Inject
public ClientProjectSessionManager(final DefinitionUtils definitionUtils,
                                   final @Any ManagedInstance<ClientSessionFactory> sessionFactoriesInstances,
                                   final Event<SessionOpenedEvent> sessionOpenedEvent,
                                   final Event<SessionDestroyedEvent> sessionDestroyedEvent,
                                   final Event<SessionPausedEvent> sessionPausedEvent,
                                   final Event<SessionResumedEvent> sessionResumedEvent,
                                   final Event<OnSessionErrorEvent> sessionErrorEvent) {
    super(definitionUtils,
          sessionFactoriesInstances,
          sessionOpenedEvent,
          sessionDestroyedEvent,
          sessionPausedEvent,
          sessionResumedEvent,
          sessionErrorEvent);
}
项目:kie-wb-common    文件:ClientSessionManagerImpl.java   
@Inject
public ClientSessionManagerImpl(final DefinitionUtils definitionUtils,
                                final @Any ManagedInstance<ClientSessionFactory> sessionFactoriesInstances,
                                final Event<SessionOpenedEvent> sessionOpenedEvent,
                                final Event<SessionDestroyedEvent> sessionDestroyedEvent,
                                final Event<SessionPausedEvent> sessionPausedEvent,
                                final Event<SessionResumedEvent> sessionResumedEvent,
                                final Event<OnSessionErrorEvent> sessionErrorEvent) {
    this.definitionUtils = definitionUtils;
    this.sessionFactoriesInstances = sessionFactoriesInstances;
    this.sessionOpenedEvent = sessionOpenedEvent;
    this.sessionPausedEvent = sessionPausedEvent;
    this.sessionResumedEvent = sessionResumedEvent;
    this.sessionDestroyedEvent = sessionDestroyedEvent;
    this.sessionErrorEvent = sessionErrorEvent;
}
项目:kie-wb-common    文件:RestRuntimeProvisioningServiceImpl.java   
@PostConstruct
public void cacheBeans() {
    LOG.info("> Initializing ProviderTypes. ");
    final Set<Bean<?>> beans = beanManager.getBeans(ProviderType.class,
                                                    new AnnotationLiteral<Any>() {
                                                    });
    for (final Bean b : beans) {
        try {
            // I don't want to register the CDI proxy, I need a fresh instance :(
            ProviderType pt = (ProviderType) b.getBeanClass().newInstance();
            LOG.info("> Registering ProviderType: " + pt.getProviderTypeName());
            runtimeRegistry.registerProviderType(pt);
        } catch (InstantiationException | IllegalAccessException ex) {
            LOG.error("Something went wrong with registering Provider Types!",
                      ex);
        }
    }
}
项目:kie-wb-common    文件:NewDeployWizard.java   
@Inject
public NewDeployWizard(final SelectPipelinePagePresenter selectPipelinePage,
                       final ManagedInstance<PipelineParamsPagePresenter> pipelineParamsPageInstance,
                       final @Any Instance<PipelineDescriptor> pipelineDescriptorInstance,
                       final PopupHelper popupHelper,
                       final TranslationService translationService,
                       final Caller<RuntimeService> runtimeService,
                       final Event<NotificationEvent> notification,
                       final Event<RefreshRuntimeEvent> refreshRuntimeEvent) {
    super(translationService,
          notification);
    this.popupHelper = popupHelper;
    this.selectPipelinePage = selectPipelinePage;
    this.pipelineParamsPageInstance = pipelineParamsPageInstance;
    this.pipelineDescriptorInstance = pipelineDescriptorInstance;
    this.runtimeService = runtimeService;
    this.refreshRuntimeEvent = refreshRuntimeEvent;
}
项目:joynr    文件:ServiceProviderDiscovery.java   
@SuppressWarnings("serial")
public Set<Bean<?>> findServiceProviderBeans() {
    Set<Bean<?>> result = new HashSet<>();
    for (Bean<?> bean : beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })) {
        ServiceProvider serviceProvider = bean.getBeanClass().getAnnotation(ServiceProvider.class);
        if (serviceProvider != null) {
            ProvidedBy providedBy = getProvidedByAnnotation(serviceProvider.serviceInterface());
            verifyProvidedBy(providedBy, serviceProvider.serviceInterface(), bean);
            result.add(bean);
            if (LOG.isTraceEnabled()) {
                LOG.trace(format("Bean %s is a service provider. Adding to result.", bean));
            }
        } else if (LOG.isTraceEnabled()) {
            LOG.trace(format("Ignoring bean: %s", bean));
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(format("Found the following service provider beans:%n%s", result));
    }
    return result;
}
项目:joynr    文件:DefaultJoynrRuntimeFactory.java   
private AbstractModule getMessageProcessorsModule() {
    final Set<Bean<?>> joynrMessageProcessorBeans = beanManager.getBeans(JoynrMessageProcessor.class,
                                                                         new AnnotationLiteral<Any>() {
                                                                             private static final long serialVersionUID = 1L;
                                                                         });
    return new AbstractModule() {
        @SuppressWarnings("unchecked")
        @Override
        protected void configure() {

            Multibinder<JoynrMessageProcessor> joynrMessageProcessorMultibinder = Multibinder.newSetBinder(binder(),
                                                                                                           new TypeLiteral<JoynrMessageProcessor>() {
                                                                                                           });
            for (Bean<?> bean : joynrMessageProcessorBeans) {
                joynrMessageProcessorMultibinder.addBinding()
                                                .toInstance((JoynrMessageProcessor) Proxy.newProxyInstance(getClass().getClassLoader(),
                                                                                                           new Class[]{
                                                                                                                   JoynrMessageProcessor.class },
                                                                                                           new BeanCallingProxy<JoynrMessageProcessor>((Bean<JoynrMessageProcessor>) bean,
                                                                                                                                                       beanManager)));
            }
        }
    };
}
项目:joynr    文件:ServiceProviderDiscoveryTest.java   
@SuppressWarnings({ "unchecked", "serial" })
@Test
public void testFindServiceProviderBeans() {
    BeanManager mockBeanManager = mock(BeanManager.class);

    Bean<DummyBeanOne> mockBeanOne = mock(Bean.class);
    Mockito.doReturn(DummyBeanOne.class).when(mockBeanOne).getBeanClass();
    Bean<DummyBeanTwo> mockBeanTwo = mock(Bean.class);
    Mockito.doReturn(DummyBeanTwo.class).when(mockBeanTwo).getBeanClass();

    Set<Bean<?>> beans = new HashSet<>();
    beans.add(mockBeanOne);
    beans.add(mockBeanTwo);
    Mockito.when(mockBeanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })).thenReturn(beans);

    ServiceProviderDiscovery subject = new ServiceProviderDiscovery(mockBeanManager);

    Set<Bean<?>> result = subject.findServiceProviderBeans();

    assertNotNull(result);
    assertEquals(1, result.size());
    assertTrue(result.iterator().next().getBeanClass().equals(DummyBeanOne.class));
}
项目:joynr    文件:ServiceProviderDiscoveryTest.java   
@Test(expected = IllegalArgumentException.class)
public void testInvalidServiceInterfaceSpecified() {
    BeanManager mockBeanManager = mock(BeanManager.class);

    Bean<DummyBeanOne> mockBeanOne = mock(Bean.class);
    Mockito.doReturn(DummyBeanOne.class).when(mockBeanOne).getBeanClass();
    Bean<DummyBeanFour> mockBeanThree = mock(Bean.class);
    Mockito.doReturn(DummyBeanThree.class).when(mockBeanThree).getBeanClass();

    Set<Bean<?>> beans = new HashSet<>();
    beans.add(mockBeanOne);
    beans.add(mockBeanThree);
    Mockito.when(mockBeanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })).thenReturn(beans);

    ServiceProviderDiscovery subject = new ServiceProviderDiscovery(mockBeanManager);

    subject.findServiceProviderBeans();
    fail("Shouldn't be able to get here with an invalid bean (DummyBeanThree)");
}
项目:joynr    文件:ServiceProviderDiscoveryTest.java   
@Test(expected = IllegalArgumentException.class)
public void testWrongServiceInterfaceSpecified() {
    BeanManager mockBeanManager = mock(BeanManager.class);

    Bean<DummyBeanOne> mockBeanOne = mock(Bean.class);
        Mockito.doReturn(DummyBeanOne.class).when(mockBeanOne).getBeanClass();
    Bean<DummyBeanFour> mockBeanFour = mock(Bean.class);
        Mockito.doReturn(DummyBeanFour.class).when(mockBeanFour).getBeanClass();

    Set<Bean<?>> beans = new HashSet<>();
        beans.add(mockBeanOne);
        beans.add(mockBeanFour);
        Mockito.when(mockBeanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })).thenReturn(beans);

    ServiceProviderDiscovery subject = new ServiceProviderDiscovery(mockBeanManager);

    subject.findServiceProviderBeans();
    fail("Shouldn't be able to get here with an invalid bean (DummyBeanFour)");
}
项目:deltaspike    文件:TransactionStrategyHelper.java   
/**
 * <p>This method uses the InvocationContext to scan the &#064;Transactional
 * interceptor for a manually specified Qualifier.</p>
 *
 * <p>If none is given (defaults to &#04;Any.class) then we scan the intercepted
 * instance and resolve the Qualifiers of all it's injected EntityManagers.</p>
 *
 * <p>Please note that we will only pickup the first Qualifier on the
 * injected EntityManager. We also do <b>not</b> parse for binding or
 * &h#064;NonBinding values. A &#064;Qualifier should not have any parameter at all.</p>
 * @param entityManagerMetadata the metadata to locate the entity manager
 * @param interceptedTargetClass the Class of the intercepted target
 */
public Set<Class<? extends Annotation>> resolveEntityManagerQualifiers(EntityManagerMetadata entityManagerMetadata,
                                                                       Class interceptedTargetClass)
{
    Set<Class<? extends Annotation>> emQualifiers = new HashSet<Class<? extends Annotation>>();
    Class<? extends Annotation>[] qualifierClasses = entityManagerMetadata.getQualifiers();

    if (qualifierClasses == null || qualifierClasses.length == 1 && Any.class.equals(qualifierClasses[0]) )
    {
        // this means we have no special EntityManager configured in the interceptor
        // thus we should scan all the EntityManagers ourselfs from the intercepted class
        collectEntityManagerQualifiersOnClass(emQualifiers, interceptedTargetClass);
    }
    else
    {
        // take the qualifierKeys from the qualifierClasses
        Collections.addAll(emQualifiers, qualifierClasses);
    }

    //see DELTASPIKE-320
    if (emQualifiers.isEmpty())
    {
        emQualifiers.add(Default.class);
    }
    return emQualifiers;
}
项目:deltaspike    文件:ConversationKey.java   
public ConversationKey(Class<?> groupKey, Annotation... qualifiers)
{
    this.groupKey = groupKey;

    //TODO maybe we have to add a real qualifier instead
    Class<? extends Annotation> annotationType;
    for (Annotation qualifier : qualifiers)
    {
        annotationType = qualifier.annotationType();

        if (Any.class.isAssignableFrom(annotationType) ||
                Default.class.isAssignableFrom(annotationType) ||
                Named.class.isAssignableFrom(annotationType) ||
                ConversationGroup.class.isAssignableFrom(annotationType))
        {
            //won't be used for this key!
            continue;
        }

        if (this.qualifiers == null)
        {
            this.qualifiers = new HashSet<Annotation>();
        }
        this.qualifiers.add(qualifier);
    }
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:BankFactory.java   
@Produces
@BankProducer
public Bank createBank(@Any Instance<Bank> instance, InjectionPoint injectionPoint) {

    Annotated annotated = injectionPoint.getAnnotated();
    BankType bankTypeAnnotation = annotated.getAnnotation(BankType.class);
    Class<? extends Bank> bankType = bankTypeAnnotation.value().getBankType();
    return instance.select(bankType).get();
}
项目:weld-vertx    文件:VertxExtension.java   
public void registerBeansAfterBeanDiscovery(@Observes AfterBeanDiscovery event) {
    if (vertx == null) {
        // Do no register beans - no Vertx instance available during bootstrap
        return;
    }
    // Allow to inject Vertx used to deploy the WeldVerticle
    event.addBean().types(getBeanTypes(vertx.getClass(), Vertx.class)).addQualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE)
            .scope(ApplicationScoped.class).createWith(c -> vertx);
    // Allow to inject Context of the WeldVerticle
    event.addBean().types(getBeanTypes(context.getClass(), Context.class)).addQualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE)
            .scope(ApplicationScoped.class).createWith(c -> context);
}
项目:wildfly-swarm    文件:ValueProducerBeanAttributes.java   
public ValueProducerBeanAttributes(Set<Type> myTypes, MPJWTExtension.ClaimIP claimIP, Class<? extends Annotation> scope) {
    this.myTypes = myTypes;
    this.myQualifiers = new HashSet<>();
    this.claimIP = claimIP;
    this.myQualifiers.add(claimIP.getClaim());
    this.myQualifiers.add(new AnnotationLiteral<Any>() {
    });
    this.scope = scope;
}
项目:Camel    文件:CdiCamelFactory.java   
@Produces
@Default @Uri("")
// Qualifiers are dynamically added in CdiCamelExtension
private static ProducerTemplate producerTemplate(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) {
    return getQualifierByType(ip, Uri.class)
        .map(uri -> producerTemplateFromUri(ip, instance, extension, uri))
        .orElseGet(() -> defaultProducerTemplate(ip, instance, extension));
}
项目:Camel    文件:CdiCamelFactory.java   
private static ProducerTemplate producerTemplateFromUri(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension, Uri uri) {
    try {
        CamelContext context = uri.context().isEmpty()
            ? selectContext(ip, instance, extension)
            : selectContext(uri.context(), instance);
        ProducerTemplate producerTemplate = context.createProducerTemplate();
        Endpoint endpoint = context.getEndpoint(uri.value(), Endpoint.class);
        producerTemplate.setDefaultEndpoint(endpoint);
        return producerTemplate;
    } catch (Exception cause) {
        throw new InjectionException("Error injecting producer template annotated with " + uri + " into " + ip, cause);
    }
}
项目:Camel    文件:CdiCamelFactory.java   
private static ProducerTemplate defaultProducerTemplate(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) {
    try {
        CamelContext context = selectContext(ip, instance, extension);
        return context.createProducerTemplate();
    } catch (Exception cause) {
        throw new InjectionException("Error injecting producer template into " + ip, cause);
    }
}
项目:Camel    文件:CdiCamelFactory.java   
@Produces
@Typed(MockEndpoint.class)
// Qualifiers are dynamically added in CdiCamelExtension
private static MockEndpoint mockEndpointFromMember(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) {
    String uri = "mock:" + ip.getMember().getName();
    try {
        return selectContext(ip, instance, extension).getEndpoint(uri, MockEndpoint.class);
    } catch (Exception cause) {
        throw new InjectionException("Error injecting mock endpoint into " + ip, cause);
    }
}
项目:Camel    文件:CdiCamelFactory.java   
@Mock
@Produces
@Typed(MockEndpoint.class)
// Qualifiers are dynamically added in CdiCamelExtension
private static MockEndpoint createMockEndpoint(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) {
    Mock mock = getQualifierByType(ip, Mock.class).get();
    try {
        CamelContext context = mock.context().isEmpty()
            ? selectContext(ip, instance, extension)
            : selectContext(mock.context(), instance);
        return context.getEndpoint(mock.value(), MockEndpoint.class);
    } catch (Exception cause) {
        throw new InjectionException("Error injecting mock endpoint annotated with " + mock + " into " + ip, cause);
    }
}
项目:Camel    文件:CdiCamelFactory.java   
@Uri("")
@Produces
// Qualifiers are dynamically added in CdiCamelExtension
private static Endpoint endpoint(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) {
    Uri uri = getQualifierByType(ip, Uri.class).get();
    try {
        CamelContext context = uri.context().isEmpty()
            ? selectContext(ip, instance, extension)
            : selectContext(uri.context(), instance);
        return context.getEndpoint(uri.value(), Endpoint.class);
    } catch (Exception cause) {
        throw new InjectionException("Error injecting endpoint annotated with " + uri + " into " + ip, cause);
    }
}
项目:Camel    文件:CdiCamelFactory.java   
@Produces
@SuppressWarnings("unchecked")
// Qualifiers are dynamically added in CdiCamelExtension
private static <T> CdiEventEndpoint<T> cdiEventEndpoint(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension, @Any Event<Object> event) throws Exception {
    CamelContext context = selectContext(ip, instance, extension);
    Type type = Object.class;
    if (ip.getType() instanceof ParameterizedType) {
        type = ((ParameterizedType) ip.getType()).getActualTypeArguments()[0];
    }
    String uri = eventEndpointUri(type, ip.getQualifiers());
    if (context.hasEndpoint(uri) == null) {
        context.addEndpoint(uri, extension.getEventEndpoint(uri));
    }
    return context.getEndpoint(uri, CdiEventEndpoint.class);
}
项目:Camel    文件:RouteBuildersWithContextNamesTest.java   
@Test
public void verifyCamelContexts(@Any Instance<CamelContext> contexts) {
    assertThat("Context instances are incorrect!", contexts,
        containsInAnyOrder(
            hasProperty("name", is(equalTo("first"))),
            hasProperty("name", is(equalTo("second")))));
}
项目:AngularBeans    文件:BeanLocator.java   
public Object lookup(String beanName, String sessionID) {

        NGSessionScopeContext.setCurrentContext(sessionID);

        Set<Bean<?>> beans = beanManager.getBeans(beanName);

        Class beanClass = CommonUtils.beanNamesHolder.get(beanName);
        if (beans.isEmpty()) {
            beans = beanManager.getBeans(beanClass, new AnnotationLiteral<Any>() { //
            });
        }

        Bean bean = beanManager.resolve(beans);

        Class scopeAnnotationClass = bean.getScope();
        Context context;

        if (scopeAnnotationClass.equals(RequestScoped.class)) {
            context = beanManager.getContext(scopeAnnotationClass);
            if (context == null)
                return bean.create(beanManager.createCreationalContext(bean));

        } else {

            if (scopeAnnotationClass.equals(NGSessionScopeContext.class)) {
                context = NGSessionScopeContext.getINSTANCE();
            } else {
                context = beanManager.getContext(scopeAnnotationClass);
            }

        }
        CreationalContext creationalContext = beanManager.createCreationalContext(bean);
        Object reference = context.get(bean, creationalContext);

        // if(reference==null && scopeAnnotationClass.equals(RequestScoped.class)){
        // reference= bean.create(beanManager.createCreationalContext(bean));
        // }

        return reference;
    }
项目:appformer    文件:ArtifactRepositoryService.java   
@Inject
public ArtifactRepositoryService(@Repository @Any Instance<ArtifactRepository> artifactRepositoryInstances) {
    this.repositories = new ArrayList<>();
    for (ArtifactRepository artifactRepository : artifactRepositoryInstances) {
        this.repositories.add(artifactRepository);
    }
}
项目:switchyard    文件:BeanDeploymentMetaDataCDIBean.java   
/**
 * Public constructor.
 * @param beanDeploymentMetaData Bean metadata.
 */
public BeanDeploymentMetaDataCDIBean(BeanDeploymentMetaData beanDeploymentMetaData) {
    _beanMetaData = beanDeploymentMetaData;
    this._qualifiers = new HashSet<Annotation>();
    this._qualifiers.add(new AnnotationLiteral<Default>() {});
    this._qualifiers.add(new AnnotationLiteral<Any>() {});
}
项目:switchyard    文件:InternalBean.java   
/**
 * Protected constructor.
 */
protected InternalBean(Object proxyObject, Class<?> beanClass) {
    _qualifiers = new HashSet<Annotation>();
    _qualifiers.add(new AnnotationLiteral<Default>() {});
    _qualifiers.add(new AnnotationLiteral<Any>() {});
    _proxyObject = proxyObject;
    _beanClass = beanClass;
}
项目:cdi-tutorial    文件:ChatView.java   
private void observeMessage(
        @Observes(notifyObserver = IF_EXISTS) @Any Message message) {
    User currentUser = userInfo.getUser();
    if (targetUser != null && message.involves(currentUser, targetUser)) {
        if (messageLayout != null) {
            if (messageLayout.getComponentCount() >= MAX_MESSAGES) {
                messageLayout.removeComponent(messageLayout
                        .getComponentIterator().next());
            }
            messageLayout.addComponent(new Label(message.toString()));
        }
    }
}
项目:camel-cdi    文件:RouteBuildersWithContextNamesTest.java   
@Test
public void verifyCamelContexts(@Any Instance<CamelContext> contexts) {
    assertThat("Context instances are incorrect!", contexts,
        containsInAnyOrder(
            hasProperty("name", is(equalTo("first"))),
            hasProperty("name", is(equalTo("second")))));
}
项目:camel-cdi    文件:CamelContextProducer.java   
@Override
public T produce(CreationalContext<T> cc) {
    T context = super.produce(cc);

    // Do not override the name if it's been already set (in the bean constructor for example)
    if (context.getNameStrategy() instanceof DefaultCamelContextNameStrategy)
        context.setNameStrategy(nameStrategy(annotated));

    // Add bean registry and Camel injector
    if (context instanceof DefaultCamelContext) {
        DefaultCamelContext adapted = context.adapt(DefaultCamelContext.class);
        adapted.setRegistry(new CdiCamelRegistry(manager));
        adapted.setInjector(new CdiCamelInjector(context.getInjector(), manager));
    } else {
        // Fail fast for the time being to avoid side effects by the time these two methods get declared on the CamelContext interface
        throw new DeploymentException("Camel CDI requires Camel context [" + context.getName() + "] to be a subtype of DefaultCamelContext");
    }

    // Add event notifier if at least one observer is present
    Set<Annotation> qualifiers = annotated.getAnnotations().stream()
        .filter(isAnnotationType(Named.class).negate()
            .and(q -> manager.isQualifier(q.annotationType())))
        .collect(toSet());
    qualifiers.add(Any.Literal.INSTANCE);
    if (qualifiers.size() == 1)
        qualifiers.add(Default.Literal.INSTANCE);
    qualifiers.retainAll(manager.getExtension(CdiCamelExtension.class).getObserverEvents());
    if (!qualifiers.isEmpty())
        context.getManagementStrategy().addEventNotifier(new CdiEventNotifier(manager, qualifiers));

    return context;
}