rzo1 commented on code in PR #329: URL: https://github.com/apache/openjpa/pull/329#discussion_r4789058375
########## openjpa-kernel/src/main/java/org/apache/openjpa/cdi/NonContextualBeanWrapperFactory.java: ########## @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.openjpa.cdi; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.openjpa.event.BeanWrapper; +import org.apache.openjpa.event.CachedBeanWrapper; +import org.apache.openjpa.lib.conf.GenericConfigurable; +import org.apache.openjpa.lib.util.J2DoPrivHelper; +import org.apache.openjpa.lib.util.Localizer; +import org.apache.openjpa.lib.util.Options; +import org.apache.openjpa.util.UserException; + +/** + * Default BeanManager factory, intended to be used in non-CDI environments + * and in CDI environments where there is no intention to use CDI injection + * on AttributeConverters and EntityListeners. + */ +public class NonContextualBeanWrapperFactory implements BeanWrapperFactory, GenericConfigurable { + + private static final Localizer _loc = Localizer.forPackage(NonContextualBeanWrapperFactory.class); + + private Map<Class<?>, BeanWrapper<?>> converterCache = new ConcurrentHashMap<>(); + + private Map<Class<?>, BeanWrapper<?>> listenerCache = new ConcurrentHashMap<>(); + + @Override + public boolean isBeanManagerAvailable() { + return false; + } + + @Override + public Object getBeanManager() { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public <T> BeanWrapper<T> getListenerWrapper(Class<T> listenerClass) { + return (BeanWrapper<T>) listenerCache.computeIfAbsent(listenerClass, this::createCacheableListener); + } + + @SuppressWarnings("unchecked") + @Override + public <T> BeanWrapper<T> getConverterWrapper(Class<T> converterClass) { Review Comment: I don't think this breaks existing code: a converter with an `@Inject` field cannot work today without CDI, it fails with an NPE on the first value. Spec 3.9 says the provider must not invoke it, so a clear error when the converter is set up is better than the NPE later. If you prefer not to fail, a warning at that point would be fine for me too, but it should not be silently invoked. ########## openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIBeanWrapperFactory.java: ########## @@ -0,0 +1,333 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.openjpa.cdi; + +import java.lang.annotation.Annotation; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.apache.openjpa.conf.OpenJPAConfiguration; +import org.apache.openjpa.conf.OpenJPAConfigurationImpl; +import org.apache.openjpa.event.BeanWrapper; +import org.apache.openjpa.event.CachedBeanWrapper; +import org.apache.openjpa.lib.conf.Configurable; +import org.apache.openjpa.lib.conf.Configuration; +import org.apache.openjpa.lib.log.Log; +import org.apache.openjpa.lib.util.J2DoPrivHelper; +import org.apache.openjpa.lib.util.Localizer; +import org.apache.openjpa.util.UserException; + +import jakarta.enterprise.context.spi.CreationalContext; +import jakarta.enterprise.inject.Instance; +import jakarta.enterprise.inject.spi.AnnotatedType; +import jakarta.enterprise.inject.spi.Bean; +import jakarta.enterprise.inject.spi.BeanManager; +import jakarta.enterprise.inject.spi.CDI; +import jakarta.enterprise.inject.spi.InjectionPoint; +import jakarta.enterprise.inject.spi.InjectionTarget; + +public class CDIBeanWrapperFactory implements BeanWrapperFactory, Configurable { + + private static final Localizer _loc = Localizer.forPackage(CDIBeanWrapperFactory.class); + + private Log _log; + + private BeanManager beanManager; + + private Map<Class<?>, BeanWrapper<?>> convertersCache = new ConcurrentHashMap<>(); + + private Map<Class<?>, BeanWrapper<?>> listenersCache = new ConcurrentHashMap<>(); + + private Map<Class<?>, InjectionInfo<?>> convertersInjectionInfo = new ConcurrentHashMap<>(); + + private Map<Class<?>, InjectionInfo<?>> listenersInjectionInfo = new ConcurrentHashMap<>(); + + private String mode = "both"; + + private boolean checkCacheability = true; + + private int cacheabilityCheckDepth = 2; + + private boolean contextualConverters = true; + + private boolean contextualListeners = true; + + public CDIBeanWrapperFactory() { + } + + @Override + public void setConfiguration(Configuration conf) { + if (conf instanceof OpenJPAConfigurationImpl c) { + _log = c.getLog(OpenJPAConfiguration.LOG_RUNTIME); + Object bm = c.getBeanManagerInstance(); + if (bm == null) { + Map<String,Object> env = c.getPersistenceEnvironment(); + bm = env == null ? null : env.getOrDefault("jakarta.persistence.bean.manager", null); + } + if (bm != null && !(bm instanceof BeanManager)) { + throw new IllegalStateException(_loc.get("bean-manager-invalid", bm.getClass().getName()).getMessage()); + } + beanManager = (BeanManager) bm; + } + } + + @Override + public void startConfiguration() { + if (beanManager != null) { + // already set + return; + } + beanManager = lookupBeanManager(); + if (beanManager == null) { + try { + beanManager = CDI.current().getBeanManager(); + } catch (IllegalStateException ex) { + String msg = _loc.get("cdi-not-available").getMessage(); + if (_log.isTraceEnabled()) { + _log.trace(msg); + } + throw new IllegalStateException(msg); + } + } + } + + @Override + public void endConfiguration() { + contextualConverters = switch (mode) { + case BeanWrapperFactoryValue.BOTH: + case BeanWrapperFactoryValue.CONVERTERS_ONLY: { + yield true; + } + default: + yield false; + }; + + contextualListeners= switch (mode) { + case BeanWrapperFactoryValue.BOTH: + case BeanWrapperFactoryValue.LISTENERS_ONLY: { + yield true; + } + default: + yield false; + }; + } + + @Override + public boolean isBeanManagerAvailable() { + return beanManager != null; + } + + @Override + public Object getBeanManager() { + return beanManager; + } + + @Override + public <T> BeanWrapper<T> getConverterWrapper(Class<T> converterClass) { + return getWrapper(converterClass, convertersCache, convertersInjectionInfo, contextualConverters); + } + + @Override + public <T> BeanWrapper<T> getListenerWrapper(Class<T> listenerClass) { + return getWrapper(listenerClass, listenersCache, listenersInjectionInfo, contextualListeners); + } + + @Override + public <T> void dropCachedConverter(Class<T> converterClass) { + dropCached(converterClass, convertersCache, convertersInjectionInfo); + } + + @Override + public <T> void dropCachedListener(Class<T> listenerClass) { + dropCached(listenerClass, listenersCache, listenersInjectionInfo); + } + + @SuppressWarnings("unchecked") + private <T> void dropCached(Class<T> cls, Map<Class<?>, BeanWrapper<?>> cache, + Map<Class<?>, InjectionInfo<?>> infoCache) { + cache.remove(cls); + InjectionInfo<T> info = (InjectionInfo<T>) infoCache.remove(cls); + if (info != null) { + info.context().release(); + } + } + + @Override + public void dispose() { + convertersCache.forEach((c, w) -> { + w.dispose(); + }); + convertersInjectionInfo.forEach((c, i) -> { + i.context().release(); + }); + convertersCache.clear(); + convertersInjectionInfo.clear(); + + listenersCache.forEach((c, w) -> { + w.dispose(); + }); + listenersInjectionInfo.forEach((c, i) -> { + i.context().release(); + }); + listenersCache.clear(); + listenersInjectionInfo.clear(); + } + + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + + public boolean isCheckCacheability() { + return checkCacheability; + } + + public void setCheckCacheability(boolean checkCacheability) { + this.checkCacheability = checkCacheability; + } + + private BeanManager lookupBeanManager() { + String[] jndiNames = {"java:comp/BeanManager", "java:comp/env/BeanManager"}; + Context ctx; + try { + ctx = new InitialContext(); + for (String jndi: jndiNames) { + try { + return (BeanManager) ctx.lookup(jndi); + } catch (NamingException ex) { + // swallow + } + } + } catch (NamingException ex) { + // swallow + } + return null; + } + + @SuppressWarnings("unchecked") + private <T> BeanWrapper<T> getWrapper(Class<T> cls, Map<Class<?>, BeanWrapper<?>> cache, + Map<Class<?>, InjectionInfo<?>> infoCache, boolean useCDI) { + if (cache.containsKey(cls)) { + return (BeanWrapper<T>) cache.get(cls); + } else { + BeanWrapper<T> wrapper = createWrapper(beanManager, cls, infoCache, useCDI); + if (wrapper.cacheable()) { + cache.putIfAbsent(cls, wrapper); + } + return wrapper; + } + } + + private <T> BeanWrapper<T> createWrapper(BeanManager bm, Class<T> cls, Map<Class<?>, InjectionInfo<?>> infoCache, boolean useCDI) { + return bm == null || !useCDI ? createNonContextualWrapper(cls) : getContextualWrapper(bm, cls, infoCache); + } + + private <T> BeanWrapper<T> createNonContextualWrapper(Class<T> cls) { + try { + T instance = J2DoPrivHelper.newInstance(cls); + return new CachedBeanWrapper<T>(instance); + } catch (Throwable t) { + throw new UserException(_loc.get("bean-constructor", cls.getName()), t); + } + } + + @SuppressWarnings("unchecked") + private <T> BeanWrapper<T> getContextualWrapper(final BeanManager bm, final Class<T> cls, final Map<Class<?>, InjectionInfo<?>> infoCache) { + InjectionInfo<T> info = (InjectionInfo<T>) infoCache.computeIfAbsent(cls, clazz -> { + // based on DeltaSpike BeanProvider#injectFields + AnnotatedType<T> type = bm.createAnnotatedType(cls); + InjectionTarget<T> target = bm.getInjectionTargetFactory(type).createInjectionTarget(null); + CreationalContext<T> creationalContext = bm.createCreationalContext(null); + boolean cacheable = checkCacheability ? isCacheable(bm, target, cacheabilityCheckDepth) : true; + return new InjectionInfo<T>(target, creationalContext, cacheable); + }); + if (info.cacheable()) { + infoCache.remove(cls); + } + return createContextualWrapper(bm, cls, info, infoCache); + } + + private <T> BeanWrapper<T> createContextualWrapper(BeanManager bm, Class<?> cls, InjectionInfo<T> info, + Map<Class<?>, InjectionInfo<?>> infoCache) { + T instance = null; + try { + InjectionTarget<T> target = info.target(); + CreationalContext<T> ctx = info.context(); + instance = target.produce(ctx); + target.inject(instance, ctx); + target.postConstruct(instance); + return new CDIBeanWrapper<T>(instance, target, ctx, info.cacheable()); + } catch (Throwable t) { + try { + if (instance != null) { + info.target().dispose(instance); + } + } finally { + if (info.context() != null) { + info.context().release(); + } + infoCache.remove(cls); + } + throw new UserException(_loc.get("cdi-bean-constructor", cls.getName(), t)); + } + } + + private <T> boolean isCacheable(BeanManager beanManager, InjectionTarget<T> target, int depth) { + Set<InjectionPoint> ips = target.getInjectionPoints(); + boolean hasInjections = !ips.isEmpty(); + if (hasInjections) { + return ips.stream().allMatch(ip -> isCacheable(beanManager, ip, depth)); + } + return true; + } + + private boolean isCacheable(BeanManager beanManager, InjectionPoint ip, int depth) { + Set<Bean<?>> candidateBeans = beanManager.getBeans(ip.getType(), ip.getQualifiers().toArray(new Annotation[0])); + Bean<?> bean = beanManager.resolve(candidateBeans); Review Comment: `beanManager.resolve(...)` returns `null` when no bean matches, e.g. an `@Inject` of a type without a bean. `bean.getScope()` then throws an NPE from the cacheability check instead of the CDI error. Please treat an unresolved bean as not cacheable (the injection then fails with the container's own message). ########## openjpa-kernel/src/main/java/org/apache/openjpa/cdi/BeanWrapperFactoryValue.java: ########## @@ -26,43 +26,51 @@ import org.apache.openjpa.lib.log.Log; import org.apache.openjpa.lib.util.Localizer; -public class EntityListenerFactoryValue extends PluginValue implements Configurable { +public class BeanWrapperFactoryValue extends PluginValue implements Configurable { - private static final Localizer _loc = Localizer.forPackage(EntityListenerFactoryValue.class); + private static final Localizer _loc = Localizer.forPackage(BeanWrapperFactoryValue.class); - private static final String KEY = "EntityListenerFactory"; + private static final String KEY = "CDISupport"; - private static final String STATELESS_ALIAS = "stateless"; + public static final String DISABLED_ALIAS = "none"; - private static final String CDI_ALIAS = "cdi"; + public static final String CDI_ALIAS = "cdi"; - private static final String CDI_FACTORY_CLASSNAME = "org.apache.openjpa.cdi.EntityListenerCDIFactory"; - - private Configuration _conf; + public static final String LISTENERS_ONLY = "listeners"; - private Log _log; + public static final String CONVERTERS_ONLY = "converters"; - public EntityListenerFactoryValue() { + public static final String BOTH = "both"; + + private static final String CDI_FACTORY_CLASSNAME = "org.apache.openjpa.cdi.CDIBeanWrapperFactory"; + + private OpenJPAConfiguration _conf; + + public BeanWrapperFactoryValue() { super(KEY, true); String[] aliases = new String[] { - STATELESS_ALIAS, EntityListenerCachedFactory.class.getName(), + DISABLED_ALIAS, NonContextualBeanWrapperFactory.class.getName(), CDI_ALIAS, CDI_FACTORY_CLASSNAME }; setAliases(aliases); - setDefault(STATELESS_ALIAS); + setDefault(DISABLED_ALIAS); } @Override - public Object instantiate(Class<?> type, Configuration c, boolean fatal) { + public Object instantiate(Class<?> type, Configuration conf) { Object instance = null; try { - instance = super.instantiate(type, c, true); + instance = super.instantiate(type, conf, true); } catch (Throwable t) { - if (_log.isTraceEnabled()) { - _log.trace(_loc.get("cdi-not-available")); + Log log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); + if (log.isTraceEnabled()) { + log.trace(_loc.get("bean-wrapper-instantiation-exception", t.getMessage())); Review Comment: This still logs only `t.getMessage()`. Please pass the throwable, e.g. `log.trace(_loc.get("bean-wrapper-instantiation-exception", t.getMessage()), t)`; the same for the warning in line 70. ########## openjpa-project/src/docs/asciidoc/migration_considerations.adoc: ########## @@ -26,13 +26,15 @@ [[jpa_4.3]] == OpenJPA 4.3.0 -[[jpa_4.3_entity_listeners]] -==== Entity listeners -As required by Jakarta API 3.2, entity listeners will receive CDI injection when available in runtime and property ``openjpa.EntityListenerFactory`` is set to ``cdi``. +[[jpa_4.3_cdi_support]] +==== Entity listeners and attribute converters +As required by Jakarta API 3.2, entity listeners and attribute converters will receive CDI injection when available in runtime and property ``openjpa.CDISupport`` is set to ``cdi``. - As the specification does not clarifies how to cache the created listeners, entity listeners in which all @NormalScoped injection points will be cached, as will be cached beans where injection points are Instance<T> beans. -In the remaining cases, the listener will be created and disposed for each lifecycle callback cycle. -Non-CDI injected entity listeners will keep previous behavior and will be cached at startup of the container. +You may limit the CDI support when using this feature setting the ``mode`` property to ``listeners`` or to ``containers``. Review Comment: `containers` should be `converters`. Please also add that CDI support is now on by default when `jakarta.persistence.bean.manager` is passed, and that `openjpa.CDISupport=none` turns it off. That changes the behaviour in containers such as TomEE. ########## openjpa-project/src/docs/asciidoc/ref_guide_conf.adoc: ########## @@ -297,6 +297,24 @@ org.apache.openjpa.conf.OpenJPAConfiguration.getBrokerImpl org.apache.openjpa.kernel.Broker] type to use at runtime. See <<ref_guide_runtime_broker_extension>> on for details. +[[openjpa.CDISupport]] +===== openjpa.CDISupport + +*Property name:* ``openjpa.CDISupport`` + +*Configuration API:* link:../../apidocs/org/apache/openjpa/conf/OpenJPAConfiguration.html#getBeanWrapperFactory()[org.apache.openjpa.conf.OpenJPAConfiguration.getBeanWrapperFactory] + +*Resource adaptor config property:* ``CDISupport`` + +*Default:* ``none`` + +*Possible values:* ``none``, ``cdi`` + +*Description:* A plugin string (see <<ref_guide_conf_plugins>>) describing the link:../../apidocs/org/apache/openjpa/cdi/BeanWrapperFactory.html[ +org.apache.openjpa.cdi.BeanWrapperFactory] type to use at runtime. +See <<jpa_overview_entity_listeners_cdi>> for details. Review Comment: `<<jpa_overview_entity_listeners_cdi>>` no longer exists, the anchor is now `jpa_overview_cdi_integration`. ########## openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIBeanWrapperFactory.java: ########## @@ -0,0 +1,333 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.openjpa.cdi; + +import java.lang.annotation.Annotation; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.apache.openjpa.conf.OpenJPAConfiguration; +import org.apache.openjpa.conf.OpenJPAConfigurationImpl; +import org.apache.openjpa.event.BeanWrapper; +import org.apache.openjpa.event.CachedBeanWrapper; +import org.apache.openjpa.lib.conf.Configurable; +import org.apache.openjpa.lib.conf.Configuration; +import org.apache.openjpa.lib.log.Log; +import org.apache.openjpa.lib.util.J2DoPrivHelper; +import org.apache.openjpa.lib.util.Localizer; +import org.apache.openjpa.util.UserException; + +import jakarta.enterprise.context.spi.CreationalContext; +import jakarta.enterprise.inject.Instance; +import jakarta.enterprise.inject.spi.AnnotatedType; +import jakarta.enterprise.inject.spi.Bean; +import jakarta.enterprise.inject.spi.BeanManager; +import jakarta.enterprise.inject.spi.CDI; +import jakarta.enterprise.inject.spi.InjectionPoint; +import jakarta.enterprise.inject.spi.InjectionTarget; + +public class CDIBeanWrapperFactory implements BeanWrapperFactory, Configurable { + + private static final Localizer _loc = Localizer.forPackage(CDIBeanWrapperFactory.class); + + private Log _log; + + private BeanManager beanManager; + + private Map<Class<?>, BeanWrapper<?>> convertersCache = new ConcurrentHashMap<>(); + + private Map<Class<?>, BeanWrapper<?>> listenersCache = new ConcurrentHashMap<>(); + + private Map<Class<?>, InjectionInfo<?>> convertersInjectionInfo = new ConcurrentHashMap<>(); + + private Map<Class<?>, InjectionInfo<?>> listenersInjectionInfo = new ConcurrentHashMap<>(); + + private String mode = "both"; + + private boolean checkCacheability = true; + + private int cacheabilityCheckDepth = 2; + + private boolean contextualConverters = true; + + private boolean contextualListeners = true; + + public CDIBeanWrapperFactory() { + } + + @Override + public void setConfiguration(Configuration conf) { + if (conf instanceof OpenJPAConfigurationImpl c) { + _log = c.getLog(OpenJPAConfiguration.LOG_RUNTIME); + Object bm = c.getBeanManagerInstance(); + if (bm == null) { + Map<String,Object> env = c.getPersistenceEnvironment(); + bm = env == null ? null : env.getOrDefault("jakarta.persistence.bean.manager", null); + } + if (bm != null && !(bm instanceof BeanManager)) { + throw new IllegalStateException(_loc.get("bean-manager-invalid", bm.getClass().getName()).getMessage()); + } + beanManager = (BeanManager) bm; + } + } + + @Override + public void startConfiguration() { + if (beanManager != null) { + // already set + return; + } + beanManager = lookupBeanManager(); + if (beanManager == null) { + try { + beanManager = CDI.current().getBeanManager(); + } catch (IllegalStateException ex) { + String msg = _loc.get("cdi-not-available").getMessage(); + if (_log.isTraceEnabled()) { + _log.trace(msg); + } + throw new IllegalStateException(msg); + } + } + } + + @Override + public void endConfiguration() { + contextualConverters = switch (mode) { + case BeanWrapperFactoryValue.BOTH: + case BeanWrapperFactoryValue.CONVERTERS_ONLY: { + yield true; + } + default: + yield false; + }; + + contextualListeners= switch (mode) { + case BeanWrapperFactoryValue.BOTH: + case BeanWrapperFactoryValue.LISTENERS_ONLY: { + yield true; + } + default: + yield false; + }; + } + + @Override + public boolean isBeanManagerAvailable() { + return beanManager != null; + } + + @Override + public Object getBeanManager() { + return beanManager; + } + + @Override + public <T> BeanWrapper<T> getConverterWrapper(Class<T> converterClass) { + return getWrapper(converterClass, convertersCache, convertersInjectionInfo, contextualConverters); + } + + @Override + public <T> BeanWrapper<T> getListenerWrapper(Class<T> listenerClass) { + return getWrapper(listenerClass, listenersCache, listenersInjectionInfo, contextualListeners); + } + + @Override + public <T> void dropCachedConverter(Class<T> converterClass) { + dropCached(converterClass, convertersCache, convertersInjectionInfo); + } + + @Override + public <T> void dropCachedListener(Class<T> listenerClass) { + dropCached(listenerClass, listenersCache, listenersInjectionInfo); + } + + @SuppressWarnings("unchecked") + private <T> void dropCached(Class<T> cls, Map<Class<?>, BeanWrapper<?>> cache, + Map<Class<?>, InjectionInfo<?>> infoCache) { + cache.remove(cls); + InjectionInfo<T> info = (InjectionInfo<T>) infoCache.remove(cls); + if (info != null) { + info.context().release(); + } + } + + @Override + public void dispose() { + convertersCache.forEach((c, w) -> { + w.dispose(); + }); + convertersInjectionInfo.forEach((c, i) -> { + i.context().release(); + }); + convertersCache.clear(); + convertersInjectionInfo.clear(); + + listenersCache.forEach((c, w) -> { + w.dispose(); + }); + listenersInjectionInfo.forEach((c, i) -> { + i.context().release(); + }); + listenersCache.clear(); + listenersInjectionInfo.clear(); + } + + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + + public boolean isCheckCacheability() { + return checkCacheability; + } + + public void setCheckCacheability(boolean checkCacheability) { + this.checkCacheability = checkCacheability; + } + + private BeanManager lookupBeanManager() { + String[] jndiNames = {"java:comp/BeanManager", "java:comp/env/BeanManager"}; + Context ctx; + try { + ctx = new InitialContext(); + for (String jndi: jndiNames) { + try { + return (BeanManager) ctx.lookup(jndi); + } catch (NamingException ex) { + // swallow + } + } + } catch (NamingException ex) { + // swallow + } + return null; + } + + @SuppressWarnings("unchecked") + private <T> BeanWrapper<T> getWrapper(Class<T> cls, Map<Class<?>, BeanWrapper<?>> cache, + Map<Class<?>, InjectionInfo<?>> infoCache, boolean useCDI) { + if (cache.containsKey(cls)) { + return (BeanWrapper<T>) cache.get(cls); + } else { + BeanWrapper<T> wrapper = createWrapper(beanManager, cls, infoCache, useCDI); + if (wrapper.cacheable()) { + cache.putIfAbsent(cls, wrapper); + } + return wrapper; + } + } + + private <T> BeanWrapper<T> createWrapper(BeanManager bm, Class<T> cls, Map<Class<?>, InjectionInfo<?>> infoCache, boolean useCDI) { + return bm == null || !useCDI ? createNonContextualWrapper(cls) : getContextualWrapper(bm, cls, infoCache); + } + + private <T> BeanWrapper<T> createNonContextualWrapper(Class<T> cls) { + try { + T instance = J2DoPrivHelper.newInstance(cls); + return new CachedBeanWrapper<T>(instance); + } catch (Throwable t) { + throw new UserException(_loc.get("bean-constructor", cls.getName()), t); + } + } + + @SuppressWarnings("unchecked") + private <T> BeanWrapper<T> getContextualWrapper(final BeanManager bm, final Class<T> cls, final Map<Class<?>, InjectionInfo<?>> infoCache) { + InjectionInfo<T> info = (InjectionInfo<T>) infoCache.computeIfAbsent(cls, clazz -> { + // based on DeltaSpike BeanProvider#injectFields + AnnotatedType<T> type = bm.createAnnotatedType(cls); + InjectionTarget<T> target = bm.getInjectionTargetFactory(type).createInjectionTarget(null); + CreationalContext<T> creationalContext = bm.createCreationalContext(null); Review Comment: The `CreationalContext` is created once per class and cached in `InjectionInfo`. For a non-cacheable converter or listener every instance is then produced into the same context. `CDIBeanWrapper.dispose()` does not release it, so the `@Dependent` objects of every instance are kept until the EMF closes. For a converter that is called for every value that grows without bound. When one instance fails in `createContextualWrapper`, the shared context is released, and that destroys the dependents of the instances that are still in use. Please cache only the `InjectionTarget` and the cacheability result per class, create a new `CreationalContext` for each instance, and release it in `CDIBeanWrapper.dispose()` after `preDestroy`/`dispose`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
