<build>
<plugins>
-
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
package org.opendaylight.controller.md.sal.dom.broker.impl;
import static com.google.common.base.Preconditions.checkState;
+
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.EnumMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public abstract class AbstractDOMDataBroker extends AbstractDOMForwardedTransactionFactory<DOMStore> implements DOMDataBroker, AutoCloseable {
+public abstract class AbstractDOMDataBroker extends AbstractDOMForwardedTransactionFactory<DOMStore> implements
+ DOMDataBroker, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(AbstractDOMDataBroker.class);
private final AtomicLong txNum = new AtomicLong();
}
if (treeChange) {
- extensions = ImmutableMap.<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension>of(DOMDataTreeChangeService.class, new DOMDataTreeChangeService() {
- @Nonnull
- @Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerDataTreeChangeListener(@Nonnull final DOMDataTreeIdentifier treeId, @Nonnull final L listener) {
- DOMStore publisher = getTxFactories().get(treeId.getDatastoreType());
- checkState(publisher != null, "Requested logical data store is not available.");
-
- return ((DOMStoreTreeChangePublisher)publisher).registerTreeChangeListener(treeId.getRootIdentifier(), listener);
- }
- });
+ extensions = ImmutableMap.<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension>of(
+ DOMDataTreeChangeService.class, new DOMDataTreeChangeService() {
+ @Nonnull
+ @Override
+ public <L extends DOMDataTreeChangeListener> ListenerRegistration<L>
+ registerDataTreeChangeListener(
+ @Nonnull final DOMDataTreeIdentifier treeId, @Nonnull final L listener) {
+ DOMStore publisher = getTxFactories().get(treeId.getDatastoreType());
+ checkState(publisher != null,
+ "Requested logical data store is not available.");
+
+ return ((DOMStoreTreeChangePublisher) publisher)
+ .registerTreeChangeListener(treeId.getRootIdentifier(), listener);
+ }
+ });
} else {
extensions = Collections.emptyMap();
}
}
@Override
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void close() {
super.close();
- if(closeable != null) {
+ if (closeable != null) {
try {
closeable.close();
- } catch(Exception e) {
+ } catch (Exception e) {
LOG.debug("Error closing instance", e);
}
}
@Override
public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store,
- final YangInstanceIdentifier path, final DOMDataChangeListener listener, final DataChangeScope triggeringScope) {
-
+ final YangInstanceIdentifier path, final DOMDataChangeListener listener,
+ final DataChangeScope triggeringScope) {
DOMStore potentialStore = getTxFactories().get(store);
checkState(potentialStore != null, "Requested logical data store is not available.");
return potentialStore.registerChangeListener(path, listener, triggeringScope);
public DOMTransactionChain createTransactionChain(final TransactionChainListener listener) {
checkNotClosed();
- final Map<LogicalDatastoreType, DOMStoreTransactionChain> backingChains = new EnumMap<>(LogicalDatastoreType.class);
+ final Map<LogicalDatastoreType, DOMStoreTransactionChain> backingChains = new EnumMap<>(
+ LogicalDatastoreType.class);
for (Entry<LogicalDatastoreType, DOMStore> entry : getTxFactories().entrySet()) {
backingChains.put(entry.getKey(), entry.getValue().createTransactionChain());
}
final long chainId = chainNum.getAndIncrement();
LOG.debug("Transactoin chain {} created with listener {}, backing store chains {}", chainId, listener,
- backingChains);
+ backingChains);
return new DOMDataBrokerTransactionChainImpl(chainId, backingChains, this, listener);
}
}
/**
* Composite DOM Transaction backed by {@link DOMStoreTransaction}.
*
+ * <p>
* Abstract base for composite transaction, which provides access only to common
* functionality as retrieval of subtransaction, close method and retrieval of
* identifier.
private final Object identifier;
/**
- *
* Creates new composite Transactions.
*
* @param identifier
/**
* Returns subtransaction associated with supplied key.
*
- * @param key
- * @return
+ * @param key key
+ * @return subtransaction
* @throws NullPointerException
* if key is null
* @throws IllegalArgumentException
return identifier;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
protected void closeSubtransactions() {
/*
* We share one exception for all failures, which are added
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
/**
- *
* Abstract composite transaction factory.
*
+ * <p>
* Provides an convenience common implementation for composite DOM Transactions,
* where subtransaction is identified by {@link LogicalDatastoreType} type and
* implementation of subtransaction is provided by
/**
* Implementations must return unique identifier for each and every call of
- * this method;
+ * this method.
*
* @return new Unique transaction identifier.
*/
* User-supplied implementation of {@link DOMDataWriteTransaction#submit()}
* for transaction.
*
+ * <p>
* Callback invoked when {@link DOMDataWriteTransaction#submit()} is invoked
* on transaction created by this factory.
*
* nothing is returned from the Future, On failure,
* the Future fails with a {@link TransactionCommitFailedException}.
*/
- protected abstract CheckedFuture<Void,TransactionCommitFailedException> submit(final DOMDataWriteTransaction transaction,
- final Collection<DOMStoreThreePhaseCommitCohort> cohorts);
+ protected abstract CheckedFuture<Void,
+ TransactionCommitFailedException>
+ submit(DOMDataWriteTransaction transaction, Collection<DOMStoreThreePhaseCommitCohort> cohorts);
/**
* Creates a new composite read-only transaction
*
+ * <p>
* Creates a new composite read-only transaction backed by one transaction
* per factory in {@link #getTxFactories()}.
*
+ * <p>
* Subtransaction for reading is selected by supplied
* {@link LogicalDatastoreType} as parameter for
- * {@link DOMDataReadOnlyTransaction#read(LogicalDatastoreType,org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)}
- * .
+ * {@link DOMDataReadOnlyTransaction#read(LogicalDatastoreType,
+ * org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)}.
*
+ * <p>
* Id of returned transaction is retrieved via
* {@link #newTransactionIdentifier()}.
*
* <p>
* Implementation of composite Write-only transaction is following:
*
+ * <p>
* <ul><li>
- * {@link DOMDataWriteTransaction#put(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMDataWriteTransaction#put(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
* - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreWriteTransaction#write(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMStoreWriteTransaction#write(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,
+ * org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
* is invoked on selected subtransaction.
* </li><li>
- * {@link DOMDataWriteTransaction#merge(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMDataWriteTransaction#merge(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
* - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreWriteTransaction#merge(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMStoreWriteTransaction#merge(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,
+ * org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
* is invoked on selected subtransaction.
* </li><li>
- * {@link DOMDataWriteTransaction#delete(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)}
- * - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreWriteTransaction#delete(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)} is invoked on
+ * {@link DOMDataWriteTransaction#delete(LogicalDatastoreType, Path)}
+ * {@link DOMStoreWriteTransaction#delete(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)} is
+ * invoked on
* selected subtransaction.
* </li><li> {@link DOMDataWriteTransaction#commit()} - results in invoking
* {@link DOMStoreWriteTransaction#ready()}, gathering all resulting cohorts
* </li>
* </ul>
*
+ * <p>
* Id of returned transaction is generated via
* {@link #newTransactionIdentifier()}.
*
- * @return New composite write-only transaction associated with this
- * factory.
+ * @return New composite write-only transaction associated with this factory.
*/
public final DOMDataWriteTransaction newWriteOnlyTransaction() {
checkNotClosed();
* Creates a new composite write-only transaction
*
* <p>
- * Creates a new composite write-only transaction backed by one write-only
- * transaction per factory in {@link #getTxFactories()}.
+ * Creates a new composite write-only transaction backed by one write-only transaction per factory in
+ * {@link #getTxFactories()}.
+ *
* <p>
* Implementation of composite Write-only transaction is following:
*
+ * <p>
* <ul>
* <li>
- * {@link DOMDataReadTransaction#read(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)}
+ * {@link org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction#read(LogicalDatastoreType,
+ * YangInstanceIdentifier)}
* - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreReadTransaction#read(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)} is invoked on
- * selected subtransaction.
+ * {@link DOMStoreReadTransaction#read(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)} is invoked
+ * on selected subtransaction.
* <li>
- * {@link DOMDataWriteTransaction#put(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMDataWriteTransaction#put(LogicalDatastoreType,
+ * org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,
+ * org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
* - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreWriteTransaction#write(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMStoreWriteTransaction#write(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,
+ * org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
* is invoked on selected subtransaction.
* <li>
- * {@link DOMDataWriteTransaction#merge(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMDataWriteTransaction#merge(LogicalDatastoreType,
+ * org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,
+ * org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
* - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreWriteTransaction#merge(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
+ * {@link DOMStoreWriteTransaction#merge(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier,
+ * org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode)}
* is invoked on selected subtransaction.
* <li>
- * {@link DOMDataWriteTransaction#delete(LogicalDatastoreType, org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)}
+ * {@link DOMDataWriteTransaction#delete(LogicalDatastoreType,
+ * org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)}
* - backing subtransaction is selected by {@link LogicalDatastoreType},
- * {@link DOMStoreWriteTransaction#delete(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)} is invoked on
+ * {@link DOMStoreWriteTransaction#delete(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)} is
+ * invoked on
* selected subtransaction.
* <li> {@link DOMDataWriteTransaction#commit()} - results in invoking
* {@link DOMStoreWriteTransaction#ready()}, gathering all resulting cohorts
* <li>
* </ul>
*
+ * <p>
* Id of returned transaction is generated via
* {@link #newTransactionIdentifier()}.
*
- * @return New composite read-write transaction associated with this
- * factory.
+ * @return New composite read-write transaction associated with this factory.
*/
public final DOMDataReadWriteTransaction newReadWriteTransaction() {
checkNotClosed();
return impls.containsKey(contextReference);
}
- final Set<YangInstanceIdentifier> registeredIdentifiers(final DOMRpcAvailabilityListener l) {
- return Maps.filterValues(impls, list -> list.stream().anyMatch(l::acceptsImplementation)).keySet();
+ final Set<YangInstanceIdentifier> registeredIdentifiers(final DOMRpcAvailabilityListener listener) {
+ return Maps.filterValues(impls, list -> list.stream().anyMatch(listener::acceptsImplementation)).keySet();
}
/**
+ * Adds an entry to the DOM RPC routing table.
*
- * @param implementation
+ * @param implementation RPC implementation
* @param newRpcs List of new RPCs, must be mutable
- * @return
*/
final AbstractDOMRpcRoutingTableEntry add(final DOMRpcImplementation implementation,
final List<YangInstanceIdentifier> newRpcs) {
vb.put(ve);
}
}
- for(final YangInstanceIdentifier ii : newRpcs) {
+ for (final YangInstanceIdentifier ii : newRpcs) {
final List<DOMRpcImplementation> impl = new ArrayList<>(1);
impl.add(implementation);
vb.put(ii, impl);
return v.isEmpty() ? null : newInstance(v);
}
- protected abstract CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final NormalizedNode<?, ?> input);
- protected abstract AbstractDOMRpcRoutingTableEntry newInstance(final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls);
+ protected abstract CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(NormalizedNode<?, ?> input);
+
+ protected abstract AbstractDOMRpcRoutingTableEntry newInstance(
+ Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls);
}
private final DurationStatisticsTracker commitStatTracker;
private final DOMDataWriteTransaction tx;
- public CommitCoordinationTask(final DOMDataWriteTransaction transaction,
+ CommitCoordinationTask(final DOMDataWriteTransaction transaction,
final Collection<DOMStoreThreePhaseCommitCohort> cohorts,
final DurationStatisticsTracker commitStatTracker) {
this.tx = Preconditions.checkNotNull(transaction, "transaction must not be null");
}
/**
- *
* Invokes canCommit on underlying cohorts and blocks till
* all results are returned.
*
+ * <p>
* Valid state transition is from SUBMITTED to CAN_COMMIT,
* if currentPhase is not SUBMITTED throws IllegalStateException.
*
}
/**
- *
* Invokes canCommit on underlying cohorts and returns composite future
* which will contains {@link Boolean#TRUE} only and only if
* all cohorts returned true.
*
+ * <p>
* Valid state transition is from SUBMITTED to CAN_COMMIT,
* if currentPhase is not SUBMITTED throws IllegalStateException.
*
*/
private ListenableFuture<?>[] canCommitAll() {
final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohorts.size()];
- int i = 0;
+ int index = 0;
for (final DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.canCommit();
+ ops[index++] = cohort.canCommit();
}
return ops;
}
/**
- *
* Invokes preCommit on underlying cohorts and blocks till
* all results are returned.
*
+ * <p>
* Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
* state is not CAN_COMMIT
* throws IllegalStateException.
private void preCommitBlocking() throws TransactionCommitFailedException {
final ListenableFuture<?>[] preCommitFutures = preCommitAll();
try {
- for(final ListenableFuture<?> future : preCommitFutures) {
+ for (final ListenableFuture<?> future : preCommitFutures) {
future.get();
}
} catch (InterruptedException | ExecutionException e) {
}
/**
- *
* Invokes preCommit on underlying cohorts and returns future
* which will complete once all preCommit on cohorts completed or
* failed.
*
- *
+ * <p>
* Valid state transition is from CAN_COMMIT to PRE_COMMIT, if current
* state is not CAN_COMMIT
* throws IllegalStateException.
*/
private ListenableFuture<?>[] preCommitAll() {
final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohorts.size()];
- int i = 0;
+ int index = 0;
for (final DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.preCommit();
+ ops[index++] = cohort.preCommit();
}
return ops;
}
/**
- *
* Invokes commit on underlying cohorts and blocks till
* all results are returned.
*
+ * <p>
* Valid state transition is from PRE_COMMIT to COMMIT, if not throws
* IllegalStateException.
*
private void commitBlocking() throws TransactionCommitFailedException {
final ListenableFuture<?>[] commitFutures = commitAll();
try {
- for(final ListenableFuture<?> future : commitFutures) {
+ for (final ListenableFuture<?> future : commitFutures) {
future.get();
}
} catch (InterruptedException | ExecutionException e) {
}
/**
- *
* Invokes commit on underlying cohorts and returns future which
* completes
* once all commits on cohorts are completed.
*
+ * <p>
* Valid state transition is from PRE_COMMIT to COMMIT, if not throws
* IllegalStateException
*
*/
private ListenableFuture<?>[] commitAll() {
final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohorts.size()];
- int i = 0;
+ int index = 0;
for (final DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.commit();
+ ops[index++] = cohort.commit();
}
return ops;
}
/**
* Aborts transaction.
*
+ * <p>
* Invokes {@link DOMStoreThreePhaseCommitCohort#abort()} on all
* cohorts, blocks
* for all results. If any of the abort failed throws
* IllegalStateException,
* which will contains originalCause as suppressed Exception.
*
+ * <p>
* If aborts we're successful throws supplied exception
*
* @param originalCause
* @throws IllegalStateException
* if abort failed.
*/
- private void abortBlocking(final TransactionCommitFailedException originalCause) throws TransactionCommitFailedException {
+ private void abortBlocking(
+ final TransactionCommitFailedException originalCause) throws TransactionCommitFailedException {
Exception cause = originalCause;
try {
abortAsyncAll().get();
private ListenableFuture<Void> abortAsyncAll() {
final ListenableFuture<?>[] ops = new ListenableFuture<?>[cohorts.size()];
- int i = 0;
+ int index = 0;
for (final DOMStoreThreePhaseCommitCohort cohort : cohorts) {
- ops[i++] = cohort.abort();
+ ops[index++] = cohort.abort();
}
/*
import org.slf4j.LoggerFactory;
/**
- * NormalizedNode implementation of {@link org.opendaylight.controller.md.sal.common.api.data.TransactionChain} which is backed
+ * NormalizedNode implementation of {@link org.opendaylight.controller.md.sal.common.api.data.TransactionChain} which
+ * is backed
* by several {@link DOMStoreTransactionChain} differentiated by provided
* {@link org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType} type.
- *
*/
-final class DOMDataBrokerTransactionChainImpl extends AbstractDOMForwardedTransactionFactory<DOMStoreTransactionChain>
- implements DOMTransactionChain {
+final class DOMDataBrokerTransactionChainImpl extends
+ AbstractDOMForwardedTransactionFactory<DOMStoreTransactionChain> implements DOMTransactionChain {
private enum State {
- RUNNING,
- CLOSING,
- CLOSED,
- FAILED,
+ RUNNING, CLOSING, CLOSED, FAILED,
}
- private static final AtomicIntegerFieldUpdater<DOMDataBrokerTransactionChainImpl> COUNTER_UPDATER =
- AtomicIntegerFieldUpdater.newUpdater(DOMDataBrokerTransactionChainImpl.class, "counter");
- private static final AtomicReferenceFieldUpdater<DOMDataBrokerTransactionChainImpl, State> STATE_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(DOMDataBrokerTransactionChainImpl.class, State.class, "state");
+ private static final AtomicIntegerFieldUpdater<DOMDataBrokerTransactionChainImpl> COUNTER_UPDATER
+ = AtomicIntegerFieldUpdater.newUpdater(DOMDataBrokerTransactionChainImpl.class, "counter");
+ private static final AtomicReferenceFieldUpdater<DOMDataBrokerTransactionChainImpl, State> STATE_UPDATER
+ = AtomicReferenceFieldUpdater.newUpdater(DOMDataBrokerTransactionChainImpl.class, State.class, "state");
private static final Logger LOG = LoggerFactory.getLogger(DOMDataBrokerTransactionChainImpl.class);
private final AtomicLong txNum = new AtomicLong();
private final AbstractDOMDataBroker broker;
private volatile int counter = 0;
/**
+ * DOMDataBrokerTransactionChainImpl constructor.
*
- * @param chainId
- * ID of transaction chain
- * @param chains
- * Backing {@link DOMStoreTransactionChain}s.
- * @param broker
- * Commit Coordinator which should be used to coordinate commits
- * of transaction
- * produced by this chain.
- * @param listener
- * Listener, which listens on transaction chain events.
- * @throws NullPointerException
- * If any of arguments is null.
+ * @param chainId ID of transaction chain
+ * @param chains Backing {@link DOMStoreTransactionChain}s.
+ * @param broker Commit Coordinator which should be used to coordinate commits
+ * of transaction
+ * produced by this chain.
+ * @param listener Listener, which listens on transaction chain events.
+ * @throws NullPointerException If any of arguments is null.
*/
- public DOMDataBrokerTransactionChainImpl(final long chainId,
- final Map<LogicalDatastoreType, DOMStoreTransactionChain> chains,
- final AbstractDOMDataBroker broker, final TransactionChainListener listener) {
+ DOMDataBrokerTransactionChainImpl(final long chainId,
+ final Map<LogicalDatastoreType, DOMStoreTransactionChain> chains,
+ final AbstractDOMDataBroker broker,
+ final TransactionChainListener listener) {
super(chains);
this.chainId = chainId;
this.broker = Preconditions.checkNotNull(broker);
}
@Override
- public CheckedFuture<Void, TransactionCommitFailedException> submit(
- final DOMDataWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
+ public CheckedFuture<Void, TransactionCommitFailedException> submit(final DOMDataWriteTransaction transaction,
+ final
+ Collection<DOMStoreThreePhaseCommitCohort>
+ cohorts) {
checkNotFailed();
checkNotClosed();
}
@Override
- public void onFailure(final Throwable t) {
- transactionFailed(transaction, t);
+ public void onFailure(final Throwable throwable) {
+ transactionFailed(transaction, throwable);
}
});
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
/**
- *
* Read-Write Transaction, which is composed of several
* {@link DOMStoreReadWriteTransaction} transactions. Subtransaction is selected by
* {@link LogicalDatastoreType} type parameter in:
* <li>{@link #merge(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
* </ul>
* {@link #commit()} will result in invocation of
- * {@link DOMDataCommitImplementation#submit(org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction, Iterable)}
- * invocation with all {@link org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort} for underlying
- * transactions.
+ * {@link DOMDataCommitImplementation#submit(org.opendaylight.controller.md.sal.dom
+ * .api.DOMDataWriteTransaction, Iterable)}
+ * invocation with all {@link org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort}
+ * for underlying transactions.
*
*/
-final class DOMForwardedReadWriteTransaction extends DOMForwardedWriteTransaction<DOMStoreReadWriteTransaction> implements DOMDataReadWriteTransaction {
+final class DOMForwardedReadWriteTransaction extends DOMForwardedWriteTransaction<DOMStoreReadWriteTransaction>
+ implements DOMDataReadWriteTransaction {
protected DOMForwardedReadWriteTransaction(final Object identifier,
final Map<LogicalDatastoreType, DOMStoreReadWriteTransaction> backingTxs,
final AbstractDOMForwardedTransactionFactory<?> commitImpl) {
* {@link DOMStoreWriteTransaction} transactions. A sub-transaction is selected by
* {@link LogicalDatastoreType} type parameter in:
*
+ * <p>
* <ul>
* <li>{@link #put(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
* <li>{@link #delete(LogicalDatastoreType, YangInstanceIdentifier)}
* <li>{@link #merge(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
* </ul>
+ *
* <p>
* {@link #commit()} will result in invocation of
- * {@link DOMDataCommitImplementation#submit(org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction, Iterable)}
- * invocation with all {@link org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort} for underlying
- * transactions.
+ * {@link DOMDataCommitImplementation#submit(org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction,
+ * Iterable)} invocation with all {@link org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort}
+ * for underlying transactions.
*
* @param <T> Subtype of {@link DOMStoreWriteTransaction} which is used as
* subtransaction.
class DOMForwardedWriteTransaction<T extends DOMStoreWriteTransaction> extends
AbstractDOMForwardedCompositeTransaction<LogicalDatastoreType, T> implements DOMDataWriteTransaction {
@SuppressWarnings("rawtypes")
- private static final AtomicReferenceFieldUpdater<DOMForwardedWriteTransaction, AbstractDOMForwardedTransactionFactory> IMPL_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(DOMForwardedWriteTransaction.class, AbstractDOMForwardedTransactionFactory.class, "commitImpl");
+ private static final AtomicReferenceFieldUpdater<DOMForwardedWriteTransaction,
+ AbstractDOMForwardedTransactionFactory>
+ IMPL_UPDATER = AtomicReferenceFieldUpdater
+ .newUpdater(DOMForwardedWriteTransaction.class, AbstractDOMForwardedTransactionFactory.class, "commitImpl");
@SuppressWarnings("rawtypes")
- private static final AtomicReferenceFieldUpdater<DOMForwardedWriteTransaction, Future> FUTURE_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(DOMForwardedWriteTransaction.class, Future.class, "commitFuture");
+ private static final AtomicReferenceFieldUpdater<DOMForwardedWriteTransaction, Future> FUTURE_UPDATER
+ = AtomicReferenceFieldUpdater.newUpdater(DOMForwardedWriteTransaction.class, Future.class, "commitFuture");
private static final Logger LOG = LoggerFactory.getLogger(DOMForwardedWriteTransaction.class);
private static final Future<?> CANCELLED_FUTURE = Futures.immediateCancelledFuture();
* set appropriately on {@link #submit()} and {@link #cancel()} via
* {@link AtomicReferenceFieldUpdater#lazySet(Object, Object)}.
*
+ * <p>
* Lazy set is safe for use because it is only referenced to in the
* {@link #cancel()} slow path, where we will busy-wait for it. The
* fast path gets the benefit of a store-store barrier instead of the
*/
private volatile Future<?> commitFuture;
- protected DOMForwardedWriteTransaction(final Object identifier,
- final Map<LogicalDatastoreType, T> backingTxs, final AbstractDOMForwardedTransactionFactory<?> commitImpl) {
+ protected DOMForwardedWriteTransaction(final Object identifier, final Map<LogicalDatastoreType, T> backingTxs,
+ final AbstractDOMForwardedTransactionFactory<?> commitImpl) {
super(identifier, backingTxs);
this.commitImpl = Preconditions.checkNotNull(commitImpl, "commitImpl must not be null.");
}
@Override
- public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
checkRunning(commitImpl);
getSubtransaction(store).write(path, data);
}
}
@Override
- public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
checkRunning(commitImpl);
getSubtransaction(store).merge(path, data);
}
* Joint implementation of {@link DOMNotificationPublishService} and {@link DOMNotificationService}. Provides
* routing of notifications from publishers to subscribers.
*
+ * <p>
* Internal implementation works by allocating a two-handler Disruptor. The first handler delivers notifications
* to subscribed listeners and the second one notifies whoever may be listening on the returned future. Registration
* state tracking is performed by a simple immutable multimap -- when a registration or unregistration occurs we
* re-generate the entire map from scratch and set it atomically. While registrations/unregistrations synchronize
* on this instance, notifications do not take any locks here.
*
- * The fully-blocking {@link #publish(long, DOMNotification, Collection)} and non-blocking {@link #offerNotification(DOMNotification)}
- * are realized using the Disruptor's native operations. The bounded-blocking {@link #offerNotification(DOMNotification, long, TimeUnit)}
+ * <p>
+ * The fully-blocking {@link #publish(long, DOMNotification, Collection)} and non-blocking
+ * {@link #offerNotification(DOMNotification)}
+ * are realized using the Disruptor's native operations. The bounded-blocking
+ * {@link #offerNotification(DOMNotification, long, TimeUnit)}
* is realized by arming a background wakeup interrupt.
*/
public final class DOMNotificationRouter implements AutoCloseable, DOMNotificationPublishService,
private static final Logger LOG = LoggerFactory.getLogger(DOMNotificationRouter.class);
private static final ListenableFuture<Void> NO_LISTENERS = Futures.immediateFuture(null);
- private static final WaitStrategy DEFAULT_STRATEGY = PhasedBackoffWaitStrategy.withLock(1L, 30L, TimeUnit.MILLISECONDS);
- private static final EventHandler<DOMNotificationRouterEvent> DISPATCH_NOTIFICATIONS =
- (event, sequence, endOfBatch) -> event.deliverNotification();
- private static final EventHandler<DOMNotificationRouterEvent> NOTIFY_FUTURE =
- (event, sequence, endOfBatch) -> event.setFuture();
+ private static final WaitStrategy DEFAULT_STRATEGY = PhasedBackoffWaitStrategy
+ .withLock(1L, 30L, TimeUnit.MILLISECONDS);
+ private static final EventHandler<DOMNotificationRouterEvent> DISPATCH_NOTIFICATIONS
+ = (event, sequence, endOfBatch) -> event.deliverNotification();
+ private static final EventHandler<DOMNotificationRouterEvent> NOTIFY_FUTURE = (event, sequence, endOfBatch) -> event
+ .setFuture();
private final Disruptor<DOMNotificationRouterEvent> disruptor;
private final ExecutorService executor;
- private volatile Multimap<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> listeners = ImmutableMultimap.of();
- private final ListenerRegistry<DOMNotificationSubscriptionListener> subscriptionListeners = ListenerRegistry.create();
+ private volatile Multimap<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> listeners
+ = ImmutableMultimap.of();
+ private final ListenerRegistry<DOMNotificationSubscriptionListener> subscriptionListeners = ListenerRegistry
+ .create();
@SuppressWarnings("unchecked")
private DOMNotificationRouter(final ExecutorService executor, final int queueDepth, final WaitStrategy strategy) {
this.executor = Preconditions.checkNotNull(executor);
- disruptor = new Disruptor<>(DOMNotificationRouterEvent.FACTORY, queueDepth, executor, ProducerType.MULTI, strategy);
+ disruptor = new Disruptor<>(DOMNotificationRouterEvent.FACTORY, queueDepth, executor, ProducerType.MULTI,
+ strategy);
disruptor.handleEventsWith(DISPATCH_NOTIFICATIONS);
disruptor.after(DISPATCH_NOTIFICATIONS).handleEventsWith(NOTIFY_FUTURE);
disruptor.start();
return new DOMNotificationRouter(executor, queueDepth, DEFAULT_STRATEGY);
}
- public static DOMNotificationRouter create(final int queueDepth, final long spinTime, final long parkTime, final TimeUnit unit) {
+ public static DOMNotificationRouter create(final int queueDepth, final long spinTime, final long parkTime,
+ final TimeUnit unit) {
Preconditions.checkArgument(Long.lowestOneBit(queueDepth) == Long.highestOneBit(queueDepth),
- "Queue depth %s is not power-of-two", queueDepth);
+ "Queue depth %s is not power-of-two", queueDepth);
final ExecutorService executor = Executors.newCachedThreadPool();
final WaitStrategy strategy = PhasedBackoffWaitStrategy.withLock(spinTime, parkTime, unit);
}
@Override
- public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
+ public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+ final T listener, final Collection<SchemaPath> types) {
final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
@Override
protected void removeRegistration() {
};
if (!types.isEmpty()) {
- final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
+ final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap
+ .builder();
b.putAll(listeners);
for (final SchemaPath t : types) {
}
@Override
- public <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final SchemaPath... types) {
+ public <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener,
+ final
+ SchemaPath...
+ types) {
return registerNotificationListener(listener, Arrays.asList(types));
}
/**
- * Swaps registered listeners and triggers notification update
+ * Swaps registered listeners and triggers notification update.
*
- * @param newListeners
+ * @param newListeners listeners
*/
private void replaceListeners(
final Multimap<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> newListeners) {
notifyListenerTypesChanged(newListeners.keySet());
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void notifyListenerTypesChanged(final Set<SchemaPath> typesAfter) {
- final List<ListenerRegistration<DOMNotificationSubscriptionListener>> listenersAfter =ImmutableList.copyOf(subscriptionListeners.getListeners());
+ final List<ListenerRegistration<DOMNotificationSubscriptionListener>> listenersAfter = ImmutableList
+ .copyOf(subscriptionListeners.getListeners());
executor.submit(() -> {
for (final ListenerRegistration<DOMNotificationSubscriptionListener> subListener : listenersAfter) {
try {
return subscriptionListeners.registerWithType(listener);
}
- private ListenableFuture<Void> publish(final long seq, final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
+ private ListenableFuture<Void> publish(final long seq, final DOMNotification notification,
+ final Collection<ListenerRegistration<? extends DOMNotificationListener>>
+ subscribers) {
final DOMNotificationRouterEvent event = disruptor.get(seq);
final ListenableFuture<Void> future = event.initialize(notification, subscribers);
disruptor.getRingBuffer().publish(seq);
@Override
public ListenableFuture<?> putNotification(final DOMNotification notification) throws InterruptedException {
- final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
+ final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners
+ .get(notification.getType());
if (subscribers.isEmpty()) {
return NO_LISTENERS;
}
return publish(seq, notification, subscribers);
}
- private ListenableFuture<?> tryPublish(final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
+ private ListenableFuture<?> tryPublish(final DOMNotification notification,
+ final Collection<ListenerRegistration<? extends DOMNotificationListener>>
+ subscribers) {
final long seq;
try {
- seq = disruptor.getRingBuffer().tryNext();
+ seq = disruptor.getRingBuffer().tryNext();
} catch (final InsufficientCapacityException e) {
return DOMNotificationPublishService.REJECTED;
}
@Override
public ListenableFuture<?> offerNotification(final DOMNotification notification) {
- final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
+ final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners
+ .get(notification.getType());
if (subscribers.isEmpty()) {
return NO_LISTENERS;
}
@Override
public ListenableFuture<?> offerNotification(final DOMNotification notification, final long timeout,
- final TimeUnit unit) throws InterruptedException {
- final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners.get(notification.getType());
+ final TimeUnit unit) throws InterruptedException {
+ final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers = listeners
+ .get(notification.getType());
if (subscribers.isEmpty()) {
return NO_LISTENERS;
}
// Hidden on purpose, initialized in initialize()
}
- ListenableFuture<Void> initialize(final DOMNotification notification, final Collection<ListenerRegistration<? extends DOMNotificationListener>> subscribers) {
+ ListenableFuture<Void> initialize(final DOMNotification notification,
+ final Collection<ListenerRegistration<? extends DOMNotificationListener>>
+ subscribers) {
this.notification = Preconditions.checkNotNull(notification);
this.subscribers = Preconditions.checkNotNull(subscribers);
this.future = SettableFuture.create();
for (ListenerRegistration<? extends DOMNotificationListener> r : subscribers) {
final DOMNotificationListener listener = r.getInstance();
if (listener != null) {
- try {
- LOG.trace("Notifying listener {}", listener);
- listener.onNotification(notification);
- LOG.trace("Listener notification completed");
- } catch (Exception e) {
- LOG.error("Delivery of notification {} caused an error in listener {}", notification, listener, e);
- }
+ LOG.trace("Notifying listener {}", listener);
+ listener.onNotification(notification);
+ LOG.trace("Listener notification completed");
}
}
LOG.trace("Delivery completed");
return registerRpcImplementation(implementation, ImmutableSet.copyOf(rpcs));
}
- private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation,
- final Set<DOMRpcIdentifier> rpcs) {
- final DOMRpcRoutingTable oldTable = routingTable;
- final DOMRpcRoutingTable newTable = oldTable.remove(implementation, rpcs);
- routingTable = newTable;
-
- listenerNotifier.execute(() -> notifyRemoved(newTable, implementation));
- }
-
@Override
public synchronized <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
final T implementation, final Set<DOMRpcIdentifier> rpcs) {
};
}
+ private synchronized void removeRpcImplementation(final DOMRpcImplementation implementation,
+ final Set<DOMRpcIdentifier> rpcs) {
+ final DOMRpcRoutingTable oldTable = routingTable;
+ final DOMRpcRoutingTable newTable = oldTable.remove(implementation, rpcs);
+ routingTable = newTable;
+
+ listenerNotifier.execute(() -> notifyRemoved(newTable, implementation));
+ }
+
@Override
public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(final SchemaPath type,
- final NormalizedNode<?, ?> input) {
+ final NormalizedNode<?, ?> input) {
return routingTable.invokeRpc(type, input);
}
listenerNotifier.shutdown();
}
- private static final class Registration<T extends DOMRpcAvailabilityListener>
- extends AbstractListenerRegistration<T> {
+ private static final class Registration<T extends DOMRpcAvailabilityListener> extends
+ AbstractListenerRegistration<T> {
private final DOMRpcRouter router;
private Map<SchemaPath, Set<YangInstanceIdentifier>> prevRpcs;
Registration(final DOMRpcRouter router, final T listener,
- final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs) {
+ final Map<SchemaPath, Set<YangInstanceIdentifier>> rpcs) {
super(Preconditions.checkNotNull(listener));
this.router = Preconditions.checkNotNull(router);
this.prevRpcs = Preconditions.checkNotNull(rpcs);
for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnRight().entrySet()) {
added.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
}
- for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering().entrySet()) {
+ for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering()
+ .entrySet()) {
for (YangInstanceIdentifier i : Sets.difference(e.getValue().rightValue(), e.getValue().leftValue())) {
added.add(DOMRpcIdentifier.create(e.getKey(), i));
}
for (Entry<SchemaPath, Set<YangInstanceIdentifier>> e : diff.entriesOnlyOnLeft().entrySet()) {
removed.addAll(Collections2.transform(e.getValue(), i -> DOMRpcIdentifier.create(e.getKey(), i)));
}
- for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering().entrySet()) {
+ for (Entry<SchemaPath, ValueDifference<Set<YangInstanceIdentifier>>> e : diff.entriesDiffering()
+ .entrySet()) {
for (YangInstanceIdentifier i : Sets.difference(e.getValue().leftValue(), e.getValue().rightValue())) {
removed.add(DOMRpcIdentifier.create(e.getKey(), i));
}
private final Map<SchemaPath, AbstractDOMRpcRoutingTableEntry> rpcs;
private final SchemaContext schemaContext;
- private DOMRpcRoutingTable(final Map<SchemaPath, AbstractDOMRpcRoutingTableEntry> rpcs, final SchemaContext schemaContext) {
+ private DOMRpcRoutingTable(final Map<SchemaPath, AbstractDOMRpcRoutingTableEntry> rpcs,
+ final SchemaContext schemaContext) {
this.rpcs = Preconditions.checkNotNull(rpcs);
this.schemaContext = schemaContext;
}
return contexts != null && contexts.containsContext(input.getContextReference());
}
- Map<SchemaPath, Set<YangInstanceIdentifier>> getRpcs(final DOMRpcAvailabilityListener l) {
+ Map<SchemaPath, Set<YangInstanceIdentifier>> getRpcs(final DOMRpcAvailabilityListener listener) {
final Map<SchemaPath, Set<YangInstanceIdentifier>> ret = new HashMap<>(rpcs.size());
for (Entry<SchemaPath, AbstractDOMRpcRoutingTableEntry> e : rpcs.entrySet()) {
- final Set<YangInstanceIdentifier> ids = e.getValue().registeredIdentifiers(l);
+ final Set<YangInstanceIdentifier> ids = e.getValue().registeredIdentifiers(listener);
if (!ids.isEmpty()) {
ret.put(e.getKey(), ids);
}
final class GlobalDOMRpcRoutingTableEntry extends AbstractDOMRpcRoutingTableEntry {
private final DOMRpcIdentifier rpcId;
- private GlobalDOMRpcRoutingTableEntry(final DOMRpcIdentifier rpcId, final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ private GlobalDOMRpcRoutingTableEntry(final DOMRpcIdentifier rpcId,
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
super(rpcId.getType(), impls);
this.rpcId = Preconditions.checkNotNull(rpcId);
}
// We do not need the RpcDefinition, but this makes sure we do not
// forward something we don't know to be an RPC.
- GlobalDOMRpcRoutingTableEntry(final RpcDefinition def, final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ GlobalDOMRpcRoutingTableEntry(final RpcDefinition def,
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
super(def.getPath(), impls);
this.rpcId = DOMRpcIdentifier.create(def.getPath());
}
}
@Override
- protected GlobalDOMRpcRoutingTableEntry newInstance(final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ protected GlobalDOMRpcRoutingTableEntry newInstance(
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
return new GlobalDOMRpcRoutingTableEntry(rpcId, impls);
}
}
\ No newline at end of file
/**
* An implementation of a {@link DOMDataBroker}, which forwards most requests to a delegate.
*
+ * <p>
* Its interpretation of the API contract is somewhat looser, specifically it does not
* guarantee transaction ordering between transactions allocated directly from the broker
* and its transaction chains.
*/
-public final class PingPongDataBroker extends ForwardingDOMDataBroker implements AutoCloseable, DOMDataTreeChangeService {
+public final class PingPongDataBroker extends ForwardingDOMDataBroker implements AutoCloseable,
+ DOMDataTreeChangeService {
private final DOMDataBroker delegate;
/**
}
@Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerDataTreeChangeListener(final DOMDataTreeIdentifier treeId, final L listener) {
- final DOMDataTreeChangeService treeService =
- (DOMDataTreeChangeService) delegate.getSupportedExtensions().get(DOMDataTreeChangeService.class);
+ public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerDataTreeChangeListener(
+ final DOMDataTreeIdentifier treeId, final L listener) {
+ final DOMDataTreeChangeService treeService = (DOMDataTreeChangeService) delegate.getSupportedExtensions()
+ .get(DOMDataTreeChangeService.class);
if (treeService != null) {
return treeService.registerDataTreeChangeListener(treeId, listener);
}
* {@link java.util.concurrent.Future}.
*/
final class PingPongFuture extends AbstractCheckedFuture<Void, TransactionCommitFailedException> {
- protected PingPongFuture(final ListenableFuture<Void> delegate) {
- super(delegate);
- }
+ protected PingPongFuture(final ListenableFuture<Void> delegate) {
+ super(delegate);
+ }
- @Override
- protected TransactionCommitFailedException mapException(final Exception e) {
- if (e.getCause() instanceof TransactionCommitFailedException){
- return (TransactionCommitFailedException) e.getCause();
- } else {
- return new TransactionCommitFailedException(e.getMessage(), e.getCause());
+ @Override
+ protected TransactionCommitFailedException mapException(final Exception exception) {
+ if (exception.getCause() instanceof TransactionCommitFailedException) {
+ return (TransactionCommitFailedException) exception.getCause();
+ } else {
+ return new TransactionCommitFailedException(exception.getMessage(), exception.getCause());
+ }
}
- }
}
}
@Override
- public void onFailure(final Throwable t) {
- future.setException(t);
+ public void onFailure(final Throwable throwable) {
+ future.setException(throwable);
}
void recordFrontendTransaction(final DOMDataReadWriteTransaction tx) {
* the committing transaction completes successfully, the scratch transaction
* is enqueued as soon as it is ready.
*
+ * <p>
* This mode of operation means that there is no inherent isolation between
* the front-end transactions and transactions cannot be reasonably cancelled.
*
+ * <p>
* It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()}
* counts as an outstanding transaction and the user may not allocate multiple
* read-only transactions at the same time.
* This updater is used to manipulate the "ready" transaction. We perform only atomic
* get-and-set on it.
*/
- private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "readyTx");
+ private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> READY_UPDATER
+ = AtomicReferenceFieldUpdater
+ .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "readyTx");
private volatile PingPongTransaction readyTx;
/**
* us. We perform on compare-and-swap to ensure we properly detect when a user is
* attempting to allocated multiple transactions concurrently.
*/
- private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
+ private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> LOCKED_UPDATER
+ = AtomicReferenceFieldUpdater
+ .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "lockedTx");
private volatile PingPongTransaction lockedTx;
/**
* This updater is used to manipulate the "inflight" transaction. There can be at most
* one of these at any given time. We perform only compare-and-swap on these.
*/
- private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
+ private static final AtomicReferenceFieldUpdater<PingPongTransactionChain, PingPongTransaction> INFLIGHT_UPDATER
+ = AtomicReferenceFieldUpdater
+ .newUpdater(PingPongTransactionChain.class, PingPongTransaction.class, "inflightTx");
private volatile PingPongTransaction inflightTx;
PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
this.delegate = broker.createTransactionChain(new TransactionChainListener() {
@Override
public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
- final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+ final AsyncTransaction<?, ?> transaction, final Throwable cause) {
LOG.debug("Transaction chain {} reported failure in {}", chain, transaction, cause);
delegateFailed(chain, cause);
}
Preconditions.checkState(shutdownTx == null, "Transaction chain %s has been shut down", this);
if (deadTx != null) {
- throw new IllegalStateException(String.format(
- "Transaction chain %s has failed due to transaction %s being canceled", this, deadTx.getKey()),
- deadTx.getValue());
+ throw new IllegalStateException(
+ String.format("Transaction chain %s has failed due to transaction %s being canceled", this,
+ deadTx.getKey()), deadTx.getValue());
}
final DOMDataReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
if (!LOCKED_UPDATER.compareAndSet(this, null, newTx)) {
delegateTx.cancel();
- throw new IllegalStateException(String.format("New transaction %s raced with transaction %s", newTx, lockedTx));
+ throw new IllegalStateException(
+ String.format("New transaction %s raced with transaction %s", newTx, lockedTx));
}
return newTx;
if (!LOCKED_UPDATER.compareAndSet(this, null, oldTx)) {
// Ouch. Delegate chain has not detected a duplicate transaction allocation. This is the best we can do.
oldTx.getTransaction().cancel();
- throw new IllegalStateException(String.format("Reusable transaction %s raced with transaction %s", oldTx, lockedTx));
+ throw new IllegalStateException(
+ String.format("Reusable transaction %s raced with transaction %s", oldTx, lockedTx));
}
return oldTx;
}
@Override
- public void onFailure(final Throwable t) {
- transactionFailed(tx, t);
+ public void onFailure(final Throwable throwable) {
+ transactionFailed(tx, throwable);
}
}, MoreExecutors.directExecutor());
}
processNextTransaction(tx);
}
- void transactionFailed(final PingPongTransaction tx, final Throwable t) {
- LOG.debug("Transaction {} failed", tx, t);
+ void transactionFailed(final PingPongTransaction tx, final Throwable throwable) {
+ LOG.debug("Transaction {} failed", tx, throwable);
- tx.onFailure(t);
+ tx.onFailure(throwable);
processNextTransaction(tx);
}
* and return false for everything else. Cancelling such a transaction will result in all transactions in the
* batch to be cancelled.
*
- * @param tx Backend shared transaction
- * @param frontendTx
- * @param isOpen indicator whether the transaction was already closed
+ * @param tx Backend shared transaction
+ * @param frontendTx transaction
+ * @param isOpen indicator whether the transaction was already closed
*/
synchronized void cancelTransaction(final PingPongTransaction tx, final DOMDataReadWriteTransaction frontendTx) {
// Attempt to unlock the operation.
// transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction
// at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain
// and mark the fact that we should be turning its completion into a failure.
- deadTx = new SimpleImmutableEntry<>(tx,
- new CancellationException("Transaction " + frontendTx + " canceled").fillInStackTrace());
+ deadTx = new SimpleImmutableEntry<>(tx, new CancellationException("Transaction " + frontendTx + " canceled")
+ .fillInStackTrace());
delegate.close();
}
@Override
public synchronized void close() {
final PingPongTransaction notLocked = lockedTx;
- Preconditions.checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s",
- notLocked);
+ Preconditions
+ .checkState(notLocked == null, "Attempted to close chain with outstanding transaction %s", notLocked);
// This is not reliable, but if we observe it to be null and the process has already completed,
// the backend transaction chain will throw the appropriate error.
@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
- final YangInstanceIdentifier path) {
+ final YangInstanceIdentifier path) {
return tx.getTransaction().exists(store, path);
}
private final DOMRpcIdentifier globalRpcId;
private final YangInstanceIdentifier keyId;
- private RoutedDOMRpcRoutingTableEntry(final DOMRpcIdentifier globalRpcId, final YangInstanceIdentifier keyId, final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ private RoutedDOMRpcRoutingTableEntry(final DOMRpcIdentifier globalRpcId, final YangInstanceIdentifier keyId,
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
super(globalRpcId.getType(), impls);
this.keyId = Preconditions.checkNotNull(keyId);
this.globalRpcId = Preconditions.checkNotNull(globalRpcId);
}
- RoutedDOMRpcRoutingTableEntry(final RpcDefinition def, final YangInstanceIdentifier keyId, final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ RoutedDOMRpcRoutingTableEntry(final RpcDefinition def, final YangInstanceIdentifier keyId,
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
super(def.getPath(), impls);
this.keyId = Preconditions.checkNotNull(keyId);
this.globalRpcId = DOMRpcIdentifier.create(def.getPath());
// implementation this way
final List<DOMRpcImplementation> mayBeRemoteImpls = getImplementations(YangInstanceIdentifier.EMPTY);
- if(mayBeRemoteImpls != null){
+ if (mayBeRemoteImpls != null) {
return mayBeRemoteImpls.get(0).invokeRpc(DOMRpcIdentifier.create(getSchemaPath(), iid), input);
}
if (impls != null) {
return impls.get(0).invokeRpc(globalRpcId, input);
} else {
- return Futures.<DOMRpcResult, DOMRpcException>immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available", getSchemaPath()));
+ return Futures.<DOMRpcResult, DOMRpcException>immediateFailedCheckedFuture(
+ new DOMRpcImplementationNotAvailableException("No implementation of RPC %s available",
+ getSchemaPath()));
}
}
@Override
- protected RoutedDOMRpcRoutingTableEntry newInstance(final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ protected RoutedDOMRpcRoutingTableEntry newInstance(
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
return new RoutedDOMRpcRoutingTableEntry(globalRpcId, keyId, impls);
}
}
\ No newline at end of file
* Implementation of blocking three phase commit coordinator, which which
* supports coordination on multiple {@link DOMStoreThreePhaseCommitCohort}.
*
+ * <p>
* This implementation does not support cancellation of commit,
*
+ * <p>
* In order to advance to next phase of three phase commit all subtasks of
* previous step must be finish.
*
+ * <p>
* This executor does not have an upper bound on subtask timeout.
*/
public class SerializedDOMDataBroker extends AbstractDOMDataBroker {
private final ListeningExecutorService executor;
/**
- *
* Construct DOMDataCommitCoordinator which uses supplied executor to
* process commit coordinations.
*
- * @param executor
+ * @param datastores data stores
+ * @param executor executor service
*/
- public SerializedDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores, final ListeningExecutorService executor) {
+ public SerializedDOMDataBroker(final Map<LogicalDatastoreType, DOMStore> datastores,
+ final ListeningExecutorService executor) {
super(datastores);
this.executor = Preconditions.checkNotNull(executor, "executor must not be null.");
}
}
@Override
- protected CheckedFuture<Void,TransactionCommitFailedException> submit(final DOMDataWriteTransaction transaction,
- final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
+ protected CheckedFuture<Void, TransactionCommitFailedException> submit(final DOMDataWriteTransaction transaction,
+ final
+ Collection<DOMStoreThreePhaseCommitCohort>
+ cohorts) {
Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
Preconditions.checkArgument(cohorts != null, "Cohorts must not be null.");
LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
ListenableFuture<Void> commitFuture = null;
try {
- commitFuture = executor.submit(new CommitCoordinationTask(transaction, cohorts,
- commitStatsTracker));
- } catch(RejectedExecutionException e) {
- LOG.error("The commit executor's queue is full - submit task was rejected. \n" +
- executor, e);
- return Futures.immediateFailedCheckedFuture(
- new TransactionCommitFailedException(
- "Could not submit the commit task - the commit queue capacity has been exceeded.", e));
+ commitFuture = executor.submit(new CommitCoordinationTask(transaction, cohorts, commitStatsTracker));
+ } catch (RejectedExecutionException e) {
+ LOG.error("The commit executor's queue is full - submit task was rejected. \n" + executor, e);
+ return Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException(
+ "Could not submit the commit task - the commit queue capacity has been exceeded.", e));
}
- return MappingCheckedFuture.create(commitFuture,
- TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
+ return MappingCheckedFuture.create(commitFuture, TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
}
}
import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
/**
+ * ShardRegistration.
+ *
* @deprecated To be removed with {@link ShardedDOMDataTree}.
*/
@Deprecated
import org.slf4j.LoggerFactory;
/**
+ * Shared DOM data tree.
+ *
* @deprecated Use {@link org.opendaylight.mdsal.dom.broker.ShardedDOMDataTree} instead.
*/
@Deprecated
public final class ShardedDOMDataTree implements DOMDataTreeService, DOMDataTreeShardingService {
private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTree.class);
- private final Map<LogicalDatastoreType, ShardingTableEntry> shardingTables = new EnumMap<>(LogicalDatastoreType.class);
+ private final Map<LogicalDatastoreType, ShardingTableEntry> shardingTables = new EnumMap<>(
+ LogicalDatastoreType.class);
@GuardedBy("this")
private final Map<DOMDataTreeIdentifier, DOMDataTreeProducer> idToProducer = new TreeMap<>();
@GuardedBy("this")
private void storeShard(final DOMDataTreeIdentifier prefix, final ShardRegistration<?> reg) {
- ShardingTableEntry t = shardingTables.computeIfAbsent(prefix.getDatastoreType(), k -> new ShardingTableEntry());
+ ShardingTableEntry shardingTableEntry = shardingTables
+ .computeIfAbsent(prefix.getDatastoreType(), k -> new ShardingTableEntry());
- t.store(prefix.getRootIdentifier(), reg);
+ shardingTableEntry.store(prefix.getRootIdentifier(), reg);
}
void removeShard(final ShardRegistration<?> reg) {
}
@Override
- public <T extends DOMDataTreeShard> ListenerRegistration<T> registerDataTreeShard(final DOMDataTreeIdentifier prefix, final T shard) throws DOMDataTreeShardingConflictException {
+ public <T extends DOMDataTreeShard> ListenerRegistration<T> registerDataTreeShard(
+ final DOMDataTreeIdentifier prefix, final T shard) throws DOMDataTreeShardingConflictException {
final ShardRegistration<T> reg;
final ShardRegistration<?> parentReg;
final ShardingTableEntry parent = lookupShard(prefix);
parentReg = parent.getRegistration();
if (parentReg != null && prefix.equals(parentReg.getPrefix())) {
- throw new DOMDataTreeShardingConflictException(String.format("Prefix %s is already occupied by shard %s", prefix, parentReg.getInstance()));
+ throw new DOMDataTreeShardingConflictException(
+ String.format("Prefix %s is already occupied by shard %s", prefix, parentReg.getInstance()));
}
// FIXME: wrap the shard in a proper adaptor based on implemented interface
return createProducer(shardMap);
}
- synchronized DOMDataTreeProducer createProducer(final ShardedDOMDataTreeProducer parent, final Collection<DOMDataTreeIdentifier> subtrees) {
+ synchronized DOMDataTreeProducer createProducer(final ShardedDOMDataTreeProducer parent,
+ final Collection<DOMDataTreeIdentifier> subtrees) {
Preconditions.checkNotNull(parent);
final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap = new HashMap<>();
}
@Override
- public synchronized <T extends DOMDataTreeListener> ListenerRegistration<T> registerListener(final T listener, final Collection<DOMDataTreeIdentifier> subtrees, final boolean allowRxMerges, final Collection<DOMDataTreeProducer> producers) {
+ public synchronized <T extends DOMDataTreeListener> ListenerRegistration<T>
+ registerListener(final T listener,
+ final Collection<DOMDataTreeIdentifier> subtrees,
+ final boolean allowRxMerges,
+ final Collection<DOMDataTreeProducer> producers) {
// FIXME Implement this.
throw new UnsupportedOperationException("Not implemented yet.");
}
import org.slf4j.LoggerFactory;
/**
+ * Sharded DOM Data Tree Producer.
+ *
* @deprecated To be removed with {@link ShardedDOMDataTree}.
*/
@Deprecated
+@SuppressWarnings("checkstyle:IllegalCatch")
final class ShardedDOMDataTreeProducer implements DOMDataTreeProducer {
private static final Logger LOG = LoggerFactory.getLogger(ShardedDOMDataTreeProducer.class);
private final BiMap<DOMDataTreeShard, DOMStoreTransactionChain> shardToChain;
@GuardedBy("this")
private boolean closed;
- ShardedDOMDataTreeProducer(final ShardedDOMDataTree dataTree, final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap, final Set<DOMDataTreeShard> shards) {
+ ShardedDOMDataTreeProducer(final ShardedDOMDataTree dataTree,
+ final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap,
+ final Set<DOMDataTreeShard> shards) {
this.dataTree = Preconditions.checkNotNull(dataTree);
// Create shard -> chain map
for (final DOMDataTreeShard s : shards) {
if (s instanceof DOMStore) {
try {
- final DOMStoreTransactionChain c = ((DOMStore)s).createTransactionChain();
+ final DOMStoreTransactionChain c = ((DOMStore) s).createTransactionChain();
LOG.trace("Using DOMStore chain {} to access shard {}", c, s);
cb.put(s, c);
} catch (final Exception e) {
}
}
- final IllegalStateException e = new IllegalStateException("Failed to completely allocate contexts", es.poll());
+ final IllegalStateException e = new IllegalStateException("Failed to completely allocate contexts",
+ es.poll());
while (!es.isEmpty()) {
e.addSuppressed(es.poll());
}
}
@GuardedBy("this")
- private DOMDataTreeProducer lookupChild(final DOMDataTreeIdentifier s) {
+ private DOMDataTreeProducer lookupChild(final DOMDataTreeIdentifier identifier) {
for (final Entry<DOMDataTreeIdentifier, DOMDataTreeProducer> e : children.entrySet()) {
- if (e.getKey().contains(s)) {
+ if (e.getKey().contains(identifier)) {
return e.getValue();
}
}
for (final DOMDataTreeIdentifier s : subtrees) {
// Check if the subtree was visible at any time
if (!haveSubtree(s)) {
- throw new IllegalArgumentException(String.format("Subtree %s was never available in producer %s", s, this));
+ throw new IllegalArgumentException(
+ String.format("Subtree %s was never available in producer %s", s, this));
}
// Check if the subtree has not been delegated to a child
// Check if part of the requested subtree is not delegated to a child.
for (final DOMDataTreeIdentifier c : children.keySet()) {
if (s.contains(c)) {
- throw new IllegalArgumentException(String.format("Subtree %s cannot be delegated as it is superset of already-delegated %s", s, c));
+ throw new IllegalArgumentException(
+ String.format("Subtree %s cannot be delegated as it is superset of already-delegated %s", s,
+ c));
}
}
}
}
}
- static DOMDataTreeProducer create(final ShardedDOMDataTree dataTree, final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
+ static DOMDataTreeProducer create(final ShardedDOMDataTree dataTree,
+ final Map<DOMDataTreeIdentifier, DOMDataTreeShard> shardMap) {
/*
* FIXME: we do not allow multiple multiple shards in a producer because we do not implement the
* synchronization primitives yet
import org.slf4j.LoggerFactory;
/**
+ * ShardedDOMDataWriteTransaction.
+ *
* @deprecated To be removed with {@link ShardedDOMDataTree}.
*/
@Deprecated
private final ShardedDOMDataTreeProducer producer;
private final String identifier;
@GuardedBy("this")
- private boolean closed = false;
+ private boolean closed = false;
- ShardedDOMDataWriteTransaction(final ShardedDOMDataTreeProducer producer, final Map<DOMDataTreeIdentifier, DOMStoreWriteTransaction> idToTransaction) {
+ ShardedDOMDataWriteTransaction(final ShardedDOMDataTreeProducer producer,
+ final Map<DOMDataTreeIdentifier, DOMStoreWriteTransaction> idToTransaction) {
this.producer = Preconditions.checkNotNull(producer);
this.idToTransaction = Preconditions.checkNotNull(idToTransaction);
this.identifier = "SHARDED-DOM-" + COUNTER.getAndIncrement();
}
@Override
- public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
lookup(store, path).write(path, data);
}
@Override
- public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
lookup(store, path).merge(path, data);
}
}
import org.slf4j.LoggerFactory;
/**
+ * Sharding Table Entry.
+ *
* @deprecated To be removed with {@link ShardedDOMDataTree}.
*/
@Deprecated
*
* @see ExceptionMapper
*/
-public final class TransactionCommitFailedExceptionMapper
- extends ExceptionMapper<TransactionCommitFailedException> {
+public final class TransactionCommitFailedExceptionMapper extends ExceptionMapper<TransactionCommitFailedException> {
public static final TransactionCommitFailedExceptionMapper PRE_COMMIT_MAPPER = create("preCommit");
public static final TransactionCommitFailedExceptionMapper COMMIT_ERROR_MAPPER = create("commit");
private TransactionCommitFailedExceptionMapper(final String opName) {
- super( opName, TransactionCommitFailedException.class );
+ super(opName, TransactionCommitFailedException.class);
}
public static TransactionCommitFailedExceptionMapper create(final String opName) {
}
@Override
- protected TransactionCommitFailedException newWithCause( final String message, final Throwable cause ) {
- return new TransactionCommitFailedException( message, cause );
+ protected TransactionCommitFailedException newWithCause(final String message, final Throwable cause) {
+ return new TransactionCommitFailedException(message, cause);
}
}
\ No newline at end of file
final class UnknownDOMRpcRoutingTableEntry extends AbstractDOMRpcRoutingTableEntry {
private final CheckedFuture<DOMRpcResult, DOMRpcException> unknownRpc;
- UnknownDOMRpcRoutingTableEntry(final SchemaPath schemaPath, final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ UnknownDOMRpcRoutingTableEntry(final SchemaPath schemaPath,
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
super(schemaPath, impls);
unknownRpc = Futures.<DOMRpcResult, DOMRpcException>immediateFailedCheckedFuture(
- new DOMRpcImplementationNotAvailableException("SchemaPath %s is not resolved to an RPC", schemaPath));
+ new DOMRpcImplementationNotAvailableException("SchemaPath %s is not resolved to an RPC", schemaPath));
}
@Override
}
@Override
- protected UnknownDOMRpcRoutingTableEntry newInstance(final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ protected UnknownDOMRpcRoutingTableEntry newInstance(
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
return new UnknownDOMRpcRoutingTableEntry(getSchemaPath(), impls);
}
}
\ No newline at end of file
/**
* Returns the total number of commits that have occurred.
+ *
+ * @return Returns the total number of commits that have occurred
+ *
*/
long getTotalCommits();
/**
* Returns a string representing the time duration of the longest commit, in the appropriate
* scaled units, along with the date/time that it occurred.
+ *
+ * @return string
*/
String getLongestCommitTime();
/**
* Returns a string representing the time duration of the shortest commit, in the appropriate
* scaled units, along with the date/time that it occurred.
+ *
+ * @return string
*/
String getShortestCommitTime();
/**
* Returns a string representing average commit time duration, in the appropriate
* scaled units.
+ *
+ * @return string
*/
String getAverageCommitTime();
* Constructor.
*
* @param commitStatsTracker the DurationStatsTracker used to obtain the stats.
- * @param mBeanType mBeanType Used as the <code>type</code> property in the bean's ObjectName.
+ * @param mbeantype mBeanType Used as the <code>type</code> property in the bean's ObjectName.
*/
public CommitStatsMXBeanImpl(@Nonnull DurationStatisticsTracker commitStatsTracker,
- @Nonnull String mBeanType) {
- super("CommitStats", mBeanType, null);
+ @Nonnull String mbeantype) {
+ super("CommitStats", mbeantype, null);
this.commitStatsTracker = commitStatsTracker;
}
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
/**
- * DOMDataBroker implementation that forwards calls to {@link org.opendaylight.mdsal.dom.broker.ShardedDOMDataBrokerAdapter},
- * which in turn translates calls to shard aware implementation of {@link org.opendaylight.mdsal.dom.api.DOMDataTreeService}
+ * DOMDataBroker implementation that forwards calls to
+ * {@link org.opendaylight.mdsal.dom.broker.ShardedDOMDataBrokerAdapter},
+ * which in turn translates calls to shard aware implementation of
+ * {@link org.opendaylight.mdsal.dom.api.DOMDataTreeService}
+ *
* <p>
* The incompatibility between first and latter APIs, puts restriction on {@link DOMDataReadWriteTransaction}
- * and {@link DOMDataReadOnlyTransaction} provided by this data broker. See {@link ShardedDOMDataBrokerDelegatingReadWriteTransaction}
+ * and {@link DOMDataReadOnlyTransaction} provided by this data broker. See
+ * {@link ShardedDOMDataBrokerDelegatingReadWriteTransaction}
* and {@link ShardedDOMDataBrokerDelegatingReadTransaction} respectively.
*/
// FIXME try to refactor some of the implementation to abstract class for better reusability
@Override
public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
return new ShardedDOMDataBrokerDelegatingReadTransaction(newTransactionIdentifier(),
- delegateDataBroker.newReadOnlyTransaction());
+ delegateDataBroker.newReadOnlyTransaction());
}
@Override
public DOMDataReadWriteTransaction newReadWriteTransaction() {
- return new ShardedDOMDataBrokerDelegatingReadWriteTransaction(newTransactionIdentifier(), schemaService.getGlobalContext(),
- newReadOnlyTransaction(), newWriteOnlyTransaction());
+ return new ShardedDOMDataBrokerDelegatingReadWriteTransaction(newTransactionIdentifier(),
+ schemaService.getGlobalContext(),
+ newReadOnlyTransaction(),
+ newWriteOnlyTransaction());
}
@Override
public DOMDataWriteTransaction newWriteOnlyTransaction() {
return new ShardedDOMDataBrokerDelegatingWriteTransaction(newTransactionIdentifier(),
- delegateDataBroker.newWriteOnlyTransaction());
+ delegateDataBroker.newWriteOnlyTransaction());
}
@Override
public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store,
final YangInstanceIdentifier path,
final DOMDataChangeListener listener,
- final DataChangeScope triggeringScope) {
- throw new UnsupportedOperationException("Registering data change listeners is not supported in " +
- "md-sal forwarding data broker");
+ final DataChangeScope
+ triggeringScope) {
+ throw new UnsupportedOperationException(
+ "Registering data change listeners is not supported in " + "md-sal forwarding data broker");
}
@Override
public DOMTransactionChain createTransactionChain(final TransactionChainListener listener) {
- return new ShardedDOMDataBrokerDelegatingTransactionChain(chainNum.getAndIncrement(), schemaService.getGlobalContext(),
- delegateDataBroker, listener);
+ return new ShardedDOMDataBrokerDelegatingTransactionChain(chainNum.getAndIncrement(),
+ schemaService.getGlobalContext(), delegateDataBroker,
+ listener);
}
@Nonnull
throw new AssertionError("Util class should not be instantiated");
}
- public static org.opendaylight.mdsal.common.api.LogicalDatastoreType translateDataStoreType(final LogicalDatastoreType store) {
- return store.equals(LogicalDatastoreType.CONFIGURATION) ?
- org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION :
- org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
+ public static org.opendaylight.mdsal.common.api.LogicalDatastoreType translateDataStoreType(
+ final LogicalDatastoreType store) {
+ return store
+ .equals(LogicalDatastoreType.CONFIGURATION) ? org.opendaylight.mdsal.common.api.LogicalDatastoreType
+ .CONFIGURATION : org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
}
}
/**
* Read transaction that delegates calls to {@link org.opendaylight.mdsal.dom.broker.ShardedDOMReadTransactionAdapter},
- * which in turn translates calls to shard aware implementation of {@link org.opendaylight.mdsal.dom.api.DOMDataTreeService}.
+ * which in turn translates calls to shard aware implementation of
+ * {@link org.opendaylight.mdsal.dom.api.DOMDataTreeService}.
+ *
* <p>
* Since reading data distributed on different subshards is not guaranteed to
* return all relevant data, we cannot guarantee it neither. Best effort is to
private final DOMDataTreeReadTransaction delegateTx;
private final Object txIdentifier;
- public ShardedDOMDataBrokerDelegatingReadTransaction(final Object txIdentifier, final DOMDataTreeReadTransaction delegateTx) {
+ ShardedDOMDataBrokerDelegatingReadTransaction(final Object txIdentifier,
+ final DOMDataTreeReadTransaction delegateTx) {
this.delegateTx = checkNotNull(delegateTx);
this.txIdentifier = checkNotNull(txIdentifier);
}
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
final YangInstanceIdentifier path) {
- return Futures.makeChecked(delegateTx.read(LegacyShardedDOMDataBrokerAdapterUtils.translateDataStoreType(store), path), ReadFailedException.MAPPER);
+ return Futures.makeChecked(
+ delegateTx.read(LegacyShardedDOMDataBrokerAdapterUtils.translateDataStoreType(store), path),
+ ReadFailedException.MAPPER);
}
@Override
- public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- return Futures.makeChecked(delegateTx.exists(LegacyShardedDOMDataBrokerAdapterUtils.translateDataStoreType(store), path), ReadFailedException.MAPPER);
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
+ return Futures.makeChecked(
+ delegateTx.exists(LegacyShardedDOMDataBrokerAdapterUtils.translateDataStoreType(store), path),
+ ReadFailedException.MAPPER);
}
@Override
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
/**
- * Read/write transaction that delegates write and initial read to {@link org.opendaylight.mdsal.dom.broker.ShardedDOMWriteTransactionAdapter}
+ * Read/write transaction that delegates write and initial read to
+ * {@link org.opendaylight.mdsal.dom.broker.ShardedDOMWriteTransactionAdapter}
* and {@link org.opendaylight.mdsal.dom.broker.ShardedDOMReadTransactionAdapter}
- * respectively. These two in turn rely on shard aware implementation of {@link org.opendaylight.mdsal.dom.api.DOMDataTreeService}.
+ * respectively. These two in turn rely on shard aware implementation of
+ * {@link org.opendaylight.mdsal.dom.api.DOMDataTreeService}.
+ *
* <p>
* Since reading data distributed on different subshards is not guaranteed to
* return all relevant data, best effort is to try to operate only on single
// FIXME explicitly enforce just one subtree requirement
@NotThreadSafe
class ShardedDOMDataBrokerDelegatingReadWriteTransaction implements DOMDataReadWriteTransaction {
- private static final ListenableFuture<RpcResult<TransactionStatus>> SUCCESS_FUTURE =
- Futures.immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
+ private static final ListenableFuture<RpcResult<TransactionStatus>> SUCCESS_FUTURE = Futures
+ .immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
private final DOMDataReadOnlyTransaction readTxDelegate;
private final DOMDataWriteTransaction writeTxDelegate;
private final Map<LogicalDatastoreType, ListenableFuture<Optional<NormalizedNode<?, ?>>>> initialReadMap;
private YangInstanceIdentifier root = null;
- public ShardedDOMDataBrokerDelegatingReadWriteTransaction(final Object readWriteTxId, final SchemaContext ctx,
+ ShardedDOMDataBrokerDelegatingReadWriteTransaction(final Object readWriteTxId, final SchemaContext ctx,
final DOMDataReadOnlyTransaction readTxDelegate,
final DOMDataWriteTransaction writeTxDelegate) {
this.readTxDelegate = checkNotNull(readTxDelegate);
final InMemoryDataTreeFactory treeFactory = InMemoryDataTreeFactory.getInstance();
final ImmutableMap.Builder<LogicalDatastoreType, DataTreeSnapshot> snapshotMapBuilder = ImmutableMap.builder();
- final ImmutableMap.Builder<LogicalDatastoreType, Queue<Modification>> modificationHistoryMapBuilder =
- ImmutableMap.builder();
+ final ImmutableMap.Builder<LogicalDatastoreType, Queue<Modification>> modificationHistoryMapBuilder
+ = ImmutableMap.builder();
for (final LogicalDatastoreType store : LogicalDatastoreType.values()) {
final DataTree tree = treeFactory.create(treeTypeForStore(store));
tree.setSchemaContext(ctx);
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
final YangInstanceIdentifier path) {
- checkState(root != null, "A modify operation (put, merge or delete) must be performed prior to a read operation");
+ checkState(root != null,
+ "A modify operation (put, merge or delete) must be performed prior to a read operation");
final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create();
final Queue<Modification> currentHistory = Lists.newLinkedList(modificationHistoryMap.get(store));
Futures.addCallback(initialReadMap.get(store), new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
}
@Override
- public void onFailure(final Throwable t) {
- readResult.setException(t);
+ public void onFailure(final Throwable throwable) {
+ readResult.setException(throwable);
}
}, MoreExecutors.directExecutor());
@Override
public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
final YangInstanceIdentifier path) {
- checkState(root != null, "A modify operation (put, merge or delete) must be performed prior to an exists operation");
+ checkState(root != null,
+ "A modify operation (put, merge or delete) must be performed prior to an exists operation");
return Futures.makeChecked(Futures.transform(read(store, path),
- (Function<Optional<NormalizedNode<?, ?>>, Boolean>) Optional::isPresent),
- ReadFailedException.MAPPER);
+ (Function<Optional<NormalizedNode<?, ?>>, Boolean>)
+ Optional::isPresent),
+ ReadFailedException.MAPPER);
}
@Override
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-class ShardedDOMDataBrokerDelegatingTransactionChain implements DOMTransactionChain,
- org.opendaylight.mdsal.common.api.TransactionChainListener {
+class ShardedDOMDataBrokerDelegatingTransactionChain implements DOMTransactionChain, org.opendaylight.mdsal.common
+ .api.TransactionChainListener {
private final org.opendaylight.mdsal.dom.api.DOMTransactionChain txChainDelegate;
private final SchemaContext schemaContext;
private final TransactionChainListener txChainListener;
private final Map<Object, AsyncTransaction<?, ?>> transactionMap;
- public ShardedDOMDataBrokerDelegatingTransactionChain(final Object txChainIdentifier, final SchemaContext schemaContext,
- final org.opendaylight.mdsal.dom.api.DOMDataBroker brokerDelegate,
+ ShardedDOMDataBrokerDelegatingTransactionChain(final Object txChainIdentifier,
+ final SchemaContext schemaContext,
+ final org.opendaylight.mdsal.dom.api.DOMDataBroker
+ brokerDelegate,
final TransactionChainListener txChainListener) {
checkNotNull(brokerDelegate);
this.schemaContext = checkNotNull(schemaContext);
@Override
public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
final DOMDataTreeReadTransaction readTxDelegate = txChainDelegate.newReadOnlyTransaction();
- final DOMDataReadOnlyTransaction readTx =
- new ShardedDOMDataBrokerDelegatingReadTransaction(newTransactionIdentifier(), readTxDelegate);
+ final DOMDataReadOnlyTransaction readTx = new ShardedDOMDataBrokerDelegatingReadTransaction(
+ newTransactionIdentifier(), readTxDelegate);
transactionMap.put(readTxDelegate.getIdentifier(), readTx);
return readTx;
public DOMDataReadWriteTransaction newReadWriteTransaction() {
final Object readWriteTxId = newTransactionIdentifier();
final DOMDataTreeReadTransaction readTxDelegate = txChainDelegate.newReadOnlyTransaction();
- final DOMDataReadOnlyTransaction readTx =
- new ShardedDOMDataBrokerDelegatingReadTransaction(readWriteTxId, readTxDelegate);
+ final DOMDataReadOnlyTransaction readTx = new ShardedDOMDataBrokerDelegatingReadTransaction(readWriteTxId,
+ readTxDelegate);
final DOMDataTreeWriteTransaction writeTxDelegate = txChainDelegate.newWriteOnlyTransaction();
- final DOMDataWriteTransaction writeTx =
- new ShardedDOMDataBrokerDelegatingWriteTransaction(readWriteTxId, writeTxDelegate);
+ final DOMDataWriteTransaction writeTx = new ShardedDOMDataBrokerDelegatingWriteTransaction(readWriteTxId,
+ writeTxDelegate);
- final DOMDataReadWriteTransaction readWriteTx =
- new ShardedDOMDataBrokerDelegatingReadWriteTransaction(readWriteTxId, schemaContext,
- readTx, writeTx);
+ final DOMDataReadWriteTransaction readWriteTx = new ShardedDOMDataBrokerDelegatingReadWriteTransaction(
+ readWriteTxId, schemaContext, readTx, writeTx);
transactionMap.put(readTxDelegate.getIdentifier(), readWriteTx);
transactionMap.put(writeTxDelegate.getIdentifier(), readWriteTx);
@Override
public DOMDataWriteTransaction newWriteOnlyTransaction() {
final DOMDataTreeWriteTransaction writeTxDelegate = txChainDelegate.newWriteOnlyTransaction();
- final DOMDataWriteTransaction writeTx =
- new ShardedDOMDataBrokerDelegatingWriteTransaction(newTransactionIdentifier(), writeTxDelegate);
+ final DOMDataWriteTransaction writeTx = new ShardedDOMDataBrokerDelegatingWriteTransaction(
+ newTransactionIdentifier(), writeTxDelegate);
transactionMap.put(writeTxDelegate.getIdentifier(), writeTx);
return writeTx;
@Override
public void onTransactionChainFailed(final TransactionChain<?, ?> transactionChain,
- final org.opendaylight.mdsal.common.api.AsyncTransaction<?, ?> asyncTransaction,
+ final org.opendaylight.mdsal.common.api.AsyncTransaction<?, ?>
+ asyncTransaction,
final Throwable throwable) {
- txChainListener.onTransactionChainFailed(
- this, transactionFromDelegate(asyncTransaction.getIdentifier()), throwable);
+ txChainListener
+ .onTransactionChainFailed(this, transactionFromDelegate(asyncTransaction.getIdentifier()), throwable);
}
@Override
private AsyncTransaction<?, ?> transactionFromDelegate(final Object delegateId) {
Preconditions.checkState(transactionMap.containsKey(delegateId),
- "Delegate transaction {} is not present in transaction chain history", delegateId);
+ "Delegate transaction {} is not present in transaction chain history", delegateId);
return transactionMap.get(delegateId);
}
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
class ShardedDOMDataBrokerDelegatingWriteTransaction implements DOMDataWriteTransaction {
- private static final ListenableFuture<RpcResult<TransactionStatus>> SUCCESS_FUTURE =
- Futures.immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
+ private static final ListenableFuture<RpcResult<TransactionStatus>> SUCCESS_FUTURE = Futures
+ .immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
private final DOMDataTreeWriteTransaction delegateTx;
private final Object txIdentifier;
- public ShardedDOMDataBrokerDelegatingWriteTransaction(final Object txIdentifier, final DOMDataTreeWriteTransaction delegateTx) {
+ ShardedDOMDataBrokerDelegatingWriteTransaction(final Object txIdentifier,
+ final DOMDataTreeWriteTransaction delegateTx) {
this.delegateTx = checkNotNull(delegateTx);
this.txIdentifier = checkNotNull(txIdentifier);
}
@Override
- public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
delegateTx.put(LegacyShardedDOMDataBrokerAdapterUtils.translateDataStoreType(store), path, data);
}
@Override
- public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
delegateTx.merge(LegacyShardedDOMDataBrokerAdapterUtils.translateDataStoreType(store), path, data);
}
public ObjectRegistration<DOMMountPoint> registerMountPoint(final DOMMountPoint mountPoint) {
synchronized (mountPoints) {
- Preconditions.checkState(!mountPoints.containsKey(mountPoint.getIdentifier()), "Mount point already exists");
+ Preconditions
+ .checkState(!mountPoints.containsKey(mountPoint.getIdentifier()), "Mount point already exists");
mountPoints.put(mountPoint.getIdentifier(), mountPoint);
}
notifyMountCreated(mountPoint.getIdentifier());
private final class MountRegistration implements ObjectRegistration<DOMMountPoint> {
private final DOMMountPoint mountPoint;
- public MountRegistration(final DOMMountPoint mountPoint) {
+ MountRegistration(final DOMMountPoint mountPoint) {
this.mountPoint = mountPoint;
}
}
@Override
- public EntityOwnershipCandidateRegistration registerCandidate(Entity entity)
- throws CandidateAlreadyRegisteredException {
+ public EntityOwnershipCandidateRegistration registerCandidate(
+ Entity entity) throws CandidateAlreadyRegisteredException {
try {
- return new EntityOwnershipCandidateRegistrationAdapter(domService.registerCandidate(
- toDOMEntity(entity)), entity);
- } catch(org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException e) {
+ return new EntityOwnershipCandidateRegistrationAdapter(domService.registerCandidate(toDOMEntity(entity)),
+ entity);
+ } catch (org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException e) {
throw new CandidateAlreadyRegisteredException(entity);
}
}
@Override
public EntityOwnershipListenerRegistration registerListener(String entityType, EntityOwnershipListener listener) {
- return new EntityOwnershipListenerRegistrationAdapter(entityType, listener,
- domService.registerListener(entityType, new DOMEntityOwnershipListenerAdapter(listener)));
+ return new EntityOwnershipListenerRegistrationAdapter(entityType, listener, domService
+ .registerListener(entityType, new DOMEntityOwnershipListenerAdapter(listener)));
}
@Override
private Optional<EntityOwnershipState> toEntityOwnershipState(
Optional<org.opendaylight.mdsal.eos.common.api.EntityOwnershipState> from) {
- if(!from.isPresent()) {
+ if (!from.isPresent()) {
return Optional.absent();
}
private final DOMEntityOwnershipCandidateRegistration domRegistration;
EntityOwnershipCandidateRegistrationAdapter(DOMEntityOwnershipCandidateRegistration domRegistration,
- Entity entity) {
+ Entity entity) {
super(entity);
this.domRegistration = Preconditions.checkNotNull(domRegistration);
}
}
}
- private static class EntityOwnershipListenerRegistrationAdapter extends AbstractObjectRegistration<EntityOwnershipListener>
- implements EntityOwnershipListenerRegistration {
+ private static class EntityOwnershipListenerRegistrationAdapter extends
+ AbstractObjectRegistration<EntityOwnershipListener> implements EntityOwnershipListenerRegistration {
private final String entityType;
private final DOMEntityOwnershipListenerRegistration domRegistration;
EntityOwnershipListenerRegistrationAdapter(String entityType, EntityOwnershipListener listener,
- DOMEntityOwnershipListenerRegistration domRegistration) {
+ DOMEntityOwnershipListenerRegistration domRegistration) {
super(listener);
this.entityType = Preconditions.checkNotNull(entityType);
this.domRegistration = Preconditions.checkNotNull(domRegistration);
@Override
public void ownershipChanged(DOMEntityOwnershipChange ownershipChange) {
- Entity entity = new Entity(ownershipChange.getEntity().getType(), ownershipChange.getEntity().
- getIdentifier());
- delegateListener.ownershipChanged(new EntityOwnershipChange(entity,
- ownershipChange.getState().wasOwner(), ownershipChange.getState().isOwner(),
- ownershipChange.getState().hasOwner(), ownershipChange.inJeopardy()));
+ Entity entity = new Entity(ownershipChange.getEntity().getType(),
+ ownershipChange.getEntity().getIdentifier());
+ delegateListener.ownershipChanged(new EntityOwnershipChange(entity, ownershipChange.getState().wasOwner(),
+ ownershipChange.getState().isOwner(),
+ ownershipChange.getState().hasOwner(),
+ ownershipChange.inJeopardy()));
}
}
}
return registerConsumer(consumer);
}
+ @Override
+ public ConsumerSession registerConsumer(final Consumer consumer) {
+ checkPredicates(consumer);
+ LOG.trace("Registering consumer {}", consumer);
+ final ConsumerContextImpl session = newSessionFor(consumer);
+ consumer.onSessionInitiated(session);
+ sessions.add(session);
+ return session;
+ }
+
@Override
public ProviderSession registerProvider(final Provider provider,
final BundleContext ctx) {
return registerProvider(provider);
}
+ @Override
+ public ProviderSession registerProvider(final Provider provider) {
+ checkPredicates(provider);
+ final ProviderContextImpl session = newSessionFor(provider);
+ provider.onSessionInitiated(session);
+ providerSessions.add(session);
+ return session;
+ }
+
// Validation
private void checkPredicates(final Provider prov) {
Preconditions.checkNotNull(prov, "Provider should not be null.");
}
/**
+ * Gets deactivator.
+ *
* @return the deactivator
*/
public AutoCloseable getDeactivator() {
}
/**
+ * Sets deactivator.
+ *
* @param deactivator
* the deactivator to set
*/
return Optional.fromNullable(services.getInstance(service));
}
-
- @Override
- public ConsumerSession registerConsumer(final Consumer consumer) {
- checkPredicates(consumer);
- LOG.trace("Registering consumer {}", consumer);
- final ConsumerContextImpl session = newSessionFor(consumer);
- consumer.onSessionInitiated(session);
- sessions.add(session);
- return session;
- }
-
-
- @Override
- public ProviderSession registerProvider(final Provider provider) {
- checkPredicates(provider);
- final ProviderContextImpl session = newSessionFor(provider);
- provider.onSessionInitiated(session);
- providerSessions.add(session);
- return session;
- }
-
-
@Nonnull
@Override
- public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(@Nonnull final T implementation, @Nonnull final DOMRpcIdentifier... rpcs) {
+ public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
+ @Nonnull final T implementation, @Nonnull final DOMRpcIdentifier... rpcs) {
return rpcProvider.registerRpcImplementation(implementation, rpcs);
}
@Nonnull
@Override
- public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(@Nonnull final T implementation, @Nonnull final Set<DOMRpcIdentifier> rpcs) {
+ public <T extends DOMRpcImplementation> DOMRpcImplementationRegistration<T> registerRpcImplementation(
+ @Nonnull final T implementation, @Nonnull final Set<DOMRpcIdentifier> rpcs) {
return rpcProvider.registerRpcImplementation(implementation, rpcs);
}
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+ @Nullable final NormalizedNode<?, ?> input) {
return rpcService.invokeRpc(type, input);
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
return rpcService.registerRpcListener(listener);
}
}
import com.google.common.base.Preconditions;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.MutableClassToInstanceMap;
+import java.util.Collection;
+import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
import org.opendaylight.controller.sal.core.api.BrokerService;
import org.opendaylight.controller.sal.core.api.Consumer;
import org.opendaylight.controller.sal.dom.broker.osgi.AbstractBrokerServiceProxy;
import org.opendaylight.controller.sal.dom.broker.osgi.ProxyFactory;
-import javax.annotation.concurrent.GuardedBy;
-import java.util.Collection;
-
class ConsumerContextImpl implements ConsumerSession {
- private final ClassToInstanceMap<BrokerService> instantiatedServices = MutableClassToInstanceMap
- .create();
+ private final ClassToInstanceMap<BrokerService> instantiatedServices = MutableClassToInstanceMap.create();
private final Consumer consumer;
private BrokerImpl broker = null;
@GuardedBy("this")
private boolean closed = false;
- public ConsumerContextImpl(final Consumer provider, final BrokerImpl brokerImpl) {
+ ConsumerContextImpl(final Consumer provider, final BrokerImpl brokerImpl) {
broker = brokerImpl;
consumer = provider;
}
return localProxy;
}
final Optional<T> serviceImpl = broker.getGlobalService(service);
- if(serviceImpl.isPresent()) {
- final T ret = ProxyFactory.createProxy(null,serviceImpl.get());
+ if (serviceImpl.isPresent()) {
+ final T ret = ProxyFactory.createProxy(null, serviceImpl.get());
instantiatedServices.putInstance(service, ret);
return ret;
} else {
}
/**
+ * Gets broker.
+ *
* @return the broker
*/
- protected final BrokerImpl getBrokerChecked() {
+ protected final BrokerImpl getBrokerChecked() {
checkNotClosed();
return broker;
}
/**
+ * Gets consumer.
+ *
* @return the _consumer
*/
public Consumer getConsumer() {
return consumer;
}
- protected final void checkNotClosed() {
+ protected final void checkNotClosed() {
Preconditions.checkState(!closed, "Session is closed.");
}
}
class ProviderContextImpl extends ConsumerContextImpl implements ProviderSession {
private final Provider provider;
- public ProviderContextImpl(final Provider provider, final BrokerImpl broker) {
+ ProviderContextImpl(final Provider provider, final BrokerImpl broker) {
super(null, broker);
this.provider = provider;
}
public void close() {
}
- /**
- * @return the provider
- */
public Provider getProvider() {
return provider;
}
-
- /**
- * @param provider
- * the provider to set
- */
}
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-public class SchemaContextProviders {
+public final class SchemaContextProviders {
private SchemaContextProviders() {
throw new UnsupportedOperationException("Utility class.");
}
- public static final SchemaContextProvider fromSchemaService(final SchemaService schemaService) {
+ public static SchemaContextProvider fromSchemaService(final SchemaService schemaService) {
if (schemaService instanceof SchemaContextProvider) {
return (SchemaContextProvider) schemaService;
}
private final SchemaService service;
- public SchemaServiceAdapter(final SchemaService service) {
+ SchemaServiceAdapter(final SchemaService service) {
this.service = service;
}
}
@Override
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void close() {
if (delegate != null) {
delegate = null;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.osgi.framework.ServiceReference;
-public class DOMMountPointServiceProxy extends AbstractBrokerServiceProxy<DOMMountPointService> implements DOMMountPointService{
+public class DOMMountPointServiceProxy extends AbstractBrokerServiceProxy<DOMMountPointService> implements
+ DOMMountPointService {
-
- public DOMMountPointServiceProxy(final ServiceReference<DOMMountPointService> ref, final DOMMountPointService delegate) {
+ public DOMMountPointServiceProxy(final ServiceReference<DOMMountPointService> ref,
+ final DOMMountPointService delegate) {
super(ref, delegate);
}
return getDelegate().createMountPoint(path);
}
- public ListenerRegistration<MountProvisionListener> registerProvisionListener(final MountProvisionListener listener) {
+ public ListenerRegistration<MountProvisionListener> registerProvisionListener(
+ final MountProvisionListener listener) {
return getDelegate().registerProvisionListener(listener);
}
}
*/
package org.opendaylight.controller.sal.dom.broker.osgi;
+import java.util.Arrays;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.sal.core.api.BrokerService;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.osgi.framework.ServiceReference;
-import java.util.Arrays;
-
@SuppressWarnings("unchecked")
-public class ProxyFactory {
-
- public static <T extends BrokerService> T createProxy(
- final ServiceReference<T> serviceRef, final T service) {
+public final class ProxyFactory {
- Object _createProxyImpl = ProxyFactory.createProxyImpl(serviceRef,
- service);
- return ((T) _createProxyImpl);
+ private ProxyFactory() {
}
- private static Object createProxyImpl(final ServiceReference<?> ref,
- final DOMMountPointService service) {
+ public static <T extends BrokerService> T createProxy(final ServiceReference<T> serviceRef, final T service) {
- return new DOMMountPointServiceProxy(
- ((ServiceReference<DOMMountPointService>) ref), service);
+ Object createProxyImpl = ProxyFactory.createProxyImpl(serviceRef, service);
+ return ((T) createProxyImpl);
}
- private static Object createProxyImpl(final ServiceReference<?> ref,
- final SchemaService service) {
+ private static Object createProxyImpl(final ServiceReference<?> ref, final DOMMountPointService service) {
- return new SchemaServiceProxy(((ServiceReference<SchemaService>) ref),
- service);
+ return new DOMMountPointServiceProxy(((ServiceReference<DOMMountPointService>) ref), service);
}
- private static DOMDataBrokerProxy createProxyImpl(
- final ServiceReference<?> ref, final DOMDataBroker service) {
+ private static Object createProxyImpl(final ServiceReference<?> ref, final SchemaService service) {
- return new DOMDataBrokerProxy(((ServiceReference<DOMDataBroker>) ref),
- service);
+ return new SchemaServiceProxy(((ServiceReference<SchemaService>) ref), service);
}
- private static Object createProxyImplFallback(final ServiceReference<?> reference,
- final BrokerService service) {
+ private static DOMDataBrokerProxy createProxyImpl(final ServiceReference<?> ref, final DOMDataBroker service) {
- return service;
+ return new DOMDataBrokerProxy(((ServiceReference<DOMDataBroker>) ref), service);
}
- private static Object createProxyImpl(final ServiceReference<?> ref,
- final BrokerService service) {
+ private static Object createProxyImpl(final ServiceReference<?> ref, final BrokerService service) {
if (service instanceof DOMDataBroker) {
return createProxyImpl(ref, (DOMDataBroker) service);
} else if (service != null) {
return createProxyImplFallback(ref, service);
} else {
- throw new IllegalArgumentException("Unhandled parameter types: "
- + Arrays.<Object> asList(ref, service).toString());
+ throw new IllegalArgumentException(
+ "Unhandled parameter types: " + Arrays.<Object>asList(ref, service).toString());
}
}
+
+ private static Object createProxyImplFallback(final ServiceReference<?> reference, final BrokerService service) {
+
+ return service;
+ }
}
\ No newline at end of file
@Override
public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(SchemaContextListener listener) {
- ListenerRegistration<SchemaContextListener> registration = getDelegate().registerSchemaContextListener(listener);
+ ListenerRegistration<SchemaContextListener> registration = getDelegate()
+ .registerSchemaContextListener(listener);
addRegistration(registration);
return registration;
}
package org.opendaylight.controller.sal.dom.broker.util;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
import java.net.URI;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
-
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.UsesNode;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-
/**
- * ProxySchema Context for SchemaContextProviders
+ * ProxySchema Context for SchemaContextProviders.
*/
public class ProxySchemaContext implements SchemaContext {
}
private SchemaContext getCurrentSchema() {
- Preconditions.checkState(schemaProvider.getSchemaContext() != null, "Schema context unavailable from %s", schemaProvider);
+ Preconditions.checkState(schemaProvider.getSchemaContext() != null, "Schema context unavailable from %s",
+ schemaProvider);
return schemaProvider.getSchemaContext();
}
}
@Override
- public Module findModuleByName(final String s, final Date date) {
- return getCurrentSchema().findModuleByName(s, date);
+ public Module findModuleByName(final String string, final Date date) {
+ return getCurrentSchema().findModuleByName(string, date);
}
@Override
}
@Override
- public DataSchemaNode getDataChildByName(final QName qName) {
- return getCurrentSchema().getDataChildByName(qName);
+ public DataSchemaNode getDataChildByName(final QName name) {
+ return getCurrentSchema().getDataChildByName(name);
}
@Override
private static final class NetconfDataRootNode implements ContainerSchemaNode {
- public NetconfDataRootNode(final SchemaContext schema) {
+ NetconfDataRootNode(final SchemaContext schema) {
// TODO Auto-generated constructor stub
}
*/
package org.opendaylight.controller.md.sal.dom.broker.impl;
+import com.google.common.util.concurrent.SettableFuture;
import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
-import com.google.common.util.concurrent.SettableFuture;
-
/**
* Simple implementation of {@link TransactionChainListener} for testing.
*
+ * <p>
* This transaction chain listener does not contain any logic, only update
* futures ({@link #getFailFuture()} and {@link #getSuccessFuture()} when
* transaction chain event is retrieved.
- *
*/
class BlockingTransactionChainListener implements TransactionChainListener {
@Override
public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
- final Throwable cause) {
+ final Throwable cause) {
failFuture.set(cause);
}
import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
private static final Logger LOG = LoggerFactory.getLogger(DOMBrokerPerformanceTest.class);
- private static NormalizedNode<?, ?> outerList(final int i) {
- return ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i);
+ private static NormalizedNode<?, ?> outerList(final int index) {
+ return ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, index);
}
- private static YangInstanceIdentifier outerListPath(final int i) {
+ private static YangInstanceIdentifier outerListPath(final int index) {
return YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)//
- .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i) //
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, index) //
.build();
}
operStore.onGlobalContextUpdated(schemaContext);
configStore.onGlobalContextUpdated(schemaContext);
- ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore> builder() //
+ ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder() //
.put(CONFIGURATION, configStore) //
.put(OPERATIONAL, operStore) //
.build();
}
private void measureSeparateWritesOneLevel(final int txNum, final int innerNum) throws Exception {
- final List<DOMDataReadWriteTransaction> transactions = measure("Txs:"+ txNum + " Allocate",
- () -> {
- List<DOMDataReadWriteTransaction> builder = new ArrayList<>(txNum);
- for (int i = 0; i < txNum; i++) {
- DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction();
- builder.add(writeTx);
- }
- return builder;
- });
+ final List<DOMDataReadWriteTransaction> transactions = measure("Txs:" + txNum + " Allocate", () -> {
+ List<DOMDataReadWriteTransaction> builder = new ArrayList<>(txNum);
+ for (int i = 0; i < txNum; i++) {
+ DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction();
+ builder.add(writeTx);
+ }
+ return builder;
+ });
assertEquals(txNum, transactions.size());
- measure("Txs:"+ txNum + " Writes:1", (Callable<Void>) () -> {
- int i = 0;
- for (DOMDataReadWriteTransaction writeTx :transactions) {
+ measure("Txs:" + txNum + " Writes:1", (Callable<Void>) () -> {
+ int index = 0;
+ for (DOMDataReadWriteTransaction writeTx : transactions) {
// Writes /test/outer-list/i in writeTx
- writeTx.put(OPERATIONAL, outerListPath(i), outerList(i));
- i++;
+ writeTx.put(OPERATIONAL, outerListPath(index), outerList(index));
+ index++;
}
return null;
});
- measure("Txs:"+ txNum + " Writes:" + innerNum, (Callable<Void>) () -> {
- int i = 0;
- for (DOMDataReadWriteTransaction writeTx :transactions) {
+ measure("Txs:" + txNum + " Writes:" + innerNum, (Callable<Void>) () -> {
+ int index = 0;
+ for (DOMDataReadWriteTransaction writeTx : transactions) {
// Writes /test/outer-list/i in writeTx
- YangInstanceIdentifier path = YangInstanceIdentifier.builder(outerListPath(i))
+ YangInstanceIdentifier path = YangInstanceIdentifier.builder(outerListPath(index))
.node(TestModel.INNER_LIST_QNAME).build();
writeTx.put(OPERATIONAL, path, ImmutableNodes.mapNodeBuilder(TestModel.INNER_LIST_QNAME).build());
for (int j = 0; j < innerNum; j++) {
YangInstanceIdentifier innerPath = YangInstanceIdentifier.builder(path)
- .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, String.valueOf(j))
- .build();
- writeTx.put(
- OPERATIONAL,
- innerPath,
- ImmutableNodes.mapEntry(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME,
- String.valueOf(j)));
+ .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, String.valueOf(j)).build();
+ writeTx.put(OPERATIONAL, innerPath, ImmutableNodes
+ .mapEntry(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, String.valueOf(j)));
}
- i++;
+ index++;
}
return null;
});
measure("Txs:" + txNum + " Submit, Finish", (Callable<Void>) () -> {
- List<ListenableFuture<?>> allFutures = measure(txNum + " Submits",
- () -> {
- List<ListenableFuture<?>> builder = new ArrayList<>(txNum);
- for (DOMDataReadWriteTransaction tx :transactions) {
- builder.add(tx.submit());
- }
- return builder;
- });
+ List<ListenableFuture<?>> allFutures = measure(txNum + " Submits", () -> {
+ List<ListenableFuture<?>> builder = new ArrayList<>(txNum);
+ for (DOMDataReadWriteTransaction tx : transactions) {
+ builder.add(tx.submit());
+ }
+ return builder;
+ });
Futures.allAsList(allFutures).get();
return null;
});
final DOMDataReadTransaction readTx = measure("Txs:1 (ro), Allocate",
- (Callable<DOMDataReadTransaction>) () -> domBroker.newReadOnlyTransaction());
+ (Callable<DOMDataReadTransaction>) () -> domBroker
+ .newReadOnlyTransaction());
- measure("Txs:1 (ro) Reads:" + txNum + " (1-level)" , (Callable<Void>) () -> {
+ measure("Txs:1 (ro) Reads:" + txNum + " (1-level)", (Callable<Void>) () -> {
for (int i = 0; i < txNum; i++) {
- ListenableFuture<Optional<NormalizedNode<?, ?>>> potential = readTx.read(OPERATIONAL,
- outerListPath(i));
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> potential = readTx.read(OPERATIONAL, outerListPath(i));
assertTrue("outerList/" + i, potential.get().isPresent());
}
return null;
measure("Txs:1 (ro) Reads:" + txNum * innerNum + " (2-level)", (Callable<Void>) () -> {
for (int i = 0; i < txNum; i++) {
for (int j = 0; j < innerNum; j++) {
- YangInstanceIdentifier path = YangInstanceIdentifier
- .builder(outerListPath(i))
+ YangInstanceIdentifier path = YangInstanceIdentifier.builder(outerListPath(i))
//
.node(TestModel.INNER_LIST_QNAME)
- .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, String.valueOf(j))
- .build();
+ .nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, String.valueOf(j)).build();
ListenableFuture<Optional<NormalizedNode<?, ?>>> potential = readTx.read(OPERATIONAL, path);
assertTrue("outer-list/" + i + "/inner-list/" + j, potential.get().isPresent());
}
private void measureOneTransactionTopContainer() throws Exception {
- final DOMDataReadWriteTransaction writeTx = measure("Txs:1 Allocate", () -> domBroker.newReadWriteTransaction());
+ final DOMDataReadWriteTransaction writeTx =
+ measure("Txs:1 Allocate", () -> domBroker.newReadWriteTransaction());
measure("Txs:1 Write", (Callable<Void>) () -> {
writeTx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
writeTx.put(OPERATIONAL, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
return null;
});
measure("Txs:1 Reads:1", (Callable<Void>) () -> {
// Reads /test in writeTx
- ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx.read(OPERATIONAL,
- TestModel.TEST_PATH);
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx
+ .read(OPERATIONAL, TestModel.TEST_PATH);
assertTrue(writeTxContainer.get().isPresent());
return null;
});
measure("Txs:1 Reads:1", (Callable<Void>) () -> {
// Reads /test in writeTx
- ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx.read(OPERATIONAL,
- TestModel.TEST_PATH);
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx
+ .read(OPERATIONAL, TestModel.TEST_PATH);
assertTrue(writeTxContainer.get().isPresent());
return null;
});
import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ForwardingExecutorService;
@Before
public void setupStore() {
- InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
- MoreExecutors.newDirectExecutorService());
- InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
- MoreExecutors.newDirectExecutorService());
+ InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
+ InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
schemaContext = TestModel.createTestContext();
operStore.onGlobalContextUpdated(schemaContext);
configStore.onGlobalContextUpdated(schemaContext);
- ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore> builder() //
+ final ImmutableMap<LogicalDatastoreType, DOMStore> stores =
+ ImmutableMap.<LogicalDatastoreType, DOMStore>builder() //
.put(CONFIGURATION, configStore) //
.put(OPERATIONAL, operStore) //
.build();
commitExecutor = new CommitExecutorService(Executors.newSingleThreadExecutor());
futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB");
executor = new DeadlockDetectingListeningExecutorService(commitExecutor,
- TransactionCommitDeadlockException.DEADLOCK_EXCEPTION_SUPPLIER, futureExecutor);
+ TransactionCommitDeadlockException
+ .DEADLOCK_EXCEPTION_SUPPLIER,
+ futureExecutor);
domBroker = new SerializedDOMDataBroker(stores, executor);
}
@After
public void tearDown() {
- if( executor != null ) {
+ if (executor != null) {
executor.shutdownNow();
}
- if(futureExecutor != null) {
+ if (futureExecutor != null) {
futureExecutor.shutdownNow();
}
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testTransactionIsolation() throws InterruptedException, ExecutionException {
assertNotNull(domBroker);
writeTx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
/**
- *
* Reads /test from writeTx Read should return container.
*
*/
- ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx.read(OPERATIONAL,
- TestModel.TEST_PATH);
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx
+ .read(OPERATIONAL, TestModel.TEST_PATH);
assertTrue(writeTxContainer.get().isPresent());
/**
- *
* Reads /test from readTx Read should return Absent.
*
*/
assertFalse(readTxContainer.get().isPresent());
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testTransactionCommit() throws InterruptedException, ExecutionException {
DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction();
writeTx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
/**
- *
* Reads /test from writeTx Read should return container.
*
*/
- ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx.read(OPERATIONAL,
- TestModel.TEST_PATH);
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = writeTx
+ .read(OPERATIONAL, TestModel.TEST_PATH);
assertTrue(writeTxContainer.get().isPresent());
writeTx.submit().get();
assertTrue(afterCommitRead.isPresent());
}
- @Test(expected=TransactionCommitFailedException.class)
+ @Test(expected = TransactionCommitFailedException.class)
public void testRejectedCommit() throws Exception {
- commitExecutor.delegate = Mockito.mock( ExecutorService.class );
- Mockito.doThrow( new RejectedExecutionException( "mock" ) )
- .when( commitExecutor.delegate ).execute( Mockito.any( Runnable.class ) );
- Mockito.doNothing().when( commitExecutor.delegate ).shutdown();
- Mockito.doReturn( Collections.emptyList() ).when( commitExecutor.delegate ).shutdownNow();
- Mockito.doReturn( "" ).when( commitExecutor.delegate ).toString();
- Mockito.doReturn( true ).when( commitExecutor.delegate )
- .awaitTermination( Mockito.anyLong(), Mockito.any( TimeUnit.class ) );
+ commitExecutor.delegate = Mockito.mock(ExecutorService.class);
+ Mockito.doThrow(new RejectedExecutionException("mock")).when(commitExecutor.delegate)
+ .execute(Mockito.any(Runnable.class));
+ Mockito.doNothing().when(commitExecutor.delegate).shutdown();
+ Mockito.doReturn(Collections.emptyList()).when(commitExecutor.delegate).shutdownNow();
+ Mockito.doReturn("").when(commitExecutor.delegate).toString();
+ Mockito.doReturn(true).when(commitExecutor.delegate)
+ .awaitTermination(Mockito.anyLong(), Mockito.any(TimeUnit.class));
DOMDataReadWriteTransaction writeTx = domBroker.newReadWriteTransaction();
- writeTx.put( OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME) );
+ writeTx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- writeTx.submit().checkedGet( 5, TimeUnit.SECONDS );
+ writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
}
/**
* Tests a simple DataChangeListener notification after a write.
*/
@Test
+ @SuppressWarnings("checkstyle:IllegalThrows")
public void testDataChangeListener() throws Throwable {
- final NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode( TestModel.TEST_QNAME );
+ final NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
TestDOMDataChangeListener dcListener = new TestDOMDataChangeListener();
- domBroker.registerDataChangeListener( OPERATIONAL, TestModel.TEST_PATH,
- dcListener, DataChangeScope.BASE );
+ domBroker.registerDataChangeListener(OPERATIONAL, TestModel.TEST_PATH, dcListener, DataChangeScope.BASE);
final DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
- assertNotNull( writeTx );
+ assertNotNull(writeTx);
- writeTx.put( OPERATIONAL, TestModel.TEST_PATH, testNode );
+ writeTx.put(OPERATIONAL, TestModel.TEST_PATH, testNode);
- AtomicReference<Throwable> caughtEx = submitTxAsync( writeTx );
+ AtomicReference<Throwable> caughtEx = submitTxAsync(writeTx);
dcListener.waitForChange();
- if( caughtEx.get() != null ) {
+ if (caughtEx.get() != null) {
throw caughtEx.get();
}
- NormalizedNode<?, ?> actualNode = dcListener.change.getCreatedData().get( TestModel.TEST_PATH );
- assertEquals( "Created node", testNode, actualNode );
+ NormalizedNode<?, ?> actualNode = dcListener.change.getCreatedData().get(TestModel.TEST_PATH);
+ assertEquals("Created node", testNode, actualNode);
}
/**
* This should succeed without deadlock.
*/
@Test
+ @SuppressWarnings("checkstyle:IllegalThrows")
public void testDataChangeListenerDoingAsyncWriteTxSubmit() throws Throwable {
final AtomicReference<Throwable> caughtCommitEx = new AtomicReference<>();
- final CountDownLatch commitCompletedLatch = new CountDownLatch( 1 );
+ final CountDownLatch commitCompletedLatch = new CountDownLatch(1);
TestDOMDataChangeListener dcListener = new TestDOMDataChangeListener() {
@Override
- public void onDataChanged( final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change ) {
+ public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
- writeTx.put( OPERATIONAL, TestModel.TEST2_PATH,
- ImmutableNodes.containerNode( TestModel.TEST2_QNAME ) );
- Futures.addCallback( writeTx.submit(), new FutureCallback<Void>() {
+ writeTx.put(OPERATIONAL, TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME));
+ Futures.addCallback(writeTx.submit(), new FutureCallback<Void>() {
@Override
- public void onSuccess( final Void result ) {
+ public void onSuccess(final Void result) {
commitCompletedLatch.countDown();
}
@Override
- public void onFailure( final Throwable t ) {
- caughtCommitEx.set( t );
+ public void onFailure(final Throwable throwable) {
+ caughtCommitEx.set(throwable);
commitCompletedLatch.countDown();
}
- } );
+ });
- super.onDataChanged( change );
+ super.onDataChanged(change);
}
};
- domBroker.registerDataChangeListener( OPERATIONAL, TestModel.TEST_PATH,
- dcListener, DataChangeScope.BASE );
+ domBroker.registerDataChangeListener(OPERATIONAL, TestModel.TEST_PATH, dcListener, DataChangeScope.BASE);
final DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
- assertNotNull( writeTx );
+ assertNotNull(writeTx);
- writeTx.put( OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode( TestModel.TEST_QNAME ) );
+ writeTx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- AtomicReference<Throwable> caughtEx = submitTxAsync( writeTx );
+ AtomicReference<Throwable> caughtEx = submitTxAsync(writeTx);
dcListener.waitForChange();
- if( caughtEx.get() != null ) {
+ if (caughtEx.get() != null) {
throw caughtEx.get();
}
- assertTrue( "Commit Future was not invoked", commitCompletedLatch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("Commit Future was not invoked", commitCompletedLatch.await(5, TimeUnit.SECONDS));
- if( caughtCommitEx.get() != null ) {
+ if (caughtCommitEx.get() != null) {
throw caughtCommitEx.get();
}
}
* Tests a DataChangeListener that does a blocking submit of a write Tx in its onDataChanged method.
* This should throw an exception and not deadlock.
*/
- @Test(expected=TransactionCommitDeadlockException.class)
+ @Test(expected = TransactionCommitDeadlockException.class)
+ @SuppressWarnings({"checkstyle:IllegalThrows", "checkstyle:IllegalCatch"})
public void testDataChangeListenerDoingBlockingWriteTxSubmit() throws Throwable {
final AtomicReference<Throwable> caughtCommitEx = new AtomicReference<>();
TestDOMDataChangeListener dcListener = new TestDOMDataChangeListener() {
@Override
- public void onDataChanged( final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change ) {
+ public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
- writeTx.put( OPERATIONAL, TestModel.TEST2_PATH,
- ImmutableNodes.containerNode( TestModel.TEST2_QNAME ) );
+ writeTx.put(OPERATIONAL, TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME));
try {
writeTx.submit().get();
- } catch( ExecutionException e ) {
- caughtCommitEx.set( e.getCause() );
- } catch( Exception e ) {
- caughtCommitEx.set( e );
- }
- finally {
- super.onDataChanged( change );
+ } catch (ExecutionException e) {
+ caughtCommitEx.set(e.getCause());
+ } catch (Exception e) {
+ caughtCommitEx.set(e);
+ } finally {
+ super.onDataChanged(change);
}
}
};
- domBroker.registerDataChangeListener( OPERATIONAL, TestModel.TEST_PATH,
- dcListener, DataChangeScope.BASE );
+ domBroker.registerDataChangeListener(OPERATIONAL, TestModel.TEST_PATH, dcListener, DataChangeScope.BASE);
final DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
- assertNotNull( writeTx );
+ assertNotNull(writeTx);
- writeTx.put( OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode( TestModel.TEST_QNAME ) );
+ writeTx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- AtomicReference<Throwable> caughtEx = submitTxAsync( writeTx );
+ AtomicReference<Throwable> caughtEx = submitTxAsync(writeTx);
dcListener.waitForChange();
- if( caughtEx.get() != null ) {
+ if (caughtEx.get() != null) {
throw caughtEx.get();
}
- if( caughtCommitEx.get() != null ) {
+ if (caughtCommitEx.get() != null) {
throw caughtCommitEx.get();
}
}
- AtomicReference<Throwable> submitTxAsync( final DOMDataWriteTransaction writeTx ) {
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ AtomicReference<Throwable> submitTxAsync(final DOMDataWriteTransaction writeTx) {
final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
new Thread(() -> {
try {
static class TestDOMDataChangeListener implements DOMDataChangeListener {
volatile AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change;
- private final CountDownLatch latch = new CountDownLatch( 1 );
+ private final CountDownLatch latch = new CountDownLatch(1);
@Override
- public void onDataChanged( final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change ) {
+ public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
this.change = change;
latch.countDown();
}
void waitForChange() throws InterruptedException {
- assertTrue( "onDataChanged was not called", latch.await( 5, TimeUnit.SECONDS ) );
+ assertTrue("onDataChanged was not called", latch.await(5, TimeUnit.SECONDS));
}
}
ExecutorService delegate;
- public CommitExecutorService( final ExecutorService delegate ) {
+ CommitExecutorService(final ExecutorService delegate) {
this.delegate = delegate;
}
import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
+
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ForwardingExecutorService;
import com.google.common.util.concurrent.ListeningExecutorService;
private CommitExecutorService commitExecutor;
private static final DataContainerChild<?, ?> OUTER_LIST = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
- .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1))
- .build();
+ .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build();
- private static final DataContainerChild<?, ?> OUTER_LIST_2 = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
- .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2))
- .build();
+ private static final DataContainerChild<?, ?> OUTER_LIST_2 = ImmutableNodes
+ .mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
+ .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2)).build();
private static final NormalizedNode<?, ?> TEST_CONTAINER = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
- .withChild(OUTER_LIST)
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(OUTER_LIST)
.build();
private static final NormalizedNode<?, ?> TEST_CONTAINER_2 = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
- .withChild(OUTER_LIST_2)
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(OUTER_LIST_2)
.build();
private static DOMDataTreeIdentifier ROOT_DATA_TREE_ID = new DOMDataTreeIdentifier(
@Before
public void setupStore() {
- InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
- MoreExecutors.newDirectExecutorService());
- InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
- MoreExecutors.newDirectExecutorService());
+ InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
+ InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
schemaContext = TestModel.createTestContext();
operStore.onGlobalContextUpdated(schemaContext);
configStore.onGlobalContextUpdated(schemaContext);
- ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder() //
+ final ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType,
+ DOMStore>builder() //
.put(CONFIGURATION, configStore) //
.put(OPERATIONAL, operStore) //
.build();
commitExecutor = new CommitExecutorService(Executors.newSingleThreadExecutor());
futureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(1, 5, "FCB");
executor = new DeadlockDetectingListeningExecutorService(commitExecutor,
- TransactionCommitDeadlockException.DEADLOCK_EXCEPTION_SUPPLIER, futureExecutor);
+ TransactionCommitDeadlockException
+ .DEADLOCK_EXCEPTION_SUPPLIER,
+ futureExecutor);
domBroker = new SerializedDOMDataBroker(stores, executor);
}
CountDownLatch latch = new CountDownLatch(1);
DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
- assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!",
- dataTreeChangeService);
+ assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);
final TestDataTreeListener listener = new TestDataTreeListener(latch);
- final ListenerRegistration<TestDataTreeListener> listenerReg =
- dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
+ final ListenerRegistration<TestDataTreeListener> listenerReg = dataTreeChangeService
+ .registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
final DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
@Test
public void replaceContainerContainerInTreeTest() throws InterruptedException, TransactionCommitFailedException {
- CountDownLatch latch = new CountDownLatch(2);
+ final CountDownLatch latch = new CountDownLatch(2);
DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
- assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!",
- dataTreeChangeService);
+ assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
writeTx.submit().checkedGet();
final TestDataTreeListener listener = new TestDataTreeListener(latch);
- final ListenerRegistration<TestDataTreeListener> listenerReg =
- dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
+ final ListenerRegistration<TestDataTreeListener> listenerReg = dataTreeChangeService
+ .registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER_2);
writeTx.submit();
@Test
public void deleteContainerContainerInTreeTest() throws InterruptedException, TransactionCommitFailedException {
- CountDownLatch latch = new CountDownLatch(2);
+ final CountDownLatch latch = new CountDownLatch(2);
DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
- assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!",
- dataTreeChangeService);
+ assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
writeTx.submit().checkedGet();
final TestDataTreeListener listener = new TestDataTreeListener(latch);
- final ListenerRegistration<TestDataTreeListener> listenerReg =
- dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
+ final ListenerRegistration<TestDataTreeListener> listenerReg = dataTreeChangeService
+ .registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
writeTx = domBroker.newWriteOnlyTransaction();
writeTx.delete(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH);
@Test
public void replaceChildListContainerInTreeTest() throws InterruptedException, TransactionCommitFailedException {
- CountDownLatch latch = new CountDownLatch(2);
+ final CountDownLatch latch = new CountDownLatch(2);
DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
- assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!",
- dataTreeChangeService);
+ assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
writeTx.submit().checkedGet();
final TestDataTreeListener listener = new TestDataTreeListener(latch);
- final ListenerRegistration<TestDataTreeListener> listenerReg =
- dataTreeChangeService.registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
+ final ListenerRegistration<TestDataTreeListener> listenerReg = dataTreeChangeService
+ .registerDataTreeChangeListener(ROOT_DATA_TREE_ID, listener);
writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH, OUTER_LIST_2);
assertNotNull(candidate);
candidateRoot = candidate.getRootNode();
checkChange(TEST_CONTAINER, TEST_CONTAINER_2, ModificationType.SUBTREE_MODIFIED, candidateRoot);
- final DataTreeCandidateNode modifiedChild = candidateRoot.getModifiedChild(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.OUTER_LIST_QNAME));
+ final DataTreeCandidateNode modifiedChild = candidateRoot
+ .getModifiedChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.OUTER_LIST_QNAME));
assertNotNull(modifiedChild);
checkChange(OUTER_LIST, OUTER_LIST_2, ModificationType.WRITE, modifiedChild);
listenerReg.close();
@Test
public void rootModificationChildListenerTest() throws InterruptedException, TransactionCommitFailedException {
- CountDownLatch latch = new CountDownLatch(2);
+ final CountDownLatch latch = new CountDownLatch(2);
DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
- assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!",
- dataTreeChangeService);
+ assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
writeTx.submit().checkedGet();
final TestDataTreeListener listener = new TestDataTreeListener(latch);
- final ListenerRegistration<TestDataTreeListener> listenerReg =
- dataTreeChangeService.registerDataTreeChangeListener(OUTER_LIST_DATA_TREE_ID, listener);
+ final ListenerRegistration<TestDataTreeListener> listenerReg = dataTreeChangeService
+ .registerDataTreeChangeListener(OUTER_LIST_DATA_TREE_ID, listener);
writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER_2);
@Test
public void listEntryChangeNonRootRegistrationTest() throws InterruptedException, TransactionCommitFailedException {
- CountDownLatch latch = new CountDownLatch(2);
+ final CountDownLatch latch = new CountDownLatch(2);
DOMDataTreeChangeService dataTreeChangeService = getDOMDataTreeChangeService();
- assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!",
- dataTreeChangeService);
+ assertNotNull("DOMDataTreeChangeService not found, cannot continue with test!", dataTreeChangeService);
DOMDataWriteTransaction writeTx = domBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH, TEST_CONTAINER);
writeTx.submit().checkedGet();
final TestDataTreeListener listener = new TestDataTreeListener(latch);
- final ListenerRegistration<TestDataTreeListener> listenerReg =
- dataTreeChangeService.registerDataTreeChangeListener(OUTER_LIST_DATA_TREE_ID, listener);
-
- final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId1 =
- new YangInstanceIdentifier.NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1);
- final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId2 =
- new YangInstanceIdentifier.NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2);
- final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId3 =
- new YangInstanceIdentifier.NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 3);
+ final ListenerRegistration<TestDataTreeListener> listenerReg = dataTreeChangeService
+ .registerDataTreeChangeListener(OUTER_LIST_DATA_TREE_ID, listener);
+
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId1
+ = new YangInstanceIdentifier.NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME,
+ TestModel.ID_QNAME, 1);
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId2
+ = new YangInstanceIdentifier.NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME,
+ TestModel.ID_QNAME, 2);
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates outerListEntryId3
+ = new YangInstanceIdentifier.NodeIdentifierWithPredicates(TestModel.OUTER_LIST_QNAME,
+ TestModel.ID_QNAME, 3);
final MapEntryNode outerListEntry1 = ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1);
final MapEntryNode outerListEntry2 = ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2);
final MapEntryNode outerListEntry3 = ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 3);
- final MapNode listAfter = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
- .withChild(outerListEntry2)
- .withChild(outerListEntry3)
- .build();
+ final MapNode listAfter = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).withChild(outerListEntry2)
+ .withChild(outerListEntry3).build();
writeTx = domBroker.newWriteOnlyTransaction();
writeTx.delete(LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH.node(outerListEntryId1));
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH.node(outerListEntryId2),
- outerListEntry2);
+ outerListEntry2);
writeTx.put(LogicalDatastoreType.CONFIGURATION, TestModel.OUTER_LIST_PATH.node(outerListEntryId3),
- outerListEntry3);
+ outerListEntry3);
writeTx.submit();
latch.await(5, TimeUnit.SECONDS);
listenerReg.close();
}
- private static void checkChange(final NormalizedNode<?, ?> expectedBefore,
- final NormalizedNode<?, ?> expectedAfter,
- final ModificationType expectedMod,
- final DataTreeCandidateNode candidateNode) {
+ private static void checkChange(final NormalizedNode<?, ?> expectedBefore, final NormalizedNode<?, ?> expectedAfter,
+ final ModificationType expectedMod, final DataTreeCandidateNode candidateNode) {
if (expectedBefore != null) {
assertTrue(candidateNode.getDataBefore().isPresent());
assertEquals(expectedBefore, candidateNode.getDataBefore().get());
}
private DOMDataTreeChangeService getDOMDataTreeChangeService() {
- final DOMDataBrokerExtension extension = domBroker.getSupportedExtensions()
- .get(DOMDataTreeChangeService.class);
+ final DOMDataBrokerExtension extension = domBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
if (extension == null) {
return null;
}
ExecutorService delegate;
- public CommitExecutorService(final ExecutorService delegate) {
+ CommitExecutorService(final ExecutorService delegate) {
this.delegate = delegate;
}
private final List<Collection<DataTreeCandidate>> receivedChanges = new ArrayList<>();
private final CountDownLatch latch;
- public TestDataTreeListener(final CountDownLatch latch) {
+ TestDataTreeListener(final CountDownLatch latch) {
this.latch = latch;
}
import static org.junit.Assert.fail;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.OPERATIONAL;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ListenableFuture;
operStore.onGlobalContextUpdated(schemaContext);
configStore.onGlobalContextUpdated(schemaContext);
- ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore> builder() //
+ ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder() //
.put(CONFIGURATION, configStore) //
.put(OPERATIONAL, operStore) //
.build();
assertNotNull(txChain);
/**
- * We alocate new read-write transaction and write /test
- *
- *
+ * We alocate new read-write transaction and write /test.
*/
DOMDataReadWriteTransaction firstTx = allocateAndWrite(txChain);
/**
* First transaction is marked as ready, we are able to allocate chained
- * transactions
+ * transactions.
*/
ListenableFuture<Void> firstWriteTxFuture = firstTx.submit();
*
* We test if we are able to read data from tx, read should not fail
* since we are using chained transaction.
- *
- *
*/
assertTestContainerExists(secondReadTx);
/**
- *
* We alocate next transaction, which is still based on first one, but
* is read-write.
*
DOMDataReadWriteTransaction thirdDeleteTx = allocateAndDelete(txChain);
/**
- * We commit first transaction
+ * We commit first transaction.
*
*/
assertCommitSuccessful(firstWriteTxFuture);
/**
- *
* Allocates transaction from data store.
- *
*/
DOMDataReadTransaction storeReadTx = domBroker.newReadOnlyTransaction();
assertTestContainerExists(storeReadTx);
/**
- * third transaction is sealed and commited
+ * third transaction is sealed and commited.
*/
ListenableFuture<Void> thirdDeleteTxFuture = thirdDeleteTx.submit();
assertCommitSuccessful(thirdDeleteTxFuture);
}
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void testTransactionChainNotSealed() throws InterruptedException, ExecutionException, TimeoutException {
BlockingTransactionChainListener listener = new BlockingTransactionChainListener();
DOMTransactionChain txChain = domBroker.createTransactionChain(listener);
/**
* We alocate new read-write transaction and write /test
- *
- *
*/
allocateAndWrite(txChain);
}
}
- private static DOMDataReadWriteTransaction allocateAndDelete(final DOMTransactionChain txChain)
- throws InterruptedException, ExecutionException {
+ private static DOMDataReadWriteTransaction allocateAndDelete(
+ final DOMTransactionChain txChain) throws InterruptedException, ExecutionException {
DOMDataReadWriteTransaction tx = txChain.newReadWriteTransaction();
/**
return tx;
}
- private static DOMDataReadWriteTransaction allocateAndWrite(final DOMTransactionChain txChain)
- throws InterruptedException, ExecutionException {
+ private static DOMDataReadWriteTransaction allocateAndWrite(
+ final DOMTransactionChain txChain) throws InterruptedException, ExecutionException {
DOMDataReadWriteTransaction tx = txChain.newReadWriteTransaction();
assertTestContainerWrite(tx);
return tx;
}
- private static void assertCommitSuccessful(final ListenableFuture<Void> future)
- throws InterruptedException, ExecutionException {
+ private static void assertCommitSuccessful(
+ final ListenableFuture<Void> future) throws InterruptedException, ExecutionException {
future.get();
}
- private static void assertTestContainerExists(final DOMDataReadTransaction readTx) throws InterruptedException,
- ExecutionException {
+ private static void assertTestContainerExists(
+ final DOMDataReadTransaction readTx) throws InterruptedException, ExecutionException {
ListenableFuture<Optional<NormalizedNode<?, ?>>> readFuture = readTx.read(OPERATIONAL, TestModel.TEST_PATH);
Optional<NormalizedNode<?, ?>> readedData = readFuture.get();
assertTrue(readedData.isPresent());
}
- private static void assertTestContainerWrite(final DOMDataReadWriteTransaction tx) throws InterruptedException,
- ExecutionException {
+ private static void assertTestContainerWrite(
+ final DOMDataReadWriteTransaction tx) throws InterruptedException, ExecutionException {
tx.put(OPERATIONAL, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
assertTestContainerExists(tx);
}
public class MountPointServiceTest {
private DOMMountPointService mountService;
- private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.of(QName.create("namespace", "2012-12-12", "top"));
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier
+ .of(QName.create("namespace", "2012-12-12", "top"));
@Before
public void setup() {
doNothing().when(writeTx).put(any(), any(), any());
doNothing().when(writeTx).merge(any(), any(), any());
doNothing().when(writeTx).delete(any(), any());
- rwTx = new ShardedDOMDataBrokerDelegatingReadWriteTransaction("TEST-TX", TestModel.createTestContext(), readTx, writeTx);
+ rwTx = new ShardedDOMDataBrokerDelegatingReadWriteTransaction("TEST-TX", TestModel.createTestContext(), readTx,
+ writeTx);
}
@Test(expected = IllegalStateException.class)
@Test
public void testReadWriteOperations() throws Exception {
- doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(readTx)
- .read(any(), any());
- rwTx.put(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH,
- testNodeWithOuter(1, 2, 3));
+ doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(readTx).read(any(), any());
+ rwTx.put(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH, testNodeWithOuter(1, 2, 3));
verify(writeTx).put(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH),
- Matchers.eq(testNodeWithOuter(1, 2, 3)));
+ Matchers.eq(testNodeWithOuter(1, 2, 3)));
verify(readTx).read(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH));
assertEquals(testNodeWithOuter(1, 2, 3),
- rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get());
+ rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get());
- rwTx.merge(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH,
- testNodeWithOuter(4, 5, 6));
+ rwTx.merge(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH, testNodeWithOuter(4, 5, 6));
assertEquals(testNodeWithOuter(1, 2, 3, 4, 5, 6),
- rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get());
+ rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get());
rwTx.delete(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH);
verify(writeTx).delete(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH));
- assertEquals(Optional.absent(),
- rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet());
+ assertEquals(Optional.absent(), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet());
}
private DataContainerChild<?, ?> outerNode(int... ids) {
CollectionNodeBuilder<MapEntryNode, MapNode> outer = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME);
- for(int id: ids) {
+ for (int id : ids) {
outer.addChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, id));
}
}
private NormalizedNode<?, ?> testNodeWithOuter(DataContainerChild<?, ?> outer) {
- return ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(outer).build();
+ return ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).withChild(outer)
+ .build();
}
}
\ No newline at end of file
MockitoAnnotations.initMocks(this);
doReturn(delegateTxChain).when(dataBroker).createTransactionChain(any());
- txChain = new ShardedDOMDataBrokerDelegatingTransactionChain("1", TestModel.createTestContext(), dataBroker, txChainlistener);
+ txChain = new ShardedDOMDataBrokerDelegatingTransactionChain("1", TestModel.createTestContext(), dataBroker,
+ txChainlistener);
}
@Test
final ArgumentCaptor<AsyncTransaction> txCaptor = ArgumentCaptor.forClass(AsyncTransaction.class);
final ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
- verify(txChainlistener)
- .onTransactionChainFailed(eq(txChain), txCaptor.capture(), throwableCaptor.capture());
+ verify(txChainlistener).onTransactionChainFailed(eq(txChain), txCaptor.capture(), throwableCaptor.capture());
assertEquals("DOM-CHAIN-1-0", txCaptor.getValue().getIdentifier());
assertEquals("Fail", throwableCaptor.getValue().getMessage());
verify(mockDOMReg).close();
}
- @Test(expected=CandidateAlreadyRegisteredException.class)
+ @Test(expected = CandidateAlreadyRegisteredException.class)
public void testAlreadyRegisteredCandidate() throws Exception {
- doThrow(new org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException(DOM_ENTITY)).
- when(mockDOMService).registerCandidate(DOM_ENTITY);
+ doThrow(new org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException(DOM_ENTITY))
+ .when(mockDOMService).registerCandidate(DOM_ENTITY);
adapter.registerCandidate(LEGACY_ENTITY);
}
public void testRegisterListener() {
DOMEntityOwnershipListenerRegistration mockDOMReg = mock(DOMEntityOwnershipListenerRegistration.class);
doNothing().when(mockDOMReg).close();
- doReturn(mockDOMReg).when(mockDOMService).registerListener(eq(DOM_ENTITY.getType()),
- any(DOMEntityOwnershipListener.class));
+ doReturn(mockDOMReg).when(mockDOMService)
+ .registerListener(eq(DOM_ENTITY.getType()), any(DOMEntityOwnershipListener.class));
EntityOwnershipListener mockListener = mock(EntityOwnershipListener.class);
doNothing().when(mockListener).ownershipChanged(any(EntityOwnershipChange.class));
assertEquals("getInstance", mockListener, reg.getInstance());
assertEquals("getEntityType", LEGACY_ENTITY.getType(), reg.getEntityType());
- ArgumentCaptor<DOMEntityOwnershipListener> domListenerCaptor = ArgumentCaptor.forClass(DOMEntityOwnershipListener.class);
- verify(mockDOMService).registerListener(eq(DOM_ENTITY.getType()), domListenerCaptor.capture());
+ ArgumentCaptor<DOMEntityOwnershipListener> domListenerCaptor = ArgumentCaptor
+ .forClass(DOMEntityOwnershipListener.class);
+ verify(mockDOMService).registerListener(eq(DOM_ENTITY.getType()), domListenerCaptor.capture());
DOMEntityOwnershipChange domOwnershipChange = new DOMEntityOwnershipChange(DOM_ENTITY,
- EntityOwnershipChangeState.LOCAL_OWNERSHIP_GRANTED);
- domListenerCaptor.getValue().ownershipChanged(domOwnershipChange );
+ EntityOwnershipChangeState
+ .LOCAL_OWNERSHIP_GRANTED);
+ domListenerCaptor.getValue().ownershipChanged(domOwnershipChange);
- ArgumentCaptor<EntityOwnershipChange> ownershipChangeCaptor = ArgumentCaptor.forClass(EntityOwnershipChange.class);
+ ArgumentCaptor<EntityOwnershipChange> ownershipChangeCaptor = ArgumentCaptor
+ .forClass(EntityOwnershipChange.class);
verify(mockListener).ownershipChanged(ownershipChangeCaptor.capture());
EntityOwnershipChange change = ownershipChangeCaptor.getValue();
assertEquals("isPresent", false, adapter.getOwnershipState(LEGACY_ENTITY).isPresent());
}
- @Test
- public void testIsCandidateRegistered() {
- doReturn(true).when(mockDOMService).isCandidateRegistered(DOM_ENTITY);
- assertEquals("isCandidateRegistered", true, adapter.isCandidateRegistered(LEGACY_ENTITY));
- }
-
private void testGetOwnershipState(EntityOwnershipState state, boolean expIsOwner, boolean expHasOwner) {
doReturn(Optional.of(state)).when(mockDOMService).getOwnershipState(DOM_ENTITY);
- Optional<org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState> actualState =
- adapter.getOwnershipState(LEGACY_ENTITY);
+ Optional<org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState> actualState = adapter
+ .getOwnershipState(LEGACY_ENTITY);
assertEquals("isPresent", true, actualState.isPresent());
assertEquals("isOwner", expIsOwner, actualState.get().isOwner());
}
+ @Test
+ public void testIsCandidateRegistered() {
+ doReturn(true).when(mockDOMService).isCandidateRegistered(DOM_ENTITY);
+ assertEquals("isCandidateRegistered", true, adapter.isCandidateRegistered(LEGACY_ENTITY));
+ }
}
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-public class TestModel {
+public final class TestModel {
+
+ private TestModel() {
+ }
public static final QName TEST_QNAME =
QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", "2014-03-13", "test");