@Override
  public void validate(final FacesContext context) {
    context
        .getApplication()
        .publishEvent(context, PreValidateEvent.class, UIValidateForm.class, this);
    BeanManager manager = BeanManagerAccessor.getBeanManager();
    manager.fireEvent(this, BEFORE);

    Validator validator = context.getApplication().createValidator(validatorId);
    if (validator == null) {
      throw new IllegalArgumentException(
          "Could not create Validator with id: [" + validatorId + "]");
    }

    try {
      UIComponent parent = this.getParent();
      validator.validate(context, parent, components);
    } catch (ValidatorException e) {
      setValid(false);
      for (UIInput comp : components.values()) {
        comp.setValid(false);
        // TODO Put this back when attributes can control it
        // context.addMessage(comp.getClientId(), e.getFacesMessage());
      }
      context.addMessage(null, e.getFacesMessage());
    }

    manager.fireEvent(this, AFTER);
    context
        .getApplication()
        .publishEvent(context, PostValidateEvent.class, UIValidateForm.class, this);
  }
  @SuppressWarnings("unchecked")
  <T, X> void registerBeans(@Observes AfterBeanDiscovery event, final BeanManager beanManager) {

    if (beanManager.getBeans(RemoteCacheManager.class).isEmpty()) {
      LOGGER.addDefaultRemoteCacheManager();
      event.addBean(createDefaultRemoteCacheManagerBean(beanManager));
    }

    for (Map.Entry<Type, Set<Annotation>> entry : remoteCacheInjectionPoints.entrySet()) {

      event.addBean(
          new BeanBuilder(beanManager)
              .readFromType(beanManager.createAnnotatedType(Reflections.getRawType(entry.getKey())))
              .addType(entry.getKey())
              .addQualifiers(entry.getValue())
              .beanLifecycle(
                  new ContextualLifecycle<RemoteCache<?, ?>>() {
                    @Override
                    public RemoteCache<?, ?> create(
                        Bean<RemoteCache<?, ?>> bean, CreationalContext<RemoteCache<?, ?>> ctx) {
                      return remoteCacheProducer.produce(ctx);
                    }

                    @Override
                    public void destroy(
                        Bean<RemoteCache<?, ?>> bean,
                        RemoteCache<?, ?> instance,
                        CreationalContext<RemoteCache<?, ?>> ctx) {
                      remoteCacheProducer.dispose(instance);
                    }
                  })
              .create());
    }
  }
Beispiel #3
0
  /**
   * Finds an annotation in an Annotated, taking stereo types into account
   *
   * @param beanManager the current bean manager
   * @param annotated the Annotated in which to search
   * @param annotationType the type of the annotation to search for
   * @return An Optional that contains an instance of annotation type for which was searched if the
   *     annotated contained this.
   */
  public static <A extends Annotation> Optional<A> getAnnotation(
      BeanManager beanManager, Annotated annotated, Class<A> annotationType) {

    annotated.getAnnotation(annotationType);

    if (annotated.getAnnotations().isEmpty()) {
      return empty();
    }

    if (annotated.isAnnotationPresent(annotationType)) {
      return Optional.of(annotated.getAnnotation(annotationType));
    }

    Queue<Annotation> annotations = new LinkedList<>(annotated.getAnnotations());

    while (!annotations.isEmpty()) {
      Annotation annotation = annotations.remove();

      if (annotation.annotationType().equals(annotationType)) {
        return Optional.of(annotationType.cast(annotation));
      }

      if (beanManager.isStereotype(annotation.annotationType())) {
        annotations.addAll(beanManager.getStereotypeDefinition(annotation.annotationType()));
      }
    }

    return empty();
  }
  private void afterDeploymentValidation(
      @Observes AfterDeploymentValidation adv, BeanManager manager) {
    Collection<CamelContext> contexts = new ArrayList<>();
    for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) {
      contexts.add(getReference(manager, CamelContext.class, context));
    }

    // Add type converters to Camel contexts
    CdiTypeConverterLoader loader = new CdiTypeConverterLoader();
    for (Class<?> converter : converters) {
      for (CamelContext context : contexts) {
        loader.loadConverterMethods(context.getTypeConverterRegistry(), converter);
      }
    }

    // Add routes to Camel contexts
    boolean deploymentException = false;
    Set<Bean<?>> routes = new HashSet<>(manager.getBeans(RoutesBuilder.class, ANY));
    routes.addAll(manager.getBeans(RouteContainer.class, ANY));
    for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) {
      for (Bean<?> route : routes) {
        Set<Annotation> qualifiers = new HashSet<>(context.getQualifiers());
        qualifiers.retainAll(route.getQualifiers());
        if (qualifiers.size() > 1) {
          deploymentException |= !addRouteToContext(route, context, manager, adv);
        }
      }
    }
    // Let's return to avoid starting misconfigured contexts
    if (deploymentException) {
      return;
    }

    // Trigger eager beans instantiation (calling toString is necessary to force
    // the initialization of normal-scoped beans).
    // FIXME: This does not work with OpenWebBeans for bean whose bean type is an
    // interface as the Object methods does not get forwarded to the bean instances!
    eagerBeans.forEach(type -> getReferencesByType(manager, type.getJavaClass(), ANY).toString());
    manager
        .getBeans(Object.class, ANY, STARTUP)
        .stream()
        .forEach(bean -> getReference(manager, bean.getBeanClass(), bean).toString());

    // Start Camel contexts
    for (CamelContext context : contexts) {
      if (ServiceStatus.Started.equals(context.getStatus())) {
        continue;
      }
      logger.info("Camel CDI is starting Camel context [{}]", context.getName());
      try {
        context.start();
      } catch (Exception exception) {
        adv.addDeploymentProblem(exception);
      }
    }

    // Clean-up
    Stream.of(converters, camelBeans, eagerBeans, cdiBeans).forEach(Set::clear);
    Stream.of(producerBeans, producerQualifiers).forEach(Map::clear);
  }
  @Test
  public void testNonPackageResourceUpdated() throws Exception {
    // This tests changes to a resource that is neither pom.xml nor kmodule.xml nor within a Package
    final Bean buildChangeListenerBean =
        (Bean)
            beanManager
                .getBeans(org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class)
                .iterator()
                .next();
    final CreationalContext cc = beanManager.createCreationalContext(buildChangeListenerBean);
    final org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder buildChangeListener =
        (org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder)
            beanManager.getReference(
                buildChangeListenerBean,
                org.guvnor.common.services.builder.ResourceChangeIncrementalBuilder.class,
                cc);

    final URL resourceUrl = this.getClass().getResource("/BuildChangeListenerRepo/project.imports");
    final org.uberfire.java.nio.file.Path nioResourcePath = fs.getPath(resourceUrl.toURI());
    final Path resourcePath = paths.convert(nioResourcePath);

    // Force full build before attempting incremental changes
    final KieProject project = projectService.resolveProject(resourcePath);
    final BuildResults buildResults = buildService.build(project);
    assertNotNull(buildResults);
    assertEquals(0, buildResults.getErrorMessages().size());
    assertEquals(1, buildResults.getInformationMessages().size());

    // Perform incremental build (Without a full Build first)
    buildChangeListener.updateResource(resourcePath);

    final IncrementalBuildResults incrementalBuildResults =
        buildResultsObserver.getIncrementalBuildResults();
    assertNull(incrementalBuildResults);
  }
Beispiel #6
0
  @Override
  @SuppressWarnings("unchecked")
  public JCDIInjectionContext createManagedObject(
      Class managedClass, BundleDescriptor bundle, boolean invokePostConstruct) {
    JCDIInjectionContext context = null;

    Object managedObject = null;

    try {
      managedObject =
          createEEManagedObject(bundle.getManagedBeanByBeanClass(managedClass.getName()));
    } catch (Exception e) {
      e.printStackTrace();
    }

    WeldContainer wc = getWeldContainer();
    if (wc != null) {
      BeanManager beanManager = wc.getBeanManager();

      AnnotatedType annotatedType = beanManager.createAnnotatedType(managedClass);
      InjectionTarget target = beanManager.createInjectionTarget(annotatedType);

      CreationalContext cc = beanManager.createCreationalContext(null);

      target.inject(managedObject, cc);

      if (invokePostConstruct) {
        target.postConstruct(managedObject);
      }

      context = new JCDIInjectionContextImpl(target, cc, managedObject);
    }

    return context;
  }
 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;
 }
Beispiel #8
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));
 }
Beispiel #9
0
 public void beforeShutdown(@Observes BeforeShutdown event, BeanManager beanManager) {
   // Take care of destroying singletons
   for (Bean singleton : singletons) {
     CreationalContext cc = beanManager.createCreationalContext(singleton);
     Object o = beanManager.getReference(singleton, singleton.getBeanClass(), cc);
     singleton.destroy(o, cc);
   }
 }
Beispiel #10
0
  private static <T> T getBeanReference(
      final Class<T> clazz, final Bean extensionBean, final BeanManager beanManager) {
    final CreationalContext<?> creationalContext =
        beanManager.createCreationalContext(extensionBean);
    final Object result = beanManager.getReference(extensionBean, clazz, creationalContext);

    return clazz.cast(result);
  }
 public String doLogout() {
   AlterableContext ctx = (AlterableContext) beanManager.getContext(SessionScoped.class);
   Bean<?> myBean = beanManager.getBeans(AccountBean.class).iterator().next();
   ctx.destroy(myBean);
   myBean = beanManager.getBeans(ShoppingCartBean.class).iterator().next();
   ctx.destroy(myBean);
   return "/main";
 }
 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;
 }
 public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) {
   for (Bean<?> bean : eagerBeansList) {
     // note: toString() is important to instantiate the bean
     beanManager
         .getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean))
         .toString();
   }
 }
  protected List<Interceptor<?>> resolveInterceptors(Object instance, Method method) {
    Annotation[] interceptorBindings = extractInterceptorBindings(instance, method);
    if (interceptorBindings.length > 0) {
      BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
      return beanManager.resolveInterceptors(InterceptionType.AROUND_INVOKE, interceptorBindings);
    }

    return null;
  }
Beispiel #15
0
  /** Returns true if given scope is active in current context. */
  public static <S extends Annotation> boolean isScopeActive(Class<S> scope) {
    BeanManager beanManager = Util.getCdiBeanManager(FacesContext.getCurrentInstance());

    try {
      Context context = beanManager.getContext(scope);
      return context.isActive();
    } catch (ContextNotActiveException ignore) {
      return false;
    }
  }
 public void configure() {
   Set<Bean<?>> beans = beanManager.getBeans(Object.class);
   for (Bean<?> bean : beans) {
     Annotation qualifier = tryToFindAStereotypeQualifier(bean);
     if (qualifier != null) {
       beanManager.fireEvent(new DefaultBeanClass(bean.getBeanClass()), qualifier);
     }
   }
   interceptorsCache.init();
 }
  @Test
  public void testProjectServiceInstantiation() throws Exception {

    final Bean projectServiceBean =
        (Bean) beanManager.getBeans(ProjectService.class).iterator().next();
    final CreationalContext cc = beanManager.createCreationalContext(projectServiceBean);
    final ProjectService projectService =
        (ProjectService) beanManager.getReference(projectServiceBean, ProjectService.class, cc);
    assertNotNull(projectService);
  }
 public String doLogoutAndRemoveCookie() {
   removeCookie();
   user.setUuid(null);
   em.merge(user);
   AlterableContext ctx = (AlterableContext) beanManager.getContext(SessionScoped.class);
   Bean<?> myBean = beanManager.getBeans(AccountBean.class).iterator().next();
   ctx.destroy(myBean);
   myBean = beanManager.getBeans(ShoppingCartBean.class).iterator().next();
   ctx.destroy(myBean);
   return "/main";
 }
  @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();
  }
Beispiel #20
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("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();
  }
Beispiel #22
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;
  }
  @Test
  public void test() throws Exception {
    final Orange orange = new Orange();
    beanManager.fireEvent(orange);

    final Green green = new Green();
    beanManager.fireEvent(green);

    Assert.assertEquals(2, painter.getObserved().size());
    Assert.assertSame(orange, painter.getObserved().get(0));
    Assert.assertSame(green, painter.getObserved().get(1));
  }
  /**
   * Create a Collection of {@link Transformer} instances from the supplied {@link TransformModel}
   * instance.
   *
   * @param transformModel The TransformModel instance.
   * @return The Transformer instance.
   */
  public Collection<Transformer<?, ?>> newTransformers(TransformModel transformModel) {

    Collection<Transformer<?, ?>> transformers = null;

    if (transformModel instanceof JavaTransformModel) {
      JavaTransformModel javaTransformModel = JavaTransformModel.class.cast(transformModel);
      String bean = javaTransformModel.getBean();
      if (bean != null) {
        BeanManager beanManager = CDIUtil.lookupBeanManager();
        if (beanManager == null) {
          throw TransformMessages.MESSAGES.cdiBeanManagerNotFound();
        }
        Object transformer = null;
        Set<Bean<?>> beans = beanManager.getBeans(bean);
        if (beans != null && !beans.isEmpty()) {
          Bean<?> target = beans.iterator().next();
          CreationalContext<?> context = beanManager.createCreationalContext(target);
          transformer = beanManager.getReference(target, Object.class, context);
          _cdiCreationalContexts.add(context);
        }
        if (transformer == null) {
          throw TransformMessages.MESSAGES.beanNotFoundInCDIRegistry(bean);
        }
        transformers =
            TransformerUtil.newTransformers(
                transformer, transformModel.getFrom(), transformModel.getTo());
      } else {
        String className = ((JavaTransformModel) transformModel).getClazz();
        if (className == null) {
          throw TransformMessages.MESSAGES.beanOrClassMustBeSpecified();
        }
        Class<?> transformClass = getClass(className);
        if (transformClass == null) {
          throw TransformMessages.MESSAGES.unableToLoadTransformerClass(className);
        }
        transformers =
            TransformerUtil.newTransformers(
                transformClass, transformModel.getFrom(), transformModel.getTo());
      }
    } else {
      TransformerFactory factory = getTransformerFactory(transformModel);

      transformers = new ArrayList<Transformer<?, ?>>();
      transformers.add(factory.newTransformer(_serviceDomain, transformModel));
    }

    if (transformers == null || transformers.isEmpty()) {
      throw TransformMessages.MESSAGES.unknownTransformModel(transformModel.getClass().getName());
    }

    return transformers;
  }
Beispiel #25
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;
  }
Beispiel #26
0
 /**
  * @param filterClass
  * @return contextual filter instances.
  */
 private WebSocketFilter getReference(Class<?> filterClass) {
   final Set<Bean<?>> filterBeans = beanManager.getBeans(filterClass);
   if (filterBeans.size() > 1) {
     LOGGER.error(
         "configured Errai websocket filter must be a concrete implementation of "
             + WebSocketFilter.class.getName());
     throw new IllegalArgumentException("Wrong definition of Errai websocket filter");
   }
   final Bean<?> filterBean = filterBeans.iterator().next();
   return (WebSocketFilter)
       beanManager.getReference(
           filterBean, filterBean.getBeanClass(), beanManager.createCreationalContext(filterBean));
 }
  @Before
  public void setUp() throws Exception {
    // Bootstrap WELD container
    StartMain startMain = new StartMain(new String[0]);
    beanManager = startMain.go().getBeanManager();

    // Instantiate Paths used in tests for Path conversion
    final Bean pathsBean = (Bean) beanManager.getBeans(Paths.class).iterator().next();
    final CreationalContext cc = beanManager.createCreationalContext(pathsBean);
    paths = (Paths) beanManager.getReference(pathsBean, Paths.class, cc);

    // Ensure URLs use the default:// scheme
    fs.forceAsDefault();
  }
 public Object createEntityListenerAndInjectDependancies(Class entityListenerClass)
     throws NamingException {
   AnnotatedType<Object> aType = beanManager.createAnnotatedType(entityListenerClass);
   InjectionTarget<Object> injectionTarget = beanManager.<Object>createInjectionTarget(aType);
   Object entityListener =
       injectionTarget.produce(beanManager.<Object>createCreationalContext(null));
   synchronized (injectionTargets) {
     injectionTargets.put(entityListener, injectionTarget);
   }
   injectionTarget.postConstruct(entityListener);
   creationalContext = beanManager.<Object>createCreationalContext(null);
   injectionTarget.inject(entityListener, creationalContext);
   return entityListener;
 }
Beispiel #29
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));
  }
Beispiel #30
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;
  }