- @Override
- public ListenableFuture<Void> commit() {
- try {
- dataTree.getDataTree().commit(candidate);
- } catch (Exception e) {
- if(LOG.isTraceEnabled()) {
- LOG.trace("Transaction {} failed to commit", transaction, e);
+ private <T> FutureCallback<T> switchState(final State newState) {
+ @SuppressWarnings("unchecked")
+ final FutureCallback<T> ret = (FutureCallback<T>) this.callback;
+ this.callback = null;
+ LOG.debug("Transaction {} changing state from {} to {}", transactionId, state, newState);
+ this.state = newState;
+ return ret;
+ }
+
+ void setNewCandidate(final DataTreeCandidateTip dataTreeCandidate) {
+ checkState(State.PRE_COMMIT_COMPLETE);
+ this.candidate = Verify.verifyNotNull(dataTreeCandidate);
+ }
+
+ void successfulCanCommit() {
+ switchState(State.CAN_COMMIT_COMPLETE).onSuccess(null);
+ }
+
+ void failedCanCommit(final Exception cause) {
+ switchState(State.FAILED).onFailure(cause);
+ }
+
+ /**
+ * Run user-defined canCommit and preCommit hooks. We want to run these before we initiate persistence so that
+ * any failure to validate is propagated before we record the transaction.
+ *
+ * @param dataTreeCandidate {@link DataTreeCandidate} under consideration
+ * @param futureCallback the callback to invoke on completion, which may be immediate or async.
+ */
+ void userPreCommit(final DataTreeCandidate dataTreeCandidate, final FutureCallback<Void> futureCallback) {
+ userCohorts.reset();
+
+ final Optional<CompletionStage<Void>> maybeCanCommitFuture = userCohorts.canCommit(dataTreeCandidate);
+ if (!maybeCanCommitFuture.isPresent()) {
+ doUserPreCommit(futureCallback);
+ return;
+ }
+
+ maybeCanCommitFuture.get().whenComplete((noop, failure) -> {
+ if (failure != null) {
+ futureCallback.onFailure(failure);
+ } else {
+ doUserPreCommit(futureCallback);
+ }
+ });
+ }
+
+ private void doUserPreCommit(final FutureCallback<Void> futureCallback) {
+ final Optional<CompletionStage<Void>> maybePreCommitFuture = userCohorts.preCommit();
+ if (!maybePreCommitFuture.isPresent()) {
+ futureCallback.onSuccess(null);
+ return;
+ }
+
+ maybePreCommitFuture.get().whenComplete((noop, failure) -> {
+ if (failure != null) {
+ futureCallback.onFailure(failure);