use of org.apache.webbeans.spi.ContextsService in project tomee by apache.
the class ThreadSingletonServiceImpl method initialize.
@Override
public void initialize(final StartupObject startupObject) {
if (lazyInit == null) {
// done here cause Cdibuilder trigger this class loading and that's from Warmup so we can't init too early config
synchronized (this) {
if (lazyInit == null) {
lazyInit = new Object();
cachedApplicationScoped = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.cdi.applicationScope.cached", "true").trim());
cachedRequestScoped = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.cdi.requestScope.cached", "true").trim());
cachedSessionScoped = "true".equalsIgnoreCase(SystemInstance.get().getProperty("openejb.cdi.sessionScope.cached", "true").trim());
}
}
}
final AppContext appContext = startupObject.getAppContext();
appContext.setCdiEnabled(hasBeans(startupObject.getAppInfo()));
//initialize owb context, cf geronimo's OpenWebBeansGBean
final Properties properties = new Properties();
properties.setProperty(OpenWebBeansConfiguration.APPLICATION_IS_JSP, "true");
properties.setProperty(OpenWebBeansConfiguration.USE_EJB_DISCOVERY, "true");
//from CDI builder
properties.setProperty(OpenWebBeansConfiguration.INTERCEPTOR_FORCE_NO_CHECKED_EXCEPTIONS, "false");
properties.setProperty(SecurityService.class.getName(), ManagedSecurityService.class.getName());
properties.setProperty(OpenWebBeansConfiguration.CONVERSATION_PERIODIC_DELAY, "1800000");
properties.setProperty(OpenWebBeansConfiguration.APPLICATION_SUPPORTS_CONVERSATION, "true");
properties.setProperty(OpenWebBeansConfiguration.IGNORED_INTERFACES, "org.apache.aries.proxy.weaving.WovenProxy");
final boolean tomee = SystemInstance.get().getProperty("openejb.loader", "foo").startsWith("tomcat");
final String defaultNormalScopeHandlerClass = NormalScopedBeanInterceptorHandler.class.getName();
properties.setProperty("org.apache.webbeans.proxy.mapping.javax.enterprise.context.ApplicationScoped", cachedApplicationScoped ? ApplicationScopedBeanInterceptorHandler.class.getName() : defaultNormalScopeHandlerClass);
properties.setProperty("org.apache.webbeans.proxy.mapping.javax.enterprise.context.RequestScoped", tomee && cachedRequestScoped ? RequestScopedBeanInterceptorHandler.class.getName() : defaultNormalScopeHandlerClass);
properties.setProperty("org.apache.webbeans.proxy.mapping.javax.enterprise.context.SessionScoped", tomee && cachedSessionScoped ? SessionScopedBeanInterceptorHandler.class.getName() : defaultNormalScopeHandlerClass);
properties.put(OpenWebBeansConfiguration.PRODUCER_INTERCEPTION_SUPPORT, SystemInstance.get().getProperty("openejb.cdi.producer.interception", "true"));
properties.putAll(appContext.getProperties());
// services needing WBC as constructor param
properties.put(ContextsService.class.getName(), CdiAppContextsService.class.getName());
properties.put(ResourceInjectionService.class.getName(), CdiResourceInjectionService.class.getName());
properties.put(TransactionService.class.getName(), OpenEJBTransactionService.class.getName());
// NOTE: ensure user can extend/override all the services = set it only if not present in properties, see WebBeansContext#getService()
final Map<Class<?>, Object> services = new HashMap<>();
services.put(AppContext.class, appContext);
if (!properties.containsKey(ApplicationBoundaryService.class.getName())) {
services.put(ApplicationBoundaryService.class, new DefaultApplicationBoundaryService());
}
if (!properties.containsKey(ScannerService.class.getName())) {
services.put(ScannerService.class, new CdiScanner());
}
if (!properties.containsKey(JNDIService.class.getName())) {
services.put(JNDIService.class, new OpenEJBJndiService());
}
if (!properties.containsKey(BeanArchiveService.class.getName())) {
services.put(BeanArchiveService.class, new OpenEJBBeanInfoService());
}
if (!properties.containsKey(ELAdaptor.class.getName())) {
try {
services.put(ELAdaptor.class, new CustomELAdapter(appContext));
} catch (final NoClassDefFoundError noClassDefFoundError) {
// no-op: no javax.el
}
}
if (!properties.containsKey(LoaderService.class.getName())) {
final LoaderService loaderService = SystemInstance.get().getComponent(LoaderService.class);
if (loaderService == null && !properties.containsKey(LoaderService.class.getName())) {
services.put(LoaderService.class, new OptimizedLoaderService(appContext.getProperties()));
} else if (loaderService != null) {
services.put(LoaderService.class, loaderService);
}
}
final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
final ClassLoader cl;
if (oldClassLoader != ThreadSingletonServiceImpl.class.getClassLoader() && ThreadSingletonServiceImpl.class.getClassLoader() != oldClassLoader.getParent()) {
cl = new MultipleClassLoader(oldClassLoader, ThreadSingletonServiceImpl.class.getClassLoader());
} else {
cl = oldClassLoader;
}
Thread.currentThread().setContextClassLoader(cl);
final WebBeansContext webBeansContext;
Object old = null;
try {
if (startupObject.getWebContext() == null) {
webBeansContext = new WebBeansContext(services, properties);
appContext.set(WebBeansContext.class, webBeansContext);
} else {
webBeansContext = new WebappWebBeansContext(services, properties, appContext.getWebBeansContext());
startupObject.getWebContext().setWebbeansContext(webBeansContext);
}
// we want the same reference as the ContextsService if that's our impl
if (webBeansContext.getOpenWebBeansConfiguration().supportsConversation() && "org.apache.webbeans.jsf.DefaultConversationService".equals(webBeansContext.getOpenWebBeansConfiguration().getProperty(ConversationService.class.getName()))) {
webBeansContext.registerService(ConversationService.class, ConversationService.class.cast(webBeansContext.getService(ContextsService.class)));
}
final BeanManagerImpl beanManagerImpl = webBeansContext.getBeanManagerImpl();
beanManagerImpl.addContext(new TransactionContext());
webBeansContext.getInterceptorsManager().addInterceptorBindingType(Transactional.class);
SystemInstance.get().fireEvent(new WebBeansContextCreated(webBeansContext));
old = contextEntered(webBeansContext);
setConfiguration(webBeansContext.getOpenWebBeansConfiguration());
try {
webBeansContext.getService(ContainerLifecycle.class).startApplication(startupObject);
} catch (final Exception e) {
throw new DeploymentException("couldn't start owb context", e);
}
} finally {
contextExited(old);
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
use of org.apache.webbeans.spi.ContextsService in project tomee by apache.
the class ApplicationComposers method stopApplication.
public void stopApplication() throws NamingException {
if (appContext != null && appContext.getWebBeansContext() != null) {
final ContextsService contextsService = appContext.getWebBeansContext().getContextsService();
// No need to stop the ConversationContext manually as it gets stored inside the SessionContext as Bean
contextsService.endContext(SessionScoped.class, session);
contextsService.endContext(RequestScoped.class, null);
}
if (appInfo != null) {
try {
assembler.destroyApplication(appInfo.path);
} catch (final Exception e) {
// no-op
}
}
final ContainerSystem component = SystemInstance.get().getComponent(ContainerSystem.class);
if (null != component) {
final Context context = component.getJNDIContext();
for (final String entry : globalJndiEntries) {
context.unbind(entry);
}
}
globalJndiEntries.clear();
if (mockCdiContexts() && appContext != null && appContext.getWebBeansContext() != null) {
try {
ScopeHelper.stopContexts(appContext.getWebBeansContext().getContextsService(), servletContext, session);
} catch (final Exception e) {
// no-op
}
}
}
use of org.apache.webbeans.spi.ContextsService in project tomee by apache.
the class JMS2AMQTest method cdiListenerAPI.
@Test
public void cdiListenerAPI() throws InterruptedException {
final String text = TEXT + "4";
final AtomicReference<Throwable> error = new AtomicReference<>();
final CountDownLatch ready = new CountDownLatch(1);
final CountDownLatch over = new CountDownLatch(1);
new Thread() {
{
setName(JMS2AMQTest.class.getName() + ".cdiListenerAPI#receiver");
}
@Override
public void run() {
final ContextsService contextsService = WebBeansContext.currentInstance().getContextsService();
contextsService.startContext(RequestScoped.class, null);
try {
final JMSConsumer consumer = context.createConsumer(destination3);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(final Message message) {
try {
assertEquals(text, message.getBody(String.class));
} catch (final Throwable e) {
error.set(e);
} finally {
over.countDown();
consumer.close();
}
}
});
ready.countDown();
} catch (final Throwable t) {
error.set(t);
} finally {
try {
over.await(1, TimeUnit.MINUTES);
} catch (final InterruptedException e) {
Thread.interrupted();
}
contextsService.endContext(RequestScoped.class, null);
}
}
}.start();
ready.await(1, TimeUnit.MINUTES);
// now send the message
try (final JMSContext context = cf.createContext()) {
context.createProducer().send(destination3, text);
} catch (final JMSRuntimeException ex) {
fail(ex.getMessage());
}
over.await(1, TimeUnit.MINUTES);
// ensure we got the message and no exception
final Throwable exception = error.get();
if (exception != null) {
exception.printStackTrace();
}
assertNull(exception == null ? "ok" : exception.getMessage(), exception);
}
use of org.apache.webbeans.spi.ContextsService in project tomee by apache.
the class TomcatWebAppBuilder method afterStart.
/**
* {@inheritDoc}
*/
@Override
public void afterStart(final StandardContext standardContext) {
if (isIgnored(standardContext)) {
return;
}
final Realm realm = standardContext.getRealm();
final ClassLoader classLoader = standardContext.getLoader().getClassLoader();
final Thread thread = Thread.currentThread();
final ClassLoader originalLoader = thread.getContextClassLoader();
if (realm != null && !(realm instanceof TomEERealm) && (standardContext.getParent() == null || (!realm.equals(standardContext.getParent().getRealm())))) {
thread.setContextClassLoader(classLoader);
try {
standardContext.setRealm(tomeeRealm(realm));
} finally {
thread.setContextClassLoader(originalLoader);
}
}
// if appInfo is null this is a failed deployment... just ignore
final ContextInfo contextInfo = getContextInfo(standardContext);
// shouldnt be there after startup (actually we shouldnt need it from info tree but our scanning does)
contextInfo.module = null;
if (contextInfo != null && contextInfo.appInfo == null) {
return;
} else if (contextInfo == null) {
// openejb webapp loaded from the LoaderServlet
return;
}
final String id = getId(standardContext);
WebAppInfo currentWebAppInfo = null;
for (final WebAppInfo webAppInfo : contextInfo.appInfo.webApps) {
final String wId = getId(webAppInfo.host, webAppInfo.contextRoot, contextInfo.version);
if (id.equals(wId)) {
currentWebAppInfo = webAppInfo;
break;
}
}
// bind extra stuff at the java:comp level which can only be
// bound after the context is created
thread.setContextClassLoader(classLoader);
final NamingContextListener ncl = standardContext.getNamingContextListener();
final String listenerName = ncl.getName();
ContextAccessController.setWritable(listenerName, standardContext.getNamingToken());
try {
final Context openejbContext = (Context) getContainerSystem().getJNDIContext().lookup("openejb");
final Context root = (Context) ContextBindings.getClassLoader().lookup("");
// usually fails
final Context comp = (Context) ContextBindings.getClassLoader().lookup("comp");
// Context root = ncl.getNamingContext();
// Context comp = (Context) root.lookup("comp");
safeBind(root, "openejb", openejbContext);
// add context to WebDeploymentInfo
if (currentWebAppInfo != null) {
final WebContext webContext = getContainerSystem().getWebContext(currentWebAppInfo.moduleId);
if (webContext != null) {
webContext.setJndiEnc(root);
}
try {
// Bean Validation
standardContext.getServletContext().setAttribute("javax.faces.validator.beanValidator.ValidatorFactory", openejbContext.lookup(Assembler.VALIDATOR_FACTORY_NAMING_CONTEXT.replaceFirst("openejb", "") + currentWebAppInfo.uniqueId));
} catch (final NamingException ne) {
logger.warning("no validator factory found for webapp " + currentWebAppInfo.moduleId);
}
}
try {
final Class<?> orb = TomcatWebAppBuilder.class.getClassLoader().loadClass("org.omg.CORBA.ORB");
if (SystemInstance.get().getComponent(orb) != null) {
safeBind(comp, "ORB", new SystemComponentReference(orb));
}
} catch (final NoClassDefFoundError | ClassNotFoundException cnfe) {
// no-op
}
if (SystemInstance.get().getComponent(HandleDelegate.class) != null) {
safeBind(comp, "HandleDelegate", new SystemComponentReference(HandleDelegate.class));
}
} catch (final NamingException e) {
// no-op
} finally {
// see also the start method getContainerSystem().addWebDeployment(webContext);
for (final WebAppInfo webApp : contextInfo.appInfo.webApps) {
SystemInstance.get().fireEvent(new AfterApplicationCreated(contextInfo.appInfo, webApp));
}
thread.setContextClassLoader(originalLoader);
ContextAccessController.setReadOnly(listenerName);
}
thread.setContextClassLoader(classLoader);
try {
// owb integration filters
final WebBeansContext webBeansContext = getWebBeansContext(contextInfo);
if (webBeansContext != null) {
// it is important to have a begin and a end listener
// to be sure to create contexts before other listeners
// and destroy contexts after other listeners
final BeginWebBeansListener beginWebBeansListener = new BeginWebBeansListener(webBeansContext);
final EndWebBeansListener endWebBeansListener = new EndWebBeansListener(webBeansContext);
{
final Object[] appEventListeners = standardContext.getApplicationEventListeners();
final Object[] newEventListeners = new Object[appEventListeners.length + 2];
newEventListeners[0] = beginWebBeansListener;
System.arraycopy(appEventListeners, 0, newEventListeners, 1, appEventListeners.length);
newEventListeners[newEventListeners.length - 1] = endWebBeansListener;
standardContext.setApplicationEventListeners(newEventListeners);
}
{
final Object[] lifecycleListeners = standardContext.getApplicationLifecycleListeners();
final Object[] newLifecycleListeners = new Object[lifecycleListeners.length + 2];
newLifecycleListeners[0] = beginWebBeansListener;
System.arraycopy(lifecycleListeners, 0, newLifecycleListeners, 1, lifecycleListeners.length);
newLifecycleListeners[newLifecycleListeners.length - 1] = endWebBeansListener;
standardContext.setApplicationLifecycleListeners(newLifecycleListeners);
}
// also add the ThreadBindingListener to clean up async thread executions
{
WebBeansThreadBindingListener webBeansThreadBindingListener = new WebBeansThreadBindingListener(webBeansContext, standardContext.getThreadBindingListener());
standardContext.setThreadBindingListener(webBeansThreadBindingListener);
}
final ContextsService contextsService = webBeansContext.getContextsService();
if (CdiAppContextsService.class.isInstance(contextsService)) {
// here ServletContext is usable
CdiAppContextsService.class.cast(contextsService).applicationStarted(standardContext.getServletContext());
}
} else {
// just add the end listener to be able to stack tasks to execute at the request end
final EndWebBeansListener endWebBeansListener = new EndWebBeansListener(webBeansContext);
{
final Object[] appEventListeners = standardContext.getApplicationEventListeners();
final Object[] newEventListeners = new Object[appEventListeners.length + 1];
System.arraycopy(appEventListeners, 0, newEventListeners, 0, appEventListeners.length);
newEventListeners[newEventListeners.length - 1] = endWebBeansListener;
standardContext.setApplicationEventListeners(newEventListeners);
}
{
final Object[] lifecycleListeners = standardContext.getApplicationLifecycleListeners();
final Object[] newLifecycleListeners = new Object[lifecycleListeners.length + 1];
System.arraycopy(lifecycleListeners, 0, newLifecycleListeners, 0, lifecycleListeners.length);
newLifecycleListeners[newLifecycleListeners.length - 1] = endWebBeansListener;
standardContext.setApplicationLifecycleListeners(newLifecycleListeners);
}
}
} finally {
thread.setContextClassLoader(originalLoader);
}
LinkageErrorProtection.preload(standardContext);
final Pipeline pipeline = standardContext.getPipeline();
pipeline.addValve(new OpenEJBValve());
final String[] valves = SystemInstance.get().getOptions().get("tomee.valves", "").split(" *, *");
for (final String className : valves) {
if ("".equals(className)) {
continue;
}
try {
final Class<?> clazz = classLoader.loadClass(className);
if (Valve.class.isAssignableFrom(clazz)) {
final Valve valve = (Valve) clazz.newInstance();
pipeline.addValve(valve);
}
} catch (final Exception e) {
logger.error("can't add the valve " + className, e);
}
}
// add servlets to webappinfo
if (currentWebAppInfo != null) {
for (final String mapping : standardContext.findServletMappings()) {
final ServletInfo info = new ServletInfo();
info.servletName = standardContext.findServletMapping(mapping);
info.mappings.add(mapping);
final Container container = standardContext.findChild(info.servletName);
if (container instanceof StandardWrapper) {
info.servletClass = ((StandardWrapper) container).getServletClass();
} else {
info.servletClass = mapping;
}
currentWebAppInfo.servlets.add(info);
}
}
addConfiguredDocBases(standardContext, contextInfo);
ensureMyFacesDontLooseFacesContext(standardContext);
}
Aggregations