javax.enterprise.context.spi.Contextual Java Examples

The following examples show how to use javax.enterprise.context.spi.Contextual. 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 Project: krazo   Author: eclipse-ee4j   File: RedirectScopeManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the instance.
 *
 * @param <T> the type.
 * @param contextual the contextual.
 * @return the instance, or null.
 */
public <T> T get(Contextual<T> contextual) {
    T result = null;

    String scopeId = (String) request.getAttribute(SCOPE_ID);
    if (null != scopeId) {
        HttpSession session = request.getSession();
        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) {
            result = (T) scopeMap.get(INSTANCE + pc.getId());
        } else {
            request.setAttribute(SCOPE_ID, null);       // old cookie, force new scope generation
        }
    }

    return result;
}
 
Example #2
Source Project: krazo   Author: eclipse-ee4j   File: RedirectScopeManager.java    License: 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 #3
Source Project: portals-pluto   Author: apache   File: PortletSessionScopedBeanMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Session binding listener method - unbinding from session. 
 * This occurs only when the session times out or is destroyed (in our case).
 * 
 * @param evt
 */
@Override
public void valueUnbound(HttpSessionBindingEvent evt) {
   if (isTrace) {
      LOG.trace("PortletSessionBeanHolder unbound from session. ID=" + evt.getName());
   }
   
   synchronized(beans) {
      for (String id : beans.keySet()) {
         Map<Contextual<?>, BeanInstance<?>> beanMap = beans.get(id);
         for (Contextual<?> bean : beanMap.keySet()) {
            remove(id, beanMap, bean);
         }
      }
      beans.clear();
   }
}
 
Example #4
Source Project: deltaspike   Author: apache   File: TransactionContext.java    License: 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 #5
Source Project: camunda-bpm-platform   Author: camunda   File: BusinessProcessContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual) {
  Bean<T> bean = (Bean<T>) contextual;
  String variableName = bean.getName();

  BusinessProcess businessProcess = getBusinessProcess();
  Object variable = businessProcess.getVariable(variableName);
  if (variable != null) {

    if (logger.isLoggable(Level.FINE)) {
      if(businessProcess.isAssociated()) {        
        logger.fine("Getting instance of bean '" + variableName + "' from Execution[" + businessProcess.getExecutionId() + "].");
      } else {
        logger.fine("Getting instance of bean '" + variableName + "' from transient bean store");
      }
    }

    return (T) variable;
  } else {
    return null;
  }

}
 
Example #6
Source Project: quarkus   Author: quarkusio   File: HttpSessionContext.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    HttpServletRequest request = servletRequest();
    if (request == null) {
        throw new ContextNotActiveException();
    }
    InjectableBean<T> bean = (InjectableBean<T>) contextual;
    ComputingCache<Key, ContextInstanceHandle<?>> contextualInstances = getContextualInstances(request);
    if (creationalContext != null) {
        return (T) contextualInstances.getValue(new Key(creationalContext, bean.getIdentifier())).get();
    } else {
        InstanceHandle<T> handle = (InstanceHandle<T>) contextualInstances
                .getValueIfPresent(new Key(null, bean.getIdentifier()));
        return handle != null ? handle.get() : null;
    }
}
 
Example #7
Source Project: deltaspike   Author: apache   File: AbstractContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Destroys all the Contextual Instances in the specified ContextualStorage.
 * This is a static method to allow various holder objects to cleanup
 * properly in &#064;PreDestroy.
 */
public static Map<Object, ContextualInstanceInfo<?>> destroyAllActive(ContextualStorage storage)
{
    //drop all entries in the storage before starting with destroying the original entries
    Map<Object, ContextualInstanceInfo<?>> contextMap =
            new HashMap<Object, ContextualInstanceInfo<?>>(storage.getStorage());
    storage.getStorage().clear();

    for (Map.Entry<Object, ContextualInstanceInfo<?>> entry : contextMap.entrySet())
    {
        Contextual bean = storage.getBean(entry.getKey());

        ContextualInstanceInfo<?> contextualInstanceInfo = entry.getValue();
        destroyBean(bean, contextualInstanceInfo);
    }
    return contextMap;
}
 
Example #8
Source Project: deltaspike   Author: apache   File: AbstractContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean)
{
    checkActive();

    ContextualStorage storage = getContextualStorage(bean, false);
    if (storage == null)
    {
        return null;
    }

    Map<Object, ContextualInstanceInfo<?>> contextMap = storage.getStorage();
    ContextualInstanceInfo<?> contextualInstanceInfo = contextMap.get(storage.getBeanKey(bean));
    if (contextualInstanceInfo == null)
    {
        return null;
    }

    return (T) contextualInstanceInfo.getContextualInstance();
}
 
Example #9
Source Project: activiti6-boot2   Author: dingziyang   File: BusinessProcessContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual) {
  Bean<T> bean = (Bean<T>) contextual;
  String variableName = bean.getName();

  BusinessProcess businessProcess = getBusinessProcess();
  Object variable = businessProcess.getVariable(variableName);
  if (variable != null) {
    if (logger.isDebugEnabled()) {
      if (businessProcess.isAssociated()) {
        logger.debug("Getting instance of bean '{}' from Execution[{}]", variableName, businessProcess.getExecutionId());
      } else {
        logger.debug("Getting instance of bean '{}' from transient bean store", variableName);
      }
    }

    return (T) variable;
  } else {
    return null;
  }

}
 
Example #10
Source Project: weld-junit   Author: weld   File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }

    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }
    return instance != null ? instance.get() : null;
}
 
Example #11
Source Project: portals-pluto   Author: apache   File: PortletStateScopedBeanHolder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove & destroy all beans. if a response is provided, store the bean state.
 * 
 * @param   resp     The state aware response
 */
protected void removeAll(StateAwareResponse resp) {
   for (Contextual<?> bean : beans.keySet()) {
      if (resp != null) {
         PortletSerializable thisBean = (PortletSerializable) beans.get(bean).instance;
         String[] vals = thisBean.serialize();
         String pn = config.getParamName((Bean<?>) bean);
         resp.getRenderParameters().setValues(pn, vals);
         
         if (isTrace) {
            StringBuilder txt = new StringBuilder(128);
            txt.append("Stored parameter for portlet with namespace: ");
            txt.append(resp.getNamespace());
            txt.append(", paramName: ").append(pn);
            txt.append(", Values: ").append(Arrays.toString(vals));
            LOG.trace(txt.toString());
         }
      }
      remove(bean);
   }
}
 
Example #12
Source Project: ozark   Author: mvc-spec   File: RedirectScopeManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Destroy the instance.
 *
 * @param contextual the contextual.
 */
public void destroy(Contextual contextual) {
    String scopeId = (String) request.getAttribute(SCOPE_ID);
    if (null != scopeId) {
        HttpSession session = request.getSession();
        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) {
            Object instance = scopeMap.get(INSTANCE + pc.getId());
            CreationalContext<?> creational = (CreationalContext<?>) scopeMap.get(CREATIONAL + pc.getId());
            if (null != instance && null != creational) {
                contextual.destroy(instance, creational);
                creational.release();
            }
        }
    }
}
 
Example #13
Source Project: ozark   Author: mvc-spec   File: RedirectScopeManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the instance.
 *
 * @param <T> the type.
 * @param contextual the contextual.
 * @return the instance, or null.
 */
public <T> T get(Contextual<T> contextual) {
    T result = null;

    String scopeId = (String) request.getAttribute(SCOPE_ID);
    if (null != scopeId) {
        HttpSession session = request.getSession();
        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) {
            result = (T) scopeMap.get(INSTANCE + pc.getId());
        } else {
            request.setAttribute(SCOPE_ID, null);       // old cookie, force new scope generation
        }
    }

    return result;
}
 
Example #14
Source Project: ozark   Author: mvc-spec   File: RedirectScopeManager.java    License: 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 #15
Source Project: portals-pluto   Author: apache   File: PortletSessionScopedContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean, CreationalContext<T> crco) {
   PortletSessionBeanHolder holder = PortletSessionBeanHolder.getBeanHolder();
   
   if (holder == null) {
      throw new ContextNotActiveException("The portlet session context is not active.");
   }
   
   T inst = holder.getBean(bean);
   if (inst == null) {
      inst = bean.create(crco);
      holder.putBeanInstance(bean, crco, inst);
   }
   
   return inst;
}
 
Example #16
Source Project: trimou   Author: trimou   File: RenderingContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {

    checkArgumentNotNull(contextual);
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        throw new ContextNotActiveException();
    }

    @SuppressWarnings("unchecked")
    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }

    return instance != null ? instance.get() : null;
}
 
Example #17
Source Project: flowable-engine   Author: flowable   File: BusinessProcessContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual) {
    Bean<T> bean = (Bean<T>) contextual;
    String variableName = bean.getName();

    BusinessProcess businessProcess = getBusinessProcess();
    Object variable = businessProcess.getVariable(variableName);
    if (variable != null) {
        if (LOGGER.isDebugEnabled()) {
            if (businessProcess.isAssociated()) {
                LOGGER.debug("Getting instance of bean '{}' from Execution[{}]", variableName, businessProcess.getExecutionId());
            } else {
                LOGGER.debug("Getting instance of bean '{}' from transient bean store", variableName);
            }
        }

        return (T) variable;
    } else {
        return null;
    }

}
 
Example #18
Source Project: trimou   Author: trimou   File: RenderingContext.java    License: Apache License 2.0 6 votes vote down vote up
void destroy(MustacheRenderingEvent event) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();
    if (ctx == null) {
        LOGGER.warn("Cannot destroy context - current context is null");
        return;
    }
    LOGGER.debug("Rendering finished - destroy context [template: {}]", event.getMustacheName());
    for (ContextualInstance<?> instance : ctx.values()) {
        try {
            LOGGER.trace("Destroying contextual instance [contextual: {}]", instance.getContextual());
            instance.destroy();
        } catch (Exception e) {
            LOGGER.warn("Unable to destroy instance" + instance.get() + " for bean: " + instance.getContextual());
        }
    }
    ctx.clear();
    currentContext.remove();
}
 
Example #19
Source Project: HotswapAgent   Author: HotswapProjects   File: ContextualReloadHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Will remove bean from context forcing a clean new instance to be created (eg calling post-construct)
 *
 * @param ctx
 * @param managedBean
 */
static void destroy(OwbHotswapContext ctx, Contextual<?> managedBean ) {
    try {
        LOGGER.debug("Removing bean '{}' from context '{}'", managedBean, ctx);
        Object get = ctx.get(managedBean);
        if (get != null) {
            ctx.destroy(managedBean);
        }
        get = ctx.get(managedBean);
        if (get != null) {
            LOGGER.error("Error removing ManagedBean '{}', it still exists as instance '{}'", managedBean, get);
            ctx.destroy(managedBean);
        }
    } catch (Exception e) {
        LOGGER.error("Error destoying bean '{}' in context '{}'", e, managedBean, ctx);
    }
}
 
Example #20
Source Project: portals-pluto   Author: apache   File: PortletSessionScopedBeanMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Removes & destroys the given bean from the given bean map
 * @param bean
 */
@SuppressWarnings("unchecked")
private <T> void remove(String id, Map<Contextual<?>, BeanInstance<?>> beanMap, Contextual<T> bean) {
   BeanInstance<?> bi = beanMap.get(bean);
   
   if (isDebug) {
      StringBuilder txt = new StringBuilder(80);
      txt.append("Removing bean: ");
      if (bean instanceof Bean<?>) {
         Bean<?> b = (Bean<?>) bean;
         txt.append(b.getBeanClass().getSimpleName());
      }
      txt.append(", window ID: ").append(id);
      if (bi == null) {
         txt.append(", instance is null.");
      }
      LOG.debug(txt.toString());
   }

   if (bi != null) {
      beans.remove(id);
      bi.crco.release();
      bean.destroy((T)bi.instance, (CreationalContext<T>)bi.crco);
   }
}
 
Example #21
Source Project: tomee   Author: apache   File: TransactionContext.java    License: Apache License 2.0 6 votes vote down vote up
private Map<Contextual<?>, BeanInstanceBag<?>> findMap() {
    final Object resource;
    try { // we can't call registry.getResource(KEY) in afterCompletion
        resource = context.geronimoTxMgr ?
            TransactionImpl.class.cast(context.transactionManager.getTransaction()).getResource(KEY):
            registry.getResource(KEY);
    } catch (final SystemException e) {
        throw new IllegalStateException(e);
    }

    if (resource == null) {
        final Map<Contextual<?>, BeanInstanceBag<?>> map = new HashMap<>();
        registry.putResource(KEY, map);
        registry.registerInterposedSynchronization(context);
        return map;
    }
    return Map.class.cast(resource);
}
 
Example #22
Source Project: quarkus   Author: quarkusio   File: InterceptedBeanMetadataProvider.java    License: 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 #23
Source Project: joynr   Author: bmwcarit   File: JoynrJeeMessageContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    T instance = get(contextual);
    if (instance == null) {
        instance = contextual.create(creationalContext);
        if (instance != null) {
            contextualStore.get().put(contextual, instance);
        }
    }
    return instance;
}
 
Example #24
Source Project: quarkus   Author: quarkusio   File: InjectableReferenceProviders.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unwraps the provider if necessary and invokes {@link Contextual#destroy(Object, CreationalContext)}.
 * 
 * @param <T>
 * @param provider
 * @param instance
 * @param creationalContext
 * @throws IllegalArgumentException If the specified provider is not a bean
 */
@SuppressWarnings("unchecked")
public static <T> void destroy(InjectableReferenceProvider<T> provider, T instance,
        CreationalContext<T> creationalContext) {
    if (provider instanceof CurrentInjectionPointProvider) {
        provider = ((CurrentInjectionPointProvider<T>) provider).getDelegate();
    }
    if (provider instanceof Contextual) {
        Contextual<T> contextual = (Contextual<T>) provider;
        contextual.destroy(instance, creationalContext);
    } else {
        throw new IllegalArgumentException("Injetable reference provider is not a bean: " + provider.getClass());
    }
}
 
Example #25
Source Project: trimou   Author: trimou   File: ContextualInstance.java    License: 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 #26
Source Project: portals-pluto   Author: apache   File: RedirectScopedContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean) {
   RedirectScopedBeanHolder holder = RedirectScopedBeanHolder.getBeanHolder();
   if (holder == null) {
      throw new ContextNotActiveException("The redirect context is not active.");
   }
   return holder.getBean(bean);
}
 
Example #27
Source Project: quarkus   Author: quarkusio   File: RequestContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ContextState getState() {
    ConcurrentMap<Contextual<?>, ContextInstanceHandle<?>> ctx = currentContext.get();
    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }
    return new RequestContextState(ctx);
}
 
Example #28
Source Project: HotswapAgent   Author: HotswapProjects   File: ContextualReloadHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void reload(OwbHotswapContext ctx) {
    Set<Contextual<Object>> beans = ctx.$$ha$getBeansToReloadOwb();

    if (beans != null && !beans.isEmpty()) {
        LOGGER.debug("Starting re-loading {} beans in context '{}'", beans.size(), ctx);

        Iterator<Contextual<Object>> it = beans.iterator();
        while (it.hasNext()) {
            Contextual<Object> managedBean = it.next();
            destroy(ctx, managedBean);
        }
        beans.clear();
        LOGGER.debug("Finished re-loading beans in context '{}'", ctx);
    }
}
 
Example #29
Source Project: deltaspike   Author: apache   File: ViewScopedContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean)
{
    subscribeToJsf();

    return super.get(bean);
}
 
Example #30
Source Project: quarkus   Author: quarkusio   File: AbstractSharedContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(Contextual<?> contextual) {
    ContextInstanceHandle<?> handle = instances.remove(new Key<>(contextual, null));
    if (handle != null) {
        handle.destroy();
    }
}