Exemple #1
0
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    // validate accessibility from the war1 module
    Set<Bean<?>> accessibleImplementations = manager.getBeans(Animal.class);
    assertEquals(accessibleImplementations.size(), 4);
    assertTrue(containsBean(accessibleImplementations, War1Impl.class));
    assertTrue(containsBean(accessibleImplementations, Library1Impl.class));
    assertTrue(containsBean(accessibleImplementations, SharedLibrary1Impl.class));
    assertTrue(containsBean(accessibleImplementations, SharedLibrary2Impl.class));

    // validate accessibility from the war1 library module
    Bean<?> library1ImplBean = getUniqueBean(accessibleImplementations, Library1Impl.class);
    Library1Impl library1Impl =
        (Library1Impl)
            manager.getReference(
                library1ImplBean, Animal.class, manager.createCreationalContext(library1ImplBean));
    BeanManager library1BeanManager = library1Impl.getBeanManager();
    accessibleImplementations = library1BeanManager.getBeans(Animal.class);
    assertEquals(accessibleImplementations.size(), 4);
    assertTrue(containsBean(accessibleImplementations, War1Impl.class));
    assertTrue(containsBean(accessibleImplementations, Library1Impl.class));
    assertTrue(containsBean(accessibleImplementations, SharedLibrary1Impl.class));
    assertTrue(containsBean(accessibleImplementations, SharedLibrary2Impl.class));

    // validate accessibility from the shared library 1
    Bean<?> sharedLibrary1ImplBean =
        getUniqueBean(accessibleImplementations, SharedLibrary1Impl.class);
    SharedLibrary1Impl sharedLibrary1Impl =
        (SharedLibrary1Impl)
            manager.getReference(
                sharedLibrary1ImplBean,
                Animal.class,
                manager.createCreationalContext(sharedLibrary1ImplBean));
    BeanManager sharedLibrary1BeanManager = sharedLibrary1Impl.getBeanManager();
    accessibleImplementations = sharedLibrary1BeanManager.getBeans(Animal.class);
    assertEquals(
        accessibleImplementations.size(), 2); // implementations within wars are not accessible
    assertTrue(containsBean(accessibleImplementations, SharedLibrary1Impl.class));
    assertTrue(containsBean(accessibleImplementations, SharedLibrary2Impl.class));

    // validate accessibility from the shared library 2
    Bean<?> sharedLibrary2ImplBean =
        getUniqueBean(accessibleImplementations, SharedLibrary2Impl.class);
    SharedLibrary2Impl sharedLibrary2Impl =
        (SharedLibrary2Impl)
            manager.getReference(
                sharedLibrary2ImplBean,
                Animal.class,
                manager.createCreationalContext(sharedLibrary2ImplBean));
    BeanManager sharedLibrary2BeanManager = sharedLibrary2Impl.getBeanManager();
    accessibleImplementations = sharedLibrary2BeanManager.getBeans(Animal.class);
    assertEquals(
        accessibleImplementations.size(), 2); // implementations within wars are not accessible
    assertTrue(containsBean(accessibleImplementations, SharedLibrary1Impl.class));
    assertTrue(containsBean(accessibleImplementations, SharedLibrary2Impl.class));
  }
  @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);
  }
Exemple #3
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 #4
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);
   }
 }
Exemple #5
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);
  }
Exemple #6
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 #7
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);
    }
  }
 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();
   }
 }
  @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);
  }
Exemple #11
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();
  }
  @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 #14
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;
  }
  /**
   * 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;
  }
Exemple #16
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 #17
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));
 }
Exemple #18
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 #19
0
 // Manually get OAuth2RSAuthService bean; it can't be injected as these classes can't be managed
 // CDI beans
 // because of Apache Amber library code
 private OAuth2RSAuthService getAuthService() throws OAuthProblemException {
   try {
     BeanManager beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
     Bean<OAuth2RSAuthService> bean =
         (Bean<OAuth2RSAuthService>)
             beanManager.getBeans(OAuth2RSAuthService.class).iterator().next();
     CreationalContext<OAuth2RSAuthService> context = beanManager.createCreationalContext(bean);
     return (OAuth2RSAuthService)
         beanManager.getReference(bean, OAuth2RSAuthService.class, context);
   } catch (NamingException e) {
     log.severe("JNDI error with OAuth2 Auth Service: " + e.getMessage());
     throw OAuthProblemException.error(SERVER_ERROR);
   }
 }
  @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();
  }
Exemple #21
0
  @SuppressWarnings("unchecked")
  public static <T> T getBean(Class<T> clazz) {
    BeanManager bm = getBeanManager();
    Set<Bean<?>> beans = (Set<Bean<?>>) bm.getBeans(clazz);

    if (beans == null || beans.isEmpty()) {
      return null;
    }

    Bean<T> bean = (Bean<T>) beans.iterator().next();

    CreationalContext<T> ctx = bm.createCreationalContext(bean);
    T o = (T) bm.getReference(bean, clazz, ctx);
    return o;
  }
 /**
  * Provide our own, CDI managed, ObjectFactory. Almost all Stripes object creation will flow
  * through this supplied instance, so very little needs to be done here besides this.
  *
  * @return
  */
 @Override
 protected ObjectFactory initObjectFactory() {
   try {
     BeanManager bm = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
     Set<Bean<?>> beans = bm.getBeans(CdiObjectFactory.class);
     Bean<CdiObjectFactory> beanType = (Bean<CdiObjectFactory>) beans.iterator().next();
     CreationalContext<CdiObjectFactory> ctx = bm.createCreationalContext(beanType);
     CdiObjectFactory objFactory =
         (CdiObjectFactory) bm.getReference(beanType, CdiObjectFactory.class, ctx);
     objFactory.init(this);
     return objFactory;
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
Exemple #23
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;
  }
  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);
  }
  @Test
  public void testResolvePackageWithRootPath() 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);

    final URL rootUrl = this.getClass().getResource("/ProjectBackendTestProjectStructureValid");
    final org.kie.commons.java.nio.file.Path nioRootPath = fs.getPath(rootUrl.toURI());
    final Path rootPath = paths.convert(nioRootPath);

    // Test a root resolves to null
    final Package result = projectService.resolvePackage(rootPath);
    assertNull(result);
  }
  @Test
  public void testResolvePackageNameWithNonProjectPath() 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);

    final URL testUrl = this.getClass().getResource("/");
    final org.kie.commons.java.nio.file.Path testNioPath = fs.getPath(testUrl.toURI());
    final Path testPath = paths.convert(testNioPath);

    // Test a non-Project Path resolves to null
    final Package result = projectService.resolvePackage(testPath);
    assertNull(result);
  }
Exemple #27
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);
       }
     }
   }
 }
  @Test
  public void testResolvePackageDefaultResources() 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);

    final URL testUrl =
        this.getClass().getResource("/ProjectBackendTestProjectStructureValid/src/main/resources");
    final org.kie.commons.java.nio.file.Path nioTestPath = fs.getPath(testUrl.toURI());
    final Path testPath = paths.convert(nioTestPath);

    // Test /src/main/resources resolves as the default package
    final Package result = projectService.resolvePackage(testPath);
    assertEquals("", result.getPackageName());
  }
  @Test
  public void testResourceDeleted() throws Exception {
    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/src/main/resources/delete.drl");
    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
    buildChangeListener.deleteResource(resourcePath);

    final IncrementalBuildResults incrementalBuildResults =
        buildResultsObserver.getIncrementalBuildResults();
    assertNotNull(incrementalBuildResults);
    assertEquals(0, incrementalBuildResults.getAddedMessages().size());
    assertEquals(0, incrementalBuildResults.getRemovedMessages().size());
  }
  @SuppressWarnings({"unchecked", "serial"})
  @Test
  public void testCustomBean(BeanManager beanManager) throws Exception {
    Set<Bean<?>> beans = beanManager.getBeans("bar");
    assertEquals(1, beans.size());
    Bean<Foo> fooBean = (Bean<Foo>) beans.iterator().next();
    assertEquals(Dependent.class, fooBean.getScope());
    Foo foo1 =
        (Foo)
            beanManager.getReference(
                fooBean, Foo.class, beanManager.createCreationalContext(fooBean));
    Foo foo2 =
        (Foo)
            beanManager.getReference(
                fooBean, Foo.class, beanManager.createCreationalContext(fooBean));
    assertFalse(foo1.getId().equals(foo2.getId()));

    beans = beanManager.getBeans(Foo.class, Juicy.Literal.INSTANCE);
    assertEquals(1, beans.size());
    fooBean = (Bean<Foo>) beans.iterator().next();
    Foo foo =
        (Foo)
            beanManager.getReference(
                fooBean, Foo.class, beanManager.createCreationalContext(fooBean));
    foo.ping();

    beans = beanManager.getBeans(Integer.class, Random.Literal.INSTANCE);
    assertEquals(1, beans.size());
    Bean<Integer> randomBean = (Bean<Integer>) beans.iterator().next();
    CreationalContext<Integer> ctx = beanManager.createCreationalContext(randomBean);
    Integer random = (Integer) beanManager.getReference(randomBean, Integer.class, ctx);
    assertNotNull(random);
    assertTrue(random >= 0 && random < 1000);
    randomBean.destroy(random, ctx);
    assertTrue(BuilderExtension.DISPOSED.get());

    beans = beanManager.getBeans(Long.class, AnotherRandom.Literal.INSTANCE);
    assertEquals(1, beans.size());
    Bean<Long> anotherRandomBean = (Bean<Long>) beans.iterator().next();
    Long anotherRandom =
        (Long)
            beanManager.getReference(
                anotherRandomBean,
                Long.class,
                beanManager.createCreationalContext(anotherRandomBean));
    assertNotNull(anotherRandom);
    assertEquals(Long.valueOf(foo.getId() * 2), anotherRandom);

    beans = beanManager.getBeans(Bar.class);
    assertEquals(1, beans.size());
    Bean<Bar> barBean = (Bean<Bar>) beans.iterator().next();
    assertEquals(Dependent.class, barBean.getScope());

    beans =
        beanManager.getBeans(new TypeLiteral<List<String>>() {}.getType(), Juicy.Literal.INSTANCE);
    assertEquals(1, beans.size());
    Bean<List<String>> listBean = (Bean<List<String>>) beans.iterator().next();
    assertEquals(Dependent.class, listBean.getScope());
    List<String> list =
        (List<String>)
            beanManager.getReference(
                listBean,
                new TypeLiteral<List<String>>() {}.getType(),
                beanManager.createCreationalContext(listBean));
    assertNotNull(list);
    assertEquals(1, list.size());
    assertEquals("FOO", list.get(0));

    beans = beanManager.getBeans(VetoedBean.class, Random.Literal.INSTANCE);
    assertEquals(1, beans.size());
    fooBean = (Bean<Foo>) beans.iterator().next();
    assertEquals(Dependent.class, fooBean.getScope());
    Foo randomFoo =
        (Foo)
            beanManager.getReference(
                fooBean, Foo.class, beanManager.createCreationalContext(listBean));
    assertEquals(Long.valueOf(-1), randomFoo.getId());

    beans = beanManager.getBeans(Configuration.class);
    assertEquals(1, beans.size());
    Bean<Configuration> configBean = (Bean<Configuration>) beans.iterator().next();
    assertEquals(Dependent.class, configBean.getScope());
    Configuration configuration =
        (Configuration)
            beanManager.getReference(
                configBean, Configuration.class, beanManager.createCreationalContext(configBean));
    assertEquals(1, configuration.getId());
  }