private <X> AnnotatedField<X> decorateContext(AnnotatedField<X> field) { final PersistenceContext persistenceContext = field.getAnnotation(PersistenceContext.class); final UniqueIdentifier identifier = UniqueIdentifierLitteral.random(); Set<Annotation> templateQualifiers = new HashSet<>(); templateQualifiers.add(ServiceLiteral.SERVICE); if (hasUnitName(persistenceContext)) { templateQualifiers.add(new FilterLiteral("(osgi.unit.name=" + persistenceContext.unitName() + ")")); } Bean<JpaTemplate> bean = manager.getExtension(OsgiExtension.class) .globalDependency(JpaTemplate.class, templateQualifiers); Set<Annotation> qualifiers = new HashSet<>(); qualifiers.add(identifier); Bean<EntityManager> b = new SimpleBean<>(EntityManager.class, Dependent.class, Collections.singleton(EntityManager.class), qualifiers, () -> { CreationalContext<JpaTemplate> context = manager.createCreationalContext(bean); JpaTemplate template = (JpaTemplate) manager.getReference(bean, JpaTemplate.class, context); return EntityManagerProducer.create(template); }); beans.add(b); Set<Annotation> fieldAnnotations = new HashSet<>(); fieldAnnotations.add(InjectLiteral.INJECT); fieldAnnotations.add(identifier); return new SyntheticAnnotatedField<>(field, fieldAnnotations); }
private <X> AnnotatedField<X> decorateUnit(AnnotatedField<X> field) { final PersistenceUnit persistenceUnit = field.getAnnotation(PersistenceUnit.class); final UniqueIdentifier identifier = UniqueIdentifierLitteral.random(); Set<Annotation> templateQualifiers = new HashSet<>(); templateQualifiers.add(ServiceLiteral.SERVICE); if (hasUnitName(persistenceUnit)) { templateQualifiers.add(new FilterLiteral("(osgi.unit.name=" + persistenceUnit.unitName() + ")")); } Bean<EntityManagerFactory> bean = manager.getExtension(OsgiExtension.class) .globalDependency(EntityManagerFactory.class, templateQualifiers); Set<Annotation> qualifiers = new HashSet<>(); qualifiers.add(identifier); Bean<EntityManagerFactory> b = new SimpleBean<>(EntityManagerFactory.class, Dependent.class, Collections.singleton(EntityManagerFactory.class), qualifiers, () -> { CreationalContext<EntityManagerFactory> context = manager.createCreationalContext(bean); return (EntityManagerFactory) manager.getReference(bean, EntityManagerFactory.class, context); }); beans.add(b); Set<Annotation> fieldAnnotations = new HashSet<>(); fieldAnnotations.add(InjectLiteral.INJECT); fieldAnnotations.add(identifier); return new SyntheticAnnotatedField<>(field, fieldAnnotations); }
@SuppressWarnings("unchecked") @Dependent @Produces @ConfigProperty <T> Optional<T> produceOptionalConfigValue(InjectionPoint injectionPoint) { Type type = injectionPoint.getAnnotated().getBaseType(); final Class<T> valueType; if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] typeArguments = parameterizedType.getActualTypeArguments(); valueType = unwrapType(typeArguments[0]); } else { valueType = (Class<T>) String.class; } return Optional.ofNullable(getValue(injectionPoint, valueType)); }
/** * * @param ip * @param parser * @param msg * @param dc * @return */ @Produces @Dependent @PathParam("nonbinding") public static String pathParam(InjectionPoint ip, PathParser parser, Message msg, DestinationChanged dc) { final String destination; if (msg != null) { destination = msg.frame().destination().get(); } else if (dc != null) { destination = dc.getDestination(); } else { throw new IllegalStateException("Neither MessageEvent or DestinationEvent is resolvable!"); } final PathParam param = ip .getAnnotated() .getAnnotation(PathParam.class); final Result r = parser.parse(destination); if (r.isSuccess()) { return r.get(param.value()); } return null; }
/** * * @param ip * @param beanManager * @return */ private <T> Bean<T> createBeanAdapter(InjectionPoint ip, BeanManager beanManager) { final Type type = ip.getType(); final Class<T> rawType = ReflectionUtils.getRawType(type); final ContextualLifecycle<T> lifecycleAdapter = new BodyLifecycle<T>(ip, beanManager); final BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager) .readFromType(new AnnotatedTypeBuilder<T>().readFromType(rawType).create()) .beanClass(Body.class) // see https://issues.jboss.org/browse/WELD-2165 .name(ip.getMember().getName()) .qualifiers(ip.getQualifiers()) .beanLifecycle(lifecycleAdapter) .scope(Dependent.class) .passivationCapable(false) .alternative(false) .nullable(true) .id("BodyBean#" + type.toString()) .addType(type); //java.lang.Object needs to be present (as type) in any case return beanBuilder.create(); }
/** * Creates a SnoopEEServiceClient for the named service. * * @param ip The injection point * @return a configured SnoopEE service client */ @SnoopEE @Produces @Dependent public SnoopEEServiceClient lookup(InjectionPoint ip) { final String applicationName = ip.getAnnotated().getAnnotation(SnoopEE.class).serviceName(); LOGGER.config(() -> "producing " + applicationName); String serviceUrl = "http://" + readProperty("snoopeeService", snoopeeConfig); LOGGER.config(() -> "Service URL: " + serviceUrl); return new SnoopEEServiceClient.Builder(applicationName) .serviceUrl(serviceUrl) .build(); }
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 @Dependent @Property public Boolean produceBooleanProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Boolean.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(boolean.class) ? Boolean.FALSE : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Integer produceIntegerProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Integer.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(int.class) ? Integer.valueOf(0) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Long produceLongProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Long.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(long.class) ? Long.valueOf(0L) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Float produceFloatProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Float.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(float.class) ? Float.valueOf(0f) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Double produceDoubleProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Double.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(double.class) ? Double.valueOf(0d) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public BigInteger produceBigIntegerProperty(InjectionPoint injectionPoint) { try { final BigDecimal value = produceBigDecimalProperty(injectionPoint); if (value != null) { return value.toBigInteger(); } } catch (Exception e) { throw new InjectionException(e); } return null; }
@Produces @Dependent @Property public Date produceDateProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); final Date date; if (value != null) { final Property annotation = injectionPoint.getAnnotated().getAnnotation(Property.class); final String pattern = annotation.pattern(); DateFormat format = new SimpleDateFormat(pattern.isEmpty() ? "yyyy-MM-dd'T'HH:mm:ss.SSSZ" : pattern); date = format.parse(value); } else { date = null; } return date; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @DefaultDatasource public String getDatasourceJndiName() { if (this.defaultDatasourceJndiName == null && this.defaultDatasourceName != null) { for (DataSource ds : this.fraction.subresources().dataSources()) { if (this.defaultDatasourceName.equals(ds.getKey())) { if (ds.jndiName() != null) { return ds.jndiName(); } return "java:jboss/datasources/" + this.defaultDatasourceName; } } } return this.defaultDatasourceJndiName; }
@Produces @Dependent() Archive deployment() { String context = TopologyWebAppFraction.DEFAULT_CONTEXT; if (this.contextPath != null) { context = this.contextPath; } if (fraction.exposeTopologyEndpoint()) { WARArchive war = ShrinkWrap.create(WARArchive.class, "topology-webapp.war"); war.addAsWebInfResource(new StringAsset(getWebXml(fraction)), "web.xml"); war.addClass(TopologySSEServlet.class); war.addModule("swarm.application"); war.addModule("org.wildfly.swarm.topology"); war.addAsWebResource(new ClassLoaderAsset("topology.js", this.getClass().getClassLoader()), "topology.js"); war.setContextRoot(context); war.as(TopologyArchive.class); return war; } return null; }
@SuppressWarnings("unchecked") @ConfigurationValue("") @Dependent @Produces <T> Optional<T> produceOptionalConfigValue(InjectionPoint injectionPoint) { Type type = injectionPoint.getAnnotated().getBaseType(); final Class<T> valueType; if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] typeArguments = parameterizedType.getActualTypeArguments(); valueType = unwrapType(typeArguments[0]); } else { valueType = (Class<T>) String.class; } return Optional.ofNullable(resolve(injectionPoint, valueType)); }
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) { CommonBean<String[]> stringBean = CommonBeanBuilder.newBuilder(String[].class) .beanClass(CommandLineArgsExtension.class) .scope(Dependent.class) .createSupplier(() -> args) .addQualifier(CommandLineArgs.Literal.INSTANCE) .addType(String[].class) .addType(Object.class).build(); abd.addBean(stringBean); CommonBean<List> listBean = CommonBeanBuilder.newBuilder(List.class) .beanClass(CommandLineArgsExtension.class) .scope(Dependent.class) .createSupplier(() -> argsList) .addQualifier(DefaultLiteral.INSTANCE) .addType(List.class) .addType(Object.class).build(); abd.addBean(listBean); }
/** * Creates a load balancer instance using a fixed server list. You need to add the servers * to this instance manually after retrieving it. This instance has Dependent scope, so you will get * a fresh instance on every injection point. * * @return a fixed server list load balancer */ @Produces @LoadBalancer(Type.Fixed) @Dependent public BaseLoadBalancer fixedServerListLoadBalancer() { LoadBalancerBuilder<Server> builder = LoadBalancerBuilder.newBuilder(); LoadBalancer qualifier = new FixedLoadBalancerQualifier(); IRule rule = select(rules, qualifier); if (rule != null) { builder.withRule(rule); } IPing ping = select(pings, qualifier); if (ping != null) { builder.withPing(ping); } return builder.buildFixedServerListLoadBalancer(new ArrayList<>()); }
/** * Creates a load balancer instance using a dynamic server list. You need to add the dynamic * servers to this instance manually after retrieving it. This instance has Dependent scope, so you * will get a fresh instance on every injection point. * * @return a dynamic server list loader balancer */ @Produces @LoadBalancer(Type.Dynamic) @Dependent public ZoneAwareLoadBalancer<Server> dynamicServerListLoadBalancer() { LoadBalancerBuilder<Server> builder = LoadBalancerBuilder.newBuilder(); LoadBalancer qualifier = new DynamicLoadBalancerQualifier(); IRule rule = select(rules, qualifier); if (rule != null) { builder.withRule(rule); } IPing ping = select(pings, qualifier); if (ping != null) { builder.withPing(ping); } return builder.buildDynamicServerListLoadBalancer(); }
/** * Creates a SnoopServiceClient for the named service. * * @param ip The injection point * @return a configured snoop service client */ @Snoop @Produces @Dependent public SnoopServiceClient lookup(InjectionPoint ip) { final String applicationName = ip.getAnnotated().getAnnotation(Snoop.class).serviceName(); LOGGER.config(() -> "producing " + applicationName); String serviceUrl = "http://" + readProperty("snoopService", snoopConfig); LOGGER.config(() -> "Service URL: " + serviceUrl); return new SnoopServiceClient.Builder(applicationName) .serviceUrl(serviceUrl) .build(); }
@Override public void destroyActivity(final Activity activity) { if (startedActivities.remove(activity) != null) { boolean isDependentScope = getBeanScope(activity) == Dependent.class; try { activity.onShutdown(); } catch (Exception ex) { lifecycleErrorHandler.handle(activity, LifecyclePhase.SHUTDOWN, ex); } if (isDependentScope) { iocManager.destroyBean(activity); } } else { throw new IllegalStateException("Activity " + activity + " is not currently in the started state"); } }
private <T extends Activity> Set<T> secure(final Collection<SyncBeanDef<T>> activityBeans, final boolean protectedAccess) { final Set<T> activities = new HashSet<T>(activityBeans.size()); for (final SyncBeanDef<T> activityBean : activityBeans) { if (!activityBean.isActivated()) { continue; } final T instance = activityBean.getInstance(); if (!protectedAccess || authzManager.authorize(instance, identity)) { activities.add(instance); } else { // Since user does not have permission, destroy bean to avoid memory leak if (activityBean.getScope().equals(Dependent.class)) { iocManager.destroyBean(instance); } } } return activities; }
protected Pair<Collection<BuildOptionExtension>, Collection<BuildOptionExtension>> getBuildExtensions() { AsyncBeanManager beanManager = IOC.getAsyncBeanManager(); Collection<AsyncBeanDef<BuildOptionExtension>> beans = beanManager.lookupBeans(BuildOptionExtension.class); final Collection<BuildOptionExtension> dependentScoped = new ArrayList<>(beans.size()); final Collection<BuildOptionExtension> instances = new ArrayList<>(beans.size()); for (final AsyncBeanDef<BuildOptionExtension> bean : beans) { /* * We are assuming that extensions are not marked with @LoadAsync. * Thus getInstance will immediately invoke the callback. */ bean.getInstance(new CreationalCallback<BuildOptionExtension>() { @Override public void callback(BuildOptionExtension extension) { instances.add(extension); if (bean.getScope().equals(Dependent.class)) { dependentScoped.add(extension); } } }); } return new Pair<>(instances, dependentScoped); }
@Override public Instance load(final String batchId) { final BeanManager bm = getBeanManager(); if (bm == null) { return super.load(batchId); } final Set<Bean<?>> beans = bm.getBeans(batchId); final Bean<?> bean = bm.resolve(beans); if (bean == null) { // fallback to try to instantiate it from TCCL as per the spec return super.load(batchId); } final Class<?> clazz = bean.getBeanClass(); final CreationalContext creationalContext = bm.createCreationalContext(bean); final Object artifactInstance = bm.getReference(bean, clazz, creationalContext); if (Dependent.class.equals(bean.getScope()) || !bm.isNormalScope(bean.getScope())) { // need to be released return new Instance(artifactInstance, new Closeable() { @Override public void close() throws IOException { creationalContext.release(); } }); } return new Instance(artifactInstance, null); }
@Produces @Dependent @PersistenceUnitName("any") // the value is nonbinding, thus 'any' is just a dummy parameter here public EntityManagerFactory createEntityManagerFactoryForUnit(InjectionPoint injectionPoint) { PersistenceUnitName unitNameAnnotation = injectionPoint.getAnnotated().getAnnotation(PersistenceUnitName.class); if (unitNameAnnotation == null) { LOG.warning("@PersisteneUnitName annotation could not be found at EntityManagerFactory injection point!"); return null; } String unitName = unitNameAnnotation.value(); Properties properties = persistenceConfigurationProvider.getEntityManagerFactoryConfiguration(unitName); EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName, properties); return emf; }
private static <T> T getContextualReference(BeanManager beanManager, Class<T> type) { Set<Bean<?>> beans = beanManager.getBeans(type); if (beans == null || beans.isEmpty()) { return null; } Bean<?> bean = beanManager.resolve(beans); CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean); @SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" }) T result = (T) beanManager.getReference(bean, type, creationalContext); if (bean.getScope().equals(Dependent.class)) { AbstractBeanStorage beanStorage = BeanProvider.getContextualReference(RequestDependentBeanStorage.class); //noinspection unchecked beanStorage.add(new DependentBeanEntry(result, bean, creationalContext)); } return result; }
@Produces @Dependent public <M> JsfMessage<M> createJsfMessage(InjectionPoint injectionPoint, MessageBundleInvocationHandler invocationHandler) { if (!(injectionPoint.getType() instanceof ParameterizedType)) { throw new IllegalArgumentException("JsfMessage must be used as generic type"); } ParameterizedType paramType = (ParameterizedType) injectionPoint.getType(); Type[] actualTypes = paramType.getActualTypeArguments(); if (actualTypes.length != 1) { throw new IllegalArgumentException("JsfMessage must have the MessageBundle as generic type parameter"); } try { @SuppressWarnings("unchecked") Class<M> type = (Class<M>) actualTypes[0]; return createJsfMessageFor(injectionPoint, type, invocationHandler); } catch (ClassCastException e) { throw new IllegalArgumentException("Incorrect class found when trying to convert to parameterized type",e); } }
@Produces @Dependent @Property2 public Long produceProperty2(InjectionPoint injectionPoint) { String configuredValue = getStringPropertyValue(injectionPoint); if (configuredValue == null) { return null; } Property2 metaData = getAnnotation(injectionPoint, Property2.class); if (metaData.logValue()) { LOG.info("value of property 2: " + configuredValue); } //X TODO integrate with the HandledHandler of DeltaSpike return Long.parseLong(configuredValue); }
@Produces @Dependent @Property2WithInverseSupport public Long produceInverseProperty2(InjectionPoint injectionPoint) { String configuredValue = getStringPropertyValue(injectionPoint); if (configuredValue == null) { return null; } //X TODO integrate with the HandledHandler of DeltaSpike Long result = Long.parseLong(configuredValue); Property2WithInverseSupport metaData = getAnnotation(injectionPoint, Property2WithInverseSupport.class); if (metaData.inverseConvert()) { return result * -1; } return result; }
@Produces @Dependent @Location public LocationId produceLocationId(InjectionPoint injectionPoint) { String configuredValue = getStringPropertyValue(injectionPoint); /* //alternative to @ConfigProperty#defaultValue if (configuredValue == null) { return LocationId.LOCATION_X; } */ return LocationId.valueOf(configuredValue.trim().toUpperCase()); }
@Produces @Dependent @CustomConfigAnnotationWithMetaData public Integer produceIntegerCustomConfig(InjectionPoint injectionPoint) { String configuredValue = getStringPropertyValue(injectionPoint); if (configuredValue == null || configuredValue.length() == 0) { return 0; } Integer result = Integer.parseInt(configuredValue); CustomConfigAnnotationWithMetaData metaData = getAnnotation(injectionPoint, CustomConfigAnnotationWithMetaData.class); if (metaData != null && metaData.inverseConvert()) { return result * -1; } return result; }
@Produces @Dependent @CustomConfigAnnotationWithMetaData public Long produceLongCustomConfig(InjectionPoint injectionPoint) { String configuredValue = getStringPropertyValue(injectionPoint); if (configuredValue == null || configuredValue.length() == 0) { return 0L; } Long result = Long.parseLong(configuredValue); CustomConfigAnnotationWithMetaData metaData = getAnnotation(injectionPoint, CustomConfigAnnotationWithMetaData.class); if (metaData != null && metaData.inverseConvert()) { return result * -1L; } return result; }
@Produces @Dependent @NumberConfig(name = "unused") public Float produceNumberProperty(InjectionPoint injectionPoint) throws ParseException { // resolve the annotation NumberConfig metaData = getAnnotation(injectionPoint, NumberConfig.class); // get the configured value from the underlying configuration system String configuredValue = getPropertyValue(metaData.name(), metaData.defaultValue()); if (configuredValue == null) { return null; } // format according to the given pattern DecimalFormat df = new DecimalFormat(metaData.pattern(), new DecimalFormatSymbols(Locale.US)); return df.parse(configuredValue).floatValue(); }
private Builder() { this.stereotypes = new HashSet<>(); this.alternative = false; this.qualifiers = new HashSet<>(); this.qualifiers.add(AnyLiteral.INSTANCE); this.scope = Dependent.class; this.types = new HashSet<>(); this.types.add(Object.class); this.beanClass = WeldCDIExtension.class; }
@Dependent @Produces public Jedis get(InjectionPoint ip) { System.out.println("injecting Jedis into " + ip.getMember().getDeclaringClass().getSimpleName()); String redisHost = System.getenv().getOrDefault("REDIS_HOST", "192.168.99.100"); String redisPort = System.getenv().getOrDefault("REDIS_PORT", "6379"); Jedis jedis = new Jedis(redisHost, Integer.valueOf(redisPort), 10000); jedis.connect(); System.out.println("Redis Connection obtained"); return jedis; }
/** * Tests that the component injected has Dependent scope */ @Test public void testHasDependentScopedByDefault() { Set<Bean<?>> beans = beanManager.getBeans(SimpleGetApi.class, RestClient.LITERAL); Bean<?> resolved = beanManager.resolve(beans); assertEquals(resolved.getScope(), Dependent.class); }
public void addRegistryBean(@Observes AfterBeanDiscovery afterBeanDiscovery) { afterBeanDiscovery.addBean() .types(ReactorObserverRegistry.class) .produceWith((Function<Instance<Object>, Object>) f -> REGISTRY) .scope(ApplicationScoped.class); eventTypes.forEach(ip -> afterBeanDiscovery.addBean() .types(ip.getType()) .scope(Dependent.class) .produceWith((Function<Instance<Object>, Object>) inst -> { ParameterizedType type = (ParameterizedType) ip.getType(); Class<?> s = (Class<?>) type.getActualTypeArguments()[0]; Class<?> r = (Class<?>) type.getActualTypeArguments()[1]; return new ReactorEventImpl<>(s,r,ip.getQualifiers(),REGISTRY); })); }
@Produces @Dependent @ConfigProperty(name = "unused") public URI produceUri(InjectionPoint injectionPoint) { String configuredValue = getStringPropertyValue(injectionPoint); return URI.create(configuredValue); }
@Override public Class<? extends Annotation> getScope() { Class<? extends Annotation> scope = Arrays.stream(javaType.getAnnotations()) .map(a -> a.getClass()) .filter(a -> a.getAnnotation(Scope.class) != null) .findFirst().orElse(null); return scope == null ? Dependent.class : scope; }