org.apache.webbeans.config.WebBeansContext Java Examples

The following examples show how to use org.apache.webbeans.config.WebBeansContext. 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: MeecrowaveSeContainerInitializer.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Override
protected SeContainer newContainer(final WebBeansContext context) {
    final Meecrowave meecrowave = new Meecrowave(builder);
    if (!services.containsKey(ContextsService.class.getName())) { // forced otherwise we mess up the env with owb-se
        context.registerService(ContextsService.class, new WebContextsService(context));
    }
    return new OWBContainer(context, meecrowave) {
        {
            meecrowave.bake();
        }

        @Override
        protected void doClose() {
            meecrowave.close();
        }
    };
}
 
Example #2
Source File: BeanContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> void inject(final T instance, CreationalContext<T> ctx) {

    final WebBeansContext webBeansContext = getWebBeansContext();
    if (webBeansContext == null) {
        return;
    }

    InjectionTargetBean<T> beanDefinition = get(CdiEjbBean.class);

    if (beanDefinition == null) {
        beanDefinition = InjectionTargetBean.class.cast(createConstructorInjectionBean(webBeansContext));
    }

    if (!(ctx instanceof CreationalContextImpl)) {
        ctx = webBeansContext.getCreationalContextFactory().wrappedCreationalContext(ctx, beanDefinition);
    }

    beanDefinition.getInjectionTarget().inject(instance, ctx);
}
 
Example #3
Source File: StatefulConversationScopedTOMEE1138Test.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Before
public void startConversation() {
    final WebBeansContext webBeansContext = WebBeansContext.currentInstance();
    webBeansContext.registerService(ConversationService.class, new ConversationService() {
        @Override
        public String getConversationId() {
            return "conversation-test";
        }

        @Override
        public String generateConversationId() {
            return "cid_1";
        }
    });
    webBeansContext.getService(ContextsService.class).startContext(ConversationScoped.class, null);
}
 
Example #4
Source File: EnsureRequestScopeThreadLocalIsCleanUpTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void ensureRequestContextCanBeRestarted() throws Exception {
    final ApplicationComposers composers = new ApplicationComposers(EnsureRequestScopeThreadLocalIsCleanUpTest.class);
    composers.before(this);
    final CdiAppContextsService contextsService = CdiAppContextsService.class.cast(WebBeansContext.currentInstance().getService(ContextsService.class));
    final Context req1 = contextsService.getCurrentContext(RequestScoped.class);
    assertNotNull(req1);
    final Context session1 = contextsService.getCurrentContext(SessionScoped.class);
    assertNotNull(session1);
    contextsService.endContext(RequestScoped.class, null);
    contextsService.startContext(RequestScoped.class, null);
    final Context req2 = contextsService.getCurrentContext(RequestScoped.class);
    assertNotSame(req1, req2);
    final Context session2 = contextsService.getCurrentContext(SessionScoped.class);
    assertSame(session1, session2);
    composers.after();
    assertNull(contextsService.getCurrentContext(RequestScoped.class));
    assertNull(contextsService.getCurrentContext(SessionScoped.class));
}
 
Example #5
Source File: HAOpenWebBeansTestLifeCycle.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
public void beforeStopApplication(Object endObject)
{
    WebBeansContext webBeansContext = getWebBeansContext();
    ContextsService contextsService = webBeansContext.getContextsService();
    contextsService.endContext(Singleton.class, null);
    contextsService.endContext(ApplicationScoped.class, null);
    contextsService.endContext(RequestScoped.class, null);
    contextsService.endContext(SessionScoped.class, mockHttpSession);

    ELContextStore elStore = ELContextStore.getInstance(false);
    if (elStore == null)
    {
        return;
    }
    elStore.destroyELContextStore();
}
 
Example #6
Source File: OpenEJBLifecycle.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static void initializeServletContext(final ServletContext servletContext, final WebBeansContext context) {
    if (context == null || !context.getBeanManagerImpl().isInUse()) {
        return;
    }

    final ELAdaptor elAdaptor = context.getService(ELAdaptor.class);
    final ELResolver resolver = elAdaptor.getOwbELResolver();
    //Application is configured as JSP
    if (context.getOpenWebBeansConfiguration().isJspApplication()) {
        logger.debug("Application is configured as JSP. Adding EL Resolver.");

        setJspELFactory(servletContext, resolver);
    }

    // Add BeanManager to the 'javax.enterprise.inject.spi.BeanManager' servlet context attribute
    servletContext.setAttribute(BeanManager.class.getName(), context.getBeanManagerImpl());
}
 
Example #7
Source File: HAAbstractUnitTest.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
protected void startContainer()
{
    WebBeansFinder.clearInstances(WebBeansUtil.getCurrentClassLoader());
    //Creates a new container
    testLifecycle = new HAOpenWebBeansTestLifeCycle();

    webBeansContext = WebBeansContext.getInstance();

    //Start application
    try
    {
        testLifecycle.startApplication(null);
    }
    catch (Exception e)
    {
        throw new WebBeansConfigurationException(e);
    }
}
 
Example #8
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 #9
Source File: HAOpenWebBeansTestLifeCycle.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
public void beforeStartApplication(Object object)
{
    WebBeansContext webBeansContext = getWebBeansContext();
    ContextsService contextsService = webBeansContext.getContextsService();
    contextsService.startContext(Singleton.class, null);
    contextsService.startContext(ApplicationScoped.class, null);
}
 
Example #10
Source File: OpenEJBLifecycle.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Manages unused conversations
 */

public OpenEJBLifecycle(final WebBeansContext webBeansContext) {
    this.webBeansContext = webBeansContext;

    this.beanManager = webBeansContext.getBeanManagerImpl();
    this.deployer = new BeansDeployer(webBeansContext);
    this.jndiService = webBeansContext.getService(JNDIService.class);
    this.scannerService = webBeansContext.getScannerService();
    this.contextsService = webBeansContext.getContextsService();
}
 
Example #11
Source File: ConfigInjection.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Test
public void inject() {
    try (final Meecrowave meecrowave = new Meecrowave(
            new Meecrowave.Builder()
                    .randomHttpPort()
                    .includePackages(ConfigInjection.class.getName())).bake()) {
        OWBInjector.inject(WebBeansContext.currentInstance().getBeanManagerImpl(), this, null);
        assertNotNull(configuration);
        assertEquals(ConfigInjection.class.getName(), configuration.getScanningPackageIncludes());
    }
}
 
Example #12
Source File: Meecrowave.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
private <T> void fire(final T event, final ClassLoader classLoader) {
    final Thread thread = Thread.currentThread();
    final ClassLoader loader = thread.getContextClassLoader();
    thread.setContextClassLoader(classLoader);
    try {
        WebBeansContext.currentInstance()
                .getBeanManagerImpl()
                .getEvent()
                .select(Class.class.cast(event.getClass()))
                .fire(event);
    } finally {
        thread.setContextClassLoader(loader);
    }
}
 
Example #13
Source File: CdiEventRealm.java    From tomee with Apache License 2.0 5 votes vote down vote up
private BeanManager beanManager() {
    final WebBeansContext webBeansContext = WebBeansContext.currentInstance();
    if (webBeansContext == null) {
        return null; // too early to have a cdi bean
    }
    return webBeansContext.getBeanManagerImpl();
}
 
Example #14
Source File: MeecrowaveSecurityService.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public MeecrowaveSecurityService(final WebBeansContext context) {
    useWrapper = "true".equalsIgnoreCase(context.getOpenWebBeansConfiguration()
            .getProperty("org.apache.webbeans.component.PrincipalBean.proxy", "true"));
    final ClassLoader loader = SimpleSecurityService.class.getClassLoader();
    final Class<?>[] apiToProxy = Stream.concat(
            Stream.of(Principal.class),
            Stream.of(context.getOpenWebBeansConfiguration()
                    .getProperty("org.apache.webbeans.component.PrincipalBean.proxyApis", "org.eclipse.microprofile.jwt.JsonWebToken").split(","))
                    .map(String::trim)
                    .filter(it -> !it.isEmpty())
                    .map(it -> {
                        try { // if MP JWT-Auth is available
                            return loader.loadClass(it.trim());
                        } catch (final NoClassDefFoundError | ClassNotFoundException e) {
                            return null;
                        }
                    })).filter(Objects::nonNull).toArray(Class[]::new);
    proxy = apiToProxy.length == 1 ? new MeecrowavePrincipal() : Principal.class.cast(
            Proxy.newProxyInstance(loader, apiToProxy, (proxy, method, args) -> {
                try {
                    return method.invoke(getCurrentPrincipal(), args);
                } catch (final InvocationTargetException ite) {
                    throw ite.getTargetException();
                }
            }));

}
 
Example #15
Source File: WebbeansContextInEmbeddedModeTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void checkWebbeansContext() {
    final WebBeansContext ctx1 = WebBeansContext.currentInstance();
    final List<AppContext> appCtxs = SystemInstance.get().getComponent(ContainerSystem.class).getAppContexts();
    assertEquals(1, appCtxs.size());
    final WebBeansContext ctx2 = appCtxs.iterator().next().getWebBeansContext();
    assertSame(ctx1, ctx2);
}
 
Example #16
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 5 votes vote down vote up
private WebBeansContext getWebBeansContext(final ContextInfo contextInfo) {
    final AppContext appContext = getContainerSystem().getAppContext(contextInfo.appInfo.appId);

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

    WebBeansContext webBeansContext = appContext.getWebBeansContext();

    if (webBeansContext == null) {
        return null;
    }

    for (final WebContext web : appContext.getWebContexts()) {
        final String stdName = removeFirstSlashAndWar(contextInfo.standardContext.getName());
        if (stdName == null) {
            continue;
        }

        final String name = removeFirstSlashAndWar(web.getContextRoot());
        if (stdName.equals(name)) {
            webBeansContext = web.getWebbeansContext();
            if (Contexts.getHostname(contextInfo.standardContext).equals(web.getHost())) {
                break;
            } // else loop hoping to find a better matching
        }
    }

    if (webBeansContext == null) {
        webBeansContext = appContext.getWebBeansContext();
    }

    return webBeansContext;
}
 
Example #17
Source File: OpenEJBLifecycle.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public T get() {
    if (webBeansContext == null) {
        webBeansContext = WebBeansContext.currentInstance();
    }
    return (T) SystemInstance.get().getComponent(type);
}
 
Example #18
Source File: CdiSingletonResourceProvider.java    From tomee with Apache License 2.0 5 votes vote down vote up
public CdiSingletonResourceProvider(final ClassLoader loader, final Class<?> clazz, final Object instance,
                                    final Collection<Injection> injectionCollection, final Context initialContext,
                                    final WebBeansContext owbCtx) {
    super(loader, clazz, injectionCollection, initialContext, owbCtx);
    if (normalScopeCreator != null) { // if the singleton is a normal scoped bean then use cdi instance instead of provided one
        creator = normalScopeCreator;
    } else { // do injections only
        creator = new SingletonBeanCreator(instance);
    }
}
 
Example #19
Source File: BeanContext.java    From tomee with Apache License 2.0 5 votes vote down vote up
private ConstructorInjectionBean<Object> createConstructorInjectionBean(final WebBeansContext webBeansContext) {
    if (constructorInjectionBean != null) {
        return constructorInjectionBean;
    }

    synchronized (this) { // concurrentmodificationexception because of annotatedtype internals otherwise
        if (constructorInjectionBean == null) {
            constructorInjectionBean = new ConstructorInjectionBean<>(
                webBeansContext, getManagedClass(),
                webBeansContext.getAnnotatedElementFactory().newAnnotatedType(getManagedClass()));
        }
    }
    return constructorInjectionBean;
}
 
Example #20
Source File: ThreadSingletonServiceImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void clear(final Object key) {
    final WebBeansContext ctx = getContext((ClassLoader) key);
    if (logger.isDebugEnabled()) {
        logger.debug("Clearing:'" + ctx + "'");
    }
    contextByClassLoader.remove(key);
    if (ctx != null) {
        ctx.clear();
    }
}
 
Example #21
Source File: OpenEJBLifecycle.java    From tomee with Apache License 2.0 5 votes vote down vote up
protected HttpServletRequestBean(final WebBeansContext webBeansContext) {
    super(webBeansContext, HttpServletRequest.class, HttpServletRequest.class);
    this.types = new HashSet<>(); // here we need 2 types (+Object) otherwise decoratione etc fails
    this.types.add(HttpServletRequest.class);
    this.types.add(ServletRequest.class);
    this.types.add(Object.class);
}
 
Example #22
Source File: CdiResourceProvider.java    From tomee with Apache License 2.0 5 votes vote down vote up
public CdiResourceProvider(final ClassLoader loader, final Class<?> clazz, final Collection<Injection> injectionCollection, final Context initialContext, final WebBeansContext owbCtx) {
    injections = injectionCollection;
    webbeansContext = owbCtx;
    classLoader = loader;
    context = (Context) Proxy.newProxyInstance(classLoader, new Class<?>[]{Context.class}, new InitialContextWrapper(initialContext));

    postConstructMethod = ResourceUtils.findPostConstructMethod(clazz);
    preDestroyMethod = ResourceUtils.findPreDestroyMethod(clazz);

    bm = webbeansContext == null ? null : webbeansContext.getBeanManagerImpl();
    this.clazz = clazz;
    if (bm != null && bm.isInUse()) {
        try {
            final Set<Bean<?>> beans = bm.getBeans(clazz);
            bean = bm.resolve(beans);
        } catch (final InjectionException ie) {
            final String msg = "Resource class " + clazz.getName() + " can not be instantiated";
            throw new WebApplicationException(Response.serverError().entity(msg).build());
        }

        if (bean != null && bm.isNormalScope(bean.getScope())) {
            // singleton is faster
            normalScopeCreator = new ProvidedInstanceBeanCreator(bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean)));
        } else {
            normalScopeCreator = null;
            validateConstructorExists();
        }
    } else {
        bean = null;
        normalScopeCreator = null;
        validateConstructorExists();
    }

    findContexts(clazz);
}
 
Example #23
Source File: EEFilter.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
    final boolean shouldWrap = active && HttpServletRequest.class.isInstance(servletRequest);
    if (!HttpServletRequest.class.isInstance(servletRequest)) {
        filterChain.doFilter(shouldWrap ?
                new NoCdiRequest(HttpServletRequest.class.cast(servletRequest), this) : servletRequest, servletResponse);
        return;
    }
    WebBeansContext ctx;
    filterChain.doFilter(servletRequest.isAsyncSupported() &&  (ctx = WebBeansContext.currentInstance()) != null ?
                new CdiRequest(HttpServletRequest.class.cast(servletRequest), ctx, this) :
                (shouldWrap ? new NoCdiRequest(HttpServletRequest.class.cast(servletRequest), this) : servletRequest),
            servletResponse);
}
 
Example #24
Source File: RemoteTomEEObserver.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void beforeSuite(@Observes final BeforeSuite event) {
    final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(
            Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
    if (webBeansContext != null) {
        beanManager.set(webBeansContext.getBeanManagerImpl());
    }
    try {
        context.set(new InitialContext());
    } catch (final NamingException e) {
        // no-op
    }
}
 
Example #25
Source File: EmbeddedTomEEContainer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void stopCdiContexts(final String name) {
    try {
        final HttpSession session = SESSIONS.remove(name);
        if (session != null) {
            final WebBeansContext wbc = container.getAppContexts(container.getInfo(name).appId).getWebBeansContext();
            if (wbc != null && wbc.getBeanManagerImpl().isInUse()) {
                wbc.getContextsService().startContext(RequestScoped.class, null);
                wbc.getContextsService().startContext(SessionScoped.class, session);
                wbc.getContextsService().startContext(ConversationScoped.class, null);
            }
        }
    } catch (final Exception e) {
        // no-op
    }
}
 
Example #26
Source File: EndWebBeansListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor
 *
 * @param webBeansContext the OWB context
 */
public EndWebBeansListener(WebBeansContext webBeansContext) {
    this.webBeansContext = webBeansContext;
    if (webBeansContext != null) {
        this.contextsService = CdiAppContextsService.class.cast(webBeansContext.getService(ContextsService.class));
        this.cleanUpSession = Boolean.parseBoolean(webBeansContext.getOpenWebBeansConfiguration()
                .getProperty("tomee.session.remove-cdi-beans-on-passivate", "false"));
    } else {
        this.contextsService = null;
        this.cleanUpSession = false; // ignored anyway
    }
}
 
Example #27
Source File: CdiPlugin.java    From tomee with Apache License 2.0 5 votes vote down vote up
private boolean isNewSessionBean(final WebBeansContext ctx, final Class<?> clazz) {
    if (ctx == null) {
        return false;
    }

    final Map<Class<?>, BeanContext> map = pluginBeans(ctx);
    return map != null && (map.containsKey(clazz) || clazz.isInterface() && findBeanContext(ctx, clazz) != null);
}
 
Example #28
Source File: BeginWebBeansListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void requestDestroyed(final ServletRequestEvent event) {
    if (webBeansContext == null) {
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Destroying a request : [{0}]", event == null ? "null" : event.getServletRequest().getRemoteAddr());
    }

    final Object oldContext;
    if (event != null) {
        oldContext = event.getServletRequest().getAttribute(contextKey);
    } else {
        oldContext = null;
    }

    try {
        // clean up the EL caches after each request
        final ELContextStore elStore = ELContextStore.getInstance(false);
        if (elStore != null) {
            elStore.destroyELContextStore();
        }

        contextsService.endContext(RequestScoped.class, event);
        if (webBeansContext instanceof WebappWebBeansContext) { // end after child
            ((WebappWebBeansContext) webBeansContext).getParent().getContextsService().endContext(RequestScoped.class, event);
        }
    } finally {
        contextsService.removeThreadLocals();
        ThreadSingletonServiceImpl.enter((WebBeansContext) oldContext);
    }
}
 
Example #29
Source File: OpenEJBHttpRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static HttpRequestImpl initCdi(final WebBeansContext context, final HttpRequestImpl request) {
    try {
        if (context.getBeanManagerImpl().isInUse()) {
            request.setBeginListener(new BeginWebBeansListener(context));
            request.setEndListener(new EndWebBeansListener(context));
        }
    } catch (IllegalStateException ise) {
        // no-op: ignore
    }
    return request;
}
 
Example #30
Source File: HttpRequestImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override // avoids the need of org.apache.openejb.server.httpd.EEFilter in embedded mode
public AsyncContext startAsync(final ServletRequest servletRequest, final ServletResponse servletResponse) {
    setAttribute("openejb_async", "true");
    final OpenEJBAsyncContext asyncContext = new OpenEJBAsyncContext(HttpServletRequest.class.cast(servletRequest) /* TODO */, servletResponse, contextPath);
    asyncContext.internalStartAsync();
    asyncStarted = true;
    final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb(
            Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE);
    return webBeansContext != null ?
            new EEFilter.AsynContextWrapper(asyncContext, servletRequest, webBeansContext) : asyncContext;
}