org.apache.webbeans.container.BeanManagerImpl Java Examples

The following examples show how to use org.apache.webbeans.container.BeanManagerImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OWBAutoSetup.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private void customizeContext(final WebBeansContext instance) {
    final BeanManagerImpl beanManager = instance.getBeanManagerImpl();

    beanManager.addInternalBean(newBean(instance, configurator ->
            configurator.beanClass(Meecrowave.Builder.class)
                    .scope(ApplicationScoped.class)
                    .qualifiers(DefaultLiteral.INSTANCE)
                    .types(Configuration.class, Meecrowave.Builder.class, Object.class)
                    .createWith(cc -> meecrowave.getConfiguration())));
    beanManager.addInternalBean(newBean(instance, configurator ->
            configurator.beanClass(Meecrowave.class)
                    .scope(ApplicationScoped.class)
                    .qualifiers(DefaultLiteral.INSTANCE)
                    .types(Meecrowave.class, AutoCloseable.class, Object.class)
                    .createWith(cc -> meecrowave)));
}
 
Example #2
Source File: WebappBeanManagerTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void containerEventsShouldntGoUp() {
    final WebappWebBeansContext ctx = new WebappWebBeansContext(Collections.<Class<?>, Object>emptyMap(), new Properties(), new WebBeansContext());
    final WebappBeanManager wbm = new WebappBeanManager(ctx) {
        @Override
        public BeanManagerImpl getParentBm() {
            throw new IllegalStateException("shouldn't be called");
        }
    };
    wbm.fireEvent(new GProcessProducer(null, null), true);
    wbm.fireEvent(new GProcessProducerField(null, null, null), true);
    wbm.fireEvent(new GProcessProducerMethod(null, null, null), true);
    wbm.fireEvent(new GProcessInjectionTarget(null, null), true);
    wbm.fireEvent(new GProcessBean(null, null), true);
    wbm.fireEvent(new GProcessAnnotatedType(ctx, null), true);
    wbm.fireEvent(new GProcessSessionBean(null, null, null, null), true);
    wbm.fireEvent(new AfterBeanDiscoveryImpl(ctx), true);
    wbm.fireEvent(new AfterDeploymentValidationImpl(wbm), true);
    wbm.fireEvent(new BeforeBeanDiscoveryImpl(ctx), true);
    wbm.fireEvent(new BeforeShutdownImpl(), true);
}
 
Example #3
Source File: CdiScanner.java    From tomee with Apache License 2.0 6 votes vote down vote up
private boolean isBean(final Class clazz) {
    try {
        for (final Annotation a : clazz.getAnnotations()) {
            final Class<? extends Annotation> annotationType = a.annotationType();
            final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
            if (beanManager.isScope(annotationType)
                    || beanManager.isStereotype(annotationType)
                    || beanManager.isInterceptorBinding(annotationType)
                    || Decorator.class == a.annotationType()) {
                return true;
            }
        }
    }
    catch (final Throwable e) {
        // no-op
    }
    return false;
}
 
Example #4
Source File: ValidatorBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static <T> T newInstance(final OpenEjbConfig config, final Class<T> clazz) throws Exception {
    final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(
            Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
    if (webBeansContext == null) {
        return clazz.newInstance();
    }

    final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
    if (!beanManager.isInUse()) {
        return clazz.newInstance();
    }

    final AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz);
    final InjectionTarget<T> it = beanManager.createInjectionTarget(annotatedType);
    final CreationalContext<T> context = beanManager.createCreationalContext(null);
    final T instance = it.produce(context);
    it.inject(instance, context);
    it.postConstruct(instance);

    config.releasables.add(new Releasable<>(context, it, instance));

    return instance;
}
 
Example #5
Source File: OpenEJBEnricher.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static BeanManagerImpl findBeanManager(final AppContext ctx) {
    if (ctx != null) {
        if (ctx.getWebBeansContext() == null) {
            return null;
        }
        return ctx.getWebBeansContext().getBeanManagerImpl();
    }

    try { // else try to find it from tccl through our SingletonService
        return WebBeansContext.currentInstance().getBeanManagerImpl();
    } catch (final Exception e) { // if not found IllegalStateException or a NPE can be thrown
        // no-op
    }

    return null;
}
 
Example #6
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static void doReloadInjectionTargetBean(BeanManagerImpl beanManager, InjectionTargetBean<?> bean,
        Map<String, String> oldSignatures, BeanReloadStrategy reloadStrategy) {

    String signatureByStrategy = OwbClassSignatureHelper.getSignatureByStrategy(reloadStrategy, bean.getBeanClass());
    String oldSignature = oldSignatures.get(bean.getBeanClass().getName());

    if (reloadStrategy == BeanReloadStrategy.CLASS_CHANGE ||
            (reloadStrategy != BeanReloadStrategy.NEVER && signatureByStrategy != null && !signatureByStrategy.equals(oldSignature))) {
        // Reload bean in contexts - invalidates existing instances
        doReloadBeanInBeanContexts(beanManager, bean);
    } else {
        // keep beans in contexts, reinitialize bean injection points
        doReinjectBean(beanManager, bean);
    }
}
 
Example #7
Source File: CdiPlugin.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void registerEEBeans()
{
    BeanManagerImpl beanManagerImpl = webBeansContext.getBeanManagerImpl();
    beanManagerImpl.addInternalBean(new org.apache.webbeans.ee.beans.ValidatorBean(webBeansContext));
    beanManagerImpl.addInternalBean(new org.apache.webbeans.ee.beans.ValidatorFactoryBean(webBeansContext));
    beanManagerImpl.addInternalBean(new org.apache.webbeans.ee.beans.UserTransactionBean(webBeansContext));
}
 
Example #8
Source File: WebappWebBeansContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.DoubleCheckedLocking")
@Override
public BeanManagerImpl getBeanManagerImpl() {
    if (bm == null) { // should be done in the constructor
        synchronized (this) {
            if (bm == null) {
                bm = new WebappBeanManager(this);
            }
        }
    }
    return bm;
}
 
Example #9
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
private Set<Bean<?>> mergeBeans() {
    final Set<Bean<?>> allBeans = new CopyOnWriteArraySet<>(); // override parent one with a "webapp" bean list
    final BeanManagerImpl parentBm = getParentBm();
    if (parentBm != null) {
        for (final Bean<?> bean : parentBm.getBeans()) {
            if (filter.accept(bean)) {
                allBeans.add(bean);
            }
        }
    }
    allBeans.addAll(super.getBeans());
    return allBeans;
}
 
Example #10
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public Object getInjectableReference(final InjectionPoint injectionPoint, final CreationalContext<?> ctx) {
    Asserts.assertNotNull(injectionPoint, "injectionPoint parameter");
    if(injectionPoint == null)  {
        return null;
    }

    final BeanManagerImpl parentBm = getParentBm();
    final Boolean existing = USE_PARENT_BM.get();
    if (existing != null && existing) { // shortcut the whole logic to keep the threadlocal set up correctly
        if (parentBm == null) {
            return null;
        }
        return parentBm.getInjectableReference(injectionPoint, ctx);
    }

    // we can do it cause there is caching but we shouldn't - easy way to overide OWB actually
    final Bean<Object> injectedBean = (Bean<Object>)getInjectionResolver().getInjectionPointBean(injectionPoint);
    try {
        if (parentBm != null && injectedBean != null && injectedBean == parentBm.getInjectionResolver().getInjectionPointBean(injectionPoint)) {
            USE_PARENT_BM.set(true);
            try {
                return parentBm.getInjectableReference(injectionPoint, ctx);
            } finally {
                USE_PARENT_BM.remove();
            }
        }
    } catch (final UnsatisfiedResolutionException ure) {
        // skip, use this bean
    }
    return super.getInjectableReference(injectionPoint, ctx);
}
 
Example #11
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Set<ObserverMethod<? super T>> resolveObserverMethods(final T event, final EventMetadataImpl metadata) {
    final Set<ObserverMethod<? super T>> set = new HashSet<>(super.resolveObserverMethods(event, metadata));

    if (isEvent(event)) {
        final BeanManagerImpl parentBm = getParentBm();
        if (parentBm != null) {
            set.addAll(parentBm.resolveObserverMethods(event, metadata));
        }
    } // else nothing since extensions are loaded by classloader so we already have it

    return set;
}
 
Example #12
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void fireEvent(final Object event, final EventMetadataImpl metadata, final boolean isLifecycleEvent) {
    super.fireEvent(event, metadata, isLifecycleEvent);
    if (isEvent(event)) {
        final BeanManagerImpl parentBm = getParentBm();
        if (parentBm != null) {
            parentBm.fireEvent(event, metadata, isLifecycleEvent);
        }
    }
}
 
Example #13
Source File: CdiPasswordCipher.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public String decrypt(final char[] encryptedPassword) {
    final String string = new String(encryptedPassword);
    final BeanManagerImpl mgr;
    try {
        final WebBeansContext wbc = WebBeansContext.currentInstance();
        mgr = wbc.getBeanManagerImpl();
        if (!mgr.isInUse()) { // not yet the time to use CDI, container is not started
            // would be cool to log a warning here but would pollute the logs with false positives
            return "cipher:cdi:" + string;
        }
    } catch (final IllegalStateException ise) { // no cdi
        return "cipher:cdi:" + string;
    }

    final int split = string.indexOf(':');
    final String delegate = string.substring(0, split);
    final String pwdStr = string.substring(split + 1, string.length());
    final char[] pwd = pwdStr.toCharArray();

    try {
        final Class<?> beanType = Thread.currentThread().getContextClassLoader().loadClass(delegate);
        final Bean<?> bean = mgr.resolve(mgr.getBeans(beanType));
        if (bean == null) {
            throw new IllegalArgumentException("No bean for " + delegate);
        }

        final CreationalContext<?> cc = mgr.createCreationalContext(null);
        try {
            return PasswordCipher.class.cast(mgr.getReference(bean, PasswordCipher.class, cc)).decrypt(pwd);
        } finally {
            if (!mgr.isNormalScope(bean.getScope())) {
                cc.release();
            }
        }
    } catch (final ClassNotFoundException e) {
        throw new IllegalArgumentException("Can't find " + delegate, e);
    }
}
 
Example #14
Source File: OpenEJBEnricher.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void doInject(final Object testInstance, final BeanContext context, final BeanManagerImpl bm) throws Exception {
    final Set<Bean<?>> beans = bm.getBeans(testInstance.getClass());
    final Bean<?> bean = bm.resolve(beans);
    final CreationalContext<?> cc = bm.createCreationalContext(bean);
    if (context != null) {
        context.set(CreationalContext.class, cc);
    }
    OWBInjector.inject(bm, testInstance, cc);
}
 
Example #15
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<Class<? extends Annotation>, Context> getSingleContextMap(BeanManagerImpl beanManagerImpl){
    try {
        Field contextsField = BeanManagerImpl.class.getField("singleContextMap");
        contextsField.setAccessible(true);
        return (Map) contextsField.get(beanManagerImpl);
    } catch (IllegalAccessException |IllegalArgumentException | NoSuchFieldException | SecurityException e) {
        LOGGER.warning("Field BeanManagerImpl.singleContextMap is not accessible", e);
    }
    return Collections.emptyMap();
}
 
Example #16
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static void doReinjectBean(BeanManagerImpl beanManager, InjectionTargetBean<?> bean) {
    try {
        if (!bean.getScope().equals(ApplicationScoped.class) &&
                (HaCdiCommons.isRegisteredScope(bean.getScope()) || HaCdiCommons.isInExtraScope(bean))) {
            doReinjectRegisteredBeanInstances(beanManager, bean);
        } else {
            doReinjectBeanInstance(beanManager, bean, beanManager.getContext(bean.getScope()));
        }
    } catch (ContextNotActiveException e) {
        LOGGER.info("No active contexts for bean '{}'", bean.getBeanClass().getName());
    }
}
 
Example #17
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void doReinjectRegisteredBeanInstances(BeanManagerImpl beanManager, InjectionTargetBean bean) {
    for (Object instance: HaCdiCommons.getBeanInstances(bean)) {
        if (instance != null) {
            instance = unwrapInstance(beanManager, instance);
            bean.getProducer().inject(instance, beanManager.createCreationalContext(bean));
            LOGGER.info("Bean '{}' injection points was reinjected.", bean.getBeanClass().getName());
        } else {
            LOGGER.info("Unexpected 'null' bean instance in registry. bean='{}'", bean.getBeanClass().getName());
        }
    }
}
 
Example #18
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void doReinjectBeanInstance(BeanManagerImpl beanManager, InjectionTargetBean bean, Context context) {
    Object instance = context.get(bean);
    if (instance != null) {
        instance = unwrapInstance(beanManager, instance);
        bean.getProducer().inject(instance, beanManager.createCreationalContext(bean));
        LOGGER.info("Bean '{}' injection points was reinjected.", bean.getBeanClass().getName());
    }
}
 
Example #19
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static Object unwrapInstance(BeanManagerImpl beanManager, Object instance) {
    if (instance instanceof OwbNormalScopeProxy) {
        instance = NormalScopeProxyFactory.unwrapInstance(instance);
    }
    if (instance instanceof OwbInterceptorProxy) {
        instance = beanManager.getWebBeansContext().getInterceptorDecoratorProxyFactory().unwrapInstance(instance);
    }
    return instance;
}
 
Example #20
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<Class<? extends Annotation>, List<Context>> getContextMap(BeanManagerImpl beanManagerImpl){
    try {
        Field contextsField = BeanManagerImpl.class.getField("contextMap");
        contextsField.setAccessible(true);
        return (Map) contextsField.get(beanManagerImpl);
    } catch (IllegalAccessException |IllegalArgumentException | NoSuchFieldException | SecurityException e) {
        LOGGER.warning("Field BeanManagerImpl.contextMap is not accessible", e);
    }
    return Collections.emptyMap();
}
 
Example #21
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static void doReloadBeanInContext(BeanManagerImpl beanManager, InjectionTargetBean bean, Context context) {
    if (ContextualReloadHelper.addToReloadSet(context, bean)) {
        LOGGER.debug("Bean {}, added to reload set in context '{}'", bean, context.getClass());
    } else {
        // fallback: try to reinitialize injection points instead...
        doReinjectBeanInstance(beanManager, bean, context);
    }
}
 
Example #22
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static boolean isCDIAnnotatedClass(BeanManagerImpl beanManager, Class<?> beanClass) {
    for (Annotation annotation: beanClass.getAnnotations()) {
        if (isCDIAnnotation(beanManager, annotation.getClass())) {
            return true;
        }
    }
    return false;
}
 
Example #23
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static boolean isCDIAnnotation(BeanManagerImpl beanManager, Class<? extends Annotation> annotation) {
    if (Interceptor.class.equals(annotation) || Decorator.class.equals(annotation)) {
        return true;
    }

    boolean isBeanAnnotation = beanManager.isScope(annotation);
    if (!isBeanAnnotation) {
        isBeanAnnotation = beanManager.isStereotype(annotation);
    }
    return isBeanAnnotation;
}
 
Example #24
Source File: HessianExtension.java    From tomee with Apache License 2.0 5 votes vote down vote up
private boolean isSameContext(final WebBeansContext app) {
    final BeanManagerImpl bm = app.getBeanManagerImpl();
    try {
        return bm.isInUse() && equals(bm.getExtension(HessianExtension.class));
    } catch (final Exception e) {
        return false;
    }
}
 
Example #25
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private static void doDefineNewBean(BeanManagerImpl beanManager, Class<?> beanClass, URL beanArchiveUrl) {

    BeanArchiveInformation beanArchiveInfo =
            beanManager.getWebBeansContext().getBeanArchiveService().getBeanArchiveInformation(beanArchiveUrl);

    if (beanArchiveInfo.isClassExcluded(beanClass.getName())) {
        LOGGER.debug("Bean '{}' is excluded in BeanArchive.", beanClass.getName());
        return;
    }

    if (beanArchiveInfo.getBeanDiscoveryMode() == BeanDiscoveryMode.ANNOTATED) {
        if (beanClass.getAnnotations().length == 0 || !isCDIAnnotatedClass(beanManager, beanClass)) {
            LOGGER.debug("Class '{}' is not considered as bean for BeanArchive with bean-discovery-mode=\"annotated\"", beanClass.getName());
            return;
        }
    }

    WebBeansContext wbc = beanManager.getWebBeansContext();

    AnnotatedElementFactory annotatedElementFactory = wbc.getAnnotatedElementFactory();
    // Clear AnnotatedElementFactory caches (is it necessary for definition ?)
    annotatedElementFactory.clear();

    // Injection resolver cache must be cleared before / after definition
    beanManager.getInjectionResolver().clearCaches();

    AnnotatedType<?> annotatedType = annotatedElementFactory.newAnnotatedType(beanClass);
    BeanAttributesImpl<?> attributes = BeanAttributesBuilder.forContext(wbc).newBeanAttibutes(annotatedType).build();
    Map<AnnotatedType<?>, ExtendedBeanAttributes<?>> annotatedTypes = new HashMap<>();

    BeansDeployer beansDeployer = new BeansDeployer(wbc);

    try {
        // OWB 1.7
        ReflectionHelper.invoke(beansDeployer, BeansDeployer.class, "defineManagedBean",
                new Class[] { javax.enterprise.inject.spi.AnnotatedType.class, BeanAttributes.class, java.util.Map.class },
                annotatedType, attributes, annotatedTypes);
    } catch (Exception e) {
        try {
            // OWB 2.0
            ExtendedBeanAttributes extendedBeanAttributes =
                    ExtendedBeanAttributes.class.getConstructor(BeanAttributes.class, boolean.class, boolean.class)
                    .newInstance(attributes, false, false);
            ReflectionHelper.invoke(beansDeployer, BeansDeployer.class, "defineManagedBean",
                    new Class[] { javax.enterprise.inject.spi.AnnotatedType.class, ExtendedBeanAttributes.class, java.util.Map.class },
                    annotatedType, extendedBeanAttributes, annotatedTypes);
        } catch (Exception ex) {
            LOGGER.error("Bean '{}' definition failed.", beanClass.getName());
        }
    }
}
 
Example #26
Source File: CxfRSService.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void contextCDIIntegration(final WebBeansContext wbc) {
    if (!enabled) {
        return;
    }

    final BeanManagerImpl beanManagerImpl = wbc.getBeanManagerImpl();
    if (!beanManagerImpl.getAdditionalQualifiers().contains(Context.class)) {
        beanManagerImpl.addAdditionalQualifier(Context.class);
    }
    if (!hasBean(beanManagerImpl, SecurityContext.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(SecurityContext.class, ThreadLocalContextManager.SECURITY_CONTEXT));
    }
    if (!hasBean(beanManagerImpl, UriInfo.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(UriInfo.class, ThreadLocalContextManager.URI_INFO));
    }
    if (!hasBean(beanManagerImpl, HttpServletResponse.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(HttpServletResponse.class, ThreadLocalContextManager.HTTP_SERVLET_RESPONSE));
    }
    if (!hasBean(beanManagerImpl, HttpHeaders.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(HttpHeaders.class, ThreadLocalContextManager.HTTP_HEADERS));
    }
    if (!hasBean(beanManagerImpl, Request.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(Request.class, ThreadLocalContextManager.REQUEST));
    }
    if (!hasBean(beanManagerImpl, ServletConfig.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ServletConfig.class, ThreadLocalContextManager.SERVLET_CONFIG));
    }
    if (!hasBean(beanManagerImpl, Providers.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(Providers.class, ThreadLocalContextManager.PROVIDERS));
    }
    if (!hasBean(beanManagerImpl, ContextResolver.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ContextResolver.class, ThreadLocalContextManager.CONTEXT_RESOLVER));
    }
    if (!hasBean(beanManagerImpl, ResourceInfo.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ResourceInfo.class, ThreadLocalContextManager.RESOURCE_INFO));
    }
    if (!hasBean(beanManagerImpl, ResourceContext.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ResourceContext.class, ThreadLocalContextManager.RESOURCE_CONTEXT));
    }
    if (!hasBean(beanManagerImpl, HttpServletRequest.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(HttpServletRequest.class, ThreadLocalContextManager.HTTP_SERVLET_REQUEST));
    }
    if (!hasBean(beanManagerImpl, ServletRequest.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ServletRequest.class, ThreadLocalContextManager.SERVLET_REQUEST));
    }
    if (!hasBean(beanManagerImpl, ServletContext.class)) {
        beanManagerImpl.addInternalBean(new ContextBean<>(ServletContext.class, ThreadLocalContextManager.SERVLET_CONTEXT));
    }
    beanManagerImpl.getInjectionResolver().clearCaches(); // hasBean() usage can have cached several things
}
 
Example #27
Source File: OpenEJBEnricher.java    From tomee with Apache License 2.0 4 votes vote down vote up
public static Object[] resolve(final AppContext appContext, final TestClass ignored, final Method method) { // suppose all is a CDI bean...
    final Object[] values = new Object[method.getParameterTypes().length];

    if (appContext == null) {
        return values;
    }

    final List<BeanManager> beanManagers = new ArrayList<>();
    final BeanManager bm = findBeanManager(appContext);
    if (bm != null) {
        // then add web bean manager first, TODO: selection of the webapp containing the test?
        for (final WebContext web : appContext.getWebContexts()) {
            final WebBeansContext webBeansContext = web.getWebBeansContext();
            if (webBeansContext == null) {
                continue;
            }
            final BeanManagerImpl webAppBm = webBeansContext.getBeanManagerImpl();
            if (bm != webAppBm) {
                beanManagers.add(webAppBm);
            }
        }
        beanManagers.add(bm);
    }
    if (beanManagers.isEmpty()) {
        return values;
    }

    final Class<?>[] parameterTypes = method.getParameterTypes();
    for (int i = 0; i < parameterTypes.length; i++) {
        Exception ex = null;
        for (final BeanManager beanManager : beanManagers) {
            try {
                values[i] = getParamInstance(beanManager, i, method);
                break;
            } catch (final Exception e) {
                ex = e;
            }
        }
        if (ex != null) {
            LOGGER.info(ex.getMessage());
        }
    }
    return values;
}
 
Example #28
Source File: WebappBeanManager.java    From tomee with Apache License 2.0 4 votes vote down vote up
public BeanManagerImpl getParentBm() {
    final WebBeansContext parent = webappCtx.getParent();
    return parent != null ? parent.getBeanManagerImpl() : null;
}
 
Example #29
Source File: OpenEJBLifecycle.java    From tomee with Apache License 2.0 4 votes vote down vote up
private static boolean hasBean(final BeanManagerImpl beanManagerImpl, final Class<?> type) {
    return !beanManagerImpl.getInjectionResolver().implResolveByType(false, type).isEmpty();
}
 
Example #30
Source File: CxfRsHttpListener.java    From tomee with Apache License 2.0 4 votes vote down vote up
private Comparator<?> findProviderComparator(final ServiceConfiguration serviceConfiguration, final WebBeansContext ctx) {
    final String comparatorKey = CXF_JAXRS_PREFIX + "provider-comparator";
    final String comparatorClass = serviceConfiguration.getProperties()
            .getProperty(comparatorKey, SystemInstance.get().getProperty(comparatorKey));

    Comparator<Object> comparator = null;
    if (comparatorClass == null) {
        return null; // try to rely on CXF behavior otherwise just reactivate DefaultProviderComparator.INSTANCE if it is an issue
    } else {
        final BeanManagerImpl bm = ctx == null ? null : ctx.getBeanManagerImpl();
        if (bm != null && bm.isInUse()) {
            try {
                final Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(comparatorClass);
                final Set<Bean<?>> beans = bm.getBeans(clazz);
                if (beans != null && !beans.isEmpty()) {
                    final Bean<?> bean = bm.resolve(beans);
                    final CreationalContextImpl<?> creationalContext = bm.createCreationalContext(bean);
                    comparator = Comparator.class.cast(bm.getReference(bean, clazz, creationalContext));
                    toRelease.add(creationalContext);
                }
            } catch (final Throwable th) {
                LOGGER.debug("Can't use CDI to load comparator " + comparatorClass);
            }
        }

        if (comparator == null) {
            comparator = Comparator.class.cast(ServiceInfos.resolve(serviceConfiguration.getAvailableServices(), comparatorClass));
        }
        if (comparator == null) {
            try {
                comparator = Comparator.class.cast(Thread.currentThread().getContextClassLoader().loadClass(comparatorClass).newInstance());
            } catch (final Exception e) {
                throw new IllegalArgumentException(e);
            }
        }

        for (final Type itf : comparator.getClass().getGenericInterfaces()) {
            if (!ParameterizedType.class.isInstance(itf)) {
                continue;
            }

            final ParameterizedType pt = ParameterizedType.class.cast(itf);
            if (Comparator.class == pt.getRawType() && pt.getActualTypeArguments().length > 0) {
                final Type t = pt.getActualTypeArguments()[0];
                if (Class.class.isInstance(t) && ProviderInfo.class == t) {
                    return comparator;
                }
                if (ParameterizedType.class.isInstance(t) && ProviderInfo.class == ParameterizedType.class.cast(t).getRawType()) {
                    return comparator;
                }
            }
        }

        return new ProviderComparatorWrapper(comparator);
    }
}