void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager beanManager) { final CommandContextImpl commandContext = new CommandContextImpl(); // Register the command context event.addContext(commandContext); // Register the command context bean using CDI 2 configurators API event.addBean() .addType(CommandContext.class) .createWith(ctx -> new InjectableCommandContext(commandContext, beanManager)) .addQualifier(Default.Literal.INSTANCE) .scope(Dependent.class) .beanClass(CommandExtension.class); // Register the CommandExecution bean using CDI 2 configurators API event.addBean() .createWith(ctx -> commandContext.getCurrentCommandExecution()) .addType(CommandExecution.class) .addQualifier(Default.Literal.INSTANCE) .scope(CommandScoped.class) .beanClass(CommandExtension.class); }
@Produces @DeploymentScoped @Default IndexView index() { Indexer indexer = new Indexer(); Map<ArchivePath, Node> c = context.getCurrentArchive().getContent(); try { for (Map.Entry<ArchivePath, Node> each : c.entrySet()) { if (each.getKey().get().endsWith(CLASS_SUFFIX)) { indexer.index(each.getValue().getAsset().openStream()); } } } catch (IOException e) { throw new RuntimeException(e); } return indexer.complete(); }
private static EntityManager lookupEntityManager(InjectionPoint ip, BeanManager bm) { final Class def = Default.class; @SuppressWarnings("unchecked") final Class<? extends Annotation> annotation = ip.getQualifiers() .stream() .filter(q -> q.annotationType() == DAO.class) .map(q -> ((DAO) q).value()) .findFirst() .orElse(def); if (bm.isQualifier(annotation)) { return lookupEntityManager(bm, annotation); } else { throw new ContextNotActiveException("no datasource qualifier nor stereotype presents in the " + "injection point " + ip); } }
/** * 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)); }
/** * Reads the {@code config.json} configuration file in the classpath and builds a * {@link MongoClientConfiguration} from it. * * @return the {@link MongoClientConfiguration} * @throws IOException if a problem occurred when reading the config file */ @SuppressWarnings("static-method") @Produces @Default public MongoClientConfiguration getMongoClientConfiguration() throws IOException { try ( final InputStream jsonConfigFile = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.json"); final JsonReader reader = Json.createReader(jsonConfigFile);) { final JsonObject root = (JsonObject) reader.read(); final String databaseName = ((JsonString) root.get("databaseName")).getString(); LOGGER.debug("Database name: {}", databaseName); final MongoClientConfiguration mongoClientConfiguration = new MongoClientConfiguration(databaseName); return mongoClientConfiguration; } }
@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); }
@Override public void validate(final EjbModule ejbModule) { if (ejbModule.getBeans() == null) { return; } try { for (final Field field : ejbModule.getFinder().findAnnotatedFields(Inject.class)) { if (!field.getType().equals(InjectionPoint.class) || !HttpServlet.class.isAssignableFrom(field.getDeclaringClass())) { continue; } final Annotation[] annotations = field.getAnnotations(); if (annotations.length == 1 || (annotations.length == 2 && field.getAnnotation(Default.class) != null)) { throw new DefinitionException("Can't inject InjectionPoint in " + field.getDeclaringClass()); } // else we should check is there is no other qualifier than @Default but too early } } catch (final NoClassDefFoundError noClassDefFoundError) { // ignored: can't check but maybe it is because of an optional dep so ignore it // not important to skip it since the failure will be reported elsewhere // this validator doesn't check it } }
@Inject public WiresCanvasPresenter(final Event<CanvasClearEvent> canvasClearEvent, final Event<CanvasShapeAddedEvent> canvasShapeAddedEvent, final Event<CanvasShapeRemovedEvent> canvasShapeRemovedEvent, final Event<CanvasDrawnEvent> canvasDrawnEvent, final Event<CanvasFocusedEvent> canvasFocusedEvent, final @Lienzo Layer layer, final WiresCanvas.View view, final LienzoPanel lienzoPanel, final @Default WiresControlFactory wiresControlFactory) { super(canvasClearEvent, canvasShapeAddedEvent, canvasShapeRemovedEvent, canvasDrawnEvent, canvasFocusedEvent, layer, view); this.lienzoPanel = lienzoPanel; this.wiresControlFactory = wiresControlFactory; }
private QueryExecutor resolve(final String technology) { if (anyExecutor.isUnsatisfied()) { throw new RuntimeException( "please provide QueryExecutor-Implementations!"); } else if ("default".equalsIgnoreCase(technology)) { if (anyExecutor.isAmbiguous()) { final Instance<QueryExecutor> defaultExecutors = anyExecutor.select(new AnnotationLiteral<Default>() { private static final long serialVersionUID = 1L; }); return resolve(defaultExecutors, technology); } else { return anyExecutor.get(); } } else { final Instance<QueryExecutor> executorsByTechnology = anyExecutor.select(new TechnologyLiteral(technology)); return resolve(executorsByTechnology, technology); } }
/** * <p>This method uses the InvocationContext to scan the @Transactional * interceptor for a manually specified Qualifier.</p> * * <p>If none is given (defaults to 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 @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; }
@Test public void modifyAnnotationsOnConstructorParameter() throws NoSuchMethodException { final AnnotatedTypeBuilder<Cat> builder = new AnnotatedTypeBuilder<Cat>(); builder.readFromType(Cat.class, true); builder.removeFromConstructorParameter(Cat.class.getConstructor(String.class, String.class), 1, Default.class); builder.addToConstructorParameter(Cat.class.getConstructor(String.class, String.class), 1, new AnyLiteral()); final AnnotatedType<Cat> catAnnotatedType = builder.create(); Set<AnnotatedConstructor<Cat>> catCtors = catAnnotatedType.getConstructors(); assertThat(catCtors.size(), is(2)); for (AnnotatedConstructor<Cat> ctor : catCtors) { if (ctor.getParameters().size() == 2) { List<AnnotatedParameter<Cat>> ctorParams = ctor.getParameters(); assertThat(ctorParams.get(1).getAnnotations().size(), is(1)); assertThat((AnyLiteral) ctorParams.get(1).getAnnotations().toArray()[0], is(new AnyLiteral())); } } }
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); } }
public <T, X> void injectionPoints( final @Observes ProcessInjectionPoint<T, X> processInjectionPoint ) { final Type type = processInjectionPoint.getInjectionPoint().getType(); final Object mock = mockStore.findFor(type); if (mock == null) { return; } LOG.debug("Mocking injection point: {}", processInjectionPoint.getInjectionPoint()); final InjectionPoint original = processInjectionPoint.getInjectionPoint(); processInjectionPoint.setInjectionPoint(new ForwardingInjectionPoint() { @Override public Set<Annotation> getQualifiers() { final Set<Annotation> ret = new HashSet<>(super.getQualifiers()).stream() .filter(it -> !(it instanceof Default)) .collect(toSet()); ret.add(MOCKED); return ret; } @Override protected InjectionPoint delegate() { return original; } }); mockedInjectionPoints.add(original); }
/** * Tests annotation literals in a jar archive */ @Test public void testAnnotationLiteral() { logger.info("starting util event test"); Set<Bean<?>> beans = beanManager.getBeans(ConfigurationBean.class, new AnnotationLiteral<Default>() { private static final long serialVersionUID = -4378964126487759035L; }); assertEquals("The configuration bean has by default the @Default qualifier and it is a ManagedBean", 1, beans.size()); }
@Test @ExtendWith(CustomExtension.class) @ExplicitParamInjection public void testParametersNeedExtraAnnotation(@Default Foo foo, Bar bar, @MyQualifier BeanWithQualifier bean) { // Bar should be resolved by another extension Assertions.assertNotNull(bar); Assertions.assertEquals(CustomExtension.class.getSimpleName(), bar.ping()); // Foo should be resolved as usual Assertions.assertNotNull(foo); Assertions.assertEquals(Foo.class.getSimpleName(), foo.ping()); // BeanWithQualifier should be resolved Assertions.assertNotNull(bean); Assertions.assertEquals(BeanWithQualifier.class.getSimpleName(), bean.ping()); }
@Test @ExtendWith(CustomExtension.class) public void testParametersNeedExtraAnnotation(@Default Foo foo, Bar bar, @MyQualifier BeanWithQualifier bean) { // Bar should be resolved by another extension Assertions.assertNotNull(bar); Assertions.assertEquals(CustomExtension.class.getSimpleName(), bar.ping()); // Foo should be resolved as usual Assertions.assertNotNull(foo); Assertions.assertEquals(Foo.class.getSimpleName(), foo.ping()); // BeanWithQualifier should be resolved Assertions.assertNotNull(bean); Assertions.assertEquals(BeanWithQualifier.class.getSimpleName(), bean.ping()); }
static Set<Annotation> findQualifiers(Set<Annotation> annotations) { Set<Annotation> results = new LinkedHashSet<>(); for(Annotation annotation : annotations) { Class<? extends Annotation> annotationClass = annotation.getClass(); if(annotation instanceof Default) { continue; } else if(annotationClass.getAnnotation(Qualifier.class) != null) { results.add(annotation); } else if(annotationClass.getAnnotation(Stereotype.class) != null) { Set<Annotation> parentAnnotations = new LinkedHashSet<>(asList(annotationClass.getAnnotations())); results.addAll(findQualifiers(parentAnnotations)); } } return results; }
public void addABean(@Observes AfterBeanDiscovery event) { // get an instance of BeanConfigurator event.addBean() // set the desired data .types(Greeter.class) .scope(ApplicationScoped.class) .addQualifier(Default.Literal.INSTANCE) //.addQualifier(Custom.CustomLiteral.INSTANCE); //finally, add a callback to tell CDI how to instantiate this bean .produceWith(obj -> new Greeter()); }
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); }
/** * The CDI producer method for SLF4J loggers. * * @param ip the injection point * @return a suitable logger */ @Produces @Default public Logger createLogger(final InjectionPoint ip) { Class declaringClass = ip.getMember().getDeclaringClass(); return org.slf4j.LoggerFactory.getLogger(declaringClass); }
@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)); }
@Produces @ConversationScoped @PersistenceUnit @Default public EntityManagerFactory getEntityManagerFactory() { return emf; }
@Produces @RequestScoped @Default public SessionInfo getSessionInfo(AuthenticationService authenticationService) { String sessionId = getSessionId(); User user; if (sessionId == null) { user = getDefaultUser(); sessionId = user.getIdentifier(); } else { user = authenticationService.getUser(); } return new SessionInfoImpl(sessionId, user); }
@Produces @Dependent @Default @SuppressWarnings("unchecked") public <T> IDAO<T> produceUnqualifiedDaoWithIntegerId(@TransientReference InjectionPoint ip, @TransientReference BeanManager bm, @New @TransientReference IDAOFactory f) { return buildDaoWithOneGenericType(ip, bm, (IDAOFactory<T>) f); }
@Produces @Dependent @Default @SuppressWarnings("unchecked") public <T> LDAO<T> produceUnqualifiedDaoWithLongId(@TransientReference InjectionPoint ip, @TransientReference BeanManager bm, @New @TransientReference LDAOFactory f) { return buildDaoWithOneGenericType(ip, bm, (LDAOFactory<T>) f); }
@Produces @Dependent @Default @SuppressWarnings("unchecked") public <T> DaoWithoutId<T> produceUnqualifiedDaoWithoutId(@TransientReference InjectionPoint ip, @TransientReference BeanManager bm, @New @TransientReference DAOFactory f) { return buildDaoWithOneGenericType(ip, bm, (DAOFactory<T>) f); }
/** * 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>() {}); }
/** * 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; }
@Override public Set<Annotation> getQualifiers() { Set<Annotation> set = new HashSet<>(); Default def = new Default() { @Override public Class<? extends Annotation> annotationType() { return Default.class; } }; set.add(def); return set; }
@Produces @ApplicationScoped @Default @Startup public EntityManagerFactory entityManagerFactoryMySQL(@InjectableProperties(file = "jpa-mysql") Map<String, String> properties) { PersistenceProvider persistenceProvider = new HibernatePersistenceProvider(); return persistenceProvider.createEntityManagerFactory("MySQL", properties); }
@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; }
@Produces @Default @Uri("") // Qualifiers are dynamically added in CdiCamelExtension private static FluentProducerTemplate fluentProducerTemplate(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) { return getQualifierByType(ip, Uri.class) .map(uri -> fluentProducerTemplateFromUri(ip, instance, extension, uri)) .orElseGet(() -> defaultFluentProducerTemplate(ip, instance, extension)); }
private static <T extends CamelContext> T selectContext(InjectionPoint ip, Instance<T> instance, CdiCamelExtension extension) { Collection<Annotation> qualifiers = new HashSet<>(ip.getQualifiers()); qualifiers.retainAll(extension.getContextQualifiers()); if (qualifiers.isEmpty() && !instance.select(Default.Literal.INSTANCE).isUnsatisfied()) return instance.select(Default.Literal.INSTANCE).get(); return instance.select(qualifiers.stream().toArray(Annotation[]::new)).get(); }
@Produces @Default @Singleton public MessagePublishingService getMessagePublishingService( CQELSEngine cqelsEngine) { if(CONFIG.mbusType().equalsIgnoreCase(ServiceConfig.WAMP)) { return new WAMPMessagePublishingService(cqelsEngine); } return null; }
public void sendMessageToClient(@Observes @Default ACLMessage msg) { Set<String> processed = new HashSet<>(); AID aid = msg.receivers.iterator().next(); synchronized (sessions) { Session session = sessions.get(aid.getHost()); if (session != null && processed.add(aid.getHost())) { session.getAsyncRemote().sendText(msg.toString()); } } }
public Set<Annotation> getQualifiers() { Set<Annotation> qualifiers = new HashSet<>(); qualifiers.add(new AnnotationLiteral<Default>() { }); qualifiers.add(new AnnotationLiteral<Any>() { }); return qualifiers; }
@Inject public DMNCanvasFactory(final ManagedInstance<ResizeControl> resizeControls, final ManagedInstance<ConnectionAcceptorControl> connectionAcceptorControls, final ManagedInstance<ContainmentAcceptorControl> containmentAcceptorControls, final ManagedInstance<DockingAcceptorControl> dockingAcceptorControls, final ManagedInstance<CanvasInPlaceTextEditorControl> inPlaceTextEditorControls, final @MultipleSelection ManagedInstance<SelectionControl> selectionControls, final ManagedInstance<LocationControl> locationControls, final @DMNEditor ManagedInstance<ToolboxControl> toolboxControls, final @Default @Observer ManagedInstance<ElementBuilderControl> elementBuilderControls, final ManagedInstance<NodeBuilderControl> nodeBuilderControls, final ManagedInstance<EdgeBuilderControl> edgeBuilderControls, final ManagedInstance<ZoomControl> zoomControls, final ManagedInstance<PanControl> panControls, final ManagedInstance<KeyboardControl> keyboardControls, final ManagedInstance<ClipboardControl> clipboardControls, final @Default ManagedInstance<AbstractCanvas> canvasInstances, final @Default ManagedInstance<AbstractCanvasHandler> canvasHandlerInstances) { this.resizeControls = resizeControls; this.connectionAcceptorControls = connectionAcceptorControls; this.containmentAcceptorControls = containmentAcceptorControls; this.dockingAcceptorControls = dockingAcceptorControls; this.inPlaceTextEditorControls = inPlaceTextEditorControls; this.selectionControls = selectionControls; this.locationControls = locationControls; this.toolboxControls = toolboxControls; this.elementBuilderControls = elementBuilderControls; this.nodeBuilderControls = nodeBuilderControls; this.edgeBuilderControls = edgeBuilderControls; this.zoomControls = zoomControls; this.panControls = panControls; this.keyboardControls = keyboardControls; this.canvasInstances = canvasInstances; this.canvasHandlerInstances = canvasHandlerInstances; this.clipboardControls = clipboardControls; }
@Override @Produces @Default @ApplicationScoped public SessionInfo getSessionInfo(AuthenticationService authenticationService) { return new SessionInfoImpl("dummy-id", authenticationService.getUser()); }