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 File: BusinessProcessContext.java    From activiti6-boot2 with 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 #2
Source File: PortletSessionScopedBeanMap.java    From portals-pluto with 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 #3
Source File: PortletSessionScopedBeanMap.java    From portals-pluto with 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 #4
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 #5
Source File: ContextualReloadHelper.java    From HotswapAgent with 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 #6
Source File: TransactionContext.java    From tomee with 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 #7
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 #8
Source File: RenderingContext.java    From trimou with 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 #9
Source File: BusinessProcessContext.java    From flowable-engine with 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 File: RenderingContext.java    From trimou with 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 #11
Source File: PortletSessionScopedContext.java    From portals-pluto with 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 #12
Source File: RedirectScopeManager.java    From ozark with 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 #13
Source File: RedirectScopeManager.java    From krazo with 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 File: AbstractContext.java    From deltaspike with 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 #15
Source File: ContextImpl.java    From weld-junit with 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 #16
Source File: AbstractContext.java    From deltaspike with 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 #17
Source File: HttpSessionContext.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) {
    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 #18
Source File: PortletStateScopedBeanHolder.java    From portals-pluto with 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 #19
Source File: BusinessProcessContext.java    From camunda-bpm-platform with 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 #20
Source File: RedirectScopeManager.java    From ozark with 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 #21
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 #22
Source File: JoynrJeeMessageContext.java    From joynr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual) {
    Map<Contextual<?>, Object> store = contextualStore.get();
    if (store == null) {
        throw new ContextNotActiveException();
    }
    return (T) store.get(contextual);
}
 
Example #23
Source File: PortletStateScopedContext.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean, CreationalContext<T> crco) {
   PortletStateScopedBeanHolder holder = PortletStateScopedBeanHolder.getBeanHolder();
   
   if (holder == null) {
      throw new ContextNotActiveException("The render state context is not active.");
   }
   
   // The bean hoder will return an existing bean instance or create a new one
   // if no existing instance is available.
   T inst = holder.getBean(bean, crco);      
   return inst;
}
 
Example #24
Source File: BusinessProcessContext.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> arg1) {

  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 {

    if (logger.isDebugEnabled()) {
      if (businessProcess.isAssociated()) {
        logger.debug("Creating instance of bean '{}' in business process context representing Execution[{}]", variableName, businessProcess.getExecutionId());
      } else {
        logger.debug("Creating instance of bean '{}' in transient bean store", variableName);
      }
    }

    T beanInstance = bean.create(arg1);
    businessProcess.setVariable(variableName, beanInstance);
    return beanInstance;
  }

}
 
Example #25
Source File: PortletSessionScopedContext.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean) {
   PortletSessionBeanHolder holder = PortletSessionBeanHolder.getBeanHolder();
   if (holder == null) {
      throw new ContextNotActiveException("The portlet session context is not active.");
   }
   return holder.getBean(bean);
}
 
Example #26
Source File: BusinessScopeContext.java    From drools-workshop with Apache License 2.0 5 votes vote down vote up
public <T> T get(Contextual<T> contextual) {
    Bean bean = (Bean) contextual;
    // you can store the bean somewhere
    if (somewhere.containsKey(bean.getName())) {
        return (T) somewhere.get(bean.getName());
    } else {
        return null;
    }
}
 
Example #27
Source File: ContextualReloadHelper.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
public static void reload(WeldHotswapContext ctx) {
    Set<Contextual<Object>> beans = ctx.$$ha$getBeansToReloadWeld();

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

        Iterator<Contextual<Object>> it = beans.iterator();
        while (it.hasNext()) {
            Contextual<Object> managedBean = it.next();
            destroy(ctx, managedBean);
        }
        beans.clear();
        LOGGER.debug("Finished re-loading Contextuals in {}", ctx);
    }
}
 
Example #28
Source File: EntityManagerContext.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(final Contextual<T> component, final CreationalContext<T> creationalContext) {
    BeanInstanceBag<T> bag = (BeanInstanceBag<T>) components.get(component);
    if (bag == null) {
        bag = new BeanInstanceBag<>(creationalContext);
        components.put(component, bag);
    }
    if (bag.beanInstance == null) {
        bag.beanInstance = component.create(creationalContext);
    }
    return bag.beanInstance;
}
 
Example #29
Source File: DeploymentContextImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public void destroy(Contextual<?> contextual) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();
    if (ctx == null) {
        return;
    }
    ctx.remove(contextual);
}
 
Example #30
Source File: EntityManagerContext.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private <T> void doDestroy(final Contextual<T> contextual, final BeanInstanceBag<T> bag) {
    if ( bag.beanInstance !=null ) {
        // check null here because in case of missconfiguration, this can raise an NPE and hide the original exception
        contextual.destroy(bag.beanInstance, bag.beanCreationalContext);
    }
    bag.beanCreationalContext.release();
}