javax.enterprise.context.Dependent Java Examples

The following examples show how to use javax.enterprise.context.Dependent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TopologyWebAppDeploymentProducer.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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("thorntail.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;
}
 
Example #2
Source File: ArcContainerImpl.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static <T> InstanceHandle<T> beanInstanceHandle(InjectableBean<T> bean, CreationalContextImpl<T> parentContext,
        boolean resetCurrentInjectionPoint, Consumer<T> destroyLogic) {
    if (bean != null) {
        if (parentContext == null && Dependent.class.equals(bean.getScope())) {
            parentContext = new CreationalContextImpl<>(null);
        }
        CreationalContextImpl<T> creationalContext = parentContext != null ? parentContext.child(bean)
                : new CreationalContextImpl<>(bean);
        InjectionPoint prev = null;
        if (resetCurrentInjectionPoint) {
            prev = InjectionPointProvider.set(CurrentInjectionPointProvider.EMPTY);
        }

        try {
            return new InstanceHandleImpl<T>(bean, bean.get(creationalContext), creationalContext, parentContext,
                    destroyLogic);
        } finally {
            if (resetCurrentInjectionPoint) {
                InjectionPointProvider.set(prev);
            }
        }
    } else {
        return InstanceHandleImpl.unavailable();
    }
}
 
Example #3
Source File: ConfigBuildStep.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
BeanRegistrarBuildItem registerConfigRootsAsBeans(ConfigurationBuildItem configItem) {
    return new BeanRegistrarBuildItem(new BeanRegistrar() {
        @Override
        public void register(RegistrationContext context) {
            for (RootDefinition rootDefinition : configItem.getReadResult().getAllRoots()) {
                if (rootDefinition.getConfigPhase() == ConfigPhase.BUILD_AND_RUN_TIME_FIXED
                        || rootDefinition.getConfigPhase() == ConfigPhase.RUN_TIME) {
                    Class<?> configRootClass = rootDefinition.getConfigurationClass();
                    context.configure(configRootClass).types(configRootClass)
                            .scope(Dependent.class).creator(mc -> {
                                // e.g. return Config.ApplicationConfig
                                ResultHandle configRoot = mc.readStaticField(rootDefinition.getDescriptor());
                                // BUILD_AND_RUN_TIME_FIXED roots are always set before the container is started (in the static initializer of the generated Config class)
                                // However, RUN_TIME roots may be not be set when the bean instance is created 
                                mc.ifNull(configRoot).trueBranch().throwException(CreationException.class,
                                        String.format("Config root [%s] with config phase [%s] not initialized yet.",
                                                configRootClass.getName(), rootDefinition.getConfigPhase().name()));
                                mc.returnValue(configRoot);
                            }).done();
                }
            }
        }
    });
}
 
Example #4
Source File: SpringDIProcessorTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void springStereotypeScopes() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);

    final Map<DotName, Set<DotName>> expected = new HashMap<>();
    expected.put(SpringDIProcessor.SPRING_COMPONENT, Collections.emptySet());
    expected.put(SpringDIProcessor.SPRING_SERVICE, Collections.emptySet());
    expected.put(SpringDIProcessor.SPRING_REPOSITORY, Collections.emptySet());
    expected.put(DotName.createSimple(PrototypeService.class.getName()),
            Collections.singleton(DotName.createSimple(Dependent.class.getName())));
    expected.put(DotName.createSimple(RequestService.class.getName()),
            Collections.singleton(DotName.createSimple(RequestScoped.class.getName())));
    expected.put(DotName.createSimple(UndeclaredService.class.getName()), Collections.emptySet());
    expected.put(DotName.createSimple(ConflictService.class.getName()), setOf(
            DotName.createSimple(Dependent.class.getName()), DotName.createSimple(RequestScoped.class.getName())));
    assertEquals(expected, scopes);
}
 
Example #5
Source File: DatawaveCommonConfigPropertyProducer.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public Map<String,AuditType> produceStringAuditTypeMapConfiguration(InjectionPoint injectionPoint) {
    String propertyValue = getStringPropertyValue(injectionPoint);
    String[] pairs = StringUtils.split(propertyValue, "|");
    
    Map<String,AuditType> map = new LinkedHashMap<>();
    if (pairs != null) {
        for (String pair : pairs) {
            String[] keyValue = StringUtils.split(pair, ";");
            if (keyValue != null && keyValue.length == 2) {
                map.put(keyValue[0], AuditType.valueOf(keyValue[1]));
            } else {
                ConfigProperty configProperty = getAnnotation(injectionPoint, ConfigProperty.class);
                throw new RuntimeException("Error while converting Map<String,AuditType> property '" + configProperty.name() + "' pair: " + pair + " of "
                                + propertyValue + " happening in bean " + injectionPoint.getBean());
            }
        }
    }
    return map;
}
 
Example #6
Source File: CommandLineArgsExtension.java    From thorntail with Apache License 2.0 6 votes vote down vote up
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(Default.Literal.INSTANCE)
            .addType(List.class)
            .addType(Object.class).build();
    abd.addBean(listBean);
}
 
Example #7
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public List<Double> produceDoubleListConfiguration(InjectionPoint injectionPoint) {
    String propertyValue = getStringPropertyValue(injectionPoint);
    String[] values = StringUtils.split(propertyValue, ",");
    
    ArrayList<Double> list = new ArrayList<>();
    if (values != null) {
        for (String value : values) {
            try {
                list.add(Double.parseDouble(value));
            } catch (NumberFormatException nfe) {
                ConfigProperty configProperty = getAnnotation(injectionPoint, ConfigProperty.class);
                throw new RuntimeException("Error while converting Double property '" + configProperty.name() + "' value: " + value + " of "
                                + propertyValue + " happening in bean " + injectionPoint.getBean(), nfe);
            }
            
        }
    }
    return list;
}
 
Example #8
Source File: ConfigurationValueProducer.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #9
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public List<Long> produceLongListConfiguration(InjectionPoint injectionPoint) {
    String propertyValue = getStringPropertyValue(injectionPoint);
    String[] values = StringUtils.split(propertyValue, ",");
    
    ArrayList<Long> list = new ArrayList<>();
    if (values != null) {
        for (String value : values) {
            try {
                list.add(Long.parseLong(value));
            } catch (NumberFormatException nfe) {
                ConfigProperty configProperty = getAnnotation(injectionPoint, ConfigProperty.class);
                throw new RuntimeException("Error while converting Long property '" + configProperty.name() + "' value: " + value + " of " + propertyValue
                                + " happening in bean " + injectionPoint.getBean(), nfe);
            }
            
        }
    }
    return list;
}
 
Example #10
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public List<Integer> produceIntegerListConfiguration(InjectionPoint injectionPoint) {
    String propertyValue = getStringPropertyValue(injectionPoint);
    String[] values = StringUtils.split(propertyValue, ",");
    
    ArrayList<Integer> list = new ArrayList<>();
    if (values != null) {
        for (String value : values) {
            try {
                list.add(Integer.parseInt(value));
            } catch (NumberFormatException nfe) {
                ConfigProperty configProperty = getAnnotation(injectionPoint, ConfigProperty.class);
                throw new RuntimeException("Error while converting Integer property '" + configProperty.name() + "' value: " + value + " of "
                                + propertyValue + " happening in bean " + injectionPoint.getBean(), nfe);
            }
            
        }
    }
    return list;
}
 
Example #11
Source File: ProducerMethodParametersScanningTest.java    From weld-junit with Apache License 2.0 6 votes vote down vote up
@Produces
@Named("custom")
@Dependent
Engine getEngine(V6 v6) {
    return new Engine() {
        @Override
        public int getThrottle() {
            return v6.getThrottle();
        }

        @Override
        public void setThrottle(int value) {
            v6.setThrottle(value);
        }
    };
}
 
Example #12
Source File: DatasourceAndDriverCustomizer.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: ConfigPropertyProducer.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Produces
@ConfigProperty
@Dependent
private Object produceConfigProperty(InjectionPoint injectionPoint) {
    System.out.printf("produceConfigProperty: %s\n", injectionPoint);
    boolean isOptional = injectionPoint.getAnnotated().getBaseType().getTypeName().startsWith("java.util.Optional");
    Class<?> toType = unwrapType(injectionPoint.getAnnotated().getBaseType());

    Object value = getValue(injectionPoint, toType, isOptional);
    return isOptional ? Optional.ofNullable(value) : value;
}
 
Example #14
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
@Alternative
@Specializes
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public Long produceLongConfiguration(InjectionPoint injectionPoint) {
    return super.produceLongConfiguration(injectionPoint);
}
 
Example #15
Source File: XMLConfigProducingExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception {
    try (AutoCloseable handle = Performance.time("XMLConfigProducingExtension.afterBeanDiscovery")) {
        CommonBean<URL> urlBean = CommonBeanBuilder.newBuilder(URL.class)
                .beanClass(XMLConfigProducingExtension.class)
                .scope(Dependent.class)
                .addQualifier(XMLConfig.Literal.INSTANCE)
                .createSupplier(this::getXMLConfig)
                .addType(URL.class)
                .addType(Object.class).build();
        abd.addBean(urlBean);
    }
}
 
Example #16
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
@Alternative
@Specializes
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public Integer produceIntegerConfiguration(InjectionPoint injectionPoint) {
    return super.produceIntegerConfiguration(injectionPoint);
}
 
Example #17
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
@Alternative
@Specializes
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public Float produceFloatConfiguration(InjectionPoint injectionPoint) {
    return super.produceFloatConfiguration(injectionPoint);
}
 
Example #18
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public List<String> produceStringListConfiguration(InjectionPoint injectionPoint) {
    String propertyValue = getStringPropertyValue(injectionPoint);
    String[] values = StringUtils.split(propertyValue, ",");
    return values == null ? Collections.emptyList() : Arrays.asList(values);
}
 
Example #19
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
@Alternative
@Specializes
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public Boolean produceBooleanConfiguration(InjectionPoint injectionPoint) {
    return super.produceBooleanConfiguration(injectionPoint);
}
 
Example #20
Source File: InstanceHandle.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Delegates to {@link #destroy()} if the handle does not represent a CDI contextual instance or if it represents a
 * {@link Dependent} CDI contextual instance.
 */
@Override
default void close() {
    InjectableBean<T> bean = getBean();
    if (bean == null || Dependent.class.equals(bean.getScope())) {
        destroy();
    }
}
 
Example #21
Source File: DatawaveConfigPropertyProducer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
@Alternative
@Specializes
@Produces
@Dependent
@ConfigProperty(name = "ignored")
// we actually don't need the name
public String produceStringConfiguration(InjectionPoint injectionPoint) {
    return super.produceStringConfiguration(injectionPoint);
}
 
Example #22
Source File: InjectableInstanceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
void doSomething() {
    try (InstanceHandle<Washcloth> handle = instance.getHandle()) {
        InjectableBean<Washcloth> bean = handle.getBean();
        assertNotNull(bean);
        assertEquals(Dependent.class, bean.getScope());
        handle.get().wash();

        // Washcloth has @PreDestroy - the dependent instance should be there
        assertTrue(((InstanceImpl<?>) instance).hasDependentInstances());
    }

    // InstanceHandle.destroy() should remove the instance from the CC of the Instance
    assertFalse(((InstanceImpl<?>) instance).hasDependentInstances());
}
 
Example #23
Source File: AnnotationsTransformerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void transform(TransformationContext context) {
    if (context.isClass()) {
        if (context.getTarget().asClass().name().toString().equals(One.class.getName())) {
            // Veto bean class One
            context.transform().add(Vetoed.class).done();
        }
        if (context.getTarget().asClass().name().local().equals(IWantToBeABean.class.getSimpleName())) {
            context.transform().add(Dependent.class).done();
        }
    } else if (context.isField() && context.getTarget().asField().name().equals("seven")) {
        context.transform().add(Inject.class).done();
    }
}
 
Example #24
Source File: TransientReferenceDestroyedTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Dependent
@Produces
Beer newBeer(InjectionPoint injectionPoint) {
    int id;
    if (injectionPoint.getAnnotated() instanceof AnnotatedField) {
        id = 0;
    } else {
        id = COUNTER.incrementAndGet();
    }
    return new Beer(id);
}
 
Example #25
Source File: BeanManagerTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsScope() {
    BeanManager beanManager = Arc.container().beanManager();
    assertTrue(beanManager.isScope(Singleton.class));
    assertTrue(beanManager.isNormalScope(RequestScoped.class));
    assertFalse(beanManager.isNormalScope(Dependent.class));
}
 
Example #26
Source File: CDIInvokeSimpleGetOperationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source File: BlockingBarProducer.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
@Produces
@Dependent
@Juicy
CompletionStage<BlockingBar> juicyBlockingBar() {
    PRODUCER_USED.set(true);
    return future;
}
 
Example #28
Source File: SmallRyeReactiveMessagingProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
AnnotationsTransformerBuildItem transformBeanScope(BeanArchiveIndexBuildItem index,
        CustomScopeAnnotationsBuildItem scopes) {
    return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {
        @Override
        public boolean appliesTo(AnnotationTarget.Kind kind) {
            return kind == org.jboss.jandex.AnnotationTarget.Kind.CLASS;
        }

        @Override
        public void transform(AnnotationsTransformer.TransformationContext ctx) {
            if (ctx.isClass()) {
                ClassInfo clazz = ctx.getTarget().asClass();
                Map<DotName, List<AnnotationInstance>> annotations = clazz.annotations();
                if (scopes.isScopeDeclaredOn(clazz)
                        || annotations.containsKey(ReactiveMessagingDotNames.JAXRS_PATH)
                        || annotations.containsKey(ReactiveMessagingDotNames.REST_CONTROLLER)
                        || annotations.containsKey(ReactiveMessagingDotNames.JAXRS_PROVIDER)) {
                    // Skip - has a built-in scope annotation or is a JAX-RS endpoint/provider
                    return;
                }
                if (annotations.containsKey(ReactiveMessagingDotNames.INCOMING)
                        || annotations.containsKey(ReactiveMessagingDotNames.OUTGOING)) {
                    LOGGER.debugf(
                            "Found reactive messaging annotations on a class %s with no scope defined - adding @Dependent",
                            ctx.getTarget());
                    ctx.transform().add(Dependent.class).done();
                }
            }
        }
    });
}
 
Example #29
Source File: MockBean.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
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;
    this.priority = null;
}
 
Example #30
Source File: RequestScopedProducer.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
@Produces
@Dependent
public String produceDependentString() {
    return "foo";
}