Exemple #1
0
  /** Returns the current injection point. */
  public static InjectionPoint getCurrentInjectionPoint(
      BeanManager beanManager, CreationalContext<?> creationalContext) {
    Bean<? extends Object> bean = beanManager.resolve(beanManager.getBeans(InjectionPoint.class));
    InjectionPoint injectionPoint =
        (InjectionPoint) beanManager.getReference(bean, InjectionPoint.class, creationalContext);

    if (injectionPoint == null) { // It's broken in some Weld versions. Below is a work around.
      bean = beanManager.resolve(beanManager.getBeans(InjectionPointGenerator.class));
      injectionPoint =
          (InjectionPoint)
              beanManager.getInjectableReference(
                  bean.getInjectionPoints().iterator().next(), creationalContext);
    }

    return injectionPoint;
  }
 private MessageManager getMessageBuilder() {
   Set<Bean<?>> beans = bm.getBeans(MessageManager.class);
   Bean<?> bean = bm.resolve(beans);
   MessageManager mb =
       (MessageManager)
           bm.getReference(bean, MessageManager.class, bm.createCreationalContext(bean));
   return mb;
 }
 private Destination lookupDestination(AnnotatedParameter<?> ap) {
   log.debug("Looking up destination: " + ap);
   Set<Bean<?>> beans = bm.getBeans(Destination.class);
   Bean<?> bean = bm.resolve(beans);
   ImmutableInjectionPoint iip = new ImmutableInjectionPoint(ap, bm, bean, false, false);
   Object o = bm.getInjectableReference(iip, bm.createCreationalContext(bean));
   return (Destination) o;
 }
Exemple #4
0
  @SuppressWarnings("unchecked")
  public void teardown(Map<String, Object> properties) {
    try {
      final BeanManager manager =
          (BeanManager) new InitialContext().lookup("java:comp/BeanManager");

      if (manager != null && Container.available()) {
        final Bean<BoundSessionContext> sessionContextBean =
            (Bean<BoundSessionContext>)
                manager.resolve(manager.getBeans(BoundSessionContext.class, BoundLiteral.INSTANCE));
        CreationalContext<?> ctx = manager.createCreationalContext(sessionContextBean);
        final BoundSessionContext sessionContext =
            (BoundSessionContext)
                manager.getReference(sessionContextBean, BoundSessionContext.class, ctx);
        sessionContext.deactivate();
        sessionContext.dissociate(sessionContexts.get());

        final Bean<BoundRequestContext> requestContextBean =
            (Bean<BoundRequestContext>)
                manager.resolve(manager.getBeans(BoundRequestContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(requestContextBean);
        final BoundRequestContext requestContext =
            (BoundRequestContext)
                manager.getReference(requestContextBean, BoundRequestContext.class, ctx);
        requestContext.deactivate();
        requestContext.dissociate(requestContexts.get());

        final Bean<BoundConversationContext> conversationContextBean =
            (Bean<BoundConversationContext>)
                manager.resolve(
                    manager.getBeans(BoundConversationContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(conversationContextBean);
        final BoundConversationContext conversationContext =
            (BoundConversationContext)
                manager.getReference(conversationContextBean, BoundConversationContext.class, ctx);
        conversationContext.deactivate();
        conversationContext.dissociate(boundRequests.get());
      }
    } catch (NamingException e) {
      log.error("Failed to tear down Weld contexts", e);
    } finally {
      sessionContexts.remove();
      requestContexts.remove();
      boundRequests.remove();
    }
  }
Exemple #5
0
 /**
  * Utility method allowing managed instances of beans to provide entry points for non-managed
  * beans (such as {@link WeldContainer}). Should only called once Weld has finished booting.
  *
  * @param manager the BeanManager to use to access the managed instance
  * @param type the type of the Bean
  * @param bindings the bean's qualifiers
  * @return a managed instance of the bean
  * @throws IllegalArgumentException if the given type represents a type variable
  * @throws IllegalArgumentException if two instances of the same qualifier type are given
  * @throws IllegalArgumentException if an instance of an annotation that is not a qualifier type
  *     is given
  * @throws UnsatisfiedResolutionException if no beans can be resolved * @throws
  *     AmbiguousResolutionException if the ambiguous dependency resolution rules fail
  * @throws IllegalArgumentException if the given type is not a bean type of the given bean
  */
 protected <T> T getInstanceByType(BeanManager manager, Class<T> type, Annotation... bindings) {
   final Bean<?> bean = manager.resolve(manager.getBeans(type, bindings));
   if (bean == null) {
     throw CommonLogger.LOG.unableToResolveBean(type, Arrays.asList(bindings));
   }
   CreationalContext<?> cc = manager.createCreationalContext(bean);
   return type.cast(manager.getReference(bean, type, cc));
 }
Exemple #6
0
  @SuppressWarnings("unchecked")
  public void setup(Map<String, Object> properties) {
    try {
      final BeanManager manager =
          (BeanManager) new InitialContext().lookup(STANDARD_BEAN_MANAGER_JNDI_NAME);

      if (manager != null && Container.available()) {

        final Bean<BoundSessionContext> sessionContextBean =
            (Bean<BoundSessionContext>)
                manager.resolve(manager.getBeans(BoundSessionContext.class, BoundLiteral.INSTANCE));
        CreationalContext<?> ctx = manager.createCreationalContext(sessionContextBean);
        final BoundSessionContext sessionContext =
            (BoundSessionContext)
                manager.getReference(sessionContextBean, BoundSessionContext.class, ctx);
        sessionContext.associate(sessionContexts.get());
        sessionContext.activate();

        final Bean<BoundRequestContext> requestContextBean =
            (Bean<BoundRequestContext>)
                manager.resolve(manager.getBeans(BoundRequestContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(requestContextBean);
        final BoundRequestContext requestContext =
            (BoundRequestContext)
                manager.getReference(requestContextBean, BoundRequestContext.class, ctx);
        requestContext.associate(requestContexts.get());
        requestContext.activate();

        final Bean<BoundConversationContext> conversationContextBean =
            (Bean<BoundConversationContext>)
                manager.resolve(
                    manager.getBeans(BoundConversationContext.class, BoundLiteral.INSTANCE));
        ctx = manager.createCreationalContext(conversationContextBean);
        final BoundConversationContext conversationContext =
            (BoundConversationContext)
                manager.getReference(conversationContextBean, BoundConversationContext.class, ctx);
        BoundRequest request =
            new MutableBoundRequest(requestContexts.get(), sessionContexts.get());
        boundRequests.set(request);
        conversationContext.associate(request);
        conversationContext.activate();
      }
    } catch (NamingException e) {
      log.error("Failed to setup Weld contexts", e);
    }
  }
  @GET
  @Path("date")
  @Produces(MediaType.TEXT_PLAIN)
  public String date() {
    Set<Bean<?>> beans = bm.getBeans(DateService.class);
    Bean<?> bean = bm.resolve(beans);
    DateService dateService =
        (DateService) bm.getReference(bean, DateService.class, bm.createCreationalContext(bean));

    return dateService.time().toString() + System.lineSeparator();
  }
Exemple #8
0
  private void starts(final BeanManager beanManager, final Class<?> clazz) {
    final Bean<?> bean = beanManager.resolve(beanManager.getBeans(clazz));
    if (!beanManager.isNormalScope(bean.getScope())) {
      throw new IllegalStateException(
          "Only normal scoped beans can use @Startup - likely @ApplicationScoped");
    }

    final CreationalContext<Object> creationalContext = beanManager.createCreationalContext(null);
    beanManager.getReference(bean, clazz, creationalContext).toString();
    // don't release now, will be done by the context - why we restrict it to normal scoped beans
  }
  @GET
  @Path("calc")
  @Produces(MediaType.TEXT_PLAIN)
  public String calc(@QueryParam("p1") int p1, @QueryParam("p2") int p2) {
    Set<Bean<?>> beans = bm.getBeans(CalcService.class);
    Bean<?> bean = bm.resolve(beans);
    CalcService calcService =
        (CalcService) bm.getReference(bean, CalcService.class, bm.createCreationalContext(bean));

    return Integer.toString(calcService.add(p1, p2)) + System.lineSeparator();
  }
Exemple #10
0
  @SuppressWarnings("unchecked")
  public static Map<Class<?>, Class<? extends DataModel<?>>> getDataModelClassesMap(
      CDI<Object> cdi) {
    BeanManager beanManager = cdi.getBeanManager();

    // Get the Map with classes for which a custom DataModel implementation is available from CDI
    Bean<?> bean = beanManager.resolve(beanManager.getBeans("comSunFacesDataModelClassesMap"));
    Object beanReference =
        beanManager.getReference(bean, Map.class, beanManager.createCreationalContext(bean));

    return (Map<Class<?>, Class<? extends DataModel<?>>>) beanReference;
  }
Exemple #11
0
  public static Object getBeanReferenceByType(
      BeanManager beanManager, Type type, Annotation... qualifiers) {

    Object beanReference = null;

    Bean<?> bean = beanManager.resolve(beanManager.getBeans(type, qualifiers));
    if (bean != null) {
      beanReference =
          beanManager.getReference(bean, type, beanManager.createCreationalContext(bean));
    }

    return beanReference;
  }
Exemple #12
0
  @SuppressWarnings("unchecked")
  private static <T> T getContextualReference(
      BeanManager beanManager, Type beanType, Set<Bean<?>> beans) {

    Bean<?> bean = beanManager.resolve(beans);

    if (bean.getScope().equals(Dependent.class)) {
      logger.log("Dependent contextual instance cannot be properly destroyed!");
    }

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

    return ((T) beanManager.getReference(bean, beanType, creationalContext));
  }
Exemple #13
0
  public static <T> Bean<T> getBean(
      BeanManager beanManager, Type beanType, Annotation... bindings) {
    Set<Bean<?>> beans = beanManager.getBeans(beanType, bindings);
    Bean<?> bean = beanManager.resolve(beans);
    if (bean == null) {
      throw new UnsatisfiedResolutionException(
          UNRESOLVABLE_TYPE, beanType, Arrays.toString(bindings));
    }

    @SuppressWarnings("unchecked")
    Bean<T> typedBean = (Bean<T>) bean;

    return typedBean;
  }
  protected void process(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String path = req.getPathInfo();
    String result = null;

    if ((null == path) || (path.trim().length() <= 1)) result = "/nocturne.jsp";
    else {
      result = "/mapping_not_found.jsp";
      path = path.substring(1);
      req.setAttribute("path", path);

      if (logger.isLoggable(Level.FINE))
        logger.log(
            Level.FINE,
            "Method: {0}, path: {1}",
            new Object[] {req.getMethod().toUpperCase(), path});

      ServletContext servletCtx = getServletContext();
      NocturneActionMap actionMap = (NocturneActionMap) servletCtx.getAttribute("mappings");

      for (String p : actionMap.keySet()) {
        if (!p.startsWith(path)) continue;
        result = null;
        Class<?> c = actionMap.get(p);
        req.setAttribute("actionClass", c.getName());
        Set<Bean<?>> beans = bm.getBeans(c);
        Bean<?> actionBean = bm.resolve(beans);
        CreationalContext<?> ctx = bm.createCreationalContext(actionBean);
        Object action = bm.getReference(actionBean, c, ctx);
        try {
          result = ((Perform) action).perform(path, req, resp);
        } catch (final IOException | SecurityException ex) {
          logger.log(Level.WARNING, "Exception when executing: " + c.getName(), ex);
          throw ex;
        }
        break;
      }
    }

    if ((null == result) || (result.trim().length() <= 0)) result = "/no_result.jsp";

    if (logger.isLoggable(Level.INFO)) logger.log(Level.INFO, "Dispatch: {0}", result);

    RequestDispatcher rd = req.getRequestDispatcher(result);
    rd.forward(req, resp);
  }
Exemple #15
0
  /**
   * Returns concrete (non-proxied) bean instance of given class in current context.
   *
   * @param type the required bean type the instance must have
   * @param create whether to auto-create bean if not exist
   * @return a bean instance adhering to the required type
   */
  public static <T> T getBeanInstance(Class<T> type, boolean create) {
    BeanManager beanManager = Util.getCdiBeanManager(FacesContext.getCurrentInstance());
    @SuppressWarnings("unchecked")
    Bean<T> bean = (Bean<T>) beanManager.resolve(beanManager.getBeans(type));

    if (bean != null) {
      Context context = beanManager.getContext(bean.getScope());

      if (create) {
        return context.get(bean, beanManager.createCreationalContext(bean));
      } else {
        return context.get(bean);
      }
    } else {
      return null;
    }
  }
Exemple #16
0
 public void fireDestroyedEvent(FacesContext facesContext, UIViewRoot root) {
   if (isCdiOneOneOrGreater && null != viewScopedCDIEventFireHelperImplClass) {
     BeanManager beanManager =
         (BeanManager)
             Util.getCDIBeanManager(facesContext.getExternalContext().getApplicationMap());
     if (null != beanManager) {
       Set<Bean<?>> availableBeans = beanManager.getBeans(viewScopedCDIEventFireHelperImplClass);
       if (null != availableBeans && !availableBeans.isEmpty()) {
         Bean<?> bean = beanManager.resolve(availableBeans);
         CreationalContext<?> creationalContext = beanManager.createCreationalContext(null);
         ViewScopedCDIEventFireHelper eventHelper =
             (ViewScopedCDIEventFireHelper)
                 beanManager.getReference(bean, bean.getBeanClass(), creationalContext);
         eventHelper.fireDestroyedEvent(root);
       }
     }
   }
 }
Exemple #17
0
  /**
   * Obtain a bean reference of given type from the bean manager.
   *
   * @param beanClass type of the bean to get reference to.
   * @param beanManager bean manager used to obtain an instance of the requested bean.
   * @param <T> type of the bean to be returned.
   * @return a bean reference or {@code null} if a bean instance cannot be found.
   */
  public static <T> T getBeanReference(final Class<T> beanClass, final BeanManager beanManager) {
    final Set<Bean<?>> beans = beanManager.getBeans(beanClass);
    if (beans.isEmpty()) {
      return null;
    }

    try {
      return getBeanReference(beanClass, beanManager.resolve(beans), beanManager);
    } catch (final AmbiguousResolutionException ex) {
      // try to resolve the instance directly by looking at which one has already been initialized
      for (final Bean<?> b : beans) {
        final T reference = getBeanReference(beanClass, b, beanManager);
        if (reference != null) {
          return reference;
        }
      }
    }

    return null;
  }
Exemple #18
0
  /**
   * @param bean
   * @param probe
   * @return the set of dependents
   */
  static Set<Dependency> getDependents(Bean<?> bean, Probe probe) {
    Set<Dependency> dependents = new HashSet<Dependency>();
    for (Bean<?> candidate : probe.getBeans()) {
      if (candidate.equals(bean)) {
        continue;
      }
      BeanManager beanManager = probe.getBeanManager(candidate);
      if (beanManager == null) {
        // Don't process built-in beans
        continue;
      }
      Set<InjectionPoint> injectionPoints = candidate.getInjectionPoints();
      if (injectionPoints != null && !injectionPoints.isEmpty()) {
        for (InjectionPoint injectionPoint : injectionPoints) {

          // At this point unsatisfied or ambiguous dependency should not exits
          Bean<?> candidateDependency =
              beanManager.resolve(
                  beanManager.getBeans(
                      injectionPoint.getType(),
                      injectionPoint
                          .getQualifiers()
                          .toArray(new Annotation[injectionPoint.getQualifiers().size()])));
          boolean satisfies = false;

          if (isBuiltinBeanButNotExtension(candidateDependency)) {
            satisfies =
                bean.equals(
                    probe.getBean(
                        Components.getBuiltinBeanId((AbstractBuiltInBean<?>) candidateDependency)));
          } else {
            satisfies = bean.equals(candidateDependency);
          }
          if (satisfies) {
            dependents.add(new Dependency(candidate, injectionPoint));
          }
        }
      }
    }
    return dependents;
  }
Exemple #19
0
 /**
  * @param bean
  * @param beanManager
  * @param probe
  * @return the set of dependencies
  */
 static Set<Dependency> getDependencies(Bean<?> bean, BeanManager beanManager, Probe probe) {
   Set<Dependency> dependencies = new HashSet<Dependency>();
   Set<InjectionPoint> injectionPoints = bean.getInjectionPoints();
   if (injectionPoints != null && !injectionPoints.isEmpty()) {
     for (InjectionPoint injectionPoint : injectionPoints) {
       // At this point unsatisfied or ambiguous dependency should not exits
       Bean<?> dependency =
           beanManager.resolve(
               beanManager.getBeans(
                   injectionPoint.getType(),
                   injectionPoint
                       .getQualifiers()
                       .toArray(new Annotation[injectionPoint.getQualifiers().size()])));
       if (isBuiltinBeanButNotExtension(dependency)) {
         dependency =
             probe.getBean(Components.getBuiltinBeanId((AbstractBuiltInBean<?>) dependency));
       }
       dependencies.add(new Dependency(dependency, injectionPoint));
     }
   }
   return dependencies;
 }