javax.enterprise.context.spi.CreationalContext Java Examples

The following examples show how to use javax.enterprise.context.spi.CreationalContext. 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: RequestContext.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    if (contextual == null) {
        throw new IllegalArgumentException("Contextual parameter must not be null");
    }
    Map<Contextual<?>, ContextInstanceHandle<?>> ctx = currentContext.get();
    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }
    ContextInstanceHandle<T> instance = (ContextInstanceHandle<T>) ctx.get(contextual);
    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextInstanceHandleImpl<T>((InjectableBean<T>) contextual,
                contextual.create(creationalContext), creationalContext);
        ctx.put(contextual, instance);
    }
    return instance != null ? instance.get() : null;
}
 
Example #2
Source File: OutboundParameterValueRedefiner.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object redefineParameterValue(ParameterValue value)
{
    CreationalContext<?> ctx = BeanManagerProvider.getInstance().getBeanManager()
            .createCreationalContext(declaringBean);

    try
    {
        if (value.getPosition() == handlerMethod.getHandlerParameter().getPosition())
        {
            return event;
        }
        return value.getDefaultValue(ctx);
    }
    finally
    {
        if (ctx != null)
        {
            ctx.release();
        }
    }
}
 
Example #3
Source File: ExecutionIdTest.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testExecutionIdInjectableByQualifier() {
  getBeanInstance(BusinessProcess.class).startProcessByKey("keyOfTheProcess");
  
  Set<Bean<?>> beans = beanManager.getBeans(String.class, new ExecutionIdLiteral());    
  Bean<String> bean = (Bean<java.lang.String>) beanManager.resolve(beans);
  
  CreationalContext<String> ctx = beanManager.createCreationalContext(bean);
  String executionId = (String) beanManager.getReference(bean, String.class, ctx);   
  Assert.assertNotNull(executionId);
  
  String processInstanceId = (String) getBeanInstance("processInstanceId");
  Assert.assertNotNull(processInstanceId);
  
  assertEquals(processInstanceId, executionId);
}
 
Example #4
Source File: CdiServiceDiscovery.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
	List<Object> list = new ArrayList<>();
	BeanManager beanManager = getBeanManager();
	if (beanManager != null) {
		Set<Bean<?>> beans = beanManager.getBeans(Object.class);
		for (Bean<?> bean : beans) {
			Class<?> beanClass = bean.getBeanClass();
			Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
			if (annotation.isPresent()) {
				CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
				Object object = beanManager.getReference(bean, beanClass, creationalContext);
				list.add(object);
			}
		}
	}
	return list;
}
 
Example #5
Source File: CDIJCacheHelper.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
@PreDestroy
private void release() {
    if (CLOSE_CACHE && defaultCacheResolverFactory != null)
    {
        defaultCacheResolverFactory.release();
    }
    for (final CreationalContext<?> cc : toRelease)
    {
        try
        {
            cc.release();
        }
        catch (final RuntimeException re)
        {
            LOGGER.warning(re.getMessage());
        }
    }
}
 
Example #6
Source File: RedirectScopeManager.java    From krazo with Apache License 2.0 6 votes vote down vote up
/**
 * Get the instance (create it if it does not exist).
 *
 * @param <T> the type.
 * @param contextual the contextual.
 * @param creational the creational.
 * @return the instance.
 */
public <T> T get(Contextual<T> contextual, CreationalContext<T> creational) {
    T result = get(contextual);

    if (result == null) {
        String scopeId = (String) request.getAttribute(SCOPE_ID);
        if (null == scopeId) {
            scopeId = generateScopeId();
        }
        HttpSession session = request.getSession();
        result = contextual.create(creational);
        if (contextual instanceof PassivationCapable == false) {
            throw new RuntimeException("Unexpected type for contextual");
        }
        PassivationCapable pc = (PassivationCapable) contextual;
        final String sessionKey = SCOPE_ID + "-" + scopeId;
        Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
        if (null != scopeMap) {
            session.setAttribute(sessionKey, scopeMap);
            scopeMap.put(INSTANCE + pc.getId(), result);
            scopeMap.put(CREATIONAL + pc.getId(), creational);
        }
    }

    return result;
}
 
Example #7
Source File: RedirectScopeManager.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * Get the instance (create it if it does not exist).
 *
 * @param <T> the type.
 * @param contextual the contextual.
 * @param creational the creational.
 * @return the instance.
 */
public <T> T get(Contextual<T> contextual, CreationalContext<T> creational) {
    T result = get(contextual);

    if (result == null) {
        String scopeId = (String) request.getAttribute(SCOPE_ID);
        if (null == scopeId) {
            scopeId = generateScopeId();
        }
        HttpSession session = request.getSession();
        result = contextual.create(creational);
        if (contextual instanceof PassivationCapable == false) {
            throw new RuntimeException("Unexpected type for contextual");
        }
        PassivationCapable pc = (PassivationCapable) contextual;
        final String sessionKey = SCOPE_ID + "-" + scopeId;
        Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
        if (null != scopeMap) {
            session.setAttribute(sessionKey, scopeMap);
            scopeMap.put(INSTANCE + pc.getId(), result);
            scopeMap.put(CREATIONAL + pc.getId(), creational);
        }
    }

    return result;
}
 
Example #8
Source File: ManagedArtifactResolver.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: TransactionContext.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public <T> T get(Contextual<T> component, CreationalContext<T> creationalContext)
{
    Map<Contextual, TransactionBeanEntry> transactionBeanEntryMap =
        TransactionBeanStorage.getInstance().getActiveTransactionContext();

    if (transactionBeanEntryMap == null)
    {
        TransactionBeanStorage.close();

        throw new ContextNotActiveException("Not accessed within a transactional method - use @" +
                Transactional.class.getName());
    }

    TransactionBeanEntry transactionBeanEntry = transactionBeanEntryMap.get(component);
    if (transactionBeanEntry != null)
    {
        return (T) transactionBeanEntry.getContextualInstance();
    }

    // if it doesn't yet exist, we need to create it now!
    T instance = component.create(creationalContext);
    transactionBeanEntry = new TransactionBeanEntry(component, instance, creationalContext);
    transactionBeanEntryMap.put(component, transactionBeanEntry);

    return instance;
}
 
Example #10
Source File: ValidatorBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception {
    final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(
            Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
    if (webBeansContext == null) {
        return clazz.newInstance();
    }

    final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
    if (!beanManager.isInUse()) {
        return clazz.newInstance();
    }

    final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz);
    final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType);
    final CreationalContext<T> context = beanManager.createCreationalContext(null);
    final T instance = it.produce(context);
    it.inject(instance, context);
    it.postConstruct(instance);

    config.releasables.add(new Releasable<>(context, it, instance));

    return instance;
}
 
Example #11
Source File: CDIBatchArtifactFactory.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: CdiEjbBean.java    From tomee with Apache License 2.0 6 votes vote down vote up
protected T createEjb(final CreationalContext<T> creationalContext) {
    final CurrentCreationalContext currentCreationalContext = beanContext.get(CurrentCreationalContext.class);
    final CreationalContext existing = currentCreationalContext.get();
    currentCreationalContext.set(creationalContext);
    try {
        final T instance;
        if (homeLocalBean != null) {
            instance = (T) homeLocalBean.create();
        } else if (home != null) {
            instance = (T) home.create();
        } else if (remote != null) {
            instance = (T) remote.create();
        } else { // shouldn't be called for an MDB
            throw new IllegalStateException("no interface to proxy for ejb " + beanContext.getEjbName() + ", is this is a MDB maybe you shouldn't use a scope?");
        }

        if (isDependentAndStateful) {
            CreationalContextImpl.class.cast(creationalContext).addDependent(this, instance);
        }

        return instance;
    } finally {
        currentCreationalContext.set(existing);
    }
}
 
Example #13
Source File: JoynrJeeMessageContextTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testCreateNewInstanceAndSubsequentRetrievalOfExistingObject() {
    CreationalContext creationalContext = mock(CreationalContext.class);
    Contextual contextual = mock(Contextual.class);
    when(contextual.create(creationalContext)).thenReturn("test");

    Object result = JoynrJeeMessageContext.getInstance().get(contextual, creationalContext);

    assertNotNull(result);
    assertEquals("test", result);
    verify(contextual).create(creationalContext);

    assertEquals("test", JoynrJeeMessageContext.getInstance().get(contextual));

    reset(contextual);
    reset(creationalContext);

    assertEquals("test", JoynrJeeMessageContext.getInstance().get(contextual, creationalContext));
    verify(contextual, never()).create(creationalContext);
}
 
Example #14
Source File: TransactionContext.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private <T> T getInstance(final Contextual<T> contextual, final CreationalContext<T> creationalContext) {
    T instance;
    BeanInstanceBag<T> bag = (BeanInstanceBag<T>) componentInstanceMap.get(contextual);
    if (bag == null) {
        bag = createContextualBag(contextual, creationalContext);
    }

    instance = bag.beanInstance;
    if (instance != null) {
        return instance;
    } else {
        if (creationalContext == null) {
            return null;
        } else {
            instance = bag.create(contextual);
        }
    }

    return instance;
}
 
Example #15
Source File: OpenEJBEnricher.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void doInject(final Object testInstance, final BeanContext context, final BeanManagerImpl bm) throws Exception {
    final Set<Bean<?>> beans = bm.getBeans(testInstance.getClass());
    final Bean<?> bean = bm.resolve(beans);
    final CreationalContext<?> cc = bm.createCreationalContext(bean);
    if (context != null) {
        context.set(CreationalContext.class, cc);
    }
    OWBInjector.inject(bm, testInstance, cc);
}
 
Example #16
Source File: InjectionEnricher.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    //don't think about this too much
    if (closeable != null) {
        closeable.close();
    } else {
        ((CreationalContext) creationalContext).release();
    }
}
 
Example #17
Source File: Meecrowave.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public <T> AutoCloseable inject(final T instance) {
    final BeanManager bm = CDI.current().getBeanManager();
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType(instance.getClass());
    final InjectionTarget injectionTarget = bm.createInjectionTarget(annotatedType);
    final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
    injectionTarget.inject(instance, creationalContext);
    return creationalContext::release;
}
 
Example #18
Source File: BiFunctionBean.java    From hammock with Apache License 2.0 5 votes vote down vote up
public BiFunctionBean(Class<?> beanType, Set<Type> types, Set<Annotation> qualifiers,
                      Class<? extends Annotation> scope,
                      BiFunction<CreationalContext<Object>, BiFunctionBean<?>, Object> biFunction) {
    this.qualifiers = qualifiers;
    this.scope = scope;
    this.biFunction = biFunction;
    this.types = types;
    this.beanType = beanType;
}
 
Example #19
Source File: CreationalContextImpl.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static <T> CreationalContextImpl<T> unwrap(CreationalContext<T> ctx) {
    if (ctx instanceof CreationalContextImpl) {
        return (CreationalContextImpl<T>) ctx;
    } else {
        throw new IllegalArgumentException("Failed to unwrap CreationalContextImpl: " + ctx);
    }
}
 
Example #20
Source File: InterceptedBeanMetadataProvider.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Contextual<?> get(CreationalContext<Contextual<?>> creationalContext) {
    // First attempt to obtain the creational context of the interceptor bean and then the creational context of the intercepted bean
    CreationalContextImpl<?> parent = unwrap(creationalContext).getParent();
    if (parent != null) {
        parent = parent.getParent();
        return parent != null ? parent.getContextual() : null;
    }
    return null;
}
 
Example #21
Source File: ResourceProvider.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Object get(CreationalContext<Object> creationalContext) {
    InstanceHandle<Object> instance = ArcContainerImpl.instance().getResource(type, annotations);
    if (instance != null) {
        CreationalContextImpl<?> ctx = CreationalContextImpl.unwrap(creationalContext);
        if (ctx.getParent() != null) {
            ctx.getParent().addDependentInstance(instance);
        }
        return instance.get();
    }
    // TODO log a warning that a resource cannot be injected
    return null;
}
 
Example #22
Source File: RestClientBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(Object instance, CreationalContext<Object> creationalContext) {
    CxfTypeSafeClientBuilder builder = builders.remove(instance);
    if (builder != null) {
        builder.close();
    }
}
 
Example #23
Source File: ViewScopedContext.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> T get(Contextual<T> bean, CreationalContext<T> creationalContext)
{
    subscribeToJsf();

    return super.get(bean, creationalContext);
}
 
Example #24
Source File: CDIJCacheHelper.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
private <T> T instance(final Class<T> type)
{
    final Set<Bean<?>> beans = beanManager.getBeans(type);
    if (beans.isEmpty())
    {
        if (CacheKeyGenerator.class == type) {
            return (T) defaultCacheKeyGenerator;
        }
        if (CacheResolverFactory.class == type) {
            return (T) defaultCacheResolverFactory();
        }
        return null;
    }
    final Bean<?> bean = beanManager.resolve(beans);
    final CreationalContext<?> context = beanManager.createCreationalContext(bean);
    final Class<? extends Annotation> scope = bean.getScope();
    final boolean normalScope = beanManager.isNormalScope(scope);
    try
    {
        final Object reference = beanManager.getReference(bean, bean.getBeanClass(), context);
        if (!normalScope)
        {
            toRelease.add(context);
        }
        return (T) reference;
    }
    finally
    {
        if (normalScope)
        { // TODO: release at the right moment, @PreDestroy? question is: do we assume it is thread safe?
            context.release();
        }
    }
}
 
Example #25
Source File: Authorizer.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
void authorize(final InvocationContext ic, final Object returnValue, BeanManager beanManager)
    throws IllegalAccessException, IllegalArgumentException
{
    if (boundAuthorizerBean == null)
    {
        lazyInitTargetBean(beanManager);
    }

    final CreationalContext<?> creationalContext = beanManager.createCreationalContext(boundAuthorizerBean);

    Object reference = beanManager.getReference(boundAuthorizerBean,
        boundAuthorizerMethod.getJavaMember().getDeclaringClass(), creationalContext);

    Object result = boundAuthorizerMethodProxy.invoke(reference, creationalContext,
            new SecurityParameterValueRedefiner(creationalContext, ic, returnValue));

    if (Boolean.FALSE.equals(result))
    {
        Set<SecurityViolation> violations = new HashSet<SecurityViolation>();
        violations.add(new SecurityViolation()
        {
            private static final long serialVersionUID = 2358753444038521129L;

            @Override
            public String getReason()
            {
                return "Authorization check failed";
            }
        });

        throw new AccessDeniedException(violations);
    }
}
 
Example #26
Source File: JAXRSCdiResourceExtension.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and collects the CreationalContext instances for future releasing.
 * @param beanManager bean manager instance
 * @param bean bean instance to create CreationalContext for
 * @return CreationalContext instance
 */
private<T> CreationalContext< T > createCreationalContext(final BeanManager beanManager, Bean< T > bean) {
    final CreationalContext< T > creationalContext = beanManager.createCreationalContext(bean);
    
    if (!(bean instanceof DefaultApplicationBean)) {
        synchronized (disposableCreationalContexts) {
            disposableCreationalContexts.add(creationalContext);
        }
    }
    
    return creationalContext;
}
 
Example #27
Source File: CdiTestRunner.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public void evaluate() throws Throwable
{
    BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
    Class<?> type = this.method.getMethod().getDeclaringClass();
    Set<Bean<?>> beans = beanManager.getBeans(type);

    if (!USE_TEST_CLASS_AS_CDI_BEAN || beans == null || beans.isEmpty())
    {
        if (!ALLOW_INJECTION_POINT_MANIPULATION)
        {
            BeanProvider.injectFields(this.originalTarget); //fallback to simple injection
        }
        invokeMethod(this.originalTarget);
    }
    else
    {
        Bean<Object> bean = (Bean<Object>) beanManager.resolve(beans);

        CreationalContext<Object> creationalContext = beanManager.createCreationalContext(bean);

        Object target = beanManager.getReference(bean, type, creationalContext);

        try
        {
            invokeMethod(target);
        }
        finally
        {
            if (bean.getScope().equals(Dependent.class))
            {
                bean.destroy(target, creationalContext);
            }
        }
    }
}
 
Example #28
Source File: ThreadPoolManager.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private <T> T lookupByName(final String name, final Class<T> type)
{
    final Set<Bean<?>> tfb = beanManager.getBeans(name);
    final Bean<?> bean = beanManager.resolve(tfb);
    final CreationalContext<?> ctx = beanManager.createCreationalContext(null);
    if (!beanManager.isNormalScope(bean.getScope()))
    {
        contexts.add(ctx);
    }
    return type.cast(beanManager.getReference(bean, type, ctx));
}
 
Example #29
Source File: ContextualInstance.java    From trimou with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param instance
 * @param creationalContext
 * @param contextual
 */
ContextualInstance(T instance, CreationalContext<T> creationalContext,
        Contextual<T> contextual) {
    this.instance = instance;
    this.creationalContext = creationalContext;
    this.contextual = contextual;
}
 
Example #30
Source File: AsyncEjbBatchThreadPoolService.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Properties batchConfig) {
    beanManager = BatchCDIInjectionExtension.getInstance().getBeanManager();
    
    Set<Bean<?>> beans = beanManager.getBeans(ThreadExecutorEjb.class);
    Bean<?> bean = beanManager.resolve(beans);
    CreationalContext cc = beanManager.createCreationalContext(bean);
    
    threadExecutorEjb = (ThreadExecutorEjb) beanManager.getReference(bean, bean.getBeanClass(), cc);
}