You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@isis.apache.org by ah...@apache.org on 2019/07/23 09:16:27 UTC
[isis] branch v2 updated: ISIS-2125 fixes JDO smoketests and
demo-app launch
This is an automated email from the ASF dual-hosted git repository.
ahuber pushed a commit to branch v2
in repository https://gitbox.apache.org/repos/asf/isis.git
The following commit(s) were added to refs/heads/v2 by this push:
new 2cb509f ISIS-2125 fixes JDO smoketests and demo-app launch
2cb509f is described below
commit 2cb509fd1eb0730edfaaa5230041ba687e67e9f0
Author: Andi Huber <ah...@apache.org>
AuthorDate: Tue Jul 23 11:16:11 2019 +0200
ISIS-2125 fixes JDO smoketests and demo-app launch
---
.../IsisPlatformTransactionManagerForJdo.java | 22 +-
.../isis/jdo/persistence/IsisTransactionJdo.java | 6 +-
.../jdo/persistence/IsisTransactionManagerJdo.java | 334 ++++
.../IsisTransactionManagerJdoInternal.java | 476 ------
.../jdo/persistence/PersistenceSessionBase.java | 4 +-
.../isis/jdo/persistence/PersistenceSession5.java | 1705 ++++++++++----------
.../transaction/IsisTransactionAspectSupport.java | 9 +
.../system/transaction/IsisTransactionObject.java | 45 +-
.../bootstrapping/JdoBootstrappingTest.java | 8 +-
9 files changed, 1221 insertions(+), 1388 deletions(-)
diff --git a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisPlatformTransactionManagerForJdo.java b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisPlatformTransactionManagerForJdo.java
index 7bb7965..85f0566 100644
--- a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisPlatformTransactionManagerForJdo.java
+++ b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisPlatformTransactionManagerForJdo.java
@@ -21,11 +21,6 @@ package org.apache.isis.jdo.persistence;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.springframework.transaction.TransactionDefinition;
-import org.springframework.transaction.TransactionException;
-import org.springframework.transaction.support.AbstractPlatformTransactionManager;
-import org.springframework.transaction.support.DefaultTransactionStatus;
-
import org.apache.isis.applib.services.registry.ServiceRegistry;
import org.apache.isis.runtime.system.context.IsisContext;
import org.apache.isis.runtime.system.internal.InitialisationSession;
@@ -34,6 +29,10 @@ import org.apache.isis.runtime.system.session.IsisSessionFactory;
import org.apache.isis.runtime.system.transaction.IsisTransactionAspectSupport;
import org.apache.isis.runtime.system.transaction.IsisTransactionObject;
import org.apache.isis.security.authentication.AuthenticationSession;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionException;
+import org.springframework.transaction.support.AbstractPlatformTransactionManager;
+import org.springframework.transaction.support.DefaultTransactionStatus;
import lombok.val;
import lombok.extern.log4j.Log4j2;
@@ -80,7 +79,7 @@ public class IsisPlatformTransactionManagerForJdo extends AbstractPlatformTransa
log.debug("doBegin {}", definition);
- val tx = transactionManagerJdo().startTransaction();
+ val tx = transactionManagerJdo().beginTransaction();
txObject.setCurrentTransaction(tx);
IsisTransactionAspectSupport.putTransactionObject(txObject);
}
@@ -91,7 +90,7 @@ public class IsisPlatformTransactionManagerForJdo extends AbstractPlatformTransa
log.debug("doCommit {}", status);
- transactionManagerJdo().endTransaction();
+ transactionManagerJdo().commitTransaction(txObject);
txObject.setCurrentTransaction(null);
IsisTransactionAspectSupport.clearTransactionObject();
}
@@ -102,14 +101,19 @@ public class IsisPlatformTransactionManagerForJdo extends AbstractPlatformTransa
log.debug("doRollback {}", status);
- transactionManagerJdo().abortTransaction();
+ transactionManagerJdo().abortTransaction(txObject);
txObject.setCurrentTransaction(null);
IsisTransactionAspectSupport.clearTransactionObject();
}
- private IsisTransactionManagerJdoInternal transactionManagerJdo() {
+ private IsisTransactionManagerJdo transactionManagerJdo() {
val persistenceSessionBase = (PersistenceSessionBase)IsisContext.getPersistenceSession().get();
return persistenceSessionBase.transactionManager;
}
+// private PersistenceManager persistenceManagerJdo() {
+// val persistenceSessionBase = (PersistenceSessionBase)IsisContext.getPersistenceSession().get();
+// return persistenceSessionBase.persistenceManager;
+// }
+
}
diff --git a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionJdo.java b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionJdo.java
index 7d7fbee..6a82483 100644
--- a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionJdo.java
+++ b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionJdo.java
@@ -48,15 +48,15 @@ import lombok.val;
import lombok.extern.log4j.Log4j2;
/**
- * Used by the {@link IsisTransactionManagerJdoInternal} to captures a set of changes to be
+ * Used by the {@link IsisTransactionManagerJdo} to captures a set of changes to be
* applied.
*
* <p>
* Note that methods such as <tt>flush()</tt>, <tt>commit()</tt> and
* <tt>abort()</tt> are not part of the API. The place to control transactions
- * is through the {@link IsisTransactionManagerJdoInternal transaction manager}, because
+ * is through the {@link IsisTransactionManagerJdo transaction manager}, because
* some implementations may support nesting and such like. It is also the job of
- * the {@link IsisTransactionManagerJdoInternal} to ensure that the underlying persistence
+ * the {@link IsisTransactionManagerJdo} to ensure that the underlying persistence
* mechanism (for example, the <tt>ObjectStore</tt>) is also committed.
*/
@Vetoed @Log4j2
diff --git a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionManagerJdo.java b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionManagerJdo.java
new file mode 100644
index 0000000..7f728e1
--- /dev/null
+++ b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionManagerJdo.java
@@ -0,0 +1,334 @@
+/*
+ * 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.isis.jdo.persistence;
+
+import javax.enterprise.inject.Vetoed;
+
+import org.apache.isis.applib.services.command.Command;
+import org.apache.isis.applib.services.command.CommandContext;
+import org.apache.isis.applib.services.iactn.Interaction;
+import org.apache.isis.applib.services.iactn.InteractionContext;
+import org.apache.isis.applib.services.registry.ServiceRegistry;
+import org.apache.isis.commons.exceptions.IsisException;
+import org.apache.isis.commons.internal.components.SessionScopedComponent;
+import org.apache.isis.runtime.persistence.objectstore.transaction.PersistenceCommand;
+import org.apache.isis.runtime.system.context.IsisContext;
+import org.apache.isis.runtime.system.persistence.PersistenceSession;
+import org.apache.isis.runtime.system.transaction.IsisTransactionAspectSupport;
+import org.apache.isis.runtime.system.transaction.IsisTransactionManagerException;
+import org.apache.isis.runtime.system.transaction.IsisTransactionObject;
+
+import lombok.Getter;
+import lombok.val;
+import lombok.extern.log4j.Log4j2;
+
+@Vetoed @Log4j2
+class IsisTransactionManagerJdo implements SessionScopedComponent {
+
+ // -- constructor, fields
+
+ @Getter
+ private final PersistenceSession persistenceSession;
+ private final ServiceRegistry serviceRegistry;
+
+ private final CommandContext commandContext;
+ private final InteractionContext interactionContext;
+
+ IsisTransactionManagerJdo(PersistenceSession persistenceSession) {
+
+ this.persistenceSession = persistenceSession;
+ this.serviceRegistry = IsisContext.getServiceRegistry();
+
+ this.commandContext = serviceRegistry.lookupServiceElseFail(CommandContext.class);
+ this.interactionContext = serviceRegistry.lookupServiceElseFail(InteractionContext.class);
+ }
+
+ public IsisTransactionJdo beginTransaction() {
+ return beginTransaction(/*command*/null);
+ }
+
+ /**
+ * @param existingCommandIfAny - specifically, a previously persisted background
+ * {@link Command}, now being executed by a background execution service.
+ */
+ private IsisTransactionJdo beginTransaction(Command existingCommandIfAny) {
+ val txInProgress = isTransactionInProgress();
+ if (txInProgress) {
+
+ val txObject = IsisTransactionAspectSupport.currentTransactionObject().get();
+ txObject.incTransactionNestingLevel();
+ val nestingLevel = txObject.getTransactionNestingLevel();
+
+ if (log.isDebugEnabled()) {
+ log.debug("startTransaction: nesting-level {}->{}",
+ nestingLevel - 1,
+ nestingLevel);
+ }
+
+ return (IsisTransactionJdo) txObject.getCurrentTransaction();
+
+ } else {
+
+ // previously we called __isis_startRequest here on all RequestScopedServices. This is now
+ // done earlier, in PersistenceSession#open(). If we introduce support for @TransactionScoped
+ // services, then this would be the place to initialize them.
+
+ // allow the command to be overridden (if running as a background command with a parent command supplied)
+
+ val interaction = interactionContext.getInteraction();
+
+ if (existingCommandIfAny != null) {
+ commandContext.setCommand(existingCommandIfAny);
+ interaction.setUniqueId(existingCommandIfAny.getUniqueId());
+ }
+ val command = commandContext.getCommand();
+ val transactionId = command.getUniqueId();
+
+ val currentTransaction = new IsisTransactionJdo(transactionId,
+ interaction.next(Interaction.Sequence.TRANSACTION.id()));
+
+ persistenceSession.startTransaction();
+
+ if (log.isDebugEnabled()) {
+ log.debug("startTransaction: top-level");
+ }
+
+ return currentTransaction;
+
+ }
+
+ }
+
+
+ public void flushTransaction(IsisTransactionJdo transaction) {
+ if (transaction != null) {
+ log.debug("flushTransaction");
+ transaction.flush();
+ }
+ }
+
+ /**
+ * Ends the transaction if nesting level is 0 (but will abort the transaction instead,
+ * even if nesting level is not 0, if an {@link IsisTransactionJdo#getAbortCause() abort cause}
+ * has been {@link IsisTransactionJdo#setAbortCause(IsisException) set}.
+ *
+ * <p>
+ * If in the process of committing the transaction an exception is thrown, then this will
+ * be handled and will abort the transaction instead.
+ *
+ * <p>
+ * If an abort cause has been set (or an exception occurs), then will throw this
+ * exception in turn.
+ */
+ public void commitTransaction(IsisTransactionObject txObject) {
+
+ val transaction = (IsisTransactionJdo) txObject.getCurrentTransaction();
+
+ if (transaction == null) {
+ // allow this method to be called >1 with no adverse affects
+
+ if (log.isDebugEnabled()) {
+ log.debug("endTransaction: no transaction exists");
+ }
+
+ return;
+ }
+
+ if (transaction.getState().isComplete()) {
+ // allow this method to be called >1 with no adverse affects
+
+ if (log.isDebugEnabled()) {
+ log.debug("endTransaction: previous transaction completed");
+ }
+
+ return;
+ }
+
+ val transactionLevel = txObject.getTransactionNestingLevel();
+ val isTopLevel = txObject.isTopLevel();
+
+ if (log.isDebugEnabled()) {
+ log.debug("endTransaction: level {}->{}", transactionLevel, transactionLevel - 1);
+ }
+
+ try {
+ endTransactionInternal(txObject);
+ } finally {
+ val tx = (IsisTransactionJdo) txObject.getCurrentTransaction();
+ val state = tx.getState();
+ if(isTopLevel && !state.isComplete()) {
+ log.error("endTransaction: when top-level, "
+ + "transactionState is expected COMMITTED or ABORTED but was: '{}'", state);
+ }
+ }
+ }
+
+ private void endTransactionInternal(IsisTransactionObject txObject) {
+
+ val transaction = (IsisTransactionJdo) txObject.getCurrentTransaction();
+
+ // terminate the transaction early if an abort cause was already set.
+ RuntimeException abortCause = transaction.getAbortCause();
+ if(transaction.getState().mustAbort()) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("endTransaction: aborting instead [EARLY TERMINATION], abort cause '{}' has been set", abortCause.getMessage());
+ }
+ try {
+ abortTransaction(txObject);
+
+ // just in case any different exception was raised...
+ abortCause = this.getCurrentTransaction().getAbortCause();
+
+ } catch(RuntimeException ex) {
+
+ abortCause = ex;
+
+ }
+
+ if(abortCause != null) {
+
+ // re-introduced the throwing of exceptions in 1.15.1 (same as 1.14.x)
+
+ // in 1.15.0 we were not throwing exceptions at this point, resulting in JDOUserException errors
+ // (eg malformed SQL) simply being silently ignored
+
+ // the reason that no exceptions were being thrown in 1.15.0 was because it was observed that
+ // throwing exceptions always resulted in forwarding to the error page, even if the error had been
+ // recognised at the UI layer. This was the rationale given, at least.
+ //
+ // Not certain now it is correct; if it was to improve the UI experience.
+ //
+ // Certainly swallowing severe exceptions is much less acceptable. Therefore reverting.
+
+ throw abortCause;
+
+
+ } else {
+ // assume that any rendering of the problem has been done lower down the stack.
+ return;
+ }
+ }
+
+ if(!txObject.isTopLevel()) {
+ txObject.decTransactionNestingLevel();
+ return;
+ }
+
+ //
+ // TODO: granted, this is some fairly byzantine coding. but I'm trying to account for different types
+ // of object store implementations that could start throwing exceptions at any stage.
+ // once the contract/API for the objectstore is better tied down, hopefully can simplify this...
+ //
+
+ if(abortCause == null) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("endTransaction: committing");
+ }
+
+ try {
+ getCurrentTransaction().preCommit();
+ } catch(Exception ex) {
+ // just in case any new exception was raised...
+
+ // this bizarre code because an InvocationTargetException (which is not a RuntimeException) was
+ // being thrown due to a coding error in a domain object
+ abortCause = ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
+
+ getCurrentTransaction().setAbortCause(new IsisTransactionManagerException(ex));
+ }
+ }
+
+ if(abortCause == null) {
+ try {
+ persistenceSession.endTransaction();
+ } catch(Exception ex) {
+ // just in case any new exception was raised...
+ abortCause = ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
+
+ // hacky... moving the transaction back to something other than COMMITTED
+ getCurrentTransaction().setAbortCause(new IsisTransactionManagerException(ex));
+ }
+ }
+
+
+ // previously we called __isis_endRequest here on all RequestScopedServices. This is now
+ // done later, in PersistenceSession#close(). If we introduce support for @TransactionScoped
+ // services, then this would be the place to finalize them.
+
+ //
+ // finally, if an exception was thrown, we rollback the transaction
+ //
+
+ if(abortCause != null) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("endTransaction: aborting instead, abort cause has been set");
+ }
+ try {
+ abortTransaction(txObject);
+ } catch(RuntimeException ex) {
+ // ignore; nothing to do:
+ // * we want the existing abortCause to be available
+ // * the transactionLevel is correctly now at 0.
+ }
+
+ throw abortCause;
+ } else {
+
+ // keeping things in sync
+ getCurrentTransaction().commit();
+ }
+
+
+ }
+
+ public void abortTransaction(IsisTransactionObject txObject) {
+ val transaction = (IsisTransactionJdo) txObject.getCurrentTransaction();
+ if (transaction != null) {
+ transaction.markAsAborted();
+ persistenceSession.abortTransaction();
+ txObject.clear();
+ }
+ }
+
+ public void addCommand(PersistenceCommand command) {
+ val transaction = getCurrentTransaction();
+ if (transaction != null && command != null) {
+ transaction.addCommand(command);
+ }
+ }
+
+ // -- HELPER
+
+ private IsisTransactionJdo getCurrentTransaction() {
+ return IsisTransactionAspectSupport.currentTransactionObject()
+ .map(IsisTransactionObject::getCurrentTransaction)
+ .map(IsisTransactionJdo.class::cast)
+ .orElse(null);
+ }
+
+ private boolean isTransactionInProgress() {
+ return IsisTransactionAspectSupport.isTransactionInProgress();
+ }
+
+
+}
diff --git a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionManagerJdoInternal.java b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionManagerJdoInternal.java
deleted file mode 100644
index eb59653..0000000
--- a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/IsisTransactionManagerJdoInternal.java
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- * 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.isis.jdo.persistence;
-
-import java.util.UUID;
-import java.util.function.Supplier;
-
-import javax.enterprise.inject.Vetoed;
-
-import org.apache.isis.applib.services.command.Command;
-import org.apache.isis.applib.services.command.CommandContext;
-import org.apache.isis.applib.services.iactn.Interaction;
-import org.apache.isis.applib.services.iactn.InteractionContext;
-import org.apache.isis.applib.services.registry.ServiceRegistry;
-import org.apache.isis.commons.exceptions.IsisException;
-import org.apache.isis.commons.internal.components.SessionScopedComponent;
-import org.apache.isis.jdo.persistence.IsisTransactionJdo.State;
-import org.apache.isis.runtime.persistence.objectstore.transaction.PersistenceCommand;
-import org.apache.isis.runtime.system.context.IsisContext;
-import org.apache.isis.runtime.system.persistence.PersistenceSession;
-import org.apache.isis.runtime.system.session.IsisSession;
-import org.apache.isis.runtime.system.transaction.IsisTransactionManagerException;
-
-import lombok.extern.log4j.Log4j2;
-
-@Vetoed @Log4j2
-class IsisTransactionManagerJdoInternal implements SessionScopedComponent {
-
- private int transactionLevel;
-
- private IsisSession session;
-
- /**
- * Holds the current or most recently completed transaction.
- */
- private IsisTransactionJdo currentTransaction;
-
- // -- constructor, fields
-
- private final PersistenceSession persistenceSession;
- private final ServiceRegistry serviceRegistry;
-
- private final CommandContext commandContext;
- private final InteractionContext interactionContext;
-
- public IsisTransactionManagerJdoInternal(PersistenceSession persistenceSession) {
-
- this.persistenceSession = persistenceSession;
- this.serviceRegistry = IsisContext.getServiceRegistry();
-
- this.commandContext = this.serviceRegistry.lookupServiceElseFail(CommandContext.class);
- this.interactionContext = this.serviceRegistry.lookupServiceElseFail(InteractionContext.class);
- }
-
- public PersistenceSession getPersistenceSession() {
- return persistenceSession;
- }
-
- // -- open, close
-
- public void open() {
- assert session != null;
- }
-
- public void close() {
- if (getCurrentTransaction() != null) {
- try {
- abortTransaction();
- } catch (final Exception e2) {
- log.error("failure during abort", e2);
- }
- }
- session = null;
- }
-
-
- // -- current transaction (if any)
- /**
- * The current transaction, if any.
- */
- public IsisTransactionJdo getCurrentTransaction() {
- return currentTransaction;
- }
-
- public int getTransactionLevel() {
- return transactionLevel;
- }
-
-
-
-
- // -- Transactional Execution
- /**
- * Run the supplied {@link Runnable block of code (closure)} in a
- * {@link IsisTransactionJdo transaction}.
- *
- * <p>
- * If a transaction is in progress, then
- * uses that. Otherwise will {@link #startTransaction() start} a transaction
- * before running the block and {@link #endTransaction() commit} it at the
- * end.
- * </p>
- *
- * <p>
- * If the closure throws an exception, then will {@link #abortTransaction() abort} the transaction if was
- * started here, or will ensure that an already-in-progress transaction cannot commit.
- * </p>
- */
- public void executeWithinTransaction(final Runnable task) {
- executeWithinTransaction(null, task);
- }
-
- public void executeWithinTransaction(
- final Command existingCommandIfAny,
- final Runnable task) {
- final boolean initiallyInTransaction = inTransaction();
- if (!initiallyInTransaction) {
- startTransaction(existingCommandIfAny);
- }
- try {
- task.run();
- if (!initiallyInTransaction) {
- endTransaction();
- }
- } catch (final RuntimeException ex) {
- if (!initiallyInTransaction) {
- try {
- abortTransaction();
- } catch (final Exception e) {
- log.error("Abort failure after exception", e);
- throw new IsisTransactionManagerException("Abort failure: " + e.getMessage(), ex);
- }
- } else {
- // ensure that this xactn cannot be committed
- getCurrentTransaction().setAbortCause(new IsisException(ex));
- }
- throw ex;
- }
- }
-
- /**
- * Run the supplied {@link Runnable block of code (closure)} in a
- * {@link IsisTransactionJdo transaction}.
- *
- * <p>
- * If a transaction is in progress, then uses that. Otherwise will {@link #startTransaction() start} a transaction
- * before running the block and {@link #endTransaction() commit} it at the
- * end.
- * </p>
- *
- * <p>
- * If the closure throws an exception, then will {@link #abortTransaction() abort} the transaction if was
- * started here, or will ensure that an already-in-progress transaction cannot commit.
- * </p>
- */
- public <Q> Q executeWithinTransaction(final Supplier<Q> task) {
- return executeWithinTransaction(null, task);
- }
-
- public <Q> Q executeWithinTransaction(
- final Command existingCommandIfAny,
- final Supplier<Q> task) {
- final boolean initiallyInTransaction = inTransaction();
- if (!initiallyInTransaction) {
- startTransaction(existingCommandIfAny);
- }
- try {
- final Q retVal = task.get();
- if (!initiallyInTransaction) {
- endTransaction();
- }
- return retVal;
- } catch (final RuntimeException ex) {
- if (!initiallyInTransaction) {
- abortTransaction();
- } else {
- // ensure that this xactn cannot be committed (sets state to MUST_ABORT), and capture the cause so can be rendered appropriately by some higher level in the call stack
- getCurrentTransaction().setAbortCause(new IsisException(ex));
- }
- throw ex;
- }
- }
-
- public boolean inTransaction() {
- return getCurrentTransaction() != null && !getCurrentTransaction().getState().isComplete();
- }
-
-
-
- // -- startTransaction
-
- public IsisTransactionJdo startTransaction() {
- startTransaction(null);
- return getCurrentTransaction();
- }
-
- /**
- * @param existingCommandIfAny - specifically, a previously persisted background {@link Command}, now being executed by a background execution service.
- */
- public void startTransaction(final Command existingCommandIfAny) {
- boolean noneInProgress = false;
- if (getCurrentTransaction() == null || getCurrentTransaction().getState().isComplete()) {
- noneInProgress = true;
-
- // previously we called __isis_startRequest here on all RequestScopedServices. This is now
- // done earlier, in PersistenceSession#open(). If we introduce support for @TransactionScoped
- // services, then this would be the place to initialize them.
-
-
- // allow the command to be overridden (if running as a background command with a parent command supplied)
-
- final Interaction interaction = interactionContext.getInteraction();
-
- final Command command;
- if (existingCommandIfAny != null) {
- commandContext.setCommand(existingCommandIfAny);
- interaction.setUniqueId(existingCommandIfAny.getUniqueId());
- }
- command = commandContext.getCommand();
- final UUID transactionId = command.getUniqueId();
-
- this.currentTransaction = new IsisTransactionJdo(transactionId,
- interaction.next(Interaction.Sequence.TRANSACTION.id()));
- transactionLevel = 0;
-
- persistenceSession.startTransaction();
- }
-
- transactionLevel++;
-
- if (log.isDebugEnabled()) {
- log.debug("startTransaction: level {}->{}{}", (transactionLevel - 1), (transactionLevel), (noneInProgress ? " (no transaction in progress or was previously completed; transaction created)" : ""));
- }
- }
-
-
-
- // -- flushTransaction
- public boolean flushTransaction() {
-
- if (log.isDebugEnabled()) {
- log.debug("flushTransaction");
- }
-
- if (getCurrentTransaction() != null) {
- getCurrentTransaction().flush();
- }
- return false;
- }
-
-
-
- // -- endTransaction, abortTransaction
- /**
- * Ends the transaction if nesting level is 0 (but will abort the transaction instead,
- * even if nesting level is not 0, if an {@link IsisTransactionJdo#getAbortCause() abort cause}
- * has been {@link IsisTransactionJdo#setAbortCause(IsisException) set}.
- *
- * <p>
- * If in the process of committing the transaction an exception is thrown, then this will
- * be handled and will abort the transaction instead.
- *
- * <p>
- * If an abort cause has been set (or an exception occurs), then will throw this
- * exception in turn.
- */
- public void endTransaction() {
-
- final IsisTransactionJdo transaction = getCurrentTransaction();
- if (transaction == null) {
- // allow this method to be called >1 with no adverse affects
-
- if (log.isDebugEnabled()) {
- log.debug("endTransaction: level {} (no transaction exists)", transactionLevel);
- }
-
- return;
- } else if (transaction.getState().isComplete()) {
- // allow this method to be called >1 with no adverse affects
-
- if (log.isDebugEnabled()) {
- log.debug("endTransaction: level {} (previous transaction completed)", transactionLevel);
- }
-
- return;
- } else {
- if (log.isDebugEnabled()) {
- log.debug("endTransaction: level {}->{}", transactionLevel, transactionLevel - 1);
- }
- }
-
-
- try {
- endTransactionInternal();
- } finally {
- final IsisTransactionJdo.State state = getCurrentTransaction().getState();
- int transactionLevel = this.transactionLevel;
- if(transactionLevel == 0 && !state.isComplete()) {
- log.error("endTransaction: inconsistency detected between transactionLevel {} and transactionState '{}'", transactionLevel, state);
- }
- }
- }
-
- private void endTransactionInternal() {
-
- final IsisTransactionJdo transaction = getCurrentTransaction();
-
- // terminate the transaction early if an abort cause was already set.
- RuntimeException abortCause = this.getCurrentTransaction().getAbortCause();
- if(transaction.getState().mustAbort()) {
-
- if (log.isDebugEnabled()) {
- log.debug("endTransaction: aborting instead [EARLY TERMINATION], abort cause '{}' has been set", abortCause.getMessage());
- }
- try {
- abortTransaction();
-
- // just in case any different exception was raised...
- abortCause = this.getCurrentTransaction().getAbortCause();
-
- } catch(RuntimeException ex) {
-
- abortCause = ex;
-
- }
-
-
- if(abortCause != null) {
-
- // re-introduced the throwing of exceptions in 1.15.1 (same as 1.14.x)
-
- // in 1.15.0 we were not throwing exceptions at this point, resulting in JDOUserException errors
- // (eg malformed SQL) simply being silently ignored
-
- // the reason that no exceptions were being thrown in 1.15.0 was because it was observed that
- // throwing exceptions always resulted in forwarding to the error page, even if the error had been
- // recognised at the UI layer. This was the rationale given, at least.
- //
- // Not certain now it is correct; if it was to improve the UI experience.
- //
- // Certainly swallowing severe exceptions is much less acceptable. Therefore reverting.
-
- throw abortCause;
-
-
- } else {
- // assume that any rendering of the problem has been done lower down the stack.
- return;
- }
- }
-
- // we don't decrement the transactionLevel just yet, because an exception might end up being thrown
- // (meaning there would be more faffing around to ensure that the transactionLevel
- // and state of the currentTransaction remain in sync)
- int nextTransactionLevel = transactionLevel - 1;
- if ( nextTransactionLevel > 0) {
- transactionLevel --;
- } else if ( nextTransactionLevel == 0) {
-
- //
- // TODO: granted, this is some fairly byzantine coding. but I'm trying to account for different types
- // of object store implementations that could start throwing exceptions at any stage.
- // once the contract/API for the objectstore is better tied down, hopefully can simplify this...
- //
-
- if(abortCause == null) {
-
- if (log.isDebugEnabled()) {
- log.debug("endTransaction: committing");
- }
-
- try {
- getCurrentTransaction().preCommit();
- } catch(Exception ex) {
- // just in case any new exception was raised...
-
- // this bizarre code because an InvocationTargetException (which is not a RuntimeException) was
- // being thrown due to a coding error in a domain object
- abortCause = ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
-
- getCurrentTransaction().setAbortCause(new IsisTransactionManagerException(ex));
- }
- }
-
- if(abortCause == null) {
- try {
- persistenceSession.endTransaction();
- } catch(Exception ex) {
- // just in case any new exception was raised...
- abortCause = ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
-
- // hacky... moving the transaction back to something other than COMMITTED
- getCurrentTransaction().setAbortCause(new IsisTransactionManagerException(ex));
- }
- }
-
-
- //
- // ok, everything that could have thrown an exception is now done,
- // so it's safe to decrement the transaction level
- //
- transactionLevel = 0;
-
-
- // previously we called __isis_endRequest here on all RequestScopedServices. This is now
- // done later, in PersistenceSession#close(). If we introduce support for @TransactionScoped
- // services, then this would be the place to finalize them.
-
-
- //
- // finally, if an exception was thrown, we rollback the transaction
- //
- if(abortCause != null) {
-
- if (log.isDebugEnabled()) {
- log.debug("endTransaction: aborting instead, abort cause has been set");
- }
- try {
- abortTransaction();
- } catch(RuntimeException ex) {
- // ignore; nothing to do:
- // * we want the existing abortCause to be available
- // * the transactionLevel is correctly now at 0.
- }
-
- throw abortCause;
- } else {
-
- // keeping things in sync
- getCurrentTransaction().commit();
- }
-
- } else {
- // transactionLevel < 0
- log.error("endTransaction: transactionLevel={}", transactionLevel);
- transactionLevel = 0;
- IllegalStateException ex = new IllegalStateException(" no transaction running to end (transactionLevel < 0)");
- getCurrentTransaction().setAbortCause(new IsisException(ex));
- throw ex;
- }
- }
-
- public void abortTransaction() {
- if (getCurrentTransaction() != null) {
- getCurrentTransaction().markAsAborted();
- transactionLevel = 0;
- persistenceSession.abortTransaction();
- }
- }
-
-
-
- // -- addCommand
- public void addCommand(final PersistenceCommand command) {
- getCurrentTransaction().addCommand(command);
- }
-
-
-}
diff --git a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/PersistenceSessionBase.java b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/PersistenceSessionBase.java
index 519e434..0516076 100644
--- a/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/PersistenceSessionBase.java
+++ b/core/plugins/jdo-common/src/main/java/org/apache/isis/jdo/persistence/PersistenceSessionBase.java
@@ -84,7 +84,7 @@ abstract class PersistenceSessionBase implements PersistenceSession {
*/
protected final PersistenceManagerFactory jdoPersistenceManagerFactory;
- IsisTransactionManagerJdoInternal transactionManager;
+ IsisTransactionManagerJdo transactionManager;
/**
* populated only when {@link #open()}ed.
@@ -134,7 +134,7 @@ abstract class PersistenceSessionBase implements PersistenceSession {
this.persistenceQueryFactory = PersistenceQueryFactory.of(
obj->this.getObjectAdapterProvider().adapterFor(obj),
this.specificationLoader);
- this.transactionManager = new IsisTransactionManagerJdoInternal(this);
+ this.transactionManager = new IsisTransactionManagerJdo(this);
this.state = State.NOT_INITIALIZED;
}
diff --git a/core/plugins/jdo-datanucleus-5/src/main/java/org/apache/isis/jdo/persistence/PersistenceSession5.java b/core/plugins/jdo-datanucleus-5/src/main/java/org/apache/isis/jdo/persistence/PersistenceSession5.java
index a0f8dc1..ae299b0 100644
--- a/core/plugins/jdo-datanucleus-5/src/main/java/org/apache/isis/jdo/persistence/PersistenceSession5.java
+++ b/core/plugins/jdo-datanucleus-5/src/main/java/org/apache/isis/jdo/persistence/PersistenceSession5.java
@@ -39,10 +39,6 @@ import javax.jdo.PersistenceManagerFactory;
import javax.jdo.identity.SingleFieldIdentity;
import javax.jdo.listener.InstanceLifecycleListener;
-import org.datanucleus.enhancement.Persistable;
-import org.datanucleus.exceptions.NucleusObjectNotFoundException;
-import org.datanucleus.identity.DatastoreIdImpl;
-
import org.apache.isis.applib.query.Query;
import org.apache.isis.applib.services.command.Command;
import org.apache.isis.applib.services.exceprecog.ExceptionRecognizer;
@@ -100,6 +96,9 @@ import org.apache.isis.runtime.system.persistence.PersistenceQuery;
import org.apache.isis.runtime.system.persistence.PersistenceSession;
import org.apache.isis.runtime.system.persistence.adaptermanager.ObjectAdapterContext;
import org.apache.isis.security.authentication.AuthenticationSession;
+import org.datanucleus.enhancement.Persistable;
+import org.datanucleus.exceptions.NucleusObjectNotFoundException;
+import org.datanucleus.identity.DatastoreIdImpl;
import lombok.Getter;
import lombok.val;
@@ -114,890 +113,820 @@ import lombok.extern.log4j.Log4j2;
public class PersistenceSession5 extends PersistenceSessionBase
implements IsisLifecycleListener.PersistenceSessionLifecycleManagement {
- private ObjectAdapterContext objectAdapterContext;
- @Getter private final TransactionService transactionService;
-
- /**
- * Initialize the object store so that calls to this object store access
- * persisted objects and persist changes to the object that are saved.
- */
- public PersistenceSession5(
- final AuthenticationSession authenticationSession,
- final PersistenceManagerFactory jdoPersistenceManagerFactory,
- final FixturesInstalledStateHolder stateHolder) {
-
- super(authenticationSession, jdoPersistenceManagerFactory, stateHolder);
- transactionService = IsisContext.getTransactionService();
- }
-
- // -- open
-
- /**
- * Injects components, calls open on subcomponents, and then creates service
- * adapters.
- */
- @Override
- public void open() {
- ensureNotOpened();
-
- openedAtSystemNanos = System.nanoTime();
-
- if (log.isDebugEnabled()) {
- log.debug("opening {}", this);
- }
-
- persistenceManager = jdoPersistenceManagerFactory.getPersistenceManager();
-
- final IsisLifecycleListener.PersistenceSessionLifecycleManagement psLifecycleMgmt = this;
- final IsisLifecycleListener isisLifecycleListener = new IsisLifecycleListener(psLifecycleMgmt);
- persistenceManager.addInstanceLifecycleListener(isisLifecycleListener, (Class[]) null);
-
- persistenceQueryProcessorByClass.put(
- PersistenceQueryFindAllInstances.class,
- new PersistenceQueryFindAllInstancesProcessor(this));
- persistenceQueryProcessorByClass.put(
- PersistenceQueryFindUsingApplibQueryDefault.class,
- new PersistenceQueryFindUsingApplibQueryProcessor(this));
-
- objectAdapterContext = ObjectAdapterContext.openContext(authenticationSession, specificationLoader, this);
-
- // tell the proxy of all request-scoped services to instantiate the underlying
- // services, store onto the thread-local and inject into them...
- startRequestOnRequestScopedServices();
-
- // ... and invoke all @PostConstruct
- postConstructOnRequestScopedServices();
-
- if(metricsService instanceof InstanceLifecycleListener) {
- final InstanceLifecycleListener metricsService = (InstanceLifecycleListener) this.metricsService;
- persistenceManager.addInstanceLifecycleListener(metricsService, (Class[]) null);
- }
-
- final Command command = createCommand();
- final Interaction interaction = factoryService.instantiate(Interaction.class);
-
- final Timestamp timestamp = clockService.nowAsJavaSqlTimestamp();
- final String userName = userService.getUser().getName();
-
- command.internal().setTimestamp(timestamp);
- command.internal().setUser(userName);
-
- interaction.setUniqueId(command.getUniqueId());
-
- commandContext.setCommand(command);
- interactionContext.setInteraction(interaction);
-
- this.state = State.OPEN;
- }
-
- private void postConstructOnRequestScopedServices() {
- serviceRegistry.select(RequestScopedService.class)
- .forEach(RequestScopedService::__isis_postConstruct);
- }
-
- private void startRequestOnRequestScopedServices() {
- serviceRegistry.select(RequestScopedService.class)
- .forEach(service->service.__isis_startRequest(serviceInjector));
- }
-
- private Command createCommand() {
- final Command command = commandService.create();
-
- serviceInjector.injectServicesInto(command);
- return command;
- }
-
- // -- close
-
- /**
- * Closes the subcomponents.
- *
- * <p>
- * Automatically {@link IsisTransactionManagerJdoInternal#endTransaction() ends
- * (commits)} the current (Isis) {@link IsisTransactionJdo}. This in turn commits the underlying
- * JDO transaction.
- *
- * <p>
- * The corresponding DataNucleus entity is then closed.
- */
- @Override
- public void close() {
-
- if (state == State.CLOSED) {
- // nothing to do
- return;
- }
-
- completeCommandFromInteractionAndClearDomainEvents();
- transactionManager.flushTransaction();
-
- try {
- final IsisTransactionJdo currentTransaction = transactionManager.getCurrentTransaction();
- if (currentTransaction != null && !currentTransaction.getState().isComplete()) {
- if(currentTransaction.getState().canCommit()) {
- transactionManager.endTransaction();
- } else if(currentTransaction.getState().canAbort()) {
- transactionManager.abortTransaction();
- }
- }
- } catch(final Throwable ex) {
- // ignore
- log.error("close: failed to end transaction; continuing to avoid memory leakage");
- }
-
- // tell the proxy of all request-scoped services to invoke @PreDestroy
- // (if any) on all underlying services stored on their thread-locals...
- preDestroyOnRequestScopedServices();
-
- // ... and then remove those underlying services from the thread-local
- endRequestOnRequestScopeServices();
-
- try {
- persistenceManager.close();
- } catch(final Throwable ex) {
- // ignore
- log.error(
- "close: failed to close JDO persistenceManager; continuing to avoid memory leakage");
- }
-
- objectAdapterContext.close();
-
- this.state = State.CLOSED;
- }
-
- private void endRequestOnRequestScopeServices() {
- serviceRegistry.select(RequestScopedService.class)
- .forEach(RequestScopedService::__isis_endRequest);
- }
-
- private void preDestroyOnRequestScopedServices() {
- serviceRegistry.select(RequestScopedService.class)
- .forEach(RequestScopedService::__isis_preDestroy);
- }
-
- private void completeCommandFromInteractionAndClearDomainEvents() {
-
- final Command command = commandContext.getCommand();
- final Interaction interaction = interactionContext.getInteraction();
-
-
- if(command.getStartedAt() != null && command.getCompletedAt() == null) {
- // the guard is in case we're here as the result of a redirect following a previous exception;just ignore.
-
- final Timestamp completedAt;
- final Interaction.Execution<?, ?> priorExecution = interaction.getPriorExecution();
- if (priorExecution != null) {
- // copy over from the most recent (which will be the top-level) interaction
- completedAt = priorExecution.getCompletedAt();
- } else {
- // this could arise as the result of calling SessionManagementService#nextSession within an action
- // the best we can do is to use the current time
-
- // REVIEW: as for the interaction object, it is left somewhat high-n-dry.
- completedAt = clockService.nowAsJavaSqlTimestamp();
- }
-
- command.internal().setCompletedAt(completedAt);
- }
-
- // ensureCommandsPersistedIfDirtyXactn
-
- // ensure that any changed objects means that the command should be persisted
- if(command.getMemberIdentifier() != null) {
- if(metricsService.numberObjectsDirtied() > 0) {
- command.internal().setPersistHint(true);
- }
- }
-
- commandService.complete(command);
-
- interaction.clear();
- }
-
- // -- QuerySubmitter impl, findInstancesInTransaction
- @Override
- public <T> List<ObjectAdapter> allMatchingQuery(final Query<T> query) {
- final ObjectAdapter instances = findInstancesInTransaction(query, QueryCardinality.MULTIPLE);
- return CollectionFacet.Utils.toAdapterList(instances);
- }
- @Override
- public <T> ObjectAdapter firstMatchingQuery(final Query<T> query) {
- final ObjectAdapter instances = findInstancesInTransaction(query, QueryCardinality.SINGLE);
- final List<ObjectAdapter> list = CollectionFacet.Utils.toAdapterList(instances);
- return list.size() > 0 ? list.get(0) : null;
- }
-
- /**
- * Finds and returns instances that match the specified query.
- *
- * <p>
- * The {@link QueryCardinality} determines whether all instances or just the
- * first matching instance is returned.
- *
- * @throws org.apache.isis.runtime.persistence.UnsupportedFindException
- * if the criteria is not support by this persistor
- */
- private <T> ObjectAdapter findInstancesInTransaction(final Query<T> query, final QueryCardinality cardinality) {
- if (log.isDebugEnabled()) {
- log.debug("findInstances using (applib) Query: {}", query);
- }
-
- // TODO: unify PersistenceQuery and PersistenceQueryProcessor
- final PersistenceQuery persistenceQuery = createPersistenceQueryFor(query, cardinality);
- if (log.isDebugEnabled()) {
- log.debug("maps to (core runtime) PersistenceQuery: {}", persistenceQuery);
- }
-
- final PersistenceQueryProcessor<? extends PersistenceQuery> processor = lookupProcessorFor(persistenceQuery);
-
- final List<ObjectAdapter> instances = transactionManager.executeWithinTransaction(
- ()->processPersistenceQuery(processor, persistenceQuery) );
- final ObjectSpecification specification = persistenceQuery.getSpecification();
- final FreeStandingList results = FreeStandingList.of(specification, instances);
- return adapterFor(results);
- }
-
- /**
- * Converts the {@link Query applib representation of a query} into the
- * {@link PersistenceQuery NOF-internal representation}.
- */
- private final PersistenceQuery createPersistenceQueryFor(
- final Query<?> query,
- final QueryCardinality cardinality) {
-
- final PersistenceQuery persistenceQuery =
- persistenceQueryFactory.createPersistenceQueryFor(query, cardinality);
- if (persistenceQuery == null) {
- throw new IllegalArgumentException("Unknown Query type: " + query.getDescription());
- }
-
- return persistenceQuery;
- }
-
- private PersistenceQueryProcessor<? extends PersistenceQuery> lookupProcessorFor(final PersistenceQuery persistenceQuery) {
- final Class<? extends PersistenceQuery> persistenceQueryClass = persistenceQuery.getClass();
- final PersistenceQueryProcessor<? extends PersistenceQuery> processor =
- persistenceQueryProcessorByClass.get(persistenceQueryClass);
- if (processor == null) {
- throw new UnsupportedFindException(MessageFormat.format(
- "Unsupported PersistenceQuery class: {0}", persistenceQueryClass.getName()));
- }
- return processor;
- }
- @SuppressWarnings("unchecked")
- private <Q extends PersistenceQuery> List<ObjectAdapter> processPersistenceQuery(
- final PersistenceQueryProcessor<Q> persistenceQueryProcessor,
- final PersistenceQuery persistenceQuery) {
- return persistenceQueryProcessor.process((Q) persistenceQuery);
- }
-
-
- // -- fixture installation
-
- @Override
- public FixturesInstalledState getFixturesInstalledState() {
- if (fixturesInstalledStateHolder.getFixturesInstalledState() == null) {
- val initialStateFromConfig = initialStateFromConfig();
- fixturesInstalledStateHolder.setFixturesInstalledState(initialStateFromConfig);
- }
- return fixturesInstalledStateHolder.getFixturesInstalledState();
- }
-
- /**
- * Determine if the object store has been initialized with its set of start
- * up objects.
- *
- * <p>
- * This method is called only once after the session is opened called. If it returns <code>false</code> then the
- * framework will run the fixtures to initialise the object store.
- *
- * <p>
- * Implementation looks for the {@link #INSTALL_FIXTURES_KEY} in the injected {@link #configuration configuration}.
- *
- * <p>
- * By default this is not expected to be there, but utilities can add in on
- * the fly during bootstrapping if required.
- */
- private FixturesInstalledState initialStateFromConfig() {
- val installFixtures = configuration.getBoolean(INSTALL_FIXTURES_KEY, INSTALL_FIXTURES_DEFAULT);
- log.info("isFixturesInstalled: {} = {}", INSTALL_FIXTURES_KEY, installFixtures);
-
- val objectStoreIsFixturesInstalled = !installFixtures;
- val initialStateFromConfig = objectStoreIsFixturesInstalled
- ? FixturesInstalledState.Installed
- : FixturesInstalledState.not_Installed;
-
- return initialStateFromConfig;
- }
-
-//TODO[2112] remove when no longer needed
-// /**
-// * Determine if the object store has been initialized with its set of start
-// * up objects.
-// *
-// * <p>
-// * This method is called only once after the session is opened called. If it returns <code>false</code> then the
-// * framework will run the fixtures to initialise the object store.
-// *
-// * <p>
-// * Implementation looks for the {@link #INSTALL_FIXTURES_KEY} in the injected {@link #configuration configuration}.
-// *
-// * <p>
-// * By default this is not expected to be there, but utilities can add in on
-// * the fly during bootstrapping if required.
-// */
-// private boolean objectStoreIsFixturesInstalled() {
-// final boolean installFixtures = configuration.getBoolean(INSTALL_FIXTURES_KEY, INSTALL_FIXTURES_DEFAULT);
-// log.info("isFixturesInstalled: {} = {}", INSTALL_FIXTURES_KEY, installFixtures);
-// return !installFixtures;
-// }
-
- // -- FETCHING
-
- @Override
- public Object fetchPersistentPojo(final RootOid rootOid) {
- Objects.requireNonNull(rootOid);
- log.debug("getObject; oid={}", rootOid);
-
- Object result;
- try {
- final Class<?> cls = clsOf(rootOid);
- final Object jdoObjectId = JdoObjectIdSerializer.toJdoObjectId(rootOid);
- FetchPlan fetchPlan = persistenceManager.getFetchPlan();
- fetchPlan.addGroup(FetchGroup.DEFAULT);
- result = persistenceManager.getObjectById(cls, jdoObjectId);
- } catch (final RuntimeException e) {
-
- Class<ExceptionRecognizer> serviceClass = ExceptionRecognizer.class;
- final Iterable<ExceptionRecognizer> exceptionRecognizers = lookupServices(serviceClass);
- for (ExceptionRecognizer exceptionRecognizer : exceptionRecognizers) {
- final ExceptionRecognizer.Recognition recognition =
- exceptionRecognizer.recognize2(e);
- if(recognition != null) {
- if(recognition.getCategory() == ExceptionRecognizer.Category.NOT_FOUND) {
- throw new ObjectNotFoundException(rootOid, e);
- }
- }
- }
-
- throw e;
- }
-
- if (result == null) {
- throw new ObjectNotFoundException(rootOid);
- }
-
- return result;
- }
-
- @Override
- public Map<RootOid,Object> fetchPersistentPojos(final List<RootOid> rootOids) {
-
- if(rootOids.isEmpty()) {
- return Collections.emptyMap();
- }
-
- final List<Object> dnOids = new ArrayList<>(rootOids.size());
- for (final RootOid rootOid : rootOids) {
- final Object id = JdoObjectIdSerializer.toJdoObjectId(rootOid);
- if(id instanceof SingleFieldIdentity) {
- dnOids.add(id);
- } else if (id instanceof String && ((String) id).contains("[OID]")) {
- final DatastoreIdImpl datastoreId = new DatastoreIdImpl((String)id);
- dnOids.add(datastoreId);
- } else {
- // application identity
- final DatastoreIdImpl datastoreId = new DatastoreIdImpl(clsOf(rootOid).getName(), id);
- dnOids.add(datastoreId);
- }
- }
- FetchPlan fetchPlan = persistenceManager.getFetchPlan();
- fetchPlan.addGroup(FetchGroup.DEFAULT);
- final List<Object> persistentPojos = new ArrayList<>(rootOids.size());
- try {
- final Collection<Object> pojos = uncheckedCast(persistenceManager.getObjectsById(dnOids, true));
- for (final Object pojo : pojos) {
- try {
- persistentPojos.add(pojo);
- } catch(Exception ex) {
- persistentPojos.add(null);
- }
- }
- } catch(NucleusObjectNotFoundException nonfe) {
- // at least one not found; fall back to loading one by one
- for (final Object dnOid : dnOids) {
- try {
- final Object persistentPojo = persistenceManager.getObjectById(dnOid);
- persistentPojos.add(persistentPojo);
- } catch(Exception ex) {
- persistentPojos.add(null);
- }
- }
- }
- Map<RootOid, Object> pojoByOid = zip(rootOids, persistentPojos);
- return pojoByOid;
- }
-
- private static Map<RootOid, Object> zip(final List<RootOid> rootOids, final Collection<Object> pojos) {
- final Map<RootOid,Object> pojoByOid = _Maps.newLinkedHashMap();
- int i = 0;
- for (final Object pojo : pojos) {
- final RootOid rootOid = rootOids.get(i++);
- pojoByOid.put(rootOid, pojo);
- }
- return pojoByOid;
- }
-
- private Class<?> clsOf(final RootOid oid) {
- final ObjectSpecification objectSpec = getSpecificationLoader().lookupBySpecIdElseLoad(oid.getObjectSpecId());
- return objectSpec.getCorrespondingClass();
- }
-
-
- // -- REFRESH
-
- @Override
- public void refreshRoot(final Object domainObject) {
-
- val state = stateOf(domainObject);
- val isRepresentingPersistent = state.isAttached() || state.isDestroyed();
-
- if(!isRepresentingPersistent) {
- debugLogNotPersistentIgnoring(domainObject);
- return; // only resolve object that is representing persistent
- }
-
- debugLogRefreshImmediately(domainObject);
-
- try {
- persistenceManager.refresh(domainObject);
- } catch (final RuntimeException e) {
- final Oid oid = oidFor(domainObject);
- throw new PojoRefreshException(oid, e);
- }
-
- // possibly redundant because also called in the post-load event
- // listener, but (with JPA impl) found it was required if we were ever to
- // get an eager left-outer-join as the result of a refresh (sounds possible).
- initializeMapAndCheckConcurrency((Persistable) domainObject);
- }
-
- // -- makePersistent
-
- /**
- * Makes an {@link ObjectAdapter} persistent. The specified object should be
- * stored away via this object store's persistence mechanism, and have a
- * new and unique OID assigned to it. The object, should also be added to
- * the {@link PersistenceSession} as the object is implicitly 'in use'.
- *
- * <p>
- * If the object has any associations then each of these, where they aren't
- * already persistent, should also be made persistent by recursively calling
- * this method.
- *
- * <p>
- * If the object to be persisted is a collection, then each element of that
- * collection, that is not already persistent, should be made persistent by
- * recursively calling this method.
- */
- @Override
- public void makePersistentInTransaction(final ObjectAdapter adapter) {
- if (adapter.isRepresentingPersistent()) {
- throw new NotPersistableException("Object already persistent: " + adapter);
- }
- final ObjectSpecification specification = adapter.getSpecification();
- if (specification.isManagedBean()) {
- throw new NotPersistableException("Cannot persist beans: " + adapter);
- }
-
- transactionService.executeWithinTransaction(()->{
- makePersistentTransactionAssumed(adapter);
- });
- }
-
- private void makePersistentTransactionAssumed(final ObjectAdapter adapter) {
- if (alreadyPersistedOrNotPersistable(adapter)) {
- return;
- }
- log.debug("persist {}", adapter);
-
- // previously we called the PersistingCallback here.
- // this is now done in the JDO framework synchronizer.
- //
- // the guard below used to be because (apparently)
- // the callback might have caused the adapter to become persistent.
- // leaving it in as think it does no harm...
- if (alreadyPersistedOrNotPersistable(adapter)) {
- return;
- }
- addCreateObjectCommand(adapter);
- }
-
- /**
- * {@link #newCreateObjectCommand(ObjectAdapter) Create}s a {@link CreateObjectCommand}, and adds to the
- * {@link IsisTransactionManagerJdoInternal}.
- */
- private void addCreateObjectCommand(final ObjectAdapter object) {
- final CreateObjectCommand createObjectCommand = newCreateObjectCommand(object);
- transactionManager.addCommand(createObjectCommand);
- }
-
-
-
- private static boolean alreadyPersistedOrNotPersistable(final ObjectAdapter adapter) {
- return adapter.isRepresentingPersistent() || objectSpecNotPersistable(adapter);
- }
-
-
- private static boolean objectSpecNotPersistable(final ObjectAdapter adapter) {
- return adapter.isParentedCollection();
- }
-
- // -- destroyObjectInTransaction
-
- /**
- * Removes the specified object from the system. The specified object's data
- * should be removed from the persistence mechanism.
- */
- @Override
- public void destroyObjectInTransaction(final ObjectAdapter adapter) {
- final ObjectSpecification spec = adapter.getSpecification();
- if (spec.isParented()) {
- return;
- }
- log.debug("destroyObject {}", adapter);
- transactionManager.executeWithinTransaction(()->{
- final DestroyObjectCommand command = newDestroyObjectCommand(adapter);
- transactionManager.addCommand(command);
- });
- }
-
- // -- newXxxCommand
- /**
- * Makes an {@link ObjectAdapter} persistent. The specified object should be
- * stored away via this object store's persistence mechanism, and have an
- * new and unique OID assigned to it (by calling the object's
- * <code>setOid</code> method). The object, should also be added to the
- * cache as the object is implicitly 'in use'.
- *
- * <p>
- * If the object has any associations then each of these, where they aren't
- * already persistent, should also be made persistent by recursively calling
- * this method.
- * </p>
- *
- * <p>
- * If the object to be persisted is a collection, then each element of that
- * collection, that is not already persistent, should be made persistent by
- * recursively calling this method.
- * </p>
- *
- */
- private CreateObjectCommand newCreateObjectCommand(final ObjectAdapter adapter) {
- ensureOpened();
-
- log.debug("create object - creating command for: {}", adapter);
- if (adapter.isRepresentingPersistent()) {
- throw new IllegalArgumentException("Adapter is persistent; adapter: " + adapter);
- }
- return new DataNucleusCreateObjectCommand(adapter, persistenceManager);
- }
-
- private DestroyObjectCommand newDestroyObjectCommand(final ObjectAdapter adapter) {
- ensureOpened();
-
- log.debug("destroy object - creating command for: {}", adapter);
- if (!adapter.isRepresentingPersistent()) {
- throw new IllegalArgumentException("Adapter is not persistent; adapter: " + adapter);
- }
- return new DataNucleusDeleteObjectCommand(adapter, persistenceManager);
- }
-
-
- // -- execute
- @Override
- public void execute(final List<PersistenceCommand> commands) {
-
- // previously we used to check that there were some commands, and skip processing otherwise.
- // we no longer do that; it could be (is quite likely) that DataNucleus has some dirty objects anyway that
- // don't have commands wrapped around them...
-
- executeCommands(commands);
- }
-
- private void executeCommands(final List<PersistenceCommand> commands) {
-
- for (final PersistenceCommand command : commands) {
- command.execute(null);
- }
- persistenceManager.flush();
- }
-
- // -- FrameworkSynchronizer delegate methods
-
- @Override
- public void enlistDeletingAndInvokeIsisRemovingCallbackFacet(final Persistable pojo) {
- ObjectAdapter adapter = adapterFor(pojo);
-
- changedObjectsServiceInternal.enlistDeleting(adapter);
-
- CallbackFacet.Util.callCallback(adapter, RemovingCallbackFacet.class);
- objectAdapterContext.postLifecycleEventIfRequired(adapter, RemovingLifecycleEventFacet.class);
- }
-
- @Override
- public ObjectAdapter initializeMapAndCheckConcurrency(final Persistable pojo) {
- final Persistable pc = pojo;
-
- // need to do eagerly, because (if a viewModel then) a
- // viewModel's #viewModelMemento might need to use services
- serviceInjector.injectServicesInto(pojo);
-
- final Version datastoreVersion = getVersionIfAny(pc);
- final RootOid originalOid = objectAdapterContext.createPersistentOrViewModelOid(pojo);
-
- final ObjectAdapter adapter = objectAdapterContext.recreatePojo(originalOid, pojo);
- adapter.setVersion(datastoreVersion);
-
- CallbackFacet.Util.callCallback(adapter, LoadedCallbackFacet.class);
- objectAdapterContext.postLifecycleEventIfRequired(adapter, LoadedLifecycleEventFacet.class);
-
- return adapter;
- }
-
- @Override
- public String identifierFor(final Object pojo) {
- final Object jdoOid = pm().getObjectId(pojo);
- requireNonNull(jdoOid,
- ()->String.format("Pojo of type '%s' is not recognized by JDO.",
- pojo.getClass().getName()));
- return JdoObjectIdSerializer.toOidIdentifier(jdoOid);
- }
-
-
- /**
- * Called either when an entity is initially persisted, or when an entity is updated; fires the appropriate
- * lifecycle callback.
- *
- * <p>
- * The implementation therefore uses Isis' {@link org.apache.isis.metamodel.adapter.oid.Oid#isTransient() oid}
- * to determine which callback to fire.
- */
- @Override
- public void invokeIsisPersistingCallback(final Persistable pojo) {
- if (stateOf(pojo).isDetached()) {
- final ManagedObject adapter = ManagedObject.of(
- ()->getSpecificationLoader().loadSpecification(pojo.getClass()),
- pojo);
-
- // persisting
- // previously this was performed in the DataNucleusSimplePersistAlgorithm.
- CallbackFacet.Util.callCallback(adapter, PersistingCallbackFacet.class);
- objectAdapterContext.postLifecycleEventIfRequired(adapter, PersistingLifecycleEventFacet.class);
-
- } else {
- // updating
-
- // don't call here, already called in preDirty.
-
- // CallbackFacet.Util.callCallback(adapter, UpdatingCallbackFacet.class);
- }
- }
-
- /**
- * Called either when an entity is initially persisted, or when an entity is updated;
- * fires the appropriate lifecycle callback
- *
- * <p>
- * The implementation therefore uses Isis' {@link org.apache.isis.metamodel.adapter.oid.Oid#isTransient() oid}
- * to determine which callback to fire.
- */
- @Override
- public void enlistCreatedAndRemapIfRequiredThenInvokeIsisInvokePersistingOrUpdatedCallback(final Persistable pojo) {
- final ObjectAdapter adapter = adapterFor(pojo);
-
- final RootOid rootOid = (RootOid) adapter.getOid(); // ok since this is for a Persistable
-
- if (rootOid.isTransient()) {
- // persisting
-
- objectAdapterContext.asPersistent(adapter, this);
-
- CallbackFacet.Util.callCallback(adapter, PersistedCallbackFacet.class);
- objectAdapterContext.postLifecycleEventIfRequired(adapter, PersistedLifecycleEventFacet.class);
-
- changedObjectsServiceInternal.enlistCreated(adapter);
-
- } else {
- // updating;
- // the callback and transaction.enlist are done in the preDirty callback
- // (can't be done here, as the enlist requires to capture the 'before' values)
- CallbackFacet.Util.callCallback(adapter, UpdatedCallbackFacet.class);
- objectAdapterContext.postLifecycleEventIfRequired(adapter, UpdatedLifecycleEventFacet.class);
- }
-
- Version versionIfAny = getVersionIfAny(pojo);
- adapter.setVersion(versionIfAny);
- }
-
- @Override
- public void enlistUpdatingAndInvokeIsisUpdatingCallback(final Persistable pojo) {
-
- // seen this happen in the case when a parent entity (LeaseItem) has a collection of children
- // objects (LeaseTerm) for which we haven't had a loaded callback fired and so are not yet
- // mapped.
-
- // it seems reasonable in this case to simply map into Isis here ("just-in-time"); presumably
- // DN would not be calling this callback if the pojo was not persistent.
-
- final ObjectAdapter adapter = objectAdapterContext.fetchPersistent(pojo);
- if (adapter == null) {
- throw new RuntimeException(
- "DN could not find objectId for pojo (unexpected) and so could not map into Isis; pojo=["
- + pojo + "]");
- }
-
- final boolean wasAlreadyEnlisted = changedObjectsServiceInternal.isEnlisted(adapter);
-
- // we call this come what may;
- // additional properties may now have been changed, and the changeKind for publishing might also be modified
- changedObjectsServiceInternal.enlistUpdating(adapter);
-
- if(!wasAlreadyEnlisted) {
- // prevent an infinite loop... don't call the 'updating()' callback on this object if we have already done so
- CallbackFacet.Util.callCallback(adapter, UpdatingCallbackFacet.class);
- objectAdapterContext.postLifecycleEventIfRequired(adapter, UpdatingLifecycleEventFacet.class);
- }
-
- }
-
- /**
- * makes sure the entity is known to Isis and is a root
- * @param pojo
- */
- @Override
- public void ensureRootObject(final Persistable pojo) {
- final Oid oid = adapterFor(pojo).getOid();
- if (!(oid instanceof RootOid)) {
- throw new IsisException(MessageFormat.format("Not a RootOid: oid={0}, for {1}", oid, pojo));
- }
- }
-
- private Version getVersionIfAny(final Persistable pojo) {
- return Utils.getVersionIfAny(pojo, authenticationSession);
- }
-
- // --
-//TODO [2112] replaced by stateOf(pojo)
-// @Override
-// public boolean isTransient(@Nullable Object pojo) {
-// if (pojo!=null && pojo instanceof Persistable) {
-// final Persistable p = (Persistable) pojo;
-// final boolean isPersistent = p.dnIsPersistent();
-// final boolean isDeleted = p.dnIsDeleted();
-// if (!isPersistent && !isDeleted) {
-// return true;
-// }
-// }
-// return false;
-// }
-//
-// /**
-// * May also deleted (that is, {@link #isDestroyed(Object)} could return true).
-// * @param pojo
-// * @return
-// */
-// @Override
-// public boolean isRepresentingPersistent(@Nullable Object pojo) {
-// if (pojo instanceof Persistable) {
-// final Persistable p = (Persistable) pojo;
-// return p.dnIsPersistent();
-// }
-// return false;
-// }
-//
-// @Override
-// public boolean isDestroyed(@Nullable Object pojo) {
-// if (pojo instanceof Persistable) {
-// final Persistable p = (Persistable) pojo;
-// return p.dnIsDeleted();
-// }
-// return false;
-// }
-
- @Override
- public ManagedObjectState stateOf(@Nullable Object pojo) {
-
- // guard against misuse
- if(pojo instanceof ObjectAdapter) {
- throw _Exceptions.unexpectedCodeReach();
- }
-
- if (pojo!=null && pojo instanceof Persistable) {
- val persistable = (Persistable) pojo;
- val isDeleted = persistable.dnIsDeleted();
- if(isDeleted) {
- return ManagedObjectState.persistable_Destroyed;
- }
- val isPersistent = persistable.dnIsPersistent();
- if(isPersistent) {
- return ManagedObjectState.persistable_Attached;
- }
- return ManagedObjectState.persistable_Detached;
- }
- return ManagedObjectState.not_Persistable;
- }
-
- @Override
- public boolean isRecognized(Object pojo) {
- if (pojo!=null && pojo instanceof Persistable) {
- final Object jdoOid = pm().getObjectId(pojo);
- if(jdoOid!=null) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public ObjectAdapter adapterFor(final RootOid rootOid) {
- return objectAdapterContext.getObjectAdapterByIdProvider().adapterFor(rootOid);
- }
-
- // -- MEMENTO SUPPORT
-
- @Override
- public ObjectAdapter adapterOfMemento(ObjectSpecification spec, Oid oid, Data data) {
- return objectAdapterContext.mementoSupport().recreateObject(spec, oid, data);
- }
-
- @Override
- public ObjectAdapterProvider getObjectAdapterProvider() {
- return objectAdapterContext.getObjectAdapterProvider();
- }
-
- @Override
- public ObjectAdapterByIdProvider getObjectAdapterByIdProvider() {
- return objectAdapterContext.getObjectAdapterByIdProvider();
- }
-
- // -- HELPER
-
- private void debugLogNotPersistentIgnoring(Object domainObject) {
- if (log.isDebugEnabled() && domainObject!=null) {
- final Oid oid = oidFor(domainObject);
- log.debug("; oid={} not persistent - ignoring", oid.enString());
- }
- }
-
- private void debugLogRefreshImmediately(Object domainObject) {
- if (log.isDebugEnabled()) {
- final Oid oid = oidFor(domainObject);
- log.debug("refresh immediately; oid={}", oid.enString());
- }
- }
-
-
+ private ObjectAdapterContext objectAdapterContext;
+ @Getter private final TransactionService transactionService;
+
+ /**
+ * Initialize the object store so that calls to this object store access
+ * persisted objects and persist changes to the object that are saved.
+ */
+ public PersistenceSession5(
+ final AuthenticationSession authenticationSession,
+ final PersistenceManagerFactory jdoPersistenceManagerFactory,
+ final FixturesInstalledStateHolder stateHolder) {
+
+ super(authenticationSession, jdoPersistenceManagerFactory, stateHolder);
+ transactionService = IsisContext.getTransactionService();
+ }
+
+ // -- open
+
+ /**
+ * Injects components, calls open on subcomponents, and then creates service
+ * adapters.
+ */
+ @Override
+ public void open() {
+ ensureNotOpened();
+
+ openedAtSystemNanos = System.nanoTime();
+
+ if (log.isDebugEnabled()) {
+ log.debug("opening {}", this);
+ }
+
+ persistenceManager = jdoPersistenceManagerFactory.getPersistenceManager();
+
+ final IsisLifecycleListener.PersistenceSessionLifecycleManagement psLifecycleMgmt = this;
+ final IsisLifecycleListener isisLifecycleListener = new IsisLifecycleListener(psLifecycleMgmt);
+ persistenceManager.addInstanceLifecycleListener(isisLifecycleListener, (Class[]) null);
+
+ persistenceQueryProcessorByClass.put(
+ PersistenceQueryFindAllInstances.class,
+ new PersistenceQueryFindAllInstancesProcessor(this));
+ persistenceQueryProcessorByClass.put(
+ PersistenceQueryFindUsingApplibQueryDefault.class,
+ new PersistenceQueryFindUsingApplibQueryProcessor(this));
+
+ objectAdapterContext = ObjectAdapterContext.openContext(authenticationSession, specificationLoader, this);
+
+ // tell the proxy of all request-scoped services to instantiate the underlying
+ // services, store onto the thread-local and inject into them...
+ startRequestOnRequestScopedServices();
+
+ // ... and invoke all @PostConstruct
+ postConstructOnRequestScopedServices();
+
+ if(metricsService instanceof InstanceLifecycleListener) {
+ final InstanceLifecycleListener metricsService = (InstanceLifecycleListener) this.metricsService;
+ persistenceManager.addInstanceLifecycleListener(metricsService, (Class[]) null);
+ }
+
+ final Command command = createCommand();
+ final Interaction interaction = factoryService.instantiate(Interaction.class);
+
+ final Timestamp timestamp = clockService.nowAsJavaSqlTimestamp();
+ final String userName = userService.getUser().getName();
+
+ command.internal().setTimestamp(timestamp);
+ command.internal().setUser(userName);
+
+ interaction.setUniqueId(command.getUniqueId());
+
+ commandContext.setCommand(command);
+ interactionContext.setInteraction(interaction);
+
+ this.state = State.OPEN;
+ }
+
+ private void postConstructOnRequestScopedServices() {
+ serviceRegistry.select(RequestScopedService.class)
+ .forEach(RequestScopedService::__isis_postConstruct);
+ }
+
+ private void startRequestOnRequestScopedServices() {
+ serviceRegistry.select(RequestScopedService.class)
+ .forEach(service->service.__isis_startRequest(serviceInjector));
+ }
+
+ private Command createCommand() {
+ final Command command = commandService.create();
+
+ serviceInjector.injectServicesInto(command);
+ return command;
+ }
+
+ // -- close
+
+ /**
+ * Closes the subcomponents.
+ *
+ * <p>
+ * Automatically {@link IsisTransactionManagerJdo#commitTransaction() ends
+ * (commits)} the current (Isis) {@link IsisTransactionJdo}. This in turn commits the underlying
+ * JDO transaction.
+ *
+ * <p>
+ * The corresponding DataNucleus entity is then closed.
+ */
+ @Override
+ public void close() {
+
+ if (state == State.CLOSED) {
+ // nothing to do
+ return;
+ }
+
+ completeCommandFromInteractionAndClearDomainEvents();
+
+//TODO[2125] shold no longer be required
+// try {
+// val currentTransaction = transactionManager.getCurrentTransaction();
+// transactionManager.flushTransaction(currentTransaction);
+// if (currentTransaction != null && !currentTransaction.getState().isComplete()) {
+// if(currentTransaction.getState().canCommit()) {
+// transactionManager.commitTransaction(currentTransaction);
+// } else if(currentTransaction.getState().canAbort()) {
+// transactionManager.abortTransaction(currentTransaction);
+// }
+// }
+// } catch(final Throwable ex) {
+// // ignore
+// log.error("close: failed to end transaction; continuing to avoid memory leakage");
+// }
+
+ // tell the proxy of all request-scoped services to invoke @PreDestroy
+ // (if any) on all underlying services stored on their thread-locals...
+ preDestroyOnRequestScopedServices();
+
+ // ... and then remove those underlying services from the thread-local
+ endRequestOnRequestScopeServices();
+
+ try {
+ persistenceManager.close();
+ } catch(final Throwable ex) {
+ // ignore
+ log.error(
+ "close: failed to close JDO persistenceManager; continuing to avoid memory leakage");
+ }
+
+ objectAdapterContext.close();
+
+ this.state = State.CLOSED;
+ }
+
+ private void endRequestOnRequestScopeServices() {
+ serviceRegistry.select(RequestScopedService.class)
+ .forEach(RequestScopedService::__isis_endRequest);
+ }
+
+ private void preDestroyOnRequestScopedServices() {
+ serviceRegistry.select(RequestScopedService.class)
+ .forEach(RequestScopedService::__isis_preDestroy);
+ }
+
+ private void completeCommandFromInteractionAndClearDomainEvents() {
+
+ final Command command = commandContext.getCommand();
+ final Interaction interaction = interactionContext.getInteraction();
+
+
+ if(command.getStartedAt() != null && command.getCompletedAt() == null) {
+ // the guard is in case we're here as the result of a redirect following a previous exception;just ignore.
+
+ final Timestamp completedAt;
+ final Interaction.Execution<?, ?> priorExecution = interaction.getPriorExecution();
+ if (priorExecution != null) {
+ // copy over from the most recent (which will be the top-level) interaction
+ completedAt = priorExecution.getCompletedAt();
+ } else {
+ // this could arise as the result of calling SessionManagementService#nextSession within an action
+ // the best we can do is to use the current time
+
+ // REVIEW: as for the interaction object, it is left somewhat high-n-dry.
+ completedAt = clockService.nowAsJavaSqlTimestamp();
+ }
+
+ command.internal().setCompletedAt(completedAt);
+ }
+
+ // ensureCommandsPersistedIfDirtyXactn
+
+ // ensure that any changed objects means that the command should be persisted
+ if(command.getMemberIdentifier() != null) {
+ if(metricsService.numberObjectsDirtied() > 0) {
+ command.internal().setPersistHint(true);
+ }
+ }
+
+ commandService.complete(command);
+
+ interaction.clear();
+ }
+
+ // -- QuerySubmitter impl, findInstancesInTransaction
+ @Override
+ public <T> List<ObjectAdapter> allMatchingQuery(final Query<T> query) {
+ final ObjectAdapter instances = findInstancesInTransaction(query, QueryCardinality.MULTIPLE);
+ return CollectionFacet.Utils.toAdapterList(instances);
+ }
+ @Override
+ public <T> ObjectAdapter firstMatchingQuery(final Query<T> query) {
+ final ObjectAdapter instances = findInstancesInTransaction(query, QueryCardinality.SINGLE);
+ final List<ObjectAdapter> list = CollectionFacet.Utils.toAdapterList(instances);
+ return list.size() > 0 ? list.get(0) : null;
+ }
+
+ /**
+ * Finds and returns instances that match the specified query.
+ *
+ * <p>
+ * The {@link QueryCardinality} determines whether all instances or just the
+ * first matching instance is returned.
+ *
+ * @throws org.apache.isis.runtime.persistence.UnsupportedFindException
+ * if the criteria is not support by this persistor
+ */
+ private <T> ObjectAdapter findInstancesInTransaction(final Query<T> query, final QueryCardinality cardinality) {
+ if (log.isDebugEnabled()) {
+ log.debug("findInstances using (applib) Query: {}", query);
+ }
+
+ // TODO: unify PersistenceQuery and PersistenceQueryProcessor
+ final PersistenceQuery persistenceQuery = createPersistenceQueryFor(query, cardinality);
+ if (log.isDebugEnabled()) {
+ log.debug("maps to (core runtime) PersistenceQuery: {}", persistenceQuery);
+ }
+
+ final PersistenceQueryProcessor<? extends PersistenceQuery> processor = lookupProcessorFor(persistenceQuery);
+
+ final List<ObjectAdapter> instances = transactionService.executeWithinTransaction(
+ ()->processPersistenceQuery(processor, persistenceQuery) );
+ final ObjectSpecification specification = persistenceQuery.getSpecification();
+ final FreeStandingList results = FreeStandingList.of(specification, instances);
+ return adapterFor(results);
+ }
+
+ /**
+ * Converts the {@link Query applib representation of a query} into the
+ * {@link PersistenceQuery NOF-internal representation}.
+ */
+ private final PersistenceQuery createPersistenceQueryFor(
+ final Query<?> query,
+ final QueryCardinality cardinality) {
+
+ final PersistenceQuery persistenceQuery =
+ persistenceQueryFactory.createPersistenceQueryFor(query, cardinality);
+ if (persistenceQuery == null) {
+ throw new IllegalArgumentException("Unknown Query type: " + query.getDescription());
+ }
+
+ return persistenceQuery;
+ }
+
+ private PersistenceQueryProcessor<? extends PersistenceQuery> lookupProcessorFor(final PersistenceQuery persistenceQuery) {
+ final Class<? extends PersistenceQuery> persistenceQueryClass = persistenceQuery.getClass();
+ final PersistenceQueryProcessor<? extends PersistenceQuery> processor =
+ persistenceQueryProcessorByClass.get(persistenceQueryClass);
+ if (processor == null) {
+ throw new UnsupportedFindException(MessageFormat.format(
+ "Unsupported PersistenceQuery class: {0}", persistenceQueryClass.getName()));
+ }
+ return processor;
+ }
+ @SuppressWarnings("unchecked")
+ private <Q extends PersistenceQuery> List<ObjectAdapter> processPersistenceQuery(
+ final PersistenceQueryProcessor<Q> persistenceQueryProcessor,
+ final PersistenceQuery persistenceQuery) {
+ return persistenceQueryProcessor.process((Q) persistenceQuery);
+ }
+
+
+ // -- fixture installation
+
+ @Override
+ public FixturesInstalledState getFixturesInstalledState() {
+ if (fixturesInstalledStateHolder.getFixturesInstalledState() == null) {
+ val initialStateFromConfig = initialStateFromConfig();
+ fixturesInstalledStateHolder.setFixturesInstalledState(initialStateFromConfig);
+ }
+ return fixturesInstalledStateHolder.getFixturesInstalledState();
+ }
+
+ /**
+ * Determine if the object store has been initialized with its set of start
+ * up objects.
+ *
+ * <p>
+ * This method is called only once after the session is opened called. If it returns <code>false</code> then the
+ * framework will run the fixtures to initialise the object store.
+ *
+ * <p>
+ * Implementation looks for the {@link #INSTALL_FIXTURES_KEY} in the injected {@link #configuration configuration}.
+ *
+ * <p>
+ * By default this is not expected to be there, but utilities can add in on
+ * the fly during bootstrapping if required.
+ */
+ private FixturesInstalledState initialStateFromConfig() {
+ val installFixtures = configuration.getBoolean(INSTALL_FIXTURES_KEY, INSTALL_FIXTURES_DEFAULT);
+ log.info("isFixturesInstalled: {} = {}", INSTALL_FIXTURES_KEY, installFixtures);
+
+ val objectStoreIsFixturesInstalled = !installFixtures;
+ val initialStateFromConfig = objectStoreIsFixturesInstalled
+ ? FixturesInstalledState.Installed
+ : FixturesInstalledState.not_Installed;
+
+ return initialStateFromConfig;
+ }
+
+ // -- FETCHING
+
+ @Override
+ public Object fetchPersistentPojo(final RootOid rootOid) {
+ Objects.requireNonNull(rootOid);
+ log.debug("getObject; oid={}", rootOid);
+
+ Object result;
+ try {
+ final Class<?> cls = clsOf(rootOid);
+ final Object jdoObjectId = JdoObjectIdSerializer.toJdoObjectId(rootOid);
+ FetchPlan fetchPlan = persistenceManager.getFetchPlan();
+ fetchPlan.addGroup(FetchGroup.DEFAULT);
+ result = persistenceManager.getObjectById(cls, jdoObjectId);
+ } catch (final RuntimeException e) {
+
+ Class<ExceptionRecognizer> serviceClass = ExceptionRecognizer.class;
+ final Iterable<ExceptionRecognizer> exceptionRecognizers = lookupServices(serviceClass);
+ for (ExceptionRecognizer exceptionRecognizer : exceptionRecognizers) {
+ final ExceptionRecognizer.Recognition recognition =
+ exceptionRecognizer.recognize2(e);
+ if(recognition != null) {
+ if(recognition.getCategory() == ExceptionRecognizer.Category.NOT_FOUND) {
+ throw new ObjectNotFoundException(rootOid, e);
+ }
+ }
+ }
+
+ throw e;
+ }
+
+ if (result == null) {
+ throw new ObjectNotFoundException(rootOid);
+ }
+
+ return result;
+ }
+
+ @Override
+ public Map<RootOid,Object> fetchPersistentPojos(final List<RootOid> rootOids) {
+
+ if(rootOids.isEmpty()) {
+ return Collections.emptyMap();
+ }
+
+ final List<Object> dnOids = new ArrayList<>(rootOids.size());
+ for (final RootOid rootOid : rootOids) {
+ final Object id = JdoObjectIdSerializer.toJdoObjectId(rootOid);
+ if(id instanceof SingleFieldIdentity) {
+ dnOids.add(id);
+ } else if (id instanceof String && ((String) id).contains("[OID]")) {
+ final DatastoreIdImpl datastoreId = new DatastoreIdImpl((String)id);
+ dnOids.add(datastoreId);
+ } else {
+ // application identity
+ final DatastoreIdImpl datastoreId = new DatastoreIdImpl(clsOf(rootOid).getName(), id);
+ dnOids.add(datastoreId);
+ }
+ }
+ FetchPlan fetchPlan = persistenceManager.getFetchPlan();
+ fetchPlan.addGroup(FetchGroup.DEFAULT);
+ final List<Object> persistentPojos = new ArrayList<>(rootOids.size());
+ try {
+ final Collection<Object> pojos = uncheckedCast(persistenceManager.getObjectsById(dnOids, true));
+ for (final Object pojo : pojos) {
+ try {
+ persistentPojos.add(pojo);
+ } catch(Exception ex) {
+ persistentPojos.add(null);
+ }
+ }
+ } catch(NucleusObjectNotFoundException nonfe) {
+ // at least one not found; fall back to loading one by one
+ for (final Object dnOid : dnOids) {
+ try {
+ final Object persistentPojo = persistenceManager.getObjectById(dnOid);
+ persistentPojos.add(persistentPojo);
+ } catch(Exception ex) {
+ persistentPojos.add(null);
+ }
+ }
+ }
+ Map<RootOid, Object> pojoByOid = zip(rootOids, persistentPojos);
+ return pojoByOid;
+ }
+
+ private static Map<RootOid, Object> zip(final List<RootOid> rootOids, final Collection<Object> pojos) {
+ final Map<RootOid,Object> pojoByOid = _Maps.newLinkedHashMap();
+ int i = 0;
+ for (final Object pojo : pojos) {
+ final RootOid rootOid = rootOids.get(i++);
+ pojoByOid.put(rootOid, pojo);
+ }
+ return pojoByOid;
+ }
+
+ private Class<?> clsOf(final RootOid oid) {
+ final ObjectSpecification objectSpec = getSpecificationLoader().lookupBySpecIdElseLoad(oid.getObjectSpecId());
+ return objectSpec.getCorrespondingClass();
+ }
+
+
+ // -- REFRESH
+
+ @Override
+ public void refreshRoot(final Object domainObject) {
+
+ val state = stateOf(domainObject);
+ val isRepresentingPersistent = state.isAttached() || state.isDestroyed();
+
+ if(!isRepresentingPersistent) {
+ debugLogNotPersistentIgnoring(domainObject);
+ return; // only resolve object that is representing persistent
+ }
+
+ debugLogRefreshImmediately(domainObject);
+
+ try {
+ persistenceManager.refresh(domainObject);
+ } catch (final RuntimeException e) {
+ final Oid oid = oidFor(domainObject);
+ throw new PojoRefreshException(oid, e);
+ }
+
+ // possibly redundant because also called in the post-load event
+ // listener, but (with JPA impl) found it was required if we were ever to
+ // get an eager left-outer-join as the result of a refresh (sounds possible).
+ initializeMapAndCheckConcurrency((Persistable) domainObject);
+ }
+
+ // -- makePersistent
+
+ /**
+ * Makes an {@link ObjectAdapter} persistent. The specified object should be
+ * stored away via this object store's persistence mechanism, and have a
+ * new and unique OID assigned to it. The object, should also be added to
+ * the {@link PersistenceSession} as the object is implicitly 'in use'.
+ *
+ * <p>
+ * If the object has any associations then each of these, where they aren't
+ * already persistent, should also be made persistent by recursively calling
+ * this method.
+ *
+ * <p>
+ * If the object to be persisted is a collection, then each element of that
+ * collection, that is not already persistent, should be made persistent by
+ * recursively calling this method.
+ */
+ @Override
+ public void makePersistentInTransaction(final ObjectAdapter adapter) {
+ if (adapter.isRepresentingPersistent()) {
+ throw new NotPersistableException("Object already persistent: " + adapter);
+ }
+ final ObjectSpecification specification = adapter.getSpecification();
+ if (specification.isManagedBean()) {
+ throw new NotPersistableException("Can only persist entity beans: " + adapter);
+ }
+
+ transactionService.executeWithinTransaction(()->{
+ makePersistentTransactionAssumed(adapter);
+ });
+ }
+
+ private void makePersistentTransactionAssumed(final ObjectAdapter adapter) {
+ if (alreadyPersistedOrNotPersistable(adapter)) {
+ return;
+ }
+ log.debug("persist {}", adapter);
+ addCreateObjectCommand(adapter);
+ }
+
+ /**
+ * {@link #newCreateObjectCommand(ObjectAdapter) Create}s a {@link CreateObjectCommand},
+ * and adds to the {@link IsisTransactionManagerJdo}.
+ */
+ private void addCreateObjectCommand(final ObjectAdapter object) {
+ val createObjectCommand = newCreateObjectCommand(object);
+ transactionManager.addCommand(createObjectCommand);
+ }
+
+
+ private static boolean alreadyPersistedOrNotPersistable(final ObjectAdapter adapter) {
+ return adapter.isRepresentingPersistent() || objectSpecNotPersistable(adapter);
+ }
+
+
+ private static boolean objectSpecNotPersistable(final ObjectAdapter adapter) {
+ return adapter.isParentedCollection();
+ }
+
+ // -- destroyObjectInTransaction
+
+ /**
+ * Removes the specified object from the system. The specified object's data
+ * should be removed from the persistence mechanism.
+ */
+ @Override
+ public void destroyObjectInTransaction(final ObjectAdapter adapter) {
+ val spec = adapter.getSpecification();
+ if (spec.isParented()) {
+ return;
+ }
+ log.debug("destroyObject {}", adapter);
+ transactionService.executeWithinTransaction(()->{
+ val destroyObjectCommand = newDestroyObjectCommand(adapter);
+ transactionManager.addCommand(destroyObjectCommand);
+ });
+ }
+
+ // -- newXxxCommand
+ /**
+ * Makes an {@link ObjectAdapter} persistent. The specified object should be
+ * stored away via this object store's persistence mechanism, and have an
+ * new and unique OID assigned to it (by calling the object's
+ * <code>setOid</code> method). The object, should also be added to the
+ * cache as the object is implicitly 'in use'.
+ *
+ * <p>
+ * If the object has any associations then each of these, where they aren't
+ * already persistent, should also be made persistent by recursively calling
+ * this method.
+ * </p>
+ *
+ * <p>
+ * If the object to be persisted is a collection, then each element of that
+ * collection, that is not already persistent, should be made persistent by
+ * recursively calling this method.
+ * </p>
+ *
+ */
+ private CreateObjectCommand newCreateObjectCommand(final ObjectAdapter adapter) {
+ ensureOpened();
+
+ log.debug("create object - creating command for: {}", adapter);
+ if (adapter.isRepresentingPersistent()) {
+ throw new IllegalArgumentException("Adapter is persistent; adapter: " + adapter);
+ }
+ return new DataNucleusCreateObjectCommand(adapter, persistenceManager);
+ }
+
+ private DestroyObjectCommand newDestroyObjectCommand(final ObjectAdapter adapter) {
+ ensureOpened();
+
+ log.debug("destroy object - creating command for: {}", adapter);
+ if (!adapter.isRepresentingPersistent()) {
+ throw new IllegalArgumentException("Adapter is not persistent; adapter: " + adapter);
+ }
+ return new DataNucleusDeleteObjectCommand(adapter, persistenceManager);
+ }
+
+
+ // -- execute
+ @Override
+ public void execute(final List<PersistenceCommand> commands) {
+
+ // previously we used to check that there were some commands, and skip processing otherwise.
+ // we no longer do that; it could be (is quite likely) that DataNucleus has some dirty objects anyway that
+ // don't have commands wrapped around them...
+
+ executeCommands(commands);
+ }
+
+ private void executeCommands(final List<PersistenceCommand> commands) {
+
+ for (final PersistenceCommand command : commands) {
+ command.execute(null);
+ }
+ persistenceManager.flush();
+ }
+
+ // -- FrameworkSynchronizer delegate methods
+
+ @Override
+ public void enlistDeletingAndInvokeIsisRemovingCallbackFacet(final Persistable pojo) {
+ ObjectAdapter adapter = adapterFor(pojo);
+
+ changedObjectsServiceInternal.enlistDeleting(adapter);
+
+ CallbackFacet.Util.callCallback(adapter, RemovingCallbackFacet.class);
+ objectAdapterContext.postLifecycleEventIfRequired(adapter, RemovingLifecycleEventFacet.class);
+ }
+
+ @Override
+ public ObjectAdapter initializeMapAndCheckConcurrency(final Persistable pojo) {
+ final Persistable pc = pojo;
+
+ // need to do eagerly, because (if a viewModel then) a
+ // viewModel's #viewModelMemento might need to use services
+ serviceInjector.injectServicesInto(pojo);
+
+ final Version datastoreVersion = getVersionIfAny(pc);
+ final RootOid originalOid = objectAdapterContext.createPersistentOrViewModelOid(pojo);
+
+ final ObjectAdapter adapter = objectAdapterContext.recreatePojo(originalOid, pojo);
+ adapter.setVersion(datastoreVersion);
+
+ CallbackFacet.Util.callCallback(adapter, LoadedCallbackFacet.class);
+ objectAdapterContext.postLifecycleEventIfRequired(adapter, LoadedLifecycleEventFacet.class);
+
+ return adapter;
+ }
+
+ @Override
+ public String identifierFor(final Object pojo) {
+ final Object jdoOid = pm().getObjectId(pojo);
+ requireNonNull(jdoOid,
+ ()->String.format("Pojo of type '%s' is not recognized by JDO.",
+ pojo.getClass().getName()));
+ return JdoObjectIdSerializer.toOidIdentifier(jdoOid);
+ }
+
+
+ /**
+ * Called either when an entity is initially persisted, or when an entity is updated; fires the appropriate
+ * lifecycle callback.
+ *
+ * <p>
+ * The implementation therefore uses Isis' {@link org.apache.isis.metamodel.adapter.oid.Oid#isTransient() oid}
+ * to determine which callback to fire.
+ */
+ @Override
+ public void invokeIsisPersistingCallback(final Persistable pojo) {
+ if (stateOf(pojo).isDetached()) {
+ final ManagedObject adapter = ManagedObject.of(
+ ()->getSpecificationLoader().loadSpecification(pojo.getClass()),
+ pojo);
+
+ // persisting
+ // previously this was performed in the DataNucleusSimplePersistAlgorithm.
+ CallbackFacet.Util.callCallback(adapter, PersistingCallbackFacet.class);
+ objectAdapterContext.postLifecycleEventIfRequired(adapter, PersistingLifecycleEventFacet.class);
+
+ } else {
+ // updating
+
+ // don't call here, already called in preDirty.
+
+ // CallbackFacet.Util.callCallback(adapter, UpdatingCallbackFacet.class);
+ }
+ }
+
+ /**
+ * Called either when an entity is initially persisted, or when an entity is updated;
+ * fires the appropriate lifecycle callback
+ *
+ * <p>
+ * The implementation therefore uses Isis' {@link org.apache.isis.metamodel.adapter.oid.Oid#isTransient() oid}
+ * to determine which callback to fire.
+ */
+ @Override
+ public void enlistCreatedAndRemapIfRequiredThenInvokeIsisInvokePersistingOrUpdatedCallback(final Persistable pojo) {
+ final ObjectAdapter adapter = adapterFor(pojo);
+
+ final RootOid rootOid = (RootOid) adapter.getOid(); // ok since this is for a Persistable
+
+ if (rootOid.isTransient()) {
+ // persisting
+
+ objectAdapterContext.asPersistent(adapter, this);
+
+ CallbackFacet.Util.callCallback(adapter, PersistedCallbackFacet.class);
+ objectAdapterContext.postLifecycleEventIfRequired(adapter, PersistedLifecycleEventFacet.class);
+
+ changedObjectsServiceInternal.enlistCreated(adapter);
+
+ } else {
+ // updating;
+ // the callback and transaction.enlist are done in the preDirty callback
+ // (can't be done here, as the enlist requires to capture the 'before' values)
+ CallbackFacet.Util.callCallback(adapter, UpdatedCallbackFacet.class);
+ objectAdapterContext.postLifecycleEventIfRequired(adapter, UpdatedLifecycleEventFacet.class);
+ }
+
+ Version versionIfAny = getVersionIfAny(pojo);
+ adapter.setVersion(versionIfAny);
+ }
+
+ @Override
+ public void enlistUpdatingAndInvokeIsisUpdatingCallback(final Persistable pojo) {
+
+ // seen this happen in the case when a parent entity (LeaseItem) has a collection of children
+ // objects (LeaseTerm) for which we haven't had a loaded callback fired and so are not yet
+ // mapped.
+
+ // it seems reasonable in this case to simply map into Isis here ("just-in-time"); presumably
+ // DN would not be calling this callback if the pojo was not persistent.
+
+ final ObjectAdapter adapter = objectAdapterContext.fetchPersistent(pojo);
+ if (adapter == null) {
+ throw new RuntimeException(
+ "DN could not find objectId for pojo (unexpected) and so could not map into Isis; pojo=["
+ + pojo + "]");
+ }
+
+ final boolean wasAlreadyEnlisted = changedObjectsServiceInternal.isEnlisted(adapter);
+
+ // we call this come what may;
+ // additional properties may now have been changed, and the changeKind for publishing might also be modified
+ changedObjectsServiceInternal.enlistUpdating(adapter);
+
+ if(!wasAlreadyEnlisted) {
+ // prevent an infinite loop... don't call the 'updating()' callback on this object if we have already done so
+ CallbackFacet.Util.callCallback(adapter, UpdatingCallbackFacet.class);
+ objectAdapterContext.postLifecycleEventIfRequired(adapter, UpdatingLifecycleEventFacet.class);
+ }
+
+ }
+
+ /**
+ * makes sure the entity is known to Isis and is a root
+ * @param pojo
+ */
+ @Override
+ public void ensureRootObject(final Persistable pojo) {
+ final Oid oid = adapterFor(pojo).getOid();
+ if (!(oid instanceof RootOid)) {
+ throw new IsisException(MessageFormat.format("Not a RootOid: oid={0}, for {1}", oid, pojo));
+ }
+ }
+
+ private Version getVersionIfAny(final Persistable pojo) {
+ return Utils.getVersionIfAny(pojo, authenticationSession);
+ }
+
+ @Override
+ public ManagedObjectState stateOf(@Nullable Object pojo) {
+
+ // guard against misuse
+ if(pojo instanceof ObjectAdapter) {
+ throw _Exceptions.unexpectedCodeReach();
+ }
+
+ if (pojo!=null && pojo instanceof Persistable) {
+ val persistable = (Persistable) pojo;
+ val isDeleted = persistable.dnIsDeleted();
+ if(isDeleted) {
+ return ManagedObjectState.persistable_Destroyed;
+ }
+ val isPersistent = persistable.dnIsPersistent();
+ if(isPersistent) {
+ return ManagedObjectState.persistable_Attached;
+ }
+ return ManagedObjectState.persistable_Detached;
+ }
+ return ManagedObjectState.not_Persistable;
+ }
+
+ @Override
+ public boolean isRecognized(Object pojo) {
+ if (pojo!=null && pojo instanceof Persistable) {
+ final Object jdoOid = pm().getObjectId(pojo);
+ if(jdoOid!=null) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public ObjectAdapter adapterFor(final RootOid rootOid) {
+ return objectAdapterContext.getObjectAdapterByIdProvider().adapterFor(rootOid);
+ }
+
+ // -- MEMENTO SUPPORT
+
+ @Override
+ public ObjectAdapter adapterOfMemento(ObjectSpecification spec, Oid oid, Data data) {
+ return objectAdapterContext.mementoSupport().recreateObject(spec, oid, data);
+ }
+
+ @Override
+ public ObjectAdapterProvider getObjectAdapterProvider() {
+ return objectAdapterContext.getObjectAdapterProvider();
+ }
+
+ @Override
+ public ObjectAdapterByIdProvider getObjectAdapterByIdProvider() {
+ return objectAdapterContext.getObjectAdapterByIdProvider();
+ }
+
+ // -- HELPER
+
+ private void debugLogNotPersistentIgnoring(Object domainObject) {
+ if (log.isDebugEnabled() && domainObject!=null) {
+ final Oid oid = oidFor(domainObject);
+ log.debug("; oid={} not persistent - ignoring", oid.enString());
+ }
+ }
+
+ private void debugLogRefreshImmediately(Object domainObject) {
+ if (log.isDebugEnabled()) {
+ final Oid oid = oidFor(domainObject);
+ log.debug("refresh immediately; oid={}", oid.enString());
+ }
+ }
+
+
}
diff --git a/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionAspectSupport.java b/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionAspectSupport.java
index f91a378..a725024 100644
--- a/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionAspectSupport.java
+++ b/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionAspectSupport.java
@@ -20,6 +20,7 @@ package org.apache.isis.runtime.system.transaction;
import java.util.Optional;
+import org.apache.isis.applib.services.xactn.Transaction;
import org.apache.isis.commons.internal.context._Context;
public final class IsisTransactionAspectSupport {
@@ -37,4 +38,12 @@ public final class IsisTransactionAspectSupport {
.getFirst();
}
+ public static boolean isTransactionInProgress() {
+ return currentTransactionObject()
+ .map(IsisTransactionObject::getCurrentTransaction)
+ .map(Transaction::getCountDownLatch)
+ .map(latch->latch.getCount()>0)
+ .orElse(false);
+ }
+
}
diff --git a/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionObject.java b/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionObject.java
index b6a7add..a1086c9 100644
--- a/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionObject.java
+++ b/core/runtime/src/main/java/org/apache/isis/runtime/system/transaction/IsisTransactionObject.java
@@ -22,13 +22,21 @@ import org.apache.isis.applib.services.xactn.Transaction;
import org.apache.isis.applib.services.xactn.TransactionId;
import org.springframework.transaction.support.SmartTransactionObject;
-import lombok.AllArgsConstructor;
-import lombok.Data;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.ToString;
+import lombok.val;
-@Data @AllArgsConstructor(staticName = "of")
+@ToString
public class IsisTransactionObject implements SmartTransactionObject {
+
+ public static IsisTransactionObject of(Transaction currentTransaction) {
+ val txObject = new IsisTransactionObject();
+ txObject.setCurrentTransaction(currentTransaction);
+ return txObject;
+ }
- Transaction currentTransaction;
+ @Getter @Setter Transaction currentTransaction;
@Override
public boolean isRollbackOnly() {
@@ -47,6 +55,33 @@ public class IsisTransactionObject implements SmartTransactionObject {
return currentTransaction.getId();
}
return null;
- }
+ }
+
+ // -- RESET
+
+ public void clear() {
+ transactionNestingLevel = 0;
+ setCurrentTransaction(null);
+ }
+
+
+ // -- NESTING
+
+ @Getter private int transactionNestingLevel = 0;
+
+ public int incTransactionNestingLevel() {
+ return ++transactionNestingLevel;
+ }
+
+ public int decTransactionNestingLevel() {
+ if(transactionNestingLevel==0) {
+ return 0;
+ }
+ return --transactionNestingLevel;
+ }
+
+ public boolean isTopLevel() {
+ return transactionNestingLevel == 0;
+ }
}
diff --git a/examples/smoketest/src/test/java/org/apache/isis/testdomain/bootstrapping/JdoBootstrappingTest.java b/examples/smoketest/src/test/java/org/apache/isis/testdomain/bootstrapping/JdoBootstrappingTest.java
index a5da525..6dee813 100644
--- a/examples/smoketest/src/test/java/org/apache/isis/testdomain/bootstrapping/JdoBootstrappingTest.java
+++ b/examples/smoketest/src/test/java/org/apache/isis/testdomain/bootstrapping/JdoBootstrappingTest.java
@@ -28,7 +28,6 @@ import java.util.Set;
import javax.inject.Inject;
import org.apache.isis.applib.services.repository.RepositoryService;
-import org.apache.isis.applib.services.xactn.TransactionService;
import org.apache.isis.testdomain.jdo.Book;
import org.apache.isis.testdomain.jdo.Inventory;
import org.apache.isis.testdomain.jdo.JdoTestDomainModule;
@@ -51,8 +50,9 @@ import lombok.val;
},
properties = {
"logging.config=log4j2-test.xml",
- "logging.level.org.apache.isis.jdo.transaction.IsisPlatformTransactionManagerForJdo=DEBUG",
+ "logging.level.org.apache.isis.jdo.persistence.IsisPlatformTransactionManagerForJdo=DEBUG",
"logging.level.org.apache.isis.jdo.persistence.PersistenceSession5=DEBUG",
+ "logging.level.org.apache.isis.jdo.persistence.IsisTransactionJdo=DEBUG",
// "isis.reflector.introspector.parallelize=false",
//"logging.level.org.apache.isis.metamodel.specloader.specimpl.ObjectSpecificationAbstract=TRACE"
})
@@ -60,7 +60,7 @@ import lombok.val;
class JdoBootstrappingTest {
@Inject private RepositoryService repository;
- @Inject private TransactionService transactionService;
+ //@Inject private TransactionService transactionService;
@BeforeAll
static void beforeAll() throws SQLException {
@@ -95,8 +95,6 @@ class JdoBootstrappingTest {
val inventory = Inventory.of("Sample Inventory", products);
repository.persist(inventory);
- transactionService.flushTransaction();
-
System.out.println("!!! SETUP DONE");
}