rzo1 commented on code in PR #321:
URL: https://github.com/apache/openjpa/pull/321#discussion_r4659471765
##########
openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java:
##########
@@ -4724,6 +4724,7 @@ protected void free() {
_pending = null;
_loader = null;
_transEventManager = null;
+
_conf.getMetaDataRepositoryInstance().getCdiInjectionService().dispose();
Review Comment:
`free()` runs on every `EntityManager.close()`, but the injection service
belongs to the `MetaDataRepository`, i.e. to the EMF. So closing the first EM
calls `preDestroy`/`dispose` on all cached listeners of the EMF and releases
their creational context, while every `BeanLifecycleCallbacks` keeps the
`InjectionManager` it got at parse time and continues to call the destroyed
listener. The spec destroys listeners when the EMF closes, so this should move
to the broker factory close (`AbstractBrokerFactory.close()`). A test that
persists in a second EM after closing the first one would catch this.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
Review Comment:
For a listener that is not cacheable, every call adds an entry to `targets`
and nothing removes it, so the map grows with every callback.
`creationalContext` is a single field that each call overwrites, so with
concurrent callbacks one thread releases the context of another. Suggestion:
create the instance and its `CreationalContext` per callback and return both
(or a small handle), then dispose exactly that instance after the callback.
Only the cached instance needs to be kept for EMF close.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
+ target.inject(instance, creationalContext);
+ target.postConstruct(instance);
+ if (cacheable == null) {
+ checkInjections(target);
+ cachedInstance = cacheable ? instance : null;
+ }
+ return instance;
+ } else {
+ return cachedInstance;
+ }
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return cacheable;
+ }
+
+ @Override
+ public void dispose() {
+ try {
+ for (Entry<T, InjectionTarget<T>> entry:
targets.entrySet()) {
+ T instance = entry.getKey();
+ InjectionTarget<T> target = entry.getValue();
+ target.preDestroy(instance);
+ target.dispose(instance);
+ }
+ } finally {
+ if (creationalContext != null) {
+ creationalContext.release();
+ }
+ }
+ }
+
+ private void checkInjections(InjectionTarget<T> target) {
+ Set<InjectionPoint> ips = target.getInjectionPoints();
+ hasInjections = !ips.isEmpty();
+ if (hasInjections) {
+ cacheable = ips.stream().allMatch(ip -> isCacheable(ip,
NORMAL_BEAN_CHECK_DEPTH));
+ } else {
+ cacheable = true;
+ try {
+ cachedInstance = J2DoPrivHelper.newInstance(listenerClass);
Review Comment:
When there are no injection points, the listener was already created through
`target.produce()` above, and a second instance is created here, which is then
overwritten again by `cachedInstance = cacheable ? instance : null` in
`getInstance()`. This line can go.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
+ target.inject(instance, creationalContext);
+ target.postConstruct(instance);
+ if (cacheable == null) {
+ checkInjections(target);
+ cachedInstance = cacheable ? instance : null;
+ }
+ return instance;
+ } else {
+ return cachedInstance;
+ }
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return cacheable;
+ }
+
+ @Override
+ public void dispose() {
+ try {
+ for (Entry<T, InjectionTarget<T>> entry:
targets.entrySet()) {
+ T instance = entry.getKey();
+ InjectionTarget<T> target = entry.getValue();
+ target.preDestroy(instance);
+ target.dispose(instance);
+ }
+ } finally {
+ if (creationalContext != null) {
+ creationalContext.release();
+ }
+ }
+ }
+
+ private void checkInjections(InjectionTarget<T> target) {
+ Set<InjectionPoint> ips = target.getInjectionPoints();
+ hasInjections = !ips.isEmpty();
+ if (hasInjections) {
+ cacheable = ips.stream().allMatch(ip -> isCacheable(ip,
NORMAL_BEAN_CHECK_DEPTH));
+ } else {
+ cacheable = true;
+ try {
+ cachedInstance = J2DoPrivHelper.newInstance(listenerClass);
+ } catch (Throwable t) {
+ throw new UserException(_loc.get("bean-constructor",
listenerClass.getName()), t);
+ }
+ }
+ }
+
+ private boolean isCacheable(InjectionPoint ip, int depth) {
+ BeanContainer container = CDI.current().getBeanContainer();
Review Comment:
This uses `CDI.current()` again instead of the `beanManager` the manager was
created with. With a bean manager passed in by the container (see the comment
in `CDIInjectionService`) these could be different containers.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
+ target.inject(instance, creationalContext);
+ target.postConstruct(instance);
+ if (cacheable == null) {
+ checkInjections(target);
+ cachedInstance = cacheable ? instance : null;
+ }
+ return instance;
+ } else {
+ return cachedInstance;
+ }
+ }
+
+ @Override
+ public boolean isCacheable() {
Review Comment:
`cacheable` is a `Boolean` that is null until the first `getInstance()`, so
this throws an NPE if it is called first. The lazy initialisation of
`cacheable`/`cachedInstance` in `getInstance()` is also not synchronized, so
two threads on the first callback can both create and cache instances.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionService.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import jakarta.enterprise.inject.spi.BeanManager;
+import jakarta.enterprise.inject.spi.CDI;
+
+public class CDIInjectionService {
+
+ private boolean cdiCtxAvailable = true;
+
+ private Map<Class<?>, InjectionManager<?>> injectors =
Collections.synchronizedMap(new HashMap<>());
+
+ public CDIInjectionService() {
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> InjectionManager<T> getInjectionManager(Class<T> cls) {
+ return (InjectionManager<T>) injectors.computeIfAbsent(cls,
(clazz) -> buildInjectionManager(clazz));
+ }
+
+ private <T> InjectionManager<T> buildInjectionManager(Class<T> cls) {
+ BeanManager beanManager = null;
+ if (cdiCtxAvailable) {
+ try {
+ beanManager = CDI.current().getBeanManager();
Review Comment:
Two things here:
1. JPA 3.2 defines `jakarta.persistence.bean.manager` for this (the "Obtain
a BeanManager" step in the spec section quoted on the list). Containers pass it
to `createContainerEntityManagerFactory`. TomEE does this already
(`EntityManagerFactoryCallable`), as a lazy proxy because the EMF is often
created before OWB is running for the application, and lets users turn it off
with `tomee.jpa.cdi=false`. OpenJPA should use that property first and only
fall back to `CDI.current()`, as Romain suggested.
2. This runs from the `BeanLifecycleCallbacks` constructor, i.e. while
metadata is parsed. In TomEE, OWB resolves the context through the thread
context class loader, and for an EMF that is created eagerly
`ThreadSingletonServiceImpl` throws `IllegalStateException("On a thread without
an initialized context ...")`. Then `cdiCtxAvailable` becomes false for the
lifetime of the EMF and no listener is ever injected, without any log message.
The bean manager should be looked up on the first callback, and the fallback
should at least be logged.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIBeanManagerProvider.java:
##########
@@ -0,0 +1,98 @@
+/*
+ * 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.Iterator;
+
+import jakarta.enterprise.inject.Instance;
+import jakarta.enterprise.inject.spi.BeanManager;
+import jakarta.enterprise.inject.spi.CDI;
+import jakarta.enterprise.inject.spi.CDIProvider;
+import jakarta.enterprise.util.TypeLiteral;
+
+public class CDIBeanManagerProvider implements CDIProvider {
Review Comment:
I would drop this provider and the service file. `CDI.current()` (cdi-api
4.1) takes the first provider by priority whose `getCDI()` is non-null and
keeps it in `configuredProvider`. With Weld for example the real provider
throws `IllegalStateException` until the container is started; if anything
calls `CDI.current()` before that, this provider is chosen, and since its
`getCDI()` never returns null it stays chosen for the JVM. After that every
library gets a `CDI` whose `getBeanManager()` returns null instead of an
exception. In TomEE it is harmless only because OWB's provider has priority 0
and always returns an instance. Catching the `IllegalStateException`, as
`CDIInjectionService` already does, is enough.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
+ target.inject(instance, creationalContext);
+ target.postConstruct(instance);
+ if (cacheable == null) {
+ checkInjections(target);
+ cachedInstance = cacheable ? instance : null;
+ }
+ return instance;
+ } else {
+ return cachedInstance;
+ }
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return cacheable;
+ }
+
+ @Override
+ public void dispose() {
+ try {
+ for (Entry<T, InjectionTarget<T>> entry:
targets.entrySet()) {
+ T instance = entry.getKey();
+ InjectionTarget<T> target = entry.getValue();
+ target.preDestroy(instance);
+ target.dispose(instance);
+ }
+ } finally {
+ if (creationalContext != null) {
+ creationalContext.release();
+ }
+ }
+ }
+
+ private void checkInjections(InjectionTarget<T> target) {
+ Set<InjectionPoint> ips = target.getInjectionPoints();
+ hasInjections = !ips.isEmpty();
+ if (hasInjections) {
+ cacheable = ips.stream().allMatch(ip -> isCacheable(ip,
NORMAL_BEAN_CHECK_DEPTH));
+ } else {
+ cacheable = true;
+ try {
+ cachedInstance = J2DoPrivHelper.newInstance(listenerClass);
+ } catch (Throwable t) {
+ throw new UserException(_loc.get("bean-constructor",
listenerClass.getName()), t);
+ }
+ }
+ }
+
+ private boolean isCacheable(InjectionPoint ip, int depth) {
Review Comment:
I think this check is inverted compared to what Romain suggested on the
list. A normal-scoped bean is injected as a client proxy, so caching a listener
that holds it is safe whatever that bean injects itself; there is no need to
walk into its injection points. The risky case is a `@Dependent` bean (which is
not proxied) that captured request state when it was created, so a bounded walk
should go into `@Dependent` beans instead, and only fail when it finds state
that is not normal scoped. Right now `@Inject BeanManager` or `@Inject
Event<X>` (built-in, dependent) also make a listener non-cacheable.
##########
openjpa-kernel/src/main/resources/META-INF/services/jakarta.enterprise.inject.spi.CDIProvider:
##########
@@ -0,0 +1,17 @@
+# 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.
+org.apache.openjpa.cdi.CDIBeanManagerProvider
Review Comment:
See the comment on `CDIBeanManagerProvider`: this registers a provider for
every application that has openjpa-kernel on the class path.
##########
openjpa-kernel/pom.xml:
##########
@@ -90,6 +90,10 @@
<scope>provided</scope>
<optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>jakarta.enterprise</groupId>
+ <artifactId>jakarta.enterprise.cdi-api</artifactId>
Review Comment:
This makes the CDI API a required dependency of openjpa-kernel. Since
`BeanLifecycleCallbacks` links `CDIInjectionService` and through it
`jakarta.enterprise` classes, an application in Java SE without the CDI API
gets `NoClassDefFoundError` as soon as an entity has a listener. Could this be
`provided`/optional like the other optional APIs in this pom, with the CDI
classes only loaded after checking that the API is available, and
`CDIUnawareInjectionManager` otherwise?
##########
openjpa-kernel/src/main/java/org/apache/openjpa/meta/MetaDataRepository.java:
##########
@@ -2693,4 +2697,17 @@ public Class<?> getAutoApplyConverter(Class<?>
entityAttributeType) {
public Map<Class<?>, Class<?>> getAutoApplyConverters() {
return _autoApplyConverters;
}
+
+ /**
+ * Returns the CDI injection service used to configure entity listeners.
+ *
+ * @return
+ * @since 4.3.0
+ */
+ public CDIInjectionService getCdiInjectionService() {
+ if (cdiInjectionService == null) {
Review Comment:
Lazy initialisation without synchronization: two threads parsing metadata at
the same time can create two services, and listeners registered with the one
that is lost are never disposed. Creating it in the constructor or
`endConfiguration()` avoids this.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/event/BeanLifecycleCallbacks.java:
##########
@@ -23,73 +23,69 @@
import java.io.ObjectOutput;
import java.lang.reflect.Method;
-import org.apache.openjpa.lib.util.J2DoPrivHelper;
-import org.apache.openjpa.lib.util.Localizer;
-import org.apache.openjpa.util.UserException;
+import org.apache.openjpa.cdi.InjectionManager;
+import org.apache.openjpa.cdi.CDIInjectionService;
/**
* Performs a callback method on a cached bean instance.
*
* @author Steve Kim
*/
-public class BeanLifecycleCallbacks
+public class BeanLifecycleCallbacks<T>
extends MethodLifecycleCallbacks {
- private static final Localizer _loc = Localizer.forPackage
- (BeanLifecycleCallbacks.class);
-
- private transient Object _listener;
-
+ private final Class<T> listenerClass;
+
+ private InjectionManager<T> injectorManager;
+
/**
* Constructor. Make the callback on an instance of the given type.
*
* @param arg whether another argument is expected such as AfterDetach
*/
- public BeanLifecycleCallbacks(Class<?> cls, String method, boolean arg,
- Class<?> type) {
- this(cls, getMethod(cls, method, arg ? new Class[]{ Object.class,
- type } : new Class[]{ type }), arg);
+ public BeanLifecycleCallbacks(Class<T> cls, String method, boolean arg,
Class<?> type, CDIInjectionService injectionService) {
Review Comment:
Making the class generic and replacing the public constructors breaks binary
compatibility for code that creates these callbacks. Could the old constructors
stay and use a default (non-CDI) injection service?
##########
openjpa-kernel/src/main/java/org/apache/openjpa/event/LifecycleEventManager.java:
##########
@@ -27,6 +27,7 @@
import java.util.List;
import java.util.Map;
+import org.apache.openjpa.cdi.CDIInjectionService;
Review Comment:
Unused import (the only change to this file apart from a blank line).
##########
openjpa-kernel/src/main/java/org/apache/openjpa/event/BeanLifecycleCallbacks.java:
##########
@@ -23,73 +23,69 @@
import java.io.ObjectOutput;
import java.lang.reflect.Method;
-import org.apache.openjpa.lib.util.J2DoPrivHelper;
-import org.apache.openjpa.lib.util.Localizer;
-import org.apache.openjpa.util.UserException;
+import org.apache.openjpa.cdi.InjectionManager;
+import org.apache.openjpa.cdi.CDIInjectionService;
/**
* Performs a callback method on a cached bean instance.
*
* @author Steve Kim
*/
-public class BeanLifecycleCallbacks
+public class BeanLifecycleCallbacks<T>
extends MethodLifecycleCallbacks {
- private static final Localizer _loc = Localizer.forPackage
- (BeanLifecycleCallbacks.class);
-
- private transient Object _listener;
-
+ private final Class<T> listenerClass;
+
+ private InjectionManager<T> injectorManager;
+
/**
* Constructor. Make the callback on an instance of the given type.
*
* @param arg whether another argument is expected such as AfterDetach
*/
- public BeanLifecycleCallbacks(Class<?> cls, String method, boolean arg,
- Class<?> type) {
- this(cls, getMethod(cls, method, arg ? new Class[]{ Object.class,
- type } : new Class[]{ type }), arg);
+ public BeanLifecycleCallbacks(Class<T> cls, String method, boolean arg,
Class<?> type, CDIInjectionService injectionService) {
+ this(cls, getMethod(cls, method, arg ? new Class[]{ Object.class, type
} : new Class[]{ type }), arg, injectionService);
}
/**
* Constructor. Make the callback on an instance of the given type.
*/
- public BeanLifecycleCallbacks(Class<?> cls, Method method, boolean arg) {
+ public BeanLifecycleCallbacks(Class<T> cls, Method method, boolean arg,
CDIInjectionService injectionService) {
super(method, arg);
- _listener = newListener(cls);
+ injectorManager = injectionService.getInjectionManager(cls);
+ listenerClass = cls;
}
- private Object newListener(Class<?> cls) {
- try {
- return J2DoPrivHelper.newInstance(cls);
- } catch (Throwable t) {
- throw new UserException(_loc.get("bean-constructor",
cls.getName()), t);
- }
+ private T getListener() {
+ return injectorManager.getInstance();
}
@Override
public void makeCallback(Object obj, Object rel, int eventType) throws
Exception {
Method callback = getCallbackMethod();
- if (!callback.canAccess(_listener))
+ Object listener = getListener();
+ if (!callback.canAccess(listener))
callback.setAccessible(true);
if (requiresArgument())
- callback.invoke(_listener, new Object[]{ obj, rel });
+ callback.invoke(listener, new Object[]{ obj, rel });
else
- callback.invoke(_listener, new Object[]{ obj });
+ callback.invoke(listener, new Object[]{ obj });
+ if (!injectorManager.isCacheable()) {
+ injectorManager.dispose();
Review Comment:
With the non-cacheable path this disposes all instances of the listener
class after each callback, including ones other threads are using; see the
comments in `CDIInjectionManager`. Disposing the single instance used for this
callback (in a `finally`, so it also happens when the callback throws) would
fix both.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
+ target.inject(instance, creationalContext);
+ target.postConstruct(instance);
+ if (cacheable == null) {
+ checkInjections(target);
+ cachedInstance = cacheable ? instance : null;
+ }
+ return instance;
+ } else {
+ return cachedInstance;
+ }
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return cacheable;
+ }
+
+ @Override
+ public void dispose() {
Review Comment:
Called from `BeanLifecycleCallbacks.makeCallback()` after each callback of a
non-cacheable listener, this runs `preDestroy`/`dispose` on all instances in
`targets`: the ones of earlier callbacks again, and the ones other threads are
still using. It also only releases the last creational context. See the comment
on `targets.put` above.
##########
openjpa-project/src/docs/asciidoc/migration_considerations.adoc:
##########
@@ -23,6 +23,16 @@
[[migration_considerations]]
= Migration Considerations
+[[jpa_4.2]]
Review Comment:
Copy-paste: this is a second `[[jpa_4.2]]` id (the 4.2.0 section below has
the same one), and `jpa_4.3_entity_listeners` is a level-4 heading directly
under a level-2 one. Small wording fixes in the paragraph: "does not clarify",
and "entity listeners whose injection points are all normal scoped".
##########
openjpa-kernel/src/main/java/org/apache/openjpa/cdi/CDIInjectionManager.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.openjpa.lib.util.J2DoPrivHelper;
+import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.util.UserException;
+
+import java.util.Set;
+
+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.BeanContainer;
+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 CDIInjectionManager<T> implements InjectionManager<T>{
+
+ private static final Localizer _loc =
Localizer.forPackage(CDIUnawareInjectionManager.class);
+
+ private static final int NORMAL_BEAN_CHECK_DEPTH = 2;
+
+ private BeanManager beanManager;
+
+ private CreationalContext<T> creationalContext;
+
+ final Map<T, InjectionTarget<T>> targets =
Collections.synchronizedMap(new HashMap<>());
+
+ private transient T cachedInstance;
+
+ private Boolean cacheable;
+
+ private Boolean hasInjections = true;
+
+ private Class<T> listenerClass;
+
+ public CDIInjectionManager(BeanManager beanManager, Class<T> clazz) {
+ this.beanManager = beanManager;
+ listenerClass = clazz;
+ }
+
+ @Override
+ public T getInstance() {
+ if (cachedInstance == null) {
+ // based on DeltaSpike BeanProvider#injectFields
+ // added map to allow disposing afterwards as expected
by JPA API
+ final AnnotatedType<T> type =
beanManager.createAnnotatedType(listenerClass);
+ final InjectionTarget<T> target =
beanManager.getInjectionTargetFactory(type).createInjectionTarget(null);
+ creationalContext =
beanManager.createCreationalContext(null);
+ final T instance = target.produce(creationalContext);
+ targets.put(instance, target);
+ target.inject(instance, creationalContext);
+ target.postConstruct(instance);
+ if (cacheable == null) {
+ checkInjections(target);
+ cachedInstance = cacheable ? instance : null;
+ }
+ return instance;
+ } else {
+ return cachedInstance;
+ }
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return cacheable;
+ }
+
+ @Override
+ public void dispose() {
+ try {
+ for (Entry<T, InjectionTarget<T>> entry:
targets.entrySet()) {
+ T instance = entry.getKey();
+ InjectionTarget<T> target = entry.getValue();
+ target.preDestroy(instance);
+ target.dispose(instance);
+ }
+ } finally {
+ if (creationalContext != null) {
+ creationalContext.release();
+ }
+ }
+ }
+
+ private void checkInjections(InjectionTarget<T> target) {
+ Set<InjectionPoint> ips = target.getInjectionPoints();
+ hasInjections = !ips.isEmpty();
+ if (hasInjections) {
+ cacheable = ips.stream().allMatch(ip -> isCacheable(ip,
NORMAL_BEAN_CHECK_DEPTH));
+ } else {
+ cacheable = true;
+ try {
+ cachedInstance = J2DoPrivHelper.newInstance(listenerClass);
+ } catch (Throwable t) {
+ throw new UserException(_loc.get("bean-constructor",
listenerClass.getName()), t);
+ }
+ }
+ }
+
+ private boolean isCacheable(InjectionPoint ip, int depth) {
+ BeanContainer container = CDI.current().getBeanContainer();
+ Annotation[] qualifiers = ip.getQualifiers().toArray(new
Annotation[0]);
+ Bean<?> bean =
container.resolve(container.getBeans(ip.getType(), qualifiers));
Review Comment:
`resolve()` returns null for an unsatisfied injection point, then
`bean.getScope()` throws an NPE. Also, does
`bean.getTypes().contains(Instance.class)` match for the built-in `Instance`
bean? Its types are usually the parameterized `Instance<X>`, not the raw class.
Checking `ip.getType()` for `Instance`/`Provider` before resolving would be
simpler.
##########
openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/callbacks/TestCDIEntityListeners.java:
##########
@@ -0,0 +1,82 @@
+/*
+ * 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.persistence.callbacks;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.util.UUID;
+
+import org.apache.openjpa.persistence.test.SingleEMFTestCase;
+import org.apache.openwebbeans.junit5.Cdi;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import jakarta.inject.Inject;
+import jakarta.persistence.EntityManager;
+
+@Cdi(disableDiscovery = true, classes = CDIBean.class)
+public class TestCDIEntityListeners extends SingleEMFTestCase {
+
+ @Inject
+ private CDIBean bean;
+
+ @BeforeEach
+ public void setUp() {
+ setUp(CLEAR_TABLES);
+ CDIBean.reset();
+ }
+
+ @AfterEach
+ public void after() {
+ CDIBean.reset();
+ }
+
+ @Override
+ protected String getPersistenceUnitName() {
+ return "cdi-listener-pu";
+ }
+
+ @Test
+ void entityListeners() {
+ assertNotNull(bean);
+ try (EntityManager em = emf.createEntityManager()){
+ em.getTransaction().begin();
+ CDIListenedEntity e0 = new CDIListenedEntity();
+ CDIListenedEntity e1 = new CDIListenedEntity();
+
+ em.persist(e0);
+ assertEquals(1, CDIBean.getCount());
+
+ em.persist(e1);
+ assertEquals(2, CDIBean.getCount());
+ em.getTransaction().commit();
+ assertNotNull(e0.getValue());
+ assertNotEquals(e0.getValue(), e1.getValue());
Review Comment:
The producer returns `nextInt(1000)`, so this fails about once in 1000 runs
(same for the `Instance` value below). A counter in the producer would make it
deterministic. Cases that are missing: a second EntityManager after the first
one is closed, `@PreDestroy` on EMF close, a `@RequestScoped` bean, and a
`@Dependent` bean injected into a normal-scoped one.
##########
pom.xml:
##########
@@ -298,6 +299,11 @@
<artifactId>derbytools</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.openwebbeans</groupId>
+ <artifactId>openwebbeans-junit5</artifactId>
Review Comment:
This adds `openwebbeans-junit5` to the test class path of every module in
the Derby profile. `openjpa-persistence-jdbc/pom.xml` already declares it, so
this entry is not needed.
##########
openjpa-kernel/src/main/java/org/apache/openjpa/event/BeanLifecycleCallbacks.java:
##########
@@ -23,73 +23,69 @@
import java.io.ObjectOutput;
import java.lang.reflect.Method;
-import org.apache.openjpa.lib.util.J2DoPrivHelper;
-import org.apache.openjpa.lib.util.Localizer;
-import org.apache.openjpa.util.UserException;
+import org.apache.openjpa.cdi.InjectionManager;
+import org.apache.openjpa.cdi.CDIInjectionService;
/**
* Performs a callback method on a cached bean instance.
*
* @author Steve Kim
*/
-public class BeanLifecycleCallbacks
+public class BeanLifecycleCallbacks<T>
extends MethodLifecycleCallbacks {
- private static final Localizer _loc = Localizer.forPackage
- (BeanLifecycleCallbacks.class);
-
- private transient Object _listener;
-
+ private final Class<T> listenerClass;
+
+ private InjectionManager<T> injectorManager;
+
/**
* Constructor. Make the callback on an instance of the given type.
*
* @param arg whether another argument is expected such as AfterDetach
*/
- public BeanLifecycleCallbacks(Class<?> cls, String method, boolean arg,
- Class<?> type) {
- this(cls, getMethod(cls, method, arg ? new Class[]{ Object.class,
- type } : new Class[]{ type }), arg);
+ public BeanLifecycleCallbacks(Class<T> cls, String method, boolean arg,
Class<?> type, CDIInjectionService injectionService) {
+ this(cls, getMethod(cls, method, arg ? new Class[]{ Object.class, type
} : new Class[]{ type }), arg, injectionService);
}
/**
* Constructor. Make the callback on an instance of the given type.
*/
- public BeanLifecycleCallbacks(Class<?> cls, Method method, boolean arg) {
+ public BeanLifecycleCallbacks(Class<T> cls, Method method, boolean arg,
CDIInjectionService injectionService) {
super(method, arg);
- _listener = newListener(cls);
+ injectorManager = injectionService.getInjectionManager(cls);
+ listenerClass = cls;
}
- private Object newListener(Class<?> cls) {
- try {
- return J2DoPrivHelper.newInstance(cls);
- } catch (Throwable t) {
- throw new UserException(_loc.get("bean-constructor",
cls.getName()), t);
- }
+ private T getListener() {
+ return injectorManager.getInstance();
}
@Override
public void makeCallback(Object obj, Object rel, int eventType) throws
Exception {
Method callback = getCallbackMethod();
- if (!callback.canAccess(_listener))
+ Object listener = getListener();
+ if (!callback.canAccess(listener))
callback.setAccessible(true);
if (requiresArgument())
- callback.invoke(_listener, new Object[]{ obj, rel });
+ callback.invoke(listener, new Object[]{ obj, rel });
else
- callback.invoke(_listener, new Object[]{ obj });
+ callback.invoke(listener, new Object[]{ obj });
+ if (!injectorManager.isCacheable()) {
+ injectorManager.dispose();
+ }
}
@Override
public void readExternal(ObjectInput in)
Review Comment:
`writeExternal` still writes the listener class, but `readExternal` no
longer reads it, so the stream is out of sync for anything read after it.
`injectorManager` also stays null after deserialization (and `listenerClass` is
final, so it cannot be restored here), so the first callback throws an NPE.
##########
openjpa-project/RELEASE-NOTES.html:
##########
@@ -183,6 +183,16 @@ <h2><a name="Notice"></a>Notice</h2>
<hr>
<h2><a name="ReleaseNotes">Release Notes</a></h2>
+<hr>
+<h3><a name="420">OpenJPA 4.3.0</a></h3>
Review Comment:
The anchor is still `420`. As far as I know this file is generated at
release time from JIRA, so I would leave it out of the PR.
--
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]