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);
  }
 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";
 }
Beispiel #3
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));
  }
 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";
 }
  @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 #6
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;
  }
  @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);
  }
 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;
 }
Beispiel #9
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();
    }
  }
Beispiel #10
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);
    }
  }
Beispiel #11
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));
 }
 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;
 }
 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);
  }
Beispiel #15
0
  /**
   * @param beanManager
   * @param beanType
   * @param name
   * @return
   */
  public static <T> T getContextualReference(
      BeanManager beanManager, String name, Class<T> beanType) {

    Set<Bean<?>> beans = beanManager.getBeans(name);

    if (beans == null || beans.isEmpty()) {
      return null;
    }
    return BeanLookupUtils.<T>getContextualReference(beanManager, beanType, 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 #17
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();
  }
 /**
  * List all UI beans (whether or not they have the {@link CDIUI} annotation.
  *
  * @param beanManager
  * @return set of UI beans
  */
 public static Set<Bean<?>> getUiBeans(BeanManager beanManager) {
   // The annotation @CDIUI can have a value, so using it as the type
   // parameter of AnnotationLiteral is somewhat problematic.
   Set<Class<? extends UI>> uiBeans = MVP.getSubTypesOf(UI.class);
   HashSet<Bean<?>> beans = new HashSet<Bean<?>>();
   for (Class<?> uiBean : uiBeans) {
     Iterator<Bean<?>> iterator = beanManager.getBeans(uiBean).iterator();
     if (iterator.hasNext()) beans.add(iterator.next());
   }
   return beans;
 }
Beispiel #20
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;
  }
Beispiel #22
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 #23
0
  private static Set<Bean<?>> getBeans(
      BeanManager beanManager, Type beanType, Annotation... qualifiers) {

    Set<Bean<?>> beans = beanManager.getBeans(beanType, qualifiers);

    if (beans == null || beans.isEmpty()) {
      throw new UnsatisfiedResolutionException(
          String.format(
              "No bean matches required type %s and required qualifiers %s",
              beanType, Arrays.toString(qualifiers)));
    }
    return beans;
  }
Beispiel #24
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));
 }
Beispiel #25
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();
  }
Beispiel #27
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;
  }
 /**
  * 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);
   }
 }
Beispiel #29
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;
  }
  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);
  }