rzo1 commented on code in PR #329:
URL: https://github.com/apache/openjpa/pull/329#discussion_r4732563861
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIBeanWrapperFactory.java:
##########
@@ -40,49 +47,126 @@
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.inject.spi.InjectionTarget;
-public class EntityListenerCDIFactory implements EntityListenerFactory {
+public class CDIBeanWrapperFactory implements BeanWrapperFactory, Configurable
{
- private static final Localizer _loc =
Localizer.forPackage(EntityListenerCDIFactory.class);
+ private static final Localizer _loc =
Localizer.forPackage(CDIBeanWrapperFactory.class);
+
+ private Log _log;
- private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
-
private BeanManager beanManager;
- private Map<Class<?>, EntityListenerWrapper<?>> cache = new
ConcurrentHashMap<>();
+ private Map<Class<?>, BeanWrapper<?>> convertersCache = new HashMap<>();
Review Comment:
These were `ConcurrentHashMap`s on master (see the review on #321). The
factory is shared by all brokers of the EMF, and converters are looked up on
every read and write, so several threads call `containsKey`/`get`/`putIfAbsent`
at the same time. A `HashMap` can get corrupted by that. Please use
`ConcurrentHashMap` for both caches again (line 60 as well).
##########
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(t.getMessage());
Review Comment:
Please log the throwable and not only `t.getMessage()`, e.g.
`log.trace(_loc.get("cdi-not-available"), t)`. This is the only place where the
reason for the fallback shows up, and the message alone (often `null` for a
`NoClassDefFoundError` cause chain) is not enough to find out why CDI is not
used.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java:
##########
@@ -1557,9 +1552,12 @@ public Object getElementFieldValue(Object val) {
/**
* Pass the given value to the given method of the converter.
*/
- private Object invokeConverter(Method m, Object val) {
+ @SuppressWarnings("unchecked")
+ private Object invokeConverter(Method m, Object val) {
+ BeanWrapper<?> wrapper = null;
try {
- return m.invoke(getConverterInstance(), val);
+ wrapper = getConverterWrapper(getConverter());
Review Comment:
This runs for every value that is read or written. Before, the instance was
cached in the field (volatile). Now every conversion goes through
`getRepository().getConfiguration().getBeanWrapperFactory()` and a map lookup.
For a converter that is not cacheable, `CDIBeanWrapperFactory` even creates the
`AnnotatedType`, the `InjectionTarget` and a `CreationalContext` and runs the
cacheability check for every single value.
A sketch:
```java
// FieldMetaData
private transient volatile BeanWrapper<?> _converterWrapper;
private Object invokeConverter(Method m, Object val) {
BeanWrapper<?> wrapper = _converterWrapper;
if (wrapper == null) {
wrapper = getConverterWrapper(getConverter());
if (wrapper.cacheable()) {
_converterWrapper = wrapper; // cleared again in setConverter()
}
}
try {
return m.invoke(wrapper.instance(), val);
} ...
} finally {
if (!wrapper.cacheable()) {
wrapper.dispose();
}
}
}
```
And in `CDIBeanWrapperFactory`, cache the `InjectionTarget` and the result
of the cacheability check per class (e.g. a small record in a
`ConcurrentHashMap`), so a non-cacheable converter only needs
`produce`/`inject`/`postConstruct` per call.
##########
openjpa-kernel/src/main/resources/org/apache/openjpa/cdi/localizer.properties:
##########
@@ -14,7 +14,18 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-cdi-not-available: Could not instantiate CDI aware entity listener {0}.
-bean-constructor: Could not instantiate class {0}. Make sure it has an \
- accessible no-args constructor.
+cdi-not-available: Could not instantiate CDI aware entity listener or
attribute converter {0}.
+cdi-listeners-disabled: CDI support for entity listeners was disabled by
configuration \
+ (openjpa.CDISupport=converters). To enable it, set it to both or
listeners.
+cdi-converters-disabled: CDI support for attribute converters was disabled by
configuration \
+ (openjpa.CDISupport=listeners). To enable it, set it to both or converters.
+cdi-passed-bean-manager-not-used: CDI injection into entity listeners is \
Review Comment:
This now covers converters too, but still says "CDI injection into entity
listeners is turned off". Something like "CDI injection into entity listeners
and attribute converters is turned off ..." would fit.
##########
openjpa-kernel/src/main/resources/org/apache/openjpa/cdi/localizer.properties:
##########
@@ -14,7 +14,18 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-cdi-not-available: Could not instantiate CDI aware entity listener {0}.
-bean-constructor: Could not instantiate class {0}. Make sure it has an \
- accessible no-args constructor.
+cdi-not-available: Could not instantiate CDI aware entity listener or
attribute converter {0}.
+cdi-listeners-disabled: CDI support for entity listeners was disabled by
configuration \
Review Comment:
`cdi-listeners-disabled` and `cdi-converters-disabled` are not used
anywhere. They also mention `openjpa.CDISupport=converters`, but `converters`
is not a value of that property, it is the `mode` of the `cdi` plugin. Please
either use them with the right syntax (e.g.
`openjpa.CDISupport=cdi(Mode=converters)`) or remove them.
##########
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:
Spec 3.9 also says that in environments where CDI is not enabled, the
provider must not invoke attribute converters that depend on CDI injection
(that is point b) of OPENJPA-3101). Here a converter with `@Inject` fields is
created with `newInstance` and invoked, and then fails with an NPE. The same
happens in `CDIBeanWrapperFactory` when converters are not enabled or no
BeanManager is there. Please check for injection points (fields, methods and
constructors annotated with `jakarta.inject.Inject`, matched by name so the CDI
API stays optional) and fail with a clear error instead of invoking the
converter.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java:
##########
@@ -1630,35 +1632,22 @@ public Object copyConvertedValue(Object val,
StoreContext ctx) {
/**
* Get (or create) the cached instance of the converter class.
* <p>
- * A single converter instance is created lazily and shared by all
- * brokers and threads using this field, so AttributeConverter
- * implementations must be stateless / thread-safe.
- * <p>
- * The instance is created through its no-arg constructor. OpenJPA has no
+ * The instance is created through the ConverterFactory defined in
+ * configuration. There are two implementations of it:
+ * <ul>
+ * <li>ConverterCachedFactory: instantiates only one no-arg constructor
+ * instance by class, that is thus cached</li>
+ * <li>ConverterCDIFactory: instantiates a CDI injected instance of the
+ * converter, caching it except if the converter is configured not to
+ * cache, in which case it will create and </li>
+ * </ul>
* container hook (no BeanManager / InjectionTarget plumbing anywhere in
* the runtime, cf. {@code BeanLifecycleCallbacks}), so a converter that is
* also a CDI bean is not injected. Adding that requires a provider-wide
* instance factory first and is out of scope here.
Review Comment:
This javadoc no longer matches the code: `ConverterCachedFactory` and
`ConverterCDIFactory` do not exist, a sentence breaks off ("in which case it
will create and </li>"), and the last paragraph still says CDI converters are
out of scope. Please rewrite it for `BeanWrapperFactory`.
##########
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);
Review Comment:
Just a suggestion: when the container passes
`jakarta.persistence.bean.manager`, CDI is enabled there (spec 9.1), so `cdi`
could be the default in that case and `none` otherwise. Then TomEE and other
containers get the spec behaviour without extra configuration, and Java SE
stays as it is. Happy to discuss, not a blocker.
##########
openjpa-kernel/src/test/java/org/apache/openjpa/meta/TestConverterInstanceCaching.java:
##########
@@ -113,10 +122,6 @@ public OpenJPAConfiguration getConfiguration() {
}
assertEquals(1, CONSTRUCTED.get());
- // resetting the converter discards the cached instance
- SECOND_CONSTRUCTION = new CountDownLatch(1);
- fmd.setConverter(SlowConverter.class);
- assertEquals("ABC", fmd.getExternalValue("abc", null));
- assertEquals(2, CONSTRUCTED.get());
+ // There is no reset in the same broker.
Review Comment:
The assertion that `setConverter()` drops the cached instance was removed.
With the converter cached per class in the factory, a new `setConverter()`
keeps using the old instance. Please keep that behaviour (with the cached
wrapper in `FieldMetaData` from the comment on `invokeConverter`,
`setConverter()` can simply clear it) and keep the assertion.
##########
openjpa-project/src/docs/asciidoc/jpa_overview_pc.adoc:
##########
@@ -592,18 +592,22 @@ You can exclude default listeners and listeners defined
in superclasses from the
* [class]``ExcludeDefaultListeners``: This annotation indicates that no
default listeners will be invoked for this class, or any of its subclasses. The
XML equivalent is the empty `exclude-default-listeners` element.
* [class]``ExcludeSuperclassListeners``: This annotation will cause OpenJPA to
skip invoking any listeners declared in superclasses. The XML equivalent is the
empty `exclude-superclass-listeners` element.
-[[jpa_overview_entity_listeners_cdi]]
+[[jpa_overview_cdi_integration]]
==== CDI integration
(((lifecycle listeners , cdi)))
-Entity listeners, when called in CDI managed environments, may have contextual
beans injected as defined by
https://jakarta.ee/specifications/persistence/3.2/jakarta-persistence-spec-3.2.html#entity-listeners[
JPA 3.2 specification].
-OpenJPA implements that keeping a cache of entity listeners that have
``@NormalScoped`` CDI beans or, when applicable, when the injected fields are
``Instance<?>``s.
-``EntityListener``'s with non-``@NormalScoped`` injected beans are created and
disposed for each lifecycle call, so library clients should consider the
corresponding performance penalty when designing their listeners.
+Entity listeners and converters, when called in CDI managed environments, may
have contextual beans injected as defined by
https://jakarta.ee/specifications/persistence/3.2/jakarta-persistence-spec-3.2.html#entity-listeners[
JPA 3.2 specification].
+OpenJPA implements that keeping a cache of entity listeners and attribute
converters that have ``@NormalScoped`` CDI beans or, when applicable, when the
injected fields are ``Instance<?>``s.
+``EntityListener``'s and ``AttributeConverters``'s with non-``@NormalScoped``
injected beans are created and disposed for each lifecycle call, so library
clients should consider the corresponding performance penalty when designing
their listeners and converters.
If you want to avoid the analysis of cacheability when using CDI enabled
factory, please set the property ``checkCacheability`` to ``false`` using
``cdi(checkCacheability=false)``.
-Due backwards compatibility, these feature is *not* enabled by default. Please
add property ``openjpa.EntityListenerFactory`` with value ``cdi`` to activate
it.
+Due backwards compatibility, these feature is *not* enabled by default. Please
add property ``openjpa.CDISupport`` with value ``cdi``. You may limit the scope
of CDI integration by setting the ``mode`` to ``both`` (default), ``listeners``
or ``converters``.
Review Comment:
Please show how `mode` is set, e.g.
`openjpa.CDISupport=cdi(Mode=listeners)`. From "setting the mode to both,
listeners or converters" it is not clear that this is a plugin option. Small
wording: "For backwards compatibility, this feature is not enabled by default."
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIBeanWrapperFactory.java:
##########
@@ -40,49 +47,126 @@
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.inject.spi.InjectionTarget;
-public class EntityListenerCDIFactory implements EntityListenerFactory {
+public class CDIBeanWrapperFactory implements BeanWrapperFactory, Configurable
{
- private static final Localizer _loc =
Localizer.forPackage(EntityListenerCDIFactory.class);
+ private static final Localizer _loc =
Localizer.forPackage(CDIBeanWrapperFactory.class);
+
+ private Log _log;
- private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
-
private BeanManager beanManager;
- private Map<Class<?>, EntityListenerWrapper<?>> cache = new
ConcurrentHashMap<>();
+ private Map<Class<?>, BeanWrapper<?>> convertersCache = new HashMap<>();
+
+ private Map<Class<?>, BeanWrapper<?>> listenersCache = new HashMap<>();
+
+ private String mode = "both";
private boolean checkCacheability = true;
- public EntityListenerCDIFactory() {
+ 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) {
- throw new
IllegalStateException(_loc.get("cdi-not-available").getMessage());
+ String msg =
_loc.get("cdi-not-available").getMessage();
+ if (_log.isTraceEnabled()) {
+ _log.trace(msg);
+ }
+ throw new
IllegalStateException("cdi-not-available");
Review Comment:
This throws the key `"cdi-not-available"` as the message instead of the
text. Please use `_loc.get("cdi-not-available").getMessage()`. The text also
has a `{0}` that is not filled here.
--
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]