use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.
the class LazyRealm method instance.
private Realm instance() {
if (delegate == null) {
synchronized (this) {
if (delegate == null) {
final Object instance;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (container != null && container.getLoader() != null && container.getLoader().getClassLoader() != null) {
cl = container.getLoader().getClassLoader();
}
final Class<?> clazz;
try {
clazz = cl.loadClass(realmClass);
} catch (final ClassNotFoundException e) {
throw new TomEERuntimeException(e);
}
if (!cdi) {
try {
final ObjectRecipe recipe = new ObjectRecipe(clazz);
recipe.allow(Option.CASE_INSENSITIVE_PROPERTIES);
recipe.allow(Option.IGNORE_MISSING_PROPERTIES);
recipe.allow(Option.FIELD_INJECTION);
recipe.allow(Option.PRIVATE_PROPERTIES);
if (properties != null) {
final Properties props = new PropertiesAdapter().unmarshal(properties.trim().replaceAll("\\p{Space}*(\\p{Alnum}*)=", "\n$1="));
recipe.setAllProperties(props);
}
instance = recipe.create();
} catch (final Exception e) {
throw new TomEERuntimeException(e);
}
} else {
final WebBeansContext webBeansContext;
try {
webBeansContext = WebBeansContext.currentInstance();
if (webBeansContext == null) {
return null;
}
} catch (final IllegalStateException ise) {
// too early to have a cdi bean, skip these methods - mainly init() but @PostConstruct works then
return null;
}
final BeanManager bm = webBeansContext.getBeanManagerImpl();
final Set<Bean<?>> beans = bm.getBeans(clazz);
final Bean<?> bean = bm.resolve(beans);
if (bean == null) {
return null;
}
creationalContext = bm.createCreationalContext(null);
instance = bm.getReference(bean, clazz, creationalContext);
}
if (instance == null) {
throw new TomEERuntimeException("realm can't be retrieved from cdi");
}
if (instance instanceof Realm) {
delegate = (Realm) instance;
delegate.setContainer(container);
delegate.setCredentialHandler(credentialHandler);
if (Lifecycle.class.isInstance(delegate)) {
if (init) {
try {
final Lifecycle lifecycle = Lifecycle.class.cast(delegate);
lifecycle.init();
if (start) {
lifecycle.start();
}
} catch (final LifecycleException e) {
// no-op
}
}
}
} else {
delegate = new LowTypedRealm(instance);
delegate.setContainer(container);
delegate.setCredentialHandler(credentialHandler);
}
for (final PropertyChangeListener listener : support.getPropertyChangeListeners()) {
delegate.addPropertyChangeListener(listener);
}
}
}
}
return delegate;
}
use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.
the class TomcatWebAppBuilder method getWebBeansContext.
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;
}
use of org.apache.webbeans.config.WebBeansContext 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);
}
use of org.apache.webbeans.config.WebBeansContext in project tomee by apache.
the class TomcatJndiBuilder method mergeJava.
public static void mergeJava(final StandardContext standardContext) {
final ContainerSystem cs = SystemInstance.get().getComponent(ContainerSystem.class);
final String name = standardContext.getNamingContextListener().getName();
final Object namingToken = standardContext.getNamingToken();
ContextAccessController.setWritable(name, namingToken);
Context root = null;
try {
root = ContextBindings.getClassLoader();
} catch (final NamingException ignored) {
// shouldn't occur
// no-op
}
// classical deployment - needed because can be overriden through META-INF/context.xml
final String hostname = org.apache.tomee.catalina.Contexts.getHostname(standardContext);
String path = standardContext.findParameter(TomcatWebAppBuilder.OPENEJB_WEBAPP_MODULE_ID);
if (path == null) {
// standardContext not created by OpenEJB
path = hostname;
if (standardContext.getPath().startsWith("/")) {
path += standardContext.getPath();
} else {
path += "/" + standardContext.getPath();
}
}
WebContext webContext = cs.getWebContextByHost(path, hostname);
if (webContext == null) {
// tomee-embedded deployment
webContext = cs.getWebContextByHost(standardContext.getPath().replaceFirst("/", ""), hostname);
if (webContext == null) {
webContext = cs.getWebContextByHost(standardContext.getPath(), hostname);
}
}
final TomcatWebAppBuilder builder = (TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class);
TomcatWebAppBuilder.ContextInfo contextInfo = null;
if (builder != null) {
contextInfo = builder.getContextInfo(standardContext);
if (webContext == null && contextInfo != null && contextInfo.appInfo != null) {
// can happen if deployed from apps/
for (final WebAppInfo webAppInfo : contextInfo.appInfo.webApps) {
if (webAppInfo.path != null && webAppInfo.path.replace(File.separatorChar, '/').equals(standardContext.getDocBase())) {
webContext = cs.getWebContextByHost(webAppInfo.moduleId, hostname);
if (webContext != null) {
break;
}
}
}
}
}
Collection<String> ignoreNames = null;
if (contextInfo != null) {
ignoreNames = contextInfo.resourceNames;
}
if (webContext != null && webContext.getBindings() != null && root != null) {
for (final Map.Entry<String, Object> entry : webContext.getBindings().entrySet()) {
try {
final String key = entry.getKey();
if (key.startsWith("global/")) {
// will be done later
continue;
}
final Object value = normalize(entry.getValue());
if (ignoreNames.contains(removeCompEnv(key))) {
// keep tomcat resources
try {
// tomcat can get the reference but the bound value
// can come from OpenEJB (ejb-jar.xml for instance)
// so check the lookup can be resolved before skipping it
root.lookup(key);
continue;
} catch (final NameNotFoundException nnfe) {
// no-op: let it be rebound or bound
}
}
Contexts.createSubcontexts(root, key);
root.rebind(key, value);
} catch (final NamingException e) {
e.printStackTrace();
}
}
}
// merge global: we bind our global to be able to get a real global context and not a local one (bindigns)
if (root != null) {
try {
root.bind("global", SystemInstance.get().getComponent(ContainerSystem.class).getJNDIContext().lookup("global"));
} catch (final NamingException e) {
// bind only global bindings
if (webContext != null && webContext.getBindings() != null) {
for (final Map.Entry<String, Object> entry : webContext.getBindings().entrySet()) {
try {
final String key = entry.getKey();
if (!key.startsWith("global/")) {
continue;
}
final Object value = normalize(entry.getValue());
Contexts.createSubcontexts(root, key);
root.rebind(key, value);
} catch (final NamingException ignored) {
e.printStackTrace();
}
}
}
}
}
// try to force some binding which probably failed earlier (see in TomcatWebappBuilder)
try {
final Context comp = (Context) ContextBindings.getClassLoader().lookup("comp");
final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
comp.rebind("TransactionManager", transactionManager);
// bind TransactionSynchronizationRegistry
final TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
comp.rebind("TransactionSynchronizationRegistry", synchronizationRegistry);
try {
comp.rebind("ORB", new SystemComponentReference(TomcatJndiBuilder.class.getClassLoader().loadClass("org.omg.CORBA.ORB")));
} catch (final NoClassDefFoundError | ClassNotFoundException ncdfe) {
// no-op
}
comp.rebind("HandleDelegate", new SystemComponentReference(HandleDelegate.class));
if (webContext != null && webContext.getWebbeansContext() != null) {
comp.rebind("BeanManager", new InjectableBeanManager(webContext.getWebbeansContext().getBeanManagerImpl()));
} else if (contextInfo != null) {
final WebBeansContext webBeansContext = cs.getAppContext(contextInfo.appInfo.appId).getWebBeansContext();
if (webBeansContext != null) {
// can be null if cdi is inhibited
comp.rebind("BeanManager", new InjectableBeanManager(webBeansContext.getBeanManagerImpl()));
}
}
} catch (final Exception ignored) {
ignored.printStackTrace();
// no-op
}
// merge comp/env in app if available (some users are doing it, JBoss habit?)
try {
final Context app = (Context) ContextBindings.getClassLoader().lookup("app");
final Context ctx = (Context) ContextBindings.getClassLoader().lookup("comp/env");
final List<Binding> bindings = Collections.list(ctx.listBindings("app"));
for (final Binding binding : bindings) {
try {
app.bind(binding.getName(), binding.getObject());
} catch (final NamingException ne) {
// we don't want to rebind
// no-op
}
}
} catch (final Exception ne) {
// no-op
}
ContextAccessController.setReadOnly(name);
}
Aggregations