Do not generate 'isFoo()' methods
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / ShardedDOMDataTreeWriteTransaction.java
index fcbc9169fca9759f7ba8f5c910f2525a850ec047..8d21e936e469e51a9b8f189053799525518beb47 100644 (file)
@@ -7,55 +7,46 @@
  */
 package org.opendaylight.mdsal.dom.broker;
 
+import static java.util.Objects.requireNonNull;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
-import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FluentFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
 import com.google.common.util.concurrent.SettableFuture;
-import java.util.Collection;
+import java.util.ArrayDeque;
 import java.util.Deque;
-import java.util.LinkedList;
-import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import java.util.Set;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.BiConsumer;
 import java.util.function.Consumer;
 import java.util.stream.Collectors;
-import javax.annotation.Nonnull;
-import javax.annotation.concurrent.GuardedBy;
-import javax.annotation.concurrent.NotThreadSafe;
-import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
+import org.checkerframework.checker.lock.qual.GuardedBy;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.mdsal.common.api.CommitInfo;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
-import org.opendaylight.mdsal.dom.store.inmemory.DOMDataTreeShardProducer;
-import org.opendaylight.mdsal.dom.store.inmemory.DOMDataTreeShardWriteTransaction;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.mdsal.dom.spi.shard.DOMDataTreeShardWriteTransaction;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-@NotThreadSafe
 final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAwareTransaction {
     private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeWriteTransaction.class);
-    private static final TransactionCommitFailedExceptionMapper SUBMIT_FAILED_MAPPER =
-            TransactionCommitFailedExceptionMapper.create("submit");
     private static final AtomicLong COUNTER = new AtomicLong();
 
-    private final Map<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> idToTransaction;
-    private final Collection<YangInstanceIdentifier> childBoundaries;
+    private final Map<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> transactions;
     private final ShardedDOMDataTreeProducer producer;
+    private final ProducerLayout layout;
     private final String identifier;
 
-    private final SettableFuture<Void> future = SettableFuture.create();
-    private final CheckedFuture<Void, TransactionCommitFailedException> submitFuture =
-            Futures.makeChecked(future, SUBMIT_FAILED_MAPPER);
+    private final SettableFuture<CommitInfo> future = SettableFuture.create();
 
     @GuardedBy("this")
     private boolean closed =  false;
@@ -64,27 +55,28 @@ final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAware
     private DOMDataTreeWriteCursor openCursor;
 
     ShardedDOMDataTreeWriteTransaction(final ShardedDOMDataTreeProducer producer,
-                                       final Map<DOMDataTreeIdentifier, DOMDataTreeShardProducer> idToProducer,
-                                       final Set<YangInstanceIdentifier> childRoots) {
-        this.producer = Preconditions.checkNotNull(producer);
+        final Map<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> transactions, final ProducerLayout layout) {
+        this.producer = requireNonNull(producer);
+        this.transactions = ImmutableMap.copyOf(transactions);
+        this.layout = requireNonNull(layout);
         this.identifier = "SHARDED-DOM-" + COUNTER.getAndIncrement();
-        idToTransaction = ImmutableMap.copyOf(Maps.transformValues(idToProducer,
-            DOMDataTreeShardProducer::createTransaction));
-        childBoundaries = Preconditions.checkNotNull(childRoots);
         LOG.debug("Created new transaction {}", identifier);
     }
 
     private DOMDataTreeShardWriteTransaction lookup(final DOMDataTreeIdentifier prefix) {
-        for (final Entry<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> e : idToTransaction.entrySet()) {
+        final DOMDataTreeShardWriteTransaction fast = transactions.get(prefix);
+        if (fast != null) {
+            return fast;
+        }
+
+        LOG.debug("Prefix {} not found in available subtrees {}, fallback to slow path", prefix, transactions.keySet());
+        for (final Entry<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> e : transactions.entrySet()) {
             if (e.getKey().contains(prefix)) {
-                Preconditions.checkArgument(!producer.isDelegatedToChild(prefix),
-                    "Path %s is delegated to child producer.", prefix);
                 return e.getValue();
             }
         }
 
-        throw new IllegalArgumentException(String.format("Path %s is not accessible from transaction %s",
-                prefix, this));
+        return null;
     }
 
     @Override
@@ -102,7 +94,7 @@ final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAware
         if (openCursor != null) {
             openCursor.close();
         }
-        for (final DOMDataTreeShardWriteTransaction tx : idToTransaction.values()) {
+        for (final DOMDataTreeShardWriteTransaction tx : transactions.values()) {
             tx.close();
         }
 
@@ -115,51 +107,62 @@ final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAware
     public synchronized DOMDataTreeWriteCursor createCursor(final DOMDataTreeIdentifier prefix) {
         Preconditions.checkState(!closed, "Transaction is closed already");
         Preconditions.checkState(openCursor == null, "There is still a cursor open");
+        Preconditions.checkArgument(!producer.isDelegatedToChild(prefix), "Path %s is delegated to child producer.",
+            prefix);
+
         final DOMDataTreeShardWriteTransaction lookup = lookup(prefix);
+        Preconditions.checkArgument(lookup != null, "Path %s is not accessible from transaction %s", prefix, this);
+
         openCursor = new DelegatingCursor(lookup.createCursor(prefix), prefix);
         return openCursor;
     }
 
     @Override
-    public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
+    public synchronized FluentFuture<? extends @NonNull CommitInfo> commit() {
         Preconditions.checkState(!closed, "Transaction %s is already closed", identifier);
         Preconditions.checkState(openCursor == null, "Cannot submit transaction while there is a cursor open");
 
         producer.transactionSubmitted(this);
-        return submitFuture;
+        return FluentFuture.from(future);
     }
 
-    CheckedFuture<Void, TransactionCommitFailedException> doSubmit(
-            final Consumer<ShardedDOMDataTreeWriteTransaction> success,
+    void doSubmit(final Consumer<ShardedDOMDataTreeWriteTransaction> success,
             final BiConsumer<ShardedDOMDataTreeWriteTransaction, Throwable> failure) {
-
-        final ListenableFuture<List<Void>> listListenableFuture = Futures.allAsList(
-            idToTransaction.values().stream().map(tx -> {
-                LOG.debug("Readying tx {}", identifier);
+        LOG.debug("Readying tx {}", identifier);
+
+        final ListenableFuture<?> internalFuture;
+        switch (transactions.size()) {
+            case 0:
+                success.accept(this);
+                return;
+            case 1: {
+                final DOMDataTreeShardWriteTransaction tx = transactions.values().iterator().next();
                 tx.ready();
-                return tx.submit();
-            }).collect(Collectors.toList()));
+                internalFuture = tx.submit();
+                break;
+            }
+            default:
+                internalFuture = Futures.allAsList(transactions.values().stream().map(tx -> {
+                    tx.ready();
+                    return tx.submit();
+                }).collect(Collectors.toList()));
+        }
 
-        final SettableFuture<Void> ret = SettableFuture.create();
-        Futures.addCallback(listListenableFuture, new FutureCallback<List<Void>>() {
+        Futures.addCallback(internalFuture, new FutureCallback<Object>() {
             @Override
-            public void onSuccess(final List<Void> result) {
+            public void onSuccess(final Object result) {
                 success.accept(ShardedDOMDataTreeWriteTransaction.this);
-                ret.set(null);
             }
 
             @Override
             public void onFailure(final Throwable exp) {
                 failure.accept(ShardedDOMDataTreeWriteTransaction.this, exp);
-                ret.setException(exp);
             }
-        });
-
-        return Futures.makeChecked(ret, SUBMIT_FAILED_MAPPER);
+        }, MoreExecutors.directExecutor());
     }
 
-    void onTransactionSuccess(final Void result) {
-        future.set(result);
+    void onTransactionSuccess(final CommitInfo commitInfo) {
+        future.set(commitInfo);
     }
 
     void onTransactionFailure(final Throwable throwable) {
@@ -171,33 +174,32 @@ final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAware
     }
 
     private class DelegatingCursor implements DOMDataTreeWriteCursor {
-
+        private final Deque<PathArgument> currentArgs = new ArrayDeque<>();
         private final DOMDataTreeWriteCursor delegate;
         private final DOMDataTreeIdentifier rootPosition;
-        private final Deque<PathArgument> path = new LinkedList<>();
 
         DelegatingCursor(final DOMDataTreeWriteCursor delegate, final DOMDataTreeIdentifier rootPosition) {
-            this.delegate = Preconditions.checkNotNull(delegate);
-            this.rootPosition = Preconditions.checkNotNull(rootPosition);
-            path.addAll(rootPosition.getRootIdentifier().getPathArguments());
+            this.delegate = requireNonNull(delegate);
+            this.rootPosition = requireNonNull(rootPosition);
+            currentArgs.addAll(rootPosition.getRootIdentifier().getPathArguments());
         }
 
         @Override
-        public void enter(@Nonnull final PathArgument child) {
+        public void enter(final PathArgument child) {
             checkAvailable(child);
-            path.push(child);
             delegate.enter(child);
+            currentArgs.push(child);
         }
 
         @Override
-        public void enter(@Nonnull final PathArgument... path) {
+        public void enter(final PathArgument... path) {
             for (final PathArgument pathArgument : path) {
                 enter(pathArgument);
             }
         }
 
         @Override
-        public void enter(@Nonnull final Iterable<PathArgument> path) {
+        public void enter(final Iterable<PathArgument> path) {
             for (final PathArgument pathArgument : path) {
                 enter(pathArgument);
             }
@@ -205,21 +207,21 @@ final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAware
 
         @Override
         public void exit() {
-            path.pop();
             delegate.exit();
+            currentArgs.pop();
         }
 
         @Override
         public void exit(final int depth) {
+            delegate.exit(depth);
             for (int i = 0; i < depth; i++) {
-                path.pop();
+                currentArgs.pop();
             }
-            delegate.exit(depth);
         }
 
         @Override
         public void close() {
-            int depthEntered = path.size() - rootPosition.getRootIdentifier().getPathArguments().size();
+            int depthEntered = currentArgs.size() - rootPosition.getRootIdentifier().getPathArguments().size();
             if (depthEntered > 0) {
                 // clean up existing modification cursor in case this tx will be reused for batching
                 delegate.exit(depthEntered);
@@ -248,16 +250,11 @@ final class ShardedDOMDataTreeWriteTransaction implements DOMDataTreeCursorAware
         }
 
         void checkAvailable(final PathArgument child) {
-            path.add(child);
-            final YangInstanceIdentifier yid = YangInstanceIdentifier.create(path);
-            childBoundaries.forEach(id -> {
-                if (id.contains(yid)) {
-                    path.removeLast();
-                    throw new IllegalArgumentException("Path {" + yid + "} is not available to this cursor"
-                            + " since it's already claimed by a child producer");
-                }
-            });
-            path.removeLast();
+            layout.checkAvailable(currentArgs, child);
         }
     }
+
+    ProducerLayout getLayout() {
+        return layout;
+    }
 }