import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
+import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
-import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.md.sal.common.api.data.DataStoreUnavailableException;
DOMStore store = new InMemoryDOMDataStore("OPER",
MoreExecutors.newDirectExecutorService());
- coordinator = new ConcurrentDOMDataBroker(ImmutableMap.of(LogicalDatastoreType.OPERATIONAL, store), futureExecutor);
+ coordinator = new ConcurrentDOMDataBroker(ImmutableMap.of(LogicalDatastoreType.OPERATIONAL, store),
+ futureExecutor);
}
@After
}
@Test
- public void testSuccessfulSubmitAsync() throws Throwable {
+ public void testSuccessfulSubmitAsync() throws Exception {
testSuccessfulSubmit(true);
}
@Test
- public void testSuccessfulSubmitSync() throws Throwable {
+ public void testSuccessfulSubmitSync() throws Exception {
testSuccessfulSubmit(false);
}
- private void testSuccessfulSubmit(final boolean doAsync) throws Throwable {
+ private void testSuccessfulSubmit(final boolean doAsync) throws InterruptedException {
final CountDownLatch asyncCanCommitContinue = new CountDownLatch(1);
- Answer<ListenableFuture<Boolean>> asyncCanCommit = new Answer<ListenableFuture<Boolean>>() {
- @Override
- public ListenableFuture<Boolean> answer(final InvocationOnMock invocation) {
- final SettableFuture<Boolean> future = SettableFuture.create();
- if(doAsync) {
- new Thread() {
- @Override
- public void run() {
- Uninterruptibles.awaitUninterruptibly(asyncCanCommitContinue,
- 10, TimeUnit.SECONDS);
- future.set(true);
- }
- }.start();
- } else {
- future.set(true);
- }
-
- return future;
+ Answer<ListenableFuture<Boolean>> asyncCanCommit = invocation -> {
+ final SettableFuture<Boolean> future = SettableFuture.create();
+ if (doAsync) {
+ new Thread() {
+ @Override
+ public void run() {
+ Uninterruptibles.awaitUninterruptibly(asyncCanCommitContinue,
+ 10, TimeUnit.SECONDS);
+ future.set(true);
+ }
+ }.start();
+ } else {
+ future.set(true);
}
+
+ return future;
};
doAnswer(asyncCanCommit).when(mockCohort1).canCommit();
}
@Override
- public void onFailure(final Throwable t) {
- caughtEx.set(t);
+ public void onFailure(final Throwable failure) {
+ caughtEx.set(failure);
doneLatch.countDown();
}
});
assertEquals("Submit complete", true, doneLatch.await(5, TimeUnit.SECONDS));
- if(caughtEx.get() != null) {
- throw caughtEx.get();
+ if (caughtEx.get() != null) {
+ Throwables.propagate(caughtEx.get());
}
assertEquals("Task count", doAsync ? 1 : 0, futureExecutor.getTaskCount());
future.checkedGet(5, TimeUnit.SECONDS);
fail("Expected TransactionCommitFailedException");
} catch (TransactionCommitFailedException e) {
- if(expCause != null) {
+ if (expCause != null) {
assertSame("Expected cause", expCause.getClass(), e.getCause().getClass());
}
InOrder inOrder = inOrder((Object[])mockCohorts);
- for(DOMStoreThreePhaseCommitCohort c: mockCohorts) {
+ for (DOMStoreThreePhaseCommitCohort c: mockCohorts) {
inOrder.verify(c).abort();
}
} catch (TimeoutException e) {
DOMStoreThreePhaseCommitCohort mockCohort3 = mock(DOMStoreThreePhaseCommitCohort.class);
doReturn(Futures.immediateFuture(true)).when(mockCohort3).canCommit();
- doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock2"))).
- when(mockCohort3).preCommit();
+ doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock2")))
+ .when(mockCohort3).preCommit();
doReturn(Futures.immediateFuture(null)).when(mockCohort3).abort();
CheckedFuture<Void, TransactionCommitFailedException> future = coordinator.submit(
DOMStoreThreePhaseCommitCohort mockCohort3 = mock(DOMStoreThreePhaseCommitCohort.class);
doReturn(Futures.immediateFuture(true)).when(mockCohort3).canCommit();
doReturn(Futures.immediateFuture(null)).when(mockCohort3).preCommit();
- doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock2"))).
- when(mockCohort3).commit();
+ doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock2")))
+ .when(mockCohort3).commit();
doReturn(Futures.immediateFuture(null)).when(mockCohort3).abort();
CheckedFuture<Void, TransactionCommitFailedException> future = coordinator.submit(
@Test
public void testSubmitWithAbortException() throws Exception {
doReturn(Futures.immediateFuture(true)).when(mockCohort1).canCommit();
- doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock abort error"))).
- when(mockCohort1).abort();
+ doReturn(Futures.immediateFailedFuture(new IllegalStateException("mock abort error")))
+ .when(mockCohort1).abort();
IllegalStateException cause = new IllegalStateException("mock canCommit error");
doReturn(Futures.immediateFailedFuture(cause)).when(mockCohort2).canCommit();
}
@Test
- public void testCreateReadWriteTransaction(){
+ public void testCreateReadWriteTransaction() {
DOMStore domStore = mock(DOMStore.class);
try (ConcurrentDOMDataBroker dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
}
@Test
- public void testCreateWriteOnlyTransaction(){
+ public void testCreateWriteOnlyTransaction() {
DOMStore domStore = mock(DOMStore.class);
try (ConcurrentDOMDataBroker dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
}
@Test
- public void testCreateReadOnlyTransaction(){
+ public void testCreateReadOnlyTransaction() {
DOMStore domStore = mock(DOMStore.class);
try (ConcurrentDOMDataBroker dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
}
@Test
- public void testLazySubTransactionCreationForReadWriteTransactions(){
+ public void testLazySubTransactionCreationForReadWriteTransactions() {
DOMStore configDomStore = mock(DOMStore.class);
DOMStore operationalDomStore = mock(DOMStore.class);
DOMStoreReadWriteTransaction storeTxn = mock(DOMStoreReadWriteTransaction.class);
}
@Test
- public void testLazySubTransactionCreationForWriteOnlyTransactions(){
+ public void testLazySubTransactionCreationForWriteOnlyTransactions() {
DOMStore configDomStore = mock(DOMStore.class);
DOMStore operationalDomStore = mock(DOMStore.class);
DOMStoreWriteTransaction storeTxn = mock(DOMStoreWriteTransaction.class);
}
@Test
- public void testLazySubTransactionCreationForReadOnlyTransactions(){
+ public void testLazySubTransactionCreationForReadOnlyTransactions() {
DOMStore configDomStore = mock(DOMStore.class);
DOMStore operationalDomStore = mock(DOMStore.class);
DOMStoreReadTransaction storeTxn = mock(DOMStoreReadTransaction.class);
LogicalDatastoreType.OPERATIONAL, operationalDomStore, LogicalDatastoreType.CONFIGURATION,
configDomStore), futureExecutor) {
@Override
- public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction, Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
+ public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction writeTx,
+ Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
commitCohorts.addAll(cohorts);
latch.countDown();
- return super.submit(transaction, cohorts);
+ return super.submit(writeTx, cohorts);
}
}) {
DOMDataReadWriteTransaction domDataReadWriteTransaction = dataBroker.newReadWriteTransaction();
domDataReadWriteTransaction.submit();
- latch.await(10, TimeUnit.SECONDS);
+ assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(commitCohorts.size() == 1);
}
LogicalDatastoreType.OPERATIONAL, operationalDomStore, LogicalDatastoreType.CONFIGURATION,
configDomStore), futureExecutor) {
@Override
- public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction, Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
+ public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
+ Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
commitCohorts.addAll(cohorts);
latch.countDown();
return super.submit(transaction, cohorts);
}) {
DOMDataReadWriteTransaction domDataReadWriteTransaction = dataBroker.newReadWriteTransaction();
- domDataReadWriteTransaction.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY, mock(NormalizedNode.class));
- domDataReadWriteTransaction.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY, mock(NormalizedNode.class));
+ domDataReadWriteTransaction.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY,
+ mock(NormalizedNode.class));
+ domDataReadWriteTransaction.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY,
+ mock(NormalizedNode.class));
domDataReadWriteTransaction.submit();
- latch.await(10, TimeUnit.SECONDS);
+ assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(commitCohorts.size() == 2);
}
}
@Test
- public void testCreateTransactionChain(){
+ public void testCreateTransactionChain() {
DOMStore domStore = mock(DOMStore.class);
try (ConcurrentDOMDataBroker dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
}
@Test
- public void testCreateTransactionOnChain(){
+ public void testCreateTransactionOnChain() {
DOMStore domStore = mock(DOMStore.class);
try (ConcurrentDOMDataBroker dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
doReturn(mockChain).when(domStore).createTransactionChain();
doReturn(operationalTransaction).when(mockChain).newWriteOnlyTransaction();
- DOMTransactionChain transactionChain = dataBroker.createTransactionChain(mock(TransactionChainListener.class));
+ DOMTransactionChain transactionChain = dataBroker.createTransactionChain(
+ mock(TransactionChainListener.class));
DOMDataWriteTransaction domDataWriteTransaction = transactionChain.newWriteOnlyTransaction();
verify(mockChain, never()).newWriteOnlyTransaction();
- domDataWriteTransaction.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY, mock(NormalizedNode.class));
+ domDataWriteTransaction.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY,
+ mock(NormalizedNode.class));
}
}
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
futureExecutor)) {
- CheckedFuture<Void, TransactionCommitFailedException> submit1 = dataBroker.newWriteOnlyTransaction().submit();
+ CheckedFuture<Void, TransactionCommitFailedException> submit1 =
+ dataBroker.newWriteOnlyTransaction().submit();
assertNotNull(submit1);
submit1.get();
- CheckedFuture<Void, TransactionCommitFailedException> submit2 = dataBroker.newReadWriteTransaction().submit();
+ CheckedFuture<Void, TransactionCommitFailedException> submit2 =
+ dataBroker.newReadWriteTransaction().submit();
assertNotNull(submit2);
import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.successfulCanCommit;
import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.successfulCommit;
import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.successfulPreCommit;
+
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.yangtools.concepts.Identifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
*
* @author Thomas Pantelis
*/
-public abstract class AbstractShardTest extends AbstractActorTest{
+public abstract class AbstractShardTest extends AbstractActorTest {
protected static final SchemaContext SCHEMA_CONTEXT = TestModel.createTestContext();
private static final AtomicInteger NEXT_SHARD_NUM = new AtomicInteger();
protected final ShardIdentifier shardID = ShardIdentifier.create("inventory", MemberName.forName("member-1"),
"config" + NEXT_SHARD_NUM.getAndIncrement());
- protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder().
- shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).
- shardHeartbeatIntervalInMillis(100);
+ protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
+ .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).shardHeartbeatIntervalInMillis(100);
protected final TestActorFactory actorFactory = new TestActorFactory(getSystem());
final CountDownLatch recoveryComplete = new CountDownLatch(1);
- @SuppressWarnings("serial")
- final Creator<Shard> creator = new Creator<Shard>() {
+ final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
@Override
- public Shard create() throws Exception {
- return new Shard(newShardBuilder()) {
- @Override
- protected void onRecoveryComplete() {
- try {
- super.onRecoveryComplete();
- } finally {
- recoveryComplete.countDown();
- }
- }
- };
+ protected void onRecoveryComplete() {
+ try {
+ super.onRecoveryComplete();
+ } finally {
+ recoveryComplete.countDown();
+ }
}
};
final TestActorRef<Shard> shard = TestActorRef.create(getSystem(),
- Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()), "testRecovery");
+ Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testRecovery");
assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS));
assertNotNull(TestModel.OUTER_LIST_QNAME.getLocalName() + " not found", outerList);
assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " value is not Iterable",
outerList.getValue() instanceof Iterable);
- for(final Object entry: (Iterable<?>) outerList.getValue()) {
+ for (final Object entry: (Iterable<?>) outerList.getValue()) {
assertTrue(TestModel.OUTER_LIST_QNAME.getLocalName() + " entry is not MapEntryNode",
entry instanceof MapEntryNode);
final MapEntryNode mapEntry = (MapEntryNode)entry;
mapEntry.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
final Object value = idLeaf.get().getValue();
- assertTrue("Unexpected value for leaf "+ TestModel.ID_QNAME.getLocalName() + ": " + value,
+ assertTrue("Unexpected value for leaf " + TestModel.ID_QNAME.getLocalName() + ": " + value,
listEntryKeys.remove(value));
}
- if(!listEntryKeys.isEmpty()) {
- fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " +
- listEntryKeys);
+ if (!listEntryKeys.isEmpty()) {
+ fail("Missing " + TestModel.OUTER_LIST_QNAME.getLocalName() + " entries with keys: " + listEntryKeys);
}
assertEquals("Last log index", nListEntries,
protected void verifyLastApplied(final TestActorRef<Shard> shard, final long expectedValue) {
long lastApplied = -1;
- for(int i = 0; i < 20 * 5; i++) {
+ for (int i = 0; i < 20 * 5; i++) {
lastApplied = shard.underlyingActor().getShardMBean().getLastApplied();
- if(lastApplied == expectedValue) {
+ if (lastApplied == expectedValue) {
return;
}
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
protected Map<TransactionIdentifier, CapturingShardDataTreeCohort> setupCohortDecorator(final Shard shard,
final TransactionIdentifier... transactionIDs) {
final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = new HashMap<>();
- for(TransactionIdentifier id: transactionIDs) {
+ for (TransactionIdentifier id: transactionIDs) {
cohortMap.put(id, new CapturingShardDataTreeCohort());
}
- shard.getCommitCoordinator().setCohortDecorator(new ShardCommitCoordinator.CohortDecorator() {
- @Override
- public ShardDataTreeCohort decorate(final Identifier transactionID, final ShardDataTreeCohort actual) {
- CapturingShardDataTreeCohort cohort = cohortMap.get(transactionID);
- cohort.setDelegate(actual);
- return cohort;
- }
+ shard.getCommitCoordinator().setCohortDecorator((transactionID, actual) -> {
+ CapturingShardDataTreeCohort cohort = cohortMap.get(transactionID);
+ cohort.setDelegate(actual);
+ return cohort;
});
return cohortMap;
protected static ForwardedReadyTransaction prepareForwardedReadyTransaction(final TestActorRef<Shard> shard,
final TransactionIdentifier transactionID, final YangInstanceIdentifier path,
final NormalizedNode<?, ?> data, final boolean doCommitOnReady) {
- ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore().
- newReadWriteTransaction(transactionID);
+ ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore()
+ .newReadWriteTransaction(transactionID);
rwTx.getSnapshot().write(path, data);
return new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, doCommitOnReady);
}
- public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard, final YangInstanceIdentifier id)
- throws ExecutionException, InterruptedException {
+ public static NormalizedNode<?,?> readStore(final TestActorRef<? extends Shard> shard,
+ final YangInstanceIdentifier id) throws ExecutionException, InterruptedException {
return shard.underlyingActor().getDataStore().readNode(id).orNull();
}
public void writeToStore(final TestActorRef<Shard> shard, final YangInstanceIdentifier id,
final NormalizedNode<?,?> node) throws InterruptedException, ExecutionException {
- Future<Object> future = Patterns.ask(shard, newBatchedModifications(nextTransactionId(), id, node, true, true, 1),
- new Timeout(5, TimeUnit.SECONDS));
+ Future<Object> future = Patterns.ask(shard, newBatchedModifications(nextTransactionId(),
+ id, node, true, true, 1), new Timeout(5, TimeUnit.SECONDS));
try {
Await.ready(future, Duration.create(5, TimeUnit.SECONDS));
- } catch(TimeoutException e) {
+ } catch (TimeoutException e) {
throw new ExecutionException(e);
}
}
store.commit(modification);
}
+ public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
+ final NormalizedNode<?,?> node) throws DataValidationFailedException {
+ final DataTreeModification transaction = store.takeSnapshot().newModification();
+
+ transaction.write(id, node);
+ transaction.ready();
+ store.validate(transaction);
+ final DataTreeCandidate candidate = store.prepare(transaction);
+ store.commit(candidate);
+ }
+
public void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id,
final NormalizedNode<?,?> node) throws Exception {
final BatchedModifications batched = new BatchedModifications(nextTransactionId(), CURRENT_VERSION);
store.commit(modification);
}
- public static void writeToStore(final DataTree store, final YangInstanceIdentifier id,
- final NormalizedNode<?,?> node) throws DataValidationFailedException {
- final DataTreeModification transaction = store.takeSnapshot().newModification();
-
- transaction.write(id, node);
- transaction.ready();
- store.validate(transaction);
- final DataTreeCandidate candidate = store.prepare(transaction);
- store.commit(candidate);
- }
-
DataTree setupInMemorySnapshotStore() throws DataValidationFailedException {
final DataTree testStore = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
testStore.setSchemaContext(SCHEMA_CONTEXT);
}
static BatchedModifications newBatchedModifications(final TransactionIdentifier transactionID,
- final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready, final boolean doCommitOnReady,
- final int messagesSent) {
+ final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final boolean ready,
+ final boolean doCommitOnReady, final int messagesSent) {
final BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
batched.addModification(new WriteModification(path, data));
batched.setReady(ready);
final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
- doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME))).when(mockCandidateNode).getDataAfter();
+ doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME)))
+ .when(mockCandidateNode).getDataAfter();
doReturn(CarsModel.BASE_PATH).when(mockCandidate).getRootPath();
doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
return mockCandidate;
return mockCandidate;
}
- static void commitTransaction(final DataTree store, final DataTreeModification modification) throws DataValidationFailedException {
+ static void commitTransaction(final DataTree store, final DataTreeModification modification)
+ throws DataValidationFailedException {
modification.ready();
store.validate(modification);
store.commit(store.prepare(modification));
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.util.Timeout;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
+import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.CheckedFuture;
import com.typesafe.config.Config;
private final Configuration configuration = new MockConfiguration() {
Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
- "junk", new ShardStrategy() {
- @Override
- public String findShard(YangInstanceIdentifier path) {
- return "junk";
- }
- }).put(
- "cars", new ShardStrategy() {
- @Override
- public String findShard(YangInstanceIdentifier path) {
- return "cars";
- }
- }).build();
+ "junk", path -> "junk").put(
+ "cars", path -> "cars").build();
@Override
public ShardStrategy getStrategyForModule(String moduleName) {
@Override
public String getModuleNameFromNameSpace(String nameSpace) {
- if(TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
+ if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
return "junk";
- } else if(CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)){
+ } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) {
return "cars";
}
return null;
@BeforeClass
public static void setUpClass() throws IOException {
- Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder().
- put("akka.actor.default-dispatcher.type",
- "akka.testkit.CallingThreadDispatcherConfigurator").build()).
- withFallback(ConfigFactory.load());
+ Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
+ .put("akka.actor.default-dispatcher.type",
+ "akka.testkit.CallingThreadDispatcherConfigurator").build())
+ .withFallback(ConfigFactory.load());
system = ActorSystem.create("test", config);
}
}
@Before
- public void setUp(){
+ public void setUp() {
MockitoAnnotations.initMocks(this);
schemaContext = TestModel.createTestContext();
return system;
}
- protected CreateTransaction eqCreateTransaction(final String memberName,
+ protected CreateTransaction eqCreateTransaction(final String expMemberName,
final TransactionType type) {
ArgumentMatcher<CreateTransaction> matcher = new ArgumentMatcher<CreateTransaction>() {
@Override
public boolean matches(Object argument) {
- if(CreateTransaction.class.equals(argument.getClass())) {
+ if (CreateTransaction.class.equals(argument.getClass())) {
CreateTransaction obj = CreateTransaction.fromSerializable(argument);
- return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName().getName().equals(memberName) &&
- obj.getTransactionType() == type.ordinal();
+ return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
+ .getName().equals(expMemberName) && obj.getTransactionType() == type.ordinal();
}
return false;
ArgumentMatcher<DataExists> matcher = new ArgumentMatcher<DataExists>() {
@Override
public boolean matches(Object argument) {
- return (argument instanceof DataExists) &&
- ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
+ return argument instanceof DataExists && ((DataExists)argument).getPath().equals(TestModel.TEST_PATH);
}
};
ArgumentMatcher<ReadData> matcher = new ArgumentMatcher<ReadData>() {
@Override
public boolean matches(Object argument) {
- return (argument instanceof ReadData) && ((ReadData)argument).getPath().equals(path);
+ return argument instanceof ReadData && ((ReadData)argument).getPath().equals(path);
}
};
eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
}
+ protected void expectBatchedModifications(int count) {
+ doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
+ }
+
protected void expectBatchedModificationsReady(ActorRef actorRef) {
expectBatchedModificationsReady(actorRef, false);
}
eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
}
- protected void expectBatchedModifications(int count) {
- doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
- }
-
protected void expectIncompleteBatchedModifications() {
doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
}
- protected CreateTransactionReply createTransactionReply(ActorRef actorRef, short transactionVersion){
+ protected CreateTransactionReply createTransactionReply(ActorRef actorRef, short transactionVersion) {
return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
}
return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
}
- protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
- return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
- }
-
- protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
- short transactionVersion) {
- return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
- transactionVersion));
- }
-
protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) {
- return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION);
+ return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
+ DataStoreVersions.CURRENT_VERSION);
}
protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName,
ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
log.info("Created mock shard actor {}", actorRef);
- doReturn(actorSystem.actorSelection(actorRef.path())).
- when(mockActorContext).actorSelection(actorRef.path().toString());
+ doReturn(actorSystem.actorSelection(actorRef.path()))
+ .when(mockActorContext).actorSelection(actorRef.path().toString());
- doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion)).
- when(mockActorContext).findPrimaryShardAsync(eq(shardName));
+ doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
+ .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
return actorRef;
}
+ protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) {
+ return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
+ }
+
+ protected Future<PrimaryShardInfo> primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef,
+ short transactionVersion) {
+ return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
+ transactionVersion));
+ }
+
protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem,
TransactionType type, short transactionVersion, String shardName) {
ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) {
ActorRef txActorRef;
- if(type == TransactionType.WRITE_ONLY &&
- dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
+ if (type == TransactionType.WRITE_ONLY
+ && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
txActorRef = shardActorRef;
} else {
txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
log.info("Created mock shard Tx actor {}", txActorRef);
- doReturn(actorSystem.actorSelection(txActorRef.path())).
- when(mockActorContext).actorSelection(txActorRef.path().toString());
+ doReturn(actorSystem.actorSelection(txActorRef.path()))
+ .when(mockActorContext).actorSelection(txActorRef.path().toString());
- doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext).
- executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
+ doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
+ .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
eqCreateTransaction(prefix, type), any(Timeout.class));
}
shardName);
}
- protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future)
- throws Throwable {
-
+ protected void propagateReadFailedExceptionCause(CheckedFuture<?, ReadFailedException> future) throws Exception {
try {
future.checkedGet(5, TimeUnit.SECONDS);
fail("Expected ReadFailedException");
- } catch(ReadFailedException e) {
+ } catch (ReadFailedException e) {
assertNotNull("Expected a cause", e.getCause());
- if(e.getCause().getCause() != null) {
- throw e.getCause().getCause();
+ Throwable cause;
+ if (e.getCause().getCause() != null) {
+ cause = e.getCause().getCause();
} else {
- throw e.getCause();
+ cause = e.getCause();
}
+
+ Throwables.propagateIfInstanceOf(cause, Exception.class);
+ Throwables.propagate(cause);
}
}
protected <T> List<T> filterCaptured(ArgumentCaptor<T> captor, Class<T> type) {
List<T> captured = new ArrayList<>();
- for(T c: captor.getAllValues()) {
- if(type.isInstance(c)) {
+ for (T c: captor.getAllValues()) {
+ if (type.isInstance(c)) {
captured.add(c);
}
}
assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
assertEquals("isReady", expIsReady, batchedModifications.isReady());
assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
- for(int i = 0; i < batchedModifications.getModifications().size(); i++) {
+ for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
Modification actual = batchedModifications.getModifications().get(i);
assertEquals("Modification type", expected[i].getClass(), actual.getClass());
assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
((AbstractModification)actual).getPath());
- if(actual instanceof WriteModification) {
+ if (actual instanceof WriteModification) {
assertEquals("getData", ((WriteModification)expected[i]).getData(),
((WriteModification)actual).getData());
}
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
protected void verifyCohortFutures(AbstractThreePhaseCommitCohort<?> proxy,
Object... expReplies) throws Exception {
- assertEquals("getReadyOperationFutures size", expReplies.length,
- proxy.getCohortFutures().size());
-
- List<Object> futureResults = new ArrayList<>();
- for( Future<?> future: proxy.getCohortFutures()) {
- assertNotNull("Ready operation Future is null", future);
- try {
- futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
- } catch(Exception e) {
- futureResults.add(e);
- }
+ assertEquals("getReadyOperationFutures size", expReplies.length,
+ proxy.getCohortFutures().size());
+
+ List<Object> futureResults = new ArrayList<>();
+ for (Future<?> future : proxy.getCohortFutures()) {
+ assertNotNull("Ready operation Future is null", future);
+ try {
+ futureResults.add(Await.result(future, Duration.create(5, TimeUnit.SECONDS)));
+ } catch (Exception e) {
+ futureResults.add(e);
}
+ }
- for (Object expReply : expReplies) {
- boolean found = false;
- Iterator<?> iter = futureResults.iterator();
- while(iter.hasNext()) {
- Object actual = iter.next();
- if(CommitTransactionReply.isSerializedType(expReply) &&
- CommitTransactionReply.isSerializedType(actual)) {
- found = true;
- } else if(expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
- found = true;
- } else if(expReply instanceof Class && ((Class<?>)expReply).isInstance(actual)) {
- found = true;
- }
-
- if(found) {
- iter.remove();
- break;
- }
+ for (Object expReply : expReplies) {
+ boolean found = false;
+ Iterator<?> iter = futureResults.iterator();
+ while (iter.hasNext()) {
+ Object actual = iter.next();
+ if (CommitTransactionReply.isSerializedType(expReply)
+ && CommitTransactionReply.isSerializedType(actual)) {
+ found = true;
+ } else if (expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
+ found = true;
+ } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
+ found = true;
}
- if(!found) {
- fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
+ if (found) {
+ iter.remove();
+ break;
}
}
+
+ if (!found) {
+ fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
+ }
}
+ }
}
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-public class DataChangeListenerProxyTest extends AbstractActorTest {
-
- private static class MockDataChangedEvent implements AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> {
- Map<YangInstanceIdentifier,NormalizedNode<?,?>> createdData = new HashMap<>();
- Map<YangInstanceIdentifier,NormalizedNode<?,?>> updatedData = new HashMap<>();
- Map<YangInstanceIdentifier,NormalizedNode<?,?>> originalData = new HashMap<>();
-
-
- @Override
- public Map<YangInstanceIdentifier, NormalizedNode<?, ?>> getCreatedData() {
- createdData.put(YangInstanceIdentifier.EMPTY, CompositeModel.createDocumentOne(CompositeModel.createTestContext()));
- return createdData;
- }
-
- @Override
- public Map<YangInstanceIdentifier, NormalizedNode<?, ?>> getUpdatedData() {
- updatedData.put(YangInstanceIdentifier.EMPTY, CompositeModel.createTestContainer());
- return updatedData;
-
- }
-
- @Override
- public Set<YangInstanceIdentifier> getRemovedPaths() {
- Set<YangInstanceIdentifier>ids = new HashSet<>();
- ids.add( CompositeModel.TEST_PATH);
- return ids;
- }
-
- @Override
- public Map<YangInstanceIdentifier, NormalizedNode<?, ?>> getOriginalData() {
- originalData.put(YangInstanceIdentifier.EMPTY, CompositeModel.createFamily());
- return originalData;
- }
-
- @Override public NormalizedNode<?, ?> getOriginalSubtree() {
- return CompositeModel.createFamily() ;
- }
+public class DataChangeListenerProxyTest extends AbstractActorTest {
- @Override public NormalizedNode<?, ?> getUpdatedSubtree() {
- return CompositeModel.createTestContainer();
+ private static class MockDataChangedEvent
+ implements AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> {
+ Map<YangInstanceIdentifier,NormalizedNode<?,?>> createdData = new HashMap<>();
+ Map<YangInstanceIdentifier,NormalizedNode<?,?>> updatedData = new HashMap<>();
+ Map<YangInstanceIdentifier,NormalizedNode<?,?>> originalData = new HashMap<>();
+
+ @Override
+ public Map<YangInstanceIdentifier, NormalizedNode<?, ?>> getCreatedData() {
+ createdData.put(YangInstanceIdentifier.EMPTY, CompositeModel.createDocumentOne(
+ CompositeModel.createTestContext()));
+ return createdData;
+ }
+
+ @Override
+ public Map<YangInstanceIdentifier, NormalizedNode<?, ?>> getUpdatedData() {
+ updatedData.put(YangInstanceIdentifier.EMPTY, CompositeModel.createTestContainer());
+ return updatedData;
+
+ }
+
+ @Override
+ public Set<YangInstanceIdentifier> getRemovedPaths() {
+ Set<YangInstanceIdentifier> ids = new HashSet<>();
+ ids.add( CompositeModel.TEST_PATH);
+ return ids;
+ }
+
+ @Override
+ public Map<YangInstanceIdentifier, NormalizedNode<?, ?>> getOriginalData() {
+ originalData.put(YangInstanceIdentifier.EMPTY, CompositeModel.createFamily());
+ return originalData;
+ }
+
+ @Override public NormalizedNode<?, ?> getOriginalSubtree() {
+ return CompositeModel.createFamily() ;
+ }
+
+ @Override public NormalizedNode<?, ?> getUpdatedSubtree() {
+ return CompositeModel.createTestContainer();
+ }
}
- }
- @Test
+ @Test
public void testOnDataChanged() throws Exception {
final Props props = Props.create(MessageCollectorActor.class);
final ActorRef actorRef = getSystem().actorOf(props);
dataChangeListenerProxy.onDataChanged(new MockDataChangedEvent());
//Check if it was received by the remote actor
- ActorContext
- testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)), new MockClusterWrapper(), new MockConfiguration());
+ ActorContext testContext = new ActorContext(getSystem(), getSystem().actorOf(
+ Props.create(DoNothingActor.class)), new MockClusterWrapper(), new MockConfiguration());
Object messages = testContext
.executeOperation(actorRef, MessageCollectorActor.GET_ALL_MESSAGES);
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.opendaylight.controller.cluster.datastore.config.Configuration;
import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
@Test
public void testGetInstance() throws Exception {
- DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- "shard", Mockito.mock(ActorContext.class), mockListener);
-
- Assert.assertEquals(mockListener, proxy.getInstance());
+ try (DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ "shard", Mockito.mock(ActorContext.class), mockListener)) {
+ Assert.assertEquals(mockListener, proxy.getInstance());
+ }
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testSuccessfulRegistration() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(),
+ mock(ClusterWrapper.class), mock(Configuration.class));
- final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- "shard-1", actorContext, mockListener);
+ final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ "shard-1", actorContext, mockListener);
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
- new Thread() {
- @Override
- public void run() {
- proxy.init(path, scope);
- }
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init(path, scope);
+ }
- }.start();
+ }.start();
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
- reply(new LocalShardFound(getRef()));
+ reply(new LocalShardFound(getRef()));
- RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
- Assert.assertEquals("getPath", path, registerMsg.getPath());
- Assert.assertEquals("getScope", scope, registerMsg.getScope());
- Assert.assertEquals("isRegisterOnAllInstances", false, registerMsg.isRegisterOnAllInstances());
+ RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
+ Assert.assertEquals("getPath", path, registerMsg.getPath());
+ Assert.assertEquals("getScope", scope, registerMsg.getScope());
+ Assert.assertEquals("isRegisterOnAllInstances", false, registerMsg.isRegisterOnAllInstances());
- reply(new RegisterChangeListenerReply(getRef()));
+ reply(new RegisterChangeListenerReply(getRef()));
- for(int i = 0; (i < 20 * 5) && proxy.getListenerRegistrationActor() == null; i++) {
- Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
- }
+ for (int i = 0; i < 20 * 5 && proxy.getListenerRegistrationActor() == null; i++) {
+ Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+ }
- Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
- proxy.getListenerRegistrationActor());
+ Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
+ proxy.getListenerRegistrationActor());
- watch(proxy.getDataChangeListenerActor());
+ watch(proxy.getDataChangeListenerActor());
- proxy.close();
+ proxy.close();
- // The listener registration actor should get a Close message
- expectMsgClass(timeout, CloseDataChangeListenerRegistration.class);
+ // The listener registration actor should get a Close message
+ expectMsgClass(timeout, CloseDataChangeListenerRegistration.class);
- // The DataChangeListener actor should be terminated
- expectMsgClass(timeout, Terminated.class);
+ // The DataChangeListener actor should be terminated
+ expectMsgClass(timeout, Terminated.class);
- proxy.close();
+ proxy.close();
- expectNoMsg();
- }};
+ expectNoMsg();
+ }
+ };
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testSuccessfulRegistrationForClusteredListener() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
-
- AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> mockClusteredListener =
- Mockito.mock(ClusteredDOMDataChangeListener.class);
-
- final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- "shard-1", actorContext, mockClusteredListener);
-
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
- new Thread() {
- @Override
- public void run() {
- proxy.init(path, scope);
- }
-
- }.start();
-
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(),
+ mock(ClusterWrapper.class), mock(Configuration.class));
- reply(new LocalShardFound(getRef()));
+ AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> mockClusteredListener =
+ Mockito.mock(ClusteredDOMDataChangeListener.class);
- RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
- Assert.assertEquals("getPath", path, registerMsg.getPath());
- Assert.assertEquals("getScope", scope, registerMsg.getScope());
- Assert.assertEquals("isRegisterOnAllInstances", true, registerMsg.isRegisterOnAllInstances());
+ final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ "shard-1", actorContext, mockClusteredListener);
- reply(new RegisterChangeListenerReply(getRef()));
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init(path, scope);
+ }
- for(int i = 0; (i < 20 * 5) && proxy.getListenerRegistrationActor() == null; i++) {
- Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
- }
+ }.start();
- Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
- proxy.getListenerRegistrationActor());
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
- watch(proxy.getDataChangeListenerActor());
+ reply(new LocalShardFound(getRef()));
- proxy.close();
+ RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
+ Assert.assertEquals("getPath", path, registerMsg.getPath());
+ Assert.assertEquals("getScope", scope, registerMsg.getScope());
+ Assert.assertEquals("isRegisterOnAllInstances", true, registerMsg.isRegisterOnAllInstances());
- // The listener registration actor should get a Close message
- expectMsgClass(timeout, CloseDataChangeListenerRegistration.class);
+ reply(new RegisterChangeListenerReply(getRef()));
- // The DataChangeListener actor should be terminated
- expectMsgClass(timeout, Terminated.class);
+ for (int i = 0; i < 20 * 5 && proxy.getListenerRegistrationActor() == null; i++) {
+ Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+ }
- proxy.close();
+ Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
+ proxy.getListenerRegistrationActor());
- expectNoMsg();
- }};
- }
+ watch(proxy.getDataChangeListenerActor());
- @Test(timeout=10000)
- public void testLocalShardNotFound() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
+ proxy.close();
- final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- "shard-1", actorContext, mockListener);
+ // The listener registration actor should get a Close message
+ expectMsgClass(timeout, CloseDataChangeListenerRegistration.class);
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
- new Thread() {
- @Override
- public void run() {
- proxy.init(path, scope);
- }
+ // The DataChangeListener actor should be terminated
+ expectMsgClass(timeout, Terminated.class);
- }.start();
+ proxy.close();
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ expectNoMsg();
+ }
+ };
+ }
- reply(new LocalShardNotFound("shard-1"));
+ @Test(timeout = 10000)
+ public void testLocalShardNotFound() {
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(),
+ mock(ClusterWrapper.class), mock(Configuration.class));
- expectNoMsg(duration("1 seconds"));
- }};
- }
+ final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ "shard-1", actorContext, mockListener);
- @Test(timeout=10000)
- public void testLocalShardNotInitialized() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init(path, scope);
+ }
- final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- "shard-1", actorContext, mockListener);
+ }.start();
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
- new Thread() {
- @Override
- public void run() {
- proxy.init(path, scope);
- }
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
- }.start();
+ reply(new LocalShardNotFound("shard-1"));
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ expectNoMsg(duration("1 seconds"));
- reply(new NotInitializedException("not initialized"));
+ proxy.close();
+ }
+ };
+ }
- new Within(duration("1 seconds")) {
- @Override
- protected void run() {
- expectNoMsg();
- }
- };
- }};
+ @Test(timeout = 10000)
+ public void testLocalShardNotInitialized() {
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(),
+ mock(ClusterWrapper.class), mock(Configuration.class));
+
+ final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ "shard-1", actorContext, mockListener);
+
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init(path, scope);
+ }
+
+ }.start();
+
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+
+ reply(new NotInitializedException("not initialized"));
+
+ new Within(duration("1 seconds")) {
+ @Override
+ protected void run() {
+ expectNoMsg();
+ }
+ };
+
+ proxy.close();
+ }
+ };
}
@Test
public void testFailedRegistration() {
- new JavaTestKit(getSystem()) {{
- ActorSystem mockActorSystem = mock(ActorSystem.class);
+ new JavaTestKit(getSystem()) {
+ {
+ ActorSystem mockActorSystem = mock(ActorSystem.class);
- ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class),
- "testFailedRegistration");
- doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class));
- ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(
- MoreExecutors.directExecutor());
+ ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class),
+ "testFailedRegistration");
+ doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class));
+ ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(
+ MoreExecutors.directExecutor());
- ActorContext actorContext = mock(ActorContext.class);
+ ActorContext actorContext = mock(ActorContext.class);
- doReturn(executor).when(actorContext).getClientDispatcher();
+ doReturn(executor).when(actorContext).getClientDispatcher();
- String shardName = "shard-1";
- final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- shardName, actorContext, mockListener);
+ String shardName = "shard-1";
+ final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ shardName, actorContext, mockListener);
- doReturn(mockActorSystem).when(actorContext).getActorSystem();
- doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
- doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
- doReturn(Futures.failed(new RuntimeException("mock"))).
- when(actorContext).executeOperationAsync(any(ActorRef.class),
- any(Object.class), any(Timeout.class));
- doReturn(mock(DatastoreContext.class)).when(actorContext).getDatastoreContext();
+ doReturn(mockActorSystem).when(actorContext).getActorSystem();
+ doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
+ doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
+ doReturn(Futures.failed(new RuntimeException("mock")))
+ .when(actorContext).executeOperationAsync(any(ActorRef.class),
+ any(Object.class), any(Timeout.class));
+ doReturn(mock(DatastoreContext.class)).when(actorContext).getDatastoreContext();
- proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME),
- AsyncDataBroker.DataChangeScope.ONE);
+ proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME),
+ AsyncDataBroker.DataChangeScope.ONE);
- Assert.assertEquals("getListenerRegistrationActor", null,
- proxy.getListenerRegistrationActor());
- }};
+ Assert.assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
+
+ proxy.close();
+ }
+ };
}
@Test
public void testCloseBeforeRegistration() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = mock(ActorContext.class);
-
- String shardName = "shard-1";
- final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
- shardName, actorContext, mockListener);
-
- doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext();
- doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(actorContext).getClientDispatcher();
- doReturn(getSystem()).when(actorContext).getActorSystem();
- doReturn(Dispatchers.DEFAULT_DISPATCHER_PATH).when(actorContext).getNotificationDispatcherPath();
- doReturn(getSystem().actorSelection(getRef().path())).
- when(actorContext).actorSelection(getRef().path());
- doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
- doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
-
- Answer<Future<Object>> answer = new Answer<Future<Object>>() {
- @Override
- public Future<Object> answer(InvocationOnMock invocation) {
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = mock(ActorContext.class);
+
+ String shardName = "shard-1";
+ final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy(
+ shardName, actorContext, mockListener);
+
+ doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext();
+ doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(actorContext).getClientDispatcher();
+ doReturn(getSystem()).when(actorContext).getActorSystem();
+ doReturn(Dispatchers.DEFAULT_DISPATCHER_PATH).when(actorContext).getNotificationDispatcherPath();
+ doReturn(getSystem().actorSelection(getRef().path()))
+ .when(actorContext).actorSelection(getRef().path());
+ doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
+ doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
+
+ Answer<Future<Object>> answer = invocation -> {
proxy.close();
return Futures.successful((Object)new RegisterChangeListenerReply(getRef()));
- }
- };
+ };
- doAnswer(answer).when(actorContext).executeOperationAsync(any(ActorRef.class),
- any(Object.class), any(Timeout.class));
+ doAnswer(answer).when(actorContext).executeOperationAsync(any(ActorRef.class),
+ any(Object.class), any(Timeout.class));
- proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME),
- AsyncDataBroker.DataChangeScope.ONE);
+ proxy.init(YangInstanceIdentifier.of(TestModel.TEST_QNAME),
+ AsyncDataBroker.DataChangeScope.ONE);
- expectMsgClass(duration("5 seconds"), CloseDataChangeListenerRegistration.class);
+ expectMsgClass(duration("5 seconds"), CloseDataChangeListenerRegistration.class);
- Assert.assertEquals("getListenerRegistrationActor", null,
- proxy.getListenerRegistrationActor());
- }};
+ Assert.assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
+ proxy.close();
+ }
+ };
}
}
package org.opendaylight.controller.cluster.datastore;
import static org.junit.Assert.assertEquals;
+
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistrationReply;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
public class DataChangeListenerRegistrationTest extends AbstractActorTest {
- private static final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
-
- static {
- store.onGlobalContextUpdated(TestModel.createTestContext());
- }
-
-
- @Test
- public void testOnReceiveCloseListenerRegistration() throws Exception {
- new JavaTestKit(getSystem()) {{
- final Props props = DataChangeListenerRegistrationActor.props(store
- .registerChangeListener(TestModel.TEST_PATH, noOpDataChangeListener(),
- AsyncDataBroker.DataChangeScope.BASE));
- final ActorRef subject = getSystem().actorOf(props, "testCloseListenerRegistration");
-
- new Within(duration("1 seconds")) {
- @Override
- protected void run() {
-
- subject.tell(CloseDataChangeListenerRegistration.INSTANCE, getRef());
-
- final String out = new ExpectMsg<String>(duration("1 seconds"), "match hint") {
- // do not put code outside this method, will run afterwards
- @Override
- protected String match(final Object in) {
- if (in.getClass().equals(CloseDataChangeListenerRegistrationReply.class)) {
- return "match";
- } else {
- throw noMatch();
- }
+ private static final InMemoryDOMDataStore STORE = new InMemoryDOMDataStore("OPER",
+ MoreExecutors.newDirectExecutorService());
+
+ static {
+ STORE.onGlobalContextUpdated(TestModel.createTestContext());
+ }
+
+ @Test
+ public void testOnReceiveCloseListenerRegistration() throws Exception {
+ new JavaTestKit(getSystem()) {
+ {
+ final Props props = DataChangeListenerRegistrationActor.props(STORE.registerChangeListener(
+ TestModel.TEST_PATH, noOpDataChangeListener(), AsyncDataBroker.DataChangeScope.BASE));
+ final ActorRef subject = getSystem().actorOf(props, "testCloseListenerRegistration");
+
+ new Within(duration("1 seconds")) {
+ @Override
+ protected void run() {
+
+ subject.tell(CloseDataChangeListenerRegistration.INSTANCE, getRef());
+
+ final String out = new ExpectMsg<String>(duration("1 seconds"), "match hint") {
+ // do not put code outside this method, will run
+ // afterwards
+ @Override
+ protected String match(final Object in) {
+ if (in.getClass().equals(CloseDataChangeListenerRegistrationReply.class)) {
+ return "match";
+ } else {
+ throw noMatch();
+ }
+ }
+ }.get(); // this extracts the received message
+
+ assertEquals("match", out);
+
+ expectNoMsg();
+ }
+
+ };
}
- }.get(); // this extracts the received message
-
- assertEquals("match", out);
-
- expectNoMsg();
- }
-
-
- };
- }};
- }
-
- private static AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> noOpDataChangeListener(){
- return new AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>() {
- @Override
- public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
-
- }
- };
- }
+ };
+ }
+ private static AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> noOpDataChangeListener() {
+ return change -> {
+ };
+ }
}
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.outerNode;
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.outerNodeEntry;
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.testNodeWithOuter;
+
import akka.actor.ActorRef;
import akka.dispatch.Dispatchers;
import akka.testkit.TestActorRef;
final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
"testChangeListenerWithNoInitialData-DataChangeListener");
final DataChangeListenerSupport support = new DataChangeListenerSupport(shard);
- support.onMessage(new RegisterChangeListener(TEST_PATH, dclActor, DataChangeScope.ONE, false),true,true);
+ support.onMessage(new RegisterChangeListener(TEST_PATH, dclActor, DataChangeScope.ONE, false),
+ true,true);
listener.expectNoMoreChanges("Unexpected initial change event");
}
final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
"testInitialChangeListenerEventWithContainerPath-DataChangeListener");
final DataChangeListenerSupport support = new DataChangeListenerSupport(shard);
- support.onMessage(new RegisterChangeListener(TEST_PATH, dclActor, DataChangeScope.ONE, false),true,true);
+ support.onMessage(new RegisterChangeListener(TEST_PATH, dclActor, DataChangeScope.ONE, false),
+ true,true);
listener.waitForChangeEvents(TEST_PATH);
}
final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
"testInitialChangeListenerEventWithNestedWildcardedListsPath-DataChangeListener");
final DataChangeListenerSupport support = new DataChangeListenerSupport(shard);
- support.onMessage(new RegisterChangeListener(OUTER_LIST_PATH.node(OUTER_LIST_QNAME).node(INNER_LIST_QNAME).node(INNER_LIST_QNAME), dclActor,
- DataChangeScope.ONE, false), true, true);
+ support.onMessage(new RegisterChangeListener(OUTER_LIST_PATH.node(OUTER_LIST_QNAME)
+ .node(INNER_LIST_QNAME).node(INNER_LIST_QNAME), dclActor, DataChangeScope.ONE, false),
+ true, true);
listener.waitForChangeEvents();
listener.verifyCreatedData(0, innerEntryPath(2, "four"));
}
};
-
}
}
import org.opendaylight.controller.cluster.datastore.messages.DataChanged;
import org.opendaylight.controller.cluster.datastore.messages.DataChangedReply;
import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
-import org.opendaylight.controller.md.cluster.datastore.model.CompositeModel;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class DataChangeListenerTest extends AbstractActorTest {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void testDataChangedWhenNotificationsAreEnabled(){
- new JavaTestKit(getSystem()) {{
- final AsyncDataChangeEvent mockChangeEvent = Mockito.mock(AsyncDataChangeEvent.class);
- final AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
- final Props props = DataChangeListener.props(mockListener);
- final ActorRef subject = getSystem().actorOf(props, "testDataChangedNotificationsEnabled");
+ public void testDataChangedWhenNotificationsAreEnabled() {
+ new JavaTestKit(getSystem()) {
+ {
+ final AsyncDataChangeEvent mockChangeEvent = Mockito.mock(AsyncDataChangeEvent.class);
+ final AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
+ final Props props = DataChangeListener.props(mockListener);
+ final ActorRef subject = getSystem().actorOf(props, "testDataChangedNotificationsEnabled");
- // Let the DataChangeListener know that notifications should be enabled
- subject.tell(new EnableNotification(true), getRef());
+ // Let the DataChangeListener know that notifications should be
+ // enabled
+ subject.tell(new EnableNotification(true), getRef());
- subject.tell(new DataChanged(mockChangeEvent),
- getRef());
+ subject.tell(new DataChanged(mockChangeEvent), getRef());
- expectMsgClass(DataChangedReply.class);
+ expectMsgClass(DataChangedReply.class);
- Mockito.verify(mockListener).onDataChanged(mockChangeEvent);
- }};
+ Mockito.verify(mockListener).onDataChanged(mockChangeEvent);
+ }
+ };
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void testDataChangedWhenNotificationsAreDisabled(){
- new JavaTestKit(getSystem()) {{
- final AsyncDataChangeEvent mockChangeEvent = Mockito.mock(AsyncDataChangeEvent.class);
- final AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
- final Props props = DataChangeListener.props(mockListener);
- final ActorRef subject =
- getSystem().actorOf(props, "testDataChangedNotificationsDisabled");
-
- subject.tell(new DataChanged(mockChangeEvent),
- getRef());
-
- new Within(duration("1 seconds")) {
- @Override
- protected void run() {
- expectNoMsg();
-
- Mockito.verify(mockListener, Mockito.never()).onDataChanged(
- Mockito.any(AsyncDataChangeEvent.class));
- }
- };
- }};
+ public void testDataChangedWhenNotificationsAreDisabled() {
+ new JavaTestKit(getSystem()) {
+ {
+ final AsyncDataChangeEvent mockChangeEvent = Mockito.mock(AsyncDataChangeEvent.class);
+ final AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
+ final Props props = DataChangeListener.props(mockListener);
+ final ActorRef subject = getSystem().actorOf(props, "testDataChangedNotificationsDisabled");
+
+ subject.tell(new DataChanged(mockChangeEvent), getRef());
+
+ new Within(duration("1 seconds")) {
+ @Override
+ protected void run() {
+ expectNoMsg();
+
+ Mockito.verify(mockListener, Mockito.never())
+ .onDataChanged(Mockito.any(AsyncDataChangeEvent.class));
+ }
+ };
+ }
+ };
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void testDataChangedWithNoSender(){
- new JavaTestKit(getSystem()) {{
- final AsyncDataChangeEvent mockChangeEvent = Mockito.mock(AsyncDataChangeEvent.class);
- final AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
- final Props props = DataChangeListener.props(mockListener);
- final ActorRef subject = getSystem().actorOf(props, "testDataChangedWithNoSender");
-
- getSystem().eventStream().subscribe(getRef(), DeadLetter.class);
-
- subject.tell(new DataChanged(mockChangeEvent), ActorRef.noSender());
-
- // Make sure no DataChangedReply is sent to DeadLetters.
- while(true) {
- DeadLetter deadLetter;
- try {
- deadLetter = expectMsgClass(duration("1 seconds"), DeadLetter.class);
- } catch (AssertionError e) {
- // Timed out - got no DeadLetter - this is good
- break;
+ public void testDataChangedWithNoSender() {
+ new JavaTestKit(getSystem()) {
+ {
+ final AsyncDataChangeEvent mockChangeEvent = Mockito.mock(AsyncDataChangeEvent.class);
+ final AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
+ final Props props = DataChangeListener.props(mockListener);
+ final ActorRef subject = getSystem().actorOf(props, "testDataChangedWithNoSender");
+
+ getSystem().eventStream().subscribe(getRef(), DeadLetter.class);
+
+ subject.tell(new DataChanged(mockChangeEvent), ActorRef.noSender());
+
+ // Make sure no DataChangedReply is sent to DeadLetters.
+ while (true) {
+ DeadLetter deadLetter;
+ try {
+ deadLetter = expectMsgClass(duration("1 seconds"), DeadLetter.class);
+ } catch (AssertionError e) {
+ // Timed out - got no DeadLetter - this is good
+ break;
+ }
+
+ // We may get DeadLetters for other messages we don't care
+ // about.
+ Assert.assertFalse("Unexpected DataChangedReply", deadLetter.message() instanceof DataChangedReply);
}
-
- // We may get DeadLetters for other messages we don't care about.
- Assert.assertFalse("Unexpected DataChangedReply",
- deadLetter.message() instanceof DataChangedReply);
}
- }};
+ };
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
- public void testDataChangedWithListenerRuntimeEx(){
- new JavaTestKit(getSystem()) {{
- AsyncDataChangeEvent mockChangeEvent1 = Mockito.mock(AsyncDataChangeEvent.class);
- AsyncDataChangeEvent mockChangeEvent2 = Mockito.mock(AsyncDataChangeEvent.class);
- AsyncDataChangeEvent mockChangeEvent3 = Mockito.mock(AsyncDataChangeEvent.class);
-
- AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
- Mockito.doThrow(new RuntimeException("mock")).when(mockListener).onDataChanged(mockChangeEvent2);
+ public void testDataChangedWithListenerRuntimeEx() {
+ new JavaTestKit(getSystem()) {
+ {
+ final AsyncDataChangeEvent mockChangeEvent1 = Mockito.mock(AsyncDataChangeEvent.class);
+ final AsyncDataChangeEvent mockChangeEvent2 = Mockito.mock(AsyncDataChangeEvent.class);
+ final AsyncDataChangeEvent mockChangeEvent3 = Mockito.mock(AsyncDataChangeEvent.class);
- Props props = DataChangeListener.props(mockListener);
- ActorRef subject = getSystem().actorOf(props, "testDataChangedWithListenerRuntimeEx");
+ AsyncDataChangeListener mockListener = Mockito.mock(AsyncDataChangeListener.class);
+ Mockito.doThrow(new RuntimeException("mock")).when(mockListener).onDataChanged(mockChangeEvent2);
- // Let the DataChangeListener know that notifications should be enabled
- subject.tell(new EnableNotification(true), getRef());
+ Props props = DataChangeListener.props(mockListener);
+ ActorRef subject = getSystem().actorOf(props, "testDataChangedWithListenerRuntimeEx");
- SchemaContext schemaContext = CompositeModel.createTestContext();
+ // Let the DataChangeListener know that notifications should be
+ // enabled
+ subject.tell(new EnableNotification(true), getRef());
- subject.tell(new DataChanged(mockChangeEvent1),getRef());
- expectMsgClass(DataChangedReply.class);
+ subject.tell(new DataChanged(mockChangeEvent1), getRef());
+ expectMsgClass(DataChangedReply.class);
- subject.tell(new DataChanged(mockChangeEvent2),getRef());
- expectMsgClass(DataChangedReply.class);
+ subject.tell(new DataChanged(mockChangeEvent2), getRef());
+ expectMsgClass(DataChangedReply.class);
- subject.tell(new DataChanged(mockChangeEvent3),getRef());
- expectMsgClass(DataChangedReply.class);
+ subject.tell(new DataChanged(mockChangeEvent3), getRef());
+ expectMsgClass(DataChangedReply.class);
- Mockito.verify(mockListener).onDataChanged(mockChangeEvent1);
- Mockito.verify(mockListener).onDataChanged(mockChangeEvent2);
- Mockito.verify(mockListener).onDataChanged(mockChangeEvent3);
- }};
+ Mockito.verify(mockListener).onDataChanged(mockChangeEvent1);
+ Mockito.verify(mockListener).onDataChanged(mockChangeEvent2);
+ Mockito.verify(mockListener).onDataChanged(mockChangeEvent3);
+ }
+ };
}
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
+
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.lang3.SerializationUtils;
private DataTreeCandidate candidate;
- private static DataTreeCandidateNode findNode(final Collection<DataTreeCandidateNode> nodes, final PathArgument arg) {
+ private static DataTreeCandidateNode findNode(final Collection<DataTreeCandidateNode> nodes,
+ final PathArgument arg) {
for (DataTreeCandidateNode node : nodes) {
if (arg.equals(node.getIdentifier())) {
return node;
assertEquals("root type", expRoot.getModificationType(), actRoot.getModificationType());
switch (actRoot.getModificationType()) {
- case DELETE:
- case WRITE:
- assertEquals("root data", expRoot.getDataAfter(), actRoot.getDataAfter());
- break;
- case SUBTREE_MODIFIED:
- assertChildrenEquals(expRoot.getChildNodes(), actRoot.getChildNodes());
- break;
- default:
- fail("Unexpect root type " + actRoot.getModificationType());
- break;
+ case DELETE:
+ case WRITE:
+ assertEquals("root data", expRoot.getDataAfter(), actRoot.getDataAfter());
+ break;
+ case SUBTREE_MODIFIED:
+ assertChildrenEquals(expRoot.getChildNodes(), actRoot.getChildNodes());
+ break;
+ default:
+ fail("Unexpect root type " + actRoot.getModificationType());
+ break;
}
assertCandidateNodeEquals(expected.getRootNode(), actual.getRootNode());
}
- private static void assertCandidateNodeEquals(final DataTreeCandidateNode expected, final DataTreeCandidateNode actual) {
+ private static void assertCandidateNodeEquals(final DataTreeCandidateNode expected,
+ final DataTreeCandidateNode actual) {
assertEquals("child type", expected.getModificationType(), actual.getModificationType());
assertEquals("child identifier", expected.getIdentifier(), actual.getIdentifier());
switch (actual.getModificationType()) {
- case DELETE:
- case WRITE:
- assertEquals("child data", expected.getDataAfter(), actual.getDataAfter());
- break;
- case SUBTREE_MODIFIED:
- assertChildrenEquals(expected.getChildNodes(), actual.getChildNodes());
- break;
- default:
- fail("Unexpect root type " + actual.getModificationType());
- break;
+ case DELETE:
+ case WRITE:
+ assertEquals("child data", expected.getDataAfter(), actual.getDataAfter());
+ break;
+ case SUBTREE_MODIFIED:
+ assertChildrenEquals(expected.getChildNodes(), actual.getChildNodes());
+ break;
+ default:
+ fail("Unexpect root type " + actual.getModificationType());
+ break;
}
}
public void setUp() {
final YangInstanceIdentifier writePath = TestModel.TEST_PATH;
final NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
candidate = DataTreeCandidates.fromNormalizedNode(writePath, writeData);
}
YangInstanceIdentifier leafSetEntryPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET)
.node(entryPathArg).build();
- NormalizedNode<?, ?> leafSetEntryNode = Builders.leafSetEntryBuilder().
- withNodeIdentifier(entryPathArg).withValue("one").build();
+ NormalizedNode<?, ?> leafSetEntryNode = Builders.leafSetEntryBuilder()
+ .withNodeIdentifier(entryPathArg).withValue("one").build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafSetEntryPath, leafSetEntryNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetEntryPath, leafSetEntryNode);
DataTreeCandidatePayload payload = DataTreeCandidatePayload.create(candidate);
assertCandidateEquals(candidate, payload.getCandidate());
}
YangInstanceIdentifier.NodeWithValue entryPathArg = new YangInstanceIdentifier.NodeWithValue(LEAF_SET, "one");
YangInstanceIdentifier leafSetPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET).build();
- LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder().
- withNodeIdentifier(entryPathArg).withValue("one").build();
+ LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder()
+ .withNodeIdentifier(entryPathArg).withValue("one").build();
NormalizedNode<?, ?> leafSetNode = Builders.leafSetBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(LEAF_SET)).withChild(leafSetEntryNode).build();
YangInstanceIdentifier.NodeWithValue entryPathArg = new YangInstanceIdentifier.NodeWithValue(LEAF_SET, "one");
YangInstanceIdentifier leafSetPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET).build();
- LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder().
- withNodeIdentifier(entryPathArg).withValue("one").build();
+ LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder()
+ .withNodeIdentifier(entryPathArg).withValue("one").build();
NormalizedNode<?, ?> leafSetNode = Builders.orderedLeafSetBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(LEAF_SET)).withChild(leafSetEntryNode).build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, leafSetNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, leafSetNode);
DataTreeCandidatePayload payload = DataTreeCandidatePayload.create(candidate);
assertCandidateEquals(candidate, payload.getCandidate());
}
@Test
public void testLeafNodeCandidate() throws Exception {
- YangInstanceIdentifier leafPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(TestModel.DESC_QNAME).build();
+ YangInstanceIdentifier leafPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
+ .node(TestModel.DESC_QNAME).build();
LeafNode<Object> leafNode = Builders.leafBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(TestModel.DESC_QNAME)).withValue("test").build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafPath, leafNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafPath, leafNode);
DataTreeCandidatePayload payload = DataTreeCandidatePayload.create(candidate);
assertCandidateEquals(candidate, payload.getCandidate());
}
public class DataTreeChangeListenerActorTest extends AbstractActorTest {
@Test
- public void testDataChangedWhenNotificationsAreEnabled(){
- new JavaTestKit(getSystem()) {{
- final DataTreeCandidate mockTreeCandidate = Mockito.mock(DataTreeCandidate.class);
- final ImmutableList<DataTreeCandidate> mockCandidates = ImmutableList.of(mockTreeCandidate);
- final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
- final Props props = DataTreeChangeListenerActor.props(mockListener);
- final ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedNotificationsEnabled");
+ public void testDataChangedWhenNotificationsAreEnabled() {
+ new JavaTestKit(getSystem()) {
+ {
+ final DataTreeCandidate mockTreeCandidate = Mockito.mock(DataTreeCandidate.class);
+ final ImmutableList<DataTreeCandidate> mockCandidates = ImmutableList.of(mockTreeCandidate);
+ final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
+ final Props props = DataTreeChangeListenerActor.props(mockListener);
+ final ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedNotificationsEnabled");
- // Let the DataChangeListener know that notifications should be enabled
- subject.tell(new EnableNotification(true), getRef());
+ // Let the DataChangeListener know that notifications should be
+ // enabled
+ subject.tell(new EnableNotification(true), getRef());
- subject.tell(new DataTreeChanged(mockCandidates),
- getRef());
+ subject.tell(new DataTreeChanged(mockCandidates), getRef());
- expectMsgClass(DataTreeChangedReply.class);
+ expectMsgClass(DataTreeChangedReply.class);
- Mockito.verify(mockListener).onDataTreeChanged(mockCandidates);
- }};
+ Mockito.verify(mockListener).onDataTreeChanged(mockCandidates);
+ }
+ };
}
@Test
- public void testDataChangedWhenNotificationsAreDisabled(){
- new JavaTestKit(getSystem()) {{
- final DataTreeCandidate mockTreeCandidate = Mockito.mock(DataTreeCandidate.class);
- final ImmutableList<DataTreeCandidate> mockCandidates = ImmutableList.of(mockTreeCandidate);
- final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
- final Props props = DataTreeChangeListenerActor.props(mockListener);
- final ActorRef subject =
- getSystem().actorOf(props, "testDataTreeChangedNotificationsDisabled");
-
- subject.tell(new DataTreeChanged(mockCandidates),
- getRef());
-
- new Within(duration("1 seconds")) {
- @Override
- protected void run() {
- expectNoMsg();
-
- Mockito.verify(mockListener, Mockito.never()).onDataTreeChanged(
- Matchers.anyCollectionOf(DataTreeCandidate.class));
- }
- };
- }};
+ public void testDataChangedWhenNotificationsAreDisabled() {
+ new JavaTestKit(getSystem()) {
+ {
+ final DataTreeCandidate mockTreeCandidate = Mockito.mock(DataTreeCandidate.class);
+ final ImmutableList<DataTreeCandidate> mockCandidates = ImmutableList.of(mockTreeCandidate);
+ final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
+ final Props props = DataTreeChangeListenerActor.props(mockListener);
+ final ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedNotificationsDisabled");
+
+ subject.tell(new DataTreeChanged(mockCandidates), getRef());
+
+ new Within(duration("1 seconds")) {
+ @Override
+ protected void run() {
+ expectNoMsg();
+
+ Mockito.verify(mockListener, Mockito.never())
+ .onDataTreeChanged(Matchers.anyCollectionOf(DataTreeCandidate.class));
+ }
+ };
+ }
+ };
}
@Test
- public void testDataChangedWithNoSender(){
- new JavaTestKit(getSystem()) {{
- final DataTreeCandidate mockTreeCandidate = Mockito.mock(DataTreeCandidate.class);
- final ImmutableList<DataTreeCandidate> mockCandidates = ImmutableList.of(mockTreeCandidate);
- final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
- final Props props = DataTreeChangeListenerActor.props(mockListener);
- final ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedWithNoSender");
-
- getSystem().eventStream().subscribe(getRef(), DeadLetter.class);
-
- subject.tell(new DataTreeChanged(mockCandidates), ActorRef.noSender());
-
- // Make sure no DataChangedReply is sent to DeadLetters.
- while(true) {
- DeadLetter deadLetter;
- try {
- deadLetter = expectMsgClass(duration("1 seconds"), DeadLetter.class);
- } catch (AssertionError e) {
- // Timed out - got no DeadLetter - this is good
- break;
+ public void testDataChangedWithNoSender() {
+ new JavaTestKit(getSystem()) {
+ {
+ final DataTreeCandidate mockTreeCandidate = Mockito.mock(DataTreeCandidate.class);
+ final ImmutableList<DataTreeCandidate> mockCandidates = ImmutableList.of(mockTreeCandidate);
+ final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
+ final Props props = DataTreeChangeListenerActor.props(mockListener);
+ final ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedWithNoSender");
+
+ getSystem().eventStream().subscribe(getRef(), DeadLetter.class);
+
+ subject.tell(new DataTreeChanged(mockCandidates), ActorRef.noSender());
+
+ // Make sure no DataChangedReply is sent to DeadLetters.
+ while (true) {
+ DeadLetter deadLetter;
+ try {
+ deadLetter = expectMsgClass(duration("1 seconds"), DeadLetter.class);
+ } catch (AssertionError e) {
+ // Timed out - got no DeadLetter - this is good
+ break;
+ }
+
+ // We may get DeadLetters for other messages we don't care
+ // about.
+ Assert.assertFalse("Unexpected DataTreeChangedReply",
+ deadLetter.message() instanceof DataTreeChangedReply);
}
-
- // We may get DeadLetters for other messages we don't care about.
- Assert.assertFalse("Unexpected DataTreeChangedReply",
- deadLetter.message() instanceof DataTreeChangedReply);
}
- }};
+ };
}
@Test
- public void testDataChangedWithListenerRuntimeEx(){
- new JavaTestKit(getSystem()) {{
- final DataTreeCandidate mockTreeCandidate1 = Mockito.mock(DataTreeCandidate.class);
- final ImmutableList<DataTreeCandidate> mockCandidates1 = ImmutableList.of(mockTreeCandidate1);
- final DataTreeCandidate mockTreeCandidate2 = Mockito.mock(DataTreeCandidate.class);
- final ImmutableList<DataTreeCandidate> mockCandidates2 = ImmutableList.of(mockTreeCandidate2);
- final DataTreeCandidate mockTreeCandidate3 = Mockito.mock(DataTreeCandidate.class);
- final ImmutableList<DataTreeCandidate> mockCandidates3 = ImmutableList.of(mockTreeCandidate3);
-
- final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
- Mockito.doThrow(new RuntimeException("mock")).when(mockListener).onDataTreeChanged(mockCandidates2);
-
- Props props = DataTreeChangeListenerActor.props(mockListener);
- ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedWithListenerRuntimeEx");
-
- // Let the DataChangeListener know that notifications should be enabled
- subject.tell(new EnableNotification(true), getRef());
-
- subject.tell(new DataTreeChanged(mockCandidates1),getRef());
- expectMsgClass(DataTreeChangedReply.class);
-
- subject.tell(new DataTreeChanged(mockCandidates2),getRef());
- expectMsgClass(DataTreeChangedReply.class);
-
- subject.tell(new DataTreeChanged(mockCandidates3),getRef());
- expectMsgClass(DataTreeChangedReply.class);
-
- Mockito.verify(mockListener).onDataTreeChanged(mockCandidates1);
- Mockito.verify(mockListener).onDataTreeChanged(mockCandidates2);
- Mockito.verify(mockListener).onDataTreeChanged(mockCandidates3);
- }};
+ public void testDataChangedWithListenerRuntimeEx() {
+ new JavaTestKit(getSystem()) {
+ {
+ final DataTreeCandidate mockTreeCandidate1 = Mockito.mock(DataTreeCandidate.class);
+ final ImmutableList<DataTreeCandidate> mockCandidates1 = ImmutableList.of(mockTreeCandidate1);
+ final DataTreeCandidate mockTreeCandidate2 = Mockito.mock(DataTreeCandidate.class);
+ final ImmutableList<DataTreeCandidate> mockCandidates2 = ImmutableList.of(mockTreeCandidate2);
+ final DataTreeCandidate mockTreeCandidate3 = Mockito.mock(DataTreeCandidate.class);
+ final ImmutableList<DataTreeCandidate> mockCandidates3 = ImmutableList.of(mockTreeCandidate3);
+
+ final DOMDataTreeChangeListener mockListener = Mockito.mock(DOMDataTreeChangeListener.class);
+ Mockito.doThrow(new RuntimeException("mock")).when(mockListener).onDataTreeChanged(mockCandidates2);
+
+ Props props = DataTreeChangeListenerActor.props(mockListener);
+ ActorRef subject = getSystem().actorOf(props, "testDataTreeChangedWithListenerRuntimeEx");
+
+ // Let the DataChangeListener know that notifications should be
+ // enabled
+ subject.tell(new EnableNotification(true), getRef());
+
+ subject.tell(new DataTreeChanged(mockCandidates1), getRef());
+ expectMsgClass(DataTreeChangedReply.class);
+
+ subject.tell(new DataTreeChanged(mockCandidates2), getRef());
+ expectMsgClass(DataTreeChangedReply.class);
+
+ subject.tell(new DataTreeChanged(mockCandidates3), getRef());
+ expectMsgClass(DataTreeChangedReply.class);
+
+ Mockito.verify(mockListener).onDataTreeChanged(mockCandidates1);
+ Mockito.verify(mockListener).onDataTreeChanged(mockCandidates2);
+ Mockito.verify(mockListener).onDataTreeChanged(mockCandidates3);
+ }
+ };
}
}
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
-import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.opendaylight.controller.cluster.datastore.config.Configuration;
import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
public class DataTreeChangeListenerProxyTest extends AbstractActorTest {
private final DOMDataTreeChangeListener mockListener = mock(DOMDataTreeChangeListener.class);
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testSuccessfulRegistration() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
-
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorContext, mockListener);
-
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- new Thread() {
- @Override
- public void run() {
- proxy.init("shard-1", path);
- }
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class),
+ mock(Configuration.class));
- }.start();
+ final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
+ actorContext, mockListener);
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init("shard-1", path);
+ }
- reply(new LocalShardFound(getRef()));
+ }.start();
- RegisterDataTreeChangeListener registerMsg = expectMsgClass(timeout, RegisterDataTreeChangeListener.class);
- Assert.assertEquals("getPath", path, registerMsg.getPath());
- Assert.assertEquals("isRegisterOnAllInstances", false, registerMsg.isRegisterOnAllInstances());
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
- reply(new RegisterDataTreeChangeListenerReply(getRef()));
+ reply(new LocalShardFound(getRef()));
+ RegisterDataTreeChangeListener registerMsg = expectMsgClass(timeout,
+ RegisterDataTreeChangeListener.class);
+ Assert.assertEquals("getPath", path, registerMsg.getPath());
+ Assert.assertEquals("isRegisterOnAllInstances", false, registerMsg.isRegisterOnAllInstances());
- for(int i = 0; (i < 20 * 5) && proxy.getListenerRegistrationActor() == null; i++) {
- Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
- }
+ reply(new RegisterDataTreeChangeListenerReply(getRef()));
- Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
- proxy.getListenerRegistrationActor());
+ for (int i = 0; i < 20 * 5 && proxy.getListenerRegistrationActor() == null; i++) {
+ Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+ }
+
+ Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()),
+ proxy.getListenerRegistrationActor());
- watch(proxy.getDataChangeListenerActor());
+ watch(proxy.getDataChangeListenerActor());
- proxy.close();
+ proxy.close();
- // The listener registration actor should get a Close message
- expectMsgClass(timeout, CloseDataTreeChangeListenerRegistration.class);
+ // The listener registration actor should get a Close message
+ expectMsgClass(timeout, CloseDataTreeChangeListenerRegistration.class);
- // The DataChangeListener actor should be terminated
- expectMsgClass(timeout, Terminated.class);
+ // The DataChangeListener actor should be terminated
+ expectMsgClass(timeout, Terminated.class);
- proxy.close();
+ proxy.close();
- expectNoMsg();
- }};
+ expectNoMsg();
+ }
+ };
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testSuccessfulRegistrationForClusteredListener() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class),
+ mock(Configuration.class));
- ClusteredDOMDataTreeChangeListener mockClusteredListener = mock(ClusteredDOMDataTreeChangeListener.class);
+ ClusteredDOMDataTreeChangeListener mockClusteredListener = mock(
+ ClusteredDOMDataTreeChangeListener.class);
- final DataTreeChangeListenerProxy<ClusteredDOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorContext, mockClusteredListener);
+ final DataTreeChangeListenerProxy<ClusteredDOMDataTreeChangeListener> proxy =
+ new DataTreeChangeListenerProxy<>(actorContext, mockClusteredListener);
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- new Thread() {
- @Override
- public void run() {
- proxy.init("shard-1", path);
- }
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init("shard-1", path);
+ }
+
+ }.start();
- }.start();
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ reply(new LocalShardFound(getRef()));
- reply(new LocalShardFound(getRef()));
+ RegisterDataTreeChangeListener registerMsg = expectMsgClass(timeout,
+ RegisterDataTreeChangeListener.class);
+ Assert.assertEquals("getPath", path, registerMsg.getPath());
+ Assert.assertEquals("isRegisterOnAllInstances", true, registerMsg.isRegisterOnAllInstances());
- RegisterDataTreeChangeListener registerMsg = expectMsgClass(timeout, RegisterDataTreeChangeListener.class);
- Assert.assertEquals("getPath", path, registerMsg.getPath());
- Assert.assertEquals("isRegisterOnAllInstances", true, registerMsg.isRegisterOnAllInstances());
- }};
+ proxy.close();
+ }
+ };
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testLocalShardNotFound() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
-
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorContext, mockListener);
-
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- new Thread() {
- @Override
- public void run() {
- proxy.init("shard-1", path);
- }
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class),
+ mock(Configuration.class));
+
+ final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
+ actorContext, mockListener);
+
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init("shard-1", path);
+ }
- }.start();
+ }.start();
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
- reply(new LocalShardNotFound("shard-1"));
+ reply(new LocalShardNotFound("shard-1"));
- expectNoMsg(duration("1 seconds"));
- }};
+ expectNoMsg(duration("1 seconds"));
+
+ proxy.close();
+ }
+ };
}
- @Test(timeout=10000)
+ @Test(timeout = 10000)
public void testLocalShardNotInitialized() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(),
- mock(ClusterWrapper.class), mock(Configuration.class));
-
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorContext, mockListener);
-
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- new Thread() {
- @Override
- public void run() {
- proxy.init("shard-1", path);
- }
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class),
+ mock(Configuration.class));
- }.start();
+ final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
+ actorContext, mockListener);
- FiniteDuration timeout = duration("5 seconds");
- FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
- Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ new Thread() {
+ @Override
+ public void run() {
+ proxy.init("shard-1", path);
+ }
- reply(new NotInitializedException("not initialized"));
+ }.start();
- new Within(duration("1 seconds")) {
- @Override
- protected void run() {
- expectNoMsg();
- }
- };
- }};
+ FiniteDuration timeout = duration("5 seconds");
+ FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
+ Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+
+ reply(new NotInitializedException("not initialized"));
+
+ new Within(duration("1 seconds")) {
+ @Override
+ protected void run() {
+ expectNoMsg();
+ }
+ };
+
+ proxy.close();
+ }
+ };
}
@Test
public void testFailedRegistration() {
- new JavaTestKit(getSystem()) {{
- ActorSystem mockActorSystem = mock(ActorSystem.class);
+ new JavaTestKit(getSystem()) {
+ {
+ ActorSystem mockActorSystem = mock(ActorSystem.class);
- ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class),
- "testFailedRegistration");
- doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class));
- ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(
- MoreExecutors.directExecutor());
+ ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class), "testFailedRegistration");
+ doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class));
+ ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(MoreExecutors.directExecutor());
+ ActorContext actorContext = mock(ActorContext.class);
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- ActorContext actorContext = mock(ActorContext.class);
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ doReturn(executor).when(actorContext).getClientDispatcher();
+ doReturn(mockActorSystem).when(actorContext).getActorSystem();
- doReturn(executor).when(actorContext).getClientDispatcher();
- doReturn(mockActorSystem).when(actorContext).getActorSystem();
+ String shardName = "shard-1";
+ final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
+ actorContext, mockListener);
- String shardName = "shard-1";
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorContext, mockListener);
+ doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
+ doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
+ doReturn(Futures.failed(new RuntimeException("mock"))).when(actorContext)
+ .executeOperationAsync(any(ActorRef.class), any(Object.class), any(Timeout.class));
+ doReturn(mock(DatastoreContext.class)).when(actorContext).getDatastoreContext();
- doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
- doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
- doReturn(Futures.failed(new RuntimeException("mock"))).
- when(actorContext).executeOperationAsync(any(ActorRef.class),
- any(Object.class), any(Timeout.class));
- doReturn(mock(DatastoreContext.class)).when(actorContext).getDatastoreContext();
+ proxy.init("shard-1", path);
- proxy.init("shard-1", path);
+ Assert.assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
- Assert.assertEquals("getListenerRegistrationActor", null,
- proxy.getListenerRegistrationActor());
- }};
+ proxy.close();
+ }
+ };
}
@Test
public void testCloseBeforeRegistration() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = mock(ActorContext.class);
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = mock(ActorContext.class);
- String shardName = "shard-1";
+ String shardName = "shard-1";
- doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext();
- doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(actorContext).getClientDispatcher();
- doReturn(getSystem()).when(actorContext).getActorSystem();
- doReturn(Dispatchers.DEFAULT_DISPATCHER_PATH).when(actorContext).getNotificationDispatcherPath();
- doReturn(getSystem().actorSelection(getRef().path())).
- when(actorContext).actorSelection(getRef().path());
- doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
- doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
+ doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext();
+ doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(actorContext).getClientDispatcher();
+ doReturn(getSystem()).when(actorContext).getActorSystem();
+ doReturn(Dispatchers.DEFAULT_DISPATCHER_PATH).when(actorContext).getNotificationDispatcherPath();
+ doReturn(getSystem().actorSelection(getRef().path())).when(actorContext)
+ .actorSelection(getRef().path());
+ doReturn(duration("5 seconds")).when(actorContext).getOperationDuration();
+ doReturn(Futures.successful(getRef())).when(actorContext).findLocalShardAsync(eq(shardName));
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorContext, mockListener);
+ final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
+ actorContext, mockListener);
-
- Answer<Future<Object>> answer = new Answer<Future<Object>>() {
- @Override
- public Future<Object> answer(InvocationOnMock invocation) {
+ Answer<Future<Object>> answer = invocation -> {
proxy.close();
- return Futures.successful((Object)new RegisterDataTreeChangeListenerReply(getRef()));
- }
- };
+ return Futures.successful((Object) new RegisterDataTreeChangeListenerReply(getRef()));
+ };
- doAnswer(answer).when(actorContext).executeOperationAsync(any(ActorRef.class),
- any(Object.class), any(Timeout.class));
+ doAnswer(answer).when(actorContext).executeOperationAsync(any(ActorRef.class), any(Object.class),
+ any(Timeout.class));
- proxy.init(shardName, YangInstanceIdentifier.of(TestModel.TEST_QNAME));
+ proxy.init(shardName, YangInstanceIdentifier.of(TestModel.TEST_QNAME));
- expectMsgClass(duration("5 seconds"), CloseDataTreeChangeListenerRegistration.class);
+ expectMsgClass(duration("5 seconds"), CloseDataTreeChangeListenerRegistration.class);
- Assert.assertEquals("getListenerRegistrationActor", null,
- proxy.getListenerRegistrationActor());
- }};
+ Assert.assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
+ }
+ };
}
}
import org.opendaylight.yangtools.concepts.ListenerRegistration;
public class DataTreeChangeListenerRegistrationActorTest extends AbstractActorTest {
- private static final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
+ private static final InMemoryDOMDataStore STORE = new InMemoryDOMDataStore("OPER",
+ MoreExecutors.newDirectExecutorService());
static {
- store.onGlobalContextUpdated(TestModel.createTestContext());
+ STORE.onGlobalContextUpdated(TestModel.createTestContext());
}
- @SuppressWarnings("rawtypes")
+ @SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testOnReceiveCloseListenerRegistration() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ListenerRegistration mockListenerReg = Mockito.mock(ListenerRegistration.class);
- final Props props = DataTreeChangeListenerRegistrationActor.props(mockListenerReg);
- final ActorRef subject = getSystem().actorOf(props, "testCloseListenerRegistration");
+ new JavaTestKit(getSystem()) {
+ {
+ final ListenerRegistration mockListenerReg = Mockito.mock(ListenerRegistration.class);
+ final Props props = DataTreeChangeListenerRegistrationActor.props(mockListenerReg);
+ final ActorRef subject = getSystem().actorOf(props, "testCloseListenerRegistration");
- subject.tell(CloseDataTreeChangeListenerRegistration.getInstance(), getRef());
+ subject.tell(CloseDataTreeChangeListenerRegistration.getInstance(), getRef());
- expectMsgClass(duration("1 second"), CloseDataTreeChangeListenerRegistrationReply.class);
+ expectMsgClass(duration("1 second"), CloseDataTreeChangeListenerRegistrationReply.class);
- Mockito.verify(mockListenerReg).close();
- }};
+ Mockito.verify(mockListenerReg).close();
+ }
+ };
}
}
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.outerNode;
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.outerNodeEntry;
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.testNodeWithOuter;
+
import akka.actor.ActorRef;
import akka.testkit.TestActorRef;
import org.junit.After;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
-import org.opendaylight.controller.cluster.raft.TestActorFactory;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
* @author Thomas Pantelis
*/
public class DataTreeChangeListenerSupportTest extends AbstractShardTest {
- private final TestActorFactory actorFactory = new TestActorFactory(getSystem());
-
private Shard shard;
private DataTreeChangeListenerSupport support;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
+
import akka.actor.ActorSystem;
import akka.actor.Address;
import akka.actor.AddressFromURIString;
import akka.cluster.Cluster;
import akka.testkit.JavaTestKit;
-import akka.util.Timeout;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.typesafe.config.ConfigFactory;
import java.io.IOException;
-import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import scala.concurrent.duration.Duration;
public class DataTreeCohortIntegrationTest {
private static final DOMDataTreeIdentifier TEST_ID =
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH);
- private static final Timeout TIMEOUT = new Timeout(Duration.create(5, TimeUnit.SECONDS));
-
private static ActorSystem system;
private final DatastoreContext.Builder datastoreContextBuilder =
ArgumentCaptor<DOMDataTreeCandidate> candidateCapt = ArgumentCaptor.forClass(DOMDataTreeCandidate.class);
new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
{
- try (final DistributedDataStore dataStore = setupDistributedDataStore("transactionIntegrationTest", "test-1")) {
- final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort(TEST_ID, cohort);
+ try (final DistributedDataStore dataStore = setupDistributedDataStore("transactionIntegrationTest",
+ "test-1")) {
+ final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg =
+ dataStore.registerCommitCohort(TEST_ID, cohort);
Thread.sleep(1000); // Registration is asynchronous
assertNotNull(cohortReg);
testWriteTransaction(dataStore, TestModel.TEST_PATH,
ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- Mockito.verify(cohort).canCommit(any(Object.class), candidateCapt.capture(), any(SchemaContext.class));
+ Mockito.verify(cohort).canCommit(any(Object.class), candidateCapt.capture(),
+ any(SchemaContext.class));
DOMDataTreeCandidate candidate = candidateCapt.getValue();
assertNotNull(candidate);
assertEquals(TEST_ID, candidate.getRootPath());
testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
- Mockito.verify(cohort, Mockito.times(2)).canCommit(any(Object.class), any(DOMDataTreeCandidate.class),
- any(SchemaContext.class));
+ Mockito.verify(cohort, Mockito.times(2)).canCommit(any(Object.class),
+ any(DOMDataTreeCandidate.class), any(SchemaContext.class));
cohortReg.close();
testWriteTransaction(dataStore, TestModel.TEST_PATH,
ImmutableNodes.containerNode(TestModel.TEST_QNAME));
}
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void failCanCommitTest() throws Exception {
final DOMDataTreeCommitCohort failedCohort = mock(DOMDataTreeCommitCohort.class);
}
/**
- *
* FIXME: Weird thing is that invoking canCommit on front-end invokes also preCommit on backend
* so we can not test abort after can commit.
- *
*/
@Test
@Ignore
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
@Test
public void testUpdateOnConfigurationEvent() {
- DatastoreContextConfigAdminOverlay overlay = new DatastoreContextConfigAdminOverlay(
+ final DatastoreContextConfigAdminOverlay overlay = new DatastoreContextConfigAdminOverlay(
mockIntrospector, mockBundleContext);
reset(mockIntrospector);
@Test
public void testConfigurationEventWithDifferentPid() {
- DatastoreContextConfigAdminOverlay overlay = new DatastoreContextConfigAdminOverlay(
+ final DatastoreContextConfigAdminOverlay overlay = new DatastoreContextConfigAdminOverlay(
mockIntrospector, mockBundleContext);
reset(mockIntrospector);
@Test
public void testConfigurationEventWithNonUpdateEventType() {
- DatastoreContextConfigAdminOverlay overlay = new DatastoreContextConfigAdminOverlay(
+ final DatastoreContextConfigAdminOverlay overlay = new DatastoreContextConfigAdminOverlay(
mockIntrospector, mockBundleContext);
reset(mockIntrospector);
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_TRANSACTION_IDLE_TIMEOUT;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_TX_COMMIT_TIMEOUT_IN_SECONDS;
+
import java.util.Dictionary;
import java.util.Hashtable;
import org.junit.Test;
@Test
public void testUpdate() {
- DatastoreContext context = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
+ DatastoreContext context = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
DatastoreContextIntrospector introspector = new DatastoreContextIntrospector(context );
Dictionary<String, Object> properties = new Hashtable<>();
@Test
public void testUpdateWithInvalidValues() {
- DatastoreContext context = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
+ DatastoreContext context = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
DatastoreContextIntrospector introspector = new DatastoreContextIntrospector(context );
Dictionary<String, Object> properties = new Hashtable<>();
assertEquals(DEFAULT_SHARD_TX_COMMIT_TIMEOUT_IN_SECONDS, context.getShardTransactionCommitTimeoutInSeconds());
assertEquals(212, context.getShardRaftConfig().getSnapshotBatchCount());
assertEquals(DEFAULT_OPERATION_TIMEOUT_IN_MS, context.getOperationTimeoutInMillis());
- assertEquals(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS, context.getShardRaftConfig().getHeartBeatInterval().length());
+ assertEquals(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS,
+ context.getShardRaftConfig().getHeartBeatInterval().length());
assertEquals(567, context.getShardTransactionCommitQueueCapacity());
assertEquals(DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE,
context.getShardRaftConfig().getSnapshotDataThresholdPercentage());
properties.put("persistent", "false"); // global setting
properties.put("operational.Persistent", "true"); // operational override
- DatastoreContext operContext = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
+ DatastoreContext operContext = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
DatastoreContextIntrospector operIntrospector = new DatastoreContextIntrospector(operContext);
boolean updated = operIntrospector.update(properties);
assertEquals("updated", true, updated);
properties.put("config.shard-transaction-idle-timeout-in-minutes", "44"); // config override
properties.put("topology.shard-transaction-idle-timeout-in-minutes", "55"); // global shard override
- DatastoreContext operContext = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
+ DatastoreContext operContext = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.OPERATIONAL).build();
DatastoreContextIntrospector operIntrospector = new DatastoreContextIntrospector(operContext);
DatastoreContext shardContext = operIntrospector.newContextFactory().getShardDatastoreContext("topology");
shardContext = operIntrospector.newContextFactory().getShardDatastoreContext("topology");
assertEquals(55, shardContext.getShardTransactionIdleTimeout().toMinutes());
- DatastoreContext configContext = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.CONFIGURATION).build();
+ DatastoreContext configContext = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.CONFIGURATION).build();
DatastoreContextIntrospector configIntrospector = new DatastoreContextIntrospector(configContext);
configIntrospector.update(properties);
configContext = configIntrospector.getContext();
shardContext = configIntrospector.newContextFactory().getShardDatastoreContext("topology");
assertEquals(55, shardContext.getShardTransactionIdleTimeout().toMinutes());
- properties.put("operational.topology.shard-transaction-idle-timeout-in-minutes", "66"); // operational shard override
- properties.put("config.topology.shard-transaction-idle-timeout-in-minutes", "77"); // config shard override
+ // operational shard override
+ properties.put("operational.topology.shard-transaction-idle-timeout-in-minutes", "66");
+ // config shard override
+ properties.put("config.topology.shard-transaction-idle-timeout-in-minutes", "77");
operIntrospector.update(properties);
shardContext = operIntrospector.newContextFactory().getShardDatastoreContext("topology");
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_ELECTION_TIMEOUT_FACTOR;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_INITIALIZATION_TIMEOUT;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_LEADER_ELECTION_TIMEOUT;
+import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_SNAPSHOT_CHUNK_SIZE;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_TRANSACTION_IDLE_TIMEOUT;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_TX_COMMIT_QUEUE_CAPACITY;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_TX_COMMIT_TIMEOUT_IN_SECONDS;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SNAPSHOT_BATCH_COUNT;
import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_TX_CREATION_INITIAL_RATE_LIMIT;
-import static org.opendaylight.controller.cluster.datastore.DatastoreContext.DEFAULT_SHARD_SNAPSHOT_CHUNK_SIZE;
+
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
assertEquals(DEFAULT_SHARD_TRANSACTION_IDLE_TIMEOUT, context.getShardTransactionIdleTimeout());
assertEquals(DEFAULT_OPERATION_TIMEOUT_IN_MS, context.getOperationTimeoutInMillis());
assertEquals(DEFAULT_SHARD_TX_COMMIT_TIMEOUT_IN_SECONDS, context.getShardTransactionCommitTimeoutInSeconds());
- assertEquals(DEFAULT_JOURNAL_RECOVERY_BATCH_SIZE, context.getShardRaftConfig().getJournalRecoveryLogBatchSize());
+ assertEquals(DEFAULT_JOURNAL_RECOVERY_BATCH_SIZE,
+ context.getShardRaftConfig().getJournalRecoveryLogBatchSize());
assertEquals(DEFAULT_SNAPSHOT_BATCH_COUNT, context.getShardRaftConfig().getSnapshotBatchCount());
- assertEquals(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS, context.getShardRaftConfig().getHeartBeatInterval().length());
+ assertEquals(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS,
+ context.getShardRaftConfig().getHeartBeatInterval().length());
assertEquals(DEFAULT_SHARD_TX_COMMIT_QUEUE_CAPACITY, context.getShardTransactionCommitQueueCapacity());
assertEquals(DEFAULT_SHARD_INITIALIZATION_TIMEOUT.duration().toMillis(),
context.getShardInitializationTimeout().duration().toMillis());
context.getShardLeaderElectionTimeout().duration().toMillis());
assertEquals(DEFAULT_PERSISTENT, context.isPersistent());
assertEquals(DEFAULT_CONFIGURATION_READER, context.getConfigurationReader());
- assertEquals(DEFAULT_ISOLATED_LEADER_CHECK_INTERVAL_IN_MILLIS, context.getShardRaftConfig().getIsolatedCheckIntervalInMillis());
- assertEquals(DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE, context.getShardRaftConfig().getSnapshotDataThresholdPercentage());
+ assertEquals(DEFAULT_ISOLATED_LEADER_CHECK_INTERVAL_IN_MILLIS,
+ context.getShardRaftConfig().getIsolatedCheckIntervalInMillis());
+ assertEquals(DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE,
+ context.getShardRaftConfig().getSnapshotDataThresholdPercentage());
assertEquals(DEFAULT_SHARD_ELECTION_TIMEOUT_FACTOR, context.getShardRaftConfig().getElectionTimeoutFactor());
assertEquals(DEFAULT_TX_CREATION_INITIAL_RATE_LIMIT, context.getTransactionCreationInitialRateLimit());
- assertEquals(DatastoreContext.DEFAULT_SHARD_BATCHED_MODIFICATION_COUNT, context.getShardBatchedModificationCount());
+ assertEquals(DatastoreContext.DEFAULT_SHARD_BATCHED_MODIFICATION_COUNT,
+ context.getShardBatchedModificationCount());
assertEquals(InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_EXECUTOR_POOL_SIZE,
context.getDataStoreProperties().getMaxDataChangeExecutorPoolSize());
assertEquals(InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_EXECUTOR_QUEUE_SIZE,
builder.shardSnapshotBatchCount(DEFAULT_SNAPSHOT_BATCH_COUNT + 1);
builder.shardHeartbeatIntervalInMillis(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS + 1);
builder.shardTransactionCommitQueueCapacity(DEFAULT_SHARD_TX_COMMIT_QUEUE_CAPACITY + 1);
- builder.shardInitializationTimeout(DEFAULT_SHARD_INITIALIZATION_TIMEOUT.
- duration().toMillis() + 1, TimeUnit.MILLISECONDS);
+ builder.shardInitializationTimeout(DEFAULT_SHARD_INITIALIZATION_TIMEOUT
+ .duration().toMillis() + 1, TimeUnit.MILLISECONDS);
builder.shardInitializationTimeout(DEFAULT_SHARD_INITIALIZATION_TIMEOUT.duration().toMillis() + 1,
TimeUnit.MILLISECONDS);
builder.shardLeaderElectionTimeout(DEFAULT_SHARD_LEADER_ELECTION_TIMEOUT.duration().toMillis() + 1,
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE + 1);
builder.maxShardDataStoreExecutorQueueSize(
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_STORE_EXECUTOR_QUEUE_SIZE + 1);
- builder.shardSnapshotChunkSize(DEFAULT_SHARD_SNAPSHOT_CHUNK_SIZE+1);
+ builder.shardSnapshotChunkSize(DEFAULT_SHARD_SNAPSHOT_CHUNK_SIZE + 1);
DatastoreContext context = builder.build();
context.getShardRaftConfig().getIsolatedCheckIntervalInMillis());
assertEquals(DEFAULT_SHARD_SNAPSHOT_DATA_THRESHOLD_PERCENTAGE + 1,
context.getShardRaftConfig().getSnapshotDataThresholdPercentage());
- assertEquals(DEFAULT_SHARD_ELECTION_TIMEOUT_FACTOR + 1, context.getShardRaftConfig().getElectionTimeoutFactor());
+ assertEquals(DEFAULT_SHARD_ELECTION_TIMEOUT_FACTOR + 1,
+ context.getShardRaftConfig().getElectionTimeoutFactor());
assertEquals(DEFAULT_TX_CREATION_INITIAL_RATE_LIMIT + 1, context.getTransactionCreationInitialRateLimit());
assertEquals(DatastoreContext.DEFAULT_SHARD_BATCHED_MODIFICATION_COUNT + 1,
context.getShardBatchedModificationCount());
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
List<ShardSnapshot> shardSnapshots = new ArrayList<>();
shardSnapshots.add(new ShardSnapshot("cars", new byte[]{1,2}));
shardSnapshots.add(new ShardSnapshot("people", new byte[]{3,4}));
- DatastoreSnapshot configSnapshot = new DatastoreSnapshot("config", null, shardSnapshots );
+ final DatastoreSnapshot configSnapshot = new DatastoreSnapshot("config", null, shardSnapshots );
shardSnapshots = new ArrayList<>();
shardSnapshots.add(new ShardSnapshot("cars", new byte[]{5,6}));
snapshotList.add(configSnapshot);
snapshotList.add(operSnapshot);
- File backupFile = new File(restoreDirectoryFile, "backup");
- try(FileOutputStream fos = new FileOutputStream(backupFile)) {
+ try (FileOutputStream fos = new FileOutputStream(backupFile)) {
SerializationUtils.serialize(snapshotList, fos);
}
assertTrue("ShardManager snapshots don't match", Objects.deepEquals(expected.getShardManagerSnapshot(),
actual.getShardManagerSnapshot()));
assertEquals("ShardSnapshots size", expected.getShardSnapshots().size(), actual.getShardSnapshots().size());
- for(int i = 0; i < expected.getShardSnapshots().size(); i++) {
+ for (int i = 0; i < expected.getShardSnapshots().size(); i++) {
assertEquals("ShardSnapshot " + (i + 1) + " name", expected.getShardSnapshots().get(i).getName(),
actual.getShardSnapshots().get(i).getName());
- assertArrayEquals("ShardSnapshot " + (i + 1) + " snapshot", expected.getShardSnapshots().get(i).getSnapshot(),
- actual.getShardSnapshots().get(i).getSnapshot());
+ assertArrayEquals("ShardSnapshot " + (i + 1) + " snapshot",
+ expected.getShardSnapshots().get(i).getSnapshot(), actual.getShardSnapshots().get(i).getSnapshot());
}
}
}
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
+
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
doReturn(expCohortFutures).when(mockDelegate).getCohortFutures();
Throwable debugContext = new RuntimeException("mock");
- DebugThreePhaseCommitCohort cohort = new DebugThreePhaseCommitCohort(transactionId , mockDelegate , debugContext);
+ DebugThreePhaseCommitCohort cohort = new DebugThreePhaseCommitCohort(transactionId, mockDelegate, debugContext);
Logger mockLogger = mock(Logger.class);
cohort.setLogger(mockLogger);
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorSystem;
import akka.actor.Address;
import akka.actor.AddressFromURIString;
import akka.cluster.Cluster;
import akka.testkit.JavaTestKit;
import com.google.common.base.Optional;
+import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.ListenableFuture;
private static ActorSystem system;
- private final DatastoreContext.Builder datastoreContextBuilder =
- DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100);
+ private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder()
+ .shardHeartbeatIntervalInMillis(100);
@BeforeClass
public static void setUpClass() throws IOException {
}
@Test
- public void testWriteTransactionWithSingleShard() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("transactionIntegrationTest", "test-1")) {
+ public void testWriteTransactionWithSingleShard() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore("transactionIntegrationTest",
+ "test-1")) {
- testWriteTransaction(dataStore, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ testWriteTransaction(dataStore, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ }
}
- }};
+ };
}
@Test
- public void testWriteTransactionWithMultipleShards() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("testWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
+ public void testWriteTransactionWithMultipleShards() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
- DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
- assertNotNull("newWriteOnlyTransaction returned null", writeTx);
+ DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
+ assertNotNull("newWriteOnlyTransaction returned null", writeTx);
- writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
- writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
+ writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
+ writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
- doCommit(writeTx.ready());
+ doCommit(writeTx.ready());
- writeTx = dataStore.newWriteOnlyTransaction();
+ writeTx = dataStore.newWriteOnlyTransaction();
- writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
- writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
+ writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
+ writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
- doCommit(writeTx.ready());
+ doCommit(writeTx.ready());
- writeTx = dataStore.newWriteOnlyTransaction();
+ writeTx = dataStore.newWriteOnlyTransaction();
- MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
- YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
- writeTx.write(carPath, car);
+ MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
+ YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
+ writeTx.write(carPath, car);
- MapEntryNode person = PeopleModel.newPersonEntry("jack");
- YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
- writeTx.write(personPath, person);
+ MapEntryNode person = PeopleModel.newPersonEntry("jack");
+ YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
+ writeTx.write(personPath, person);
- doCommit(writeTx.ready());
+ doCommit(writeTx.ready());
- // Verify the data in the store
+ // Verify the data in the store
- DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
+ DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- Optional<NormalizedNode<?, ?>> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", car, optional.get());
+ Optional<NormalizedNode<?, ?>> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", car, optional.get());
- optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", person, optional.get());
+ }
}
- }};
+ };
}
@Test
- public void testReadWriteTransactionWithSingleShard() throws Exception{
+ public void testReadWriteTransactionWithSingleShard() throws Exception {
System.setProperty("shard.persistent", "true");
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("testReadWriteTransactionWithSingleShard", "test-1")) {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testReadWriteTransactionWithSingleShard", "test-1")) {
- // 1. Create a read-write Tx
+ // 1. Create a read-write Tx
- DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
- assertNotNull("newReadWriteTransaction returned null", readWriteTx);
+ DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
+ assertNotNull("newReadWriteTransaction returned null", readWriteTx);
- // 2. Write some data
+ // 2. Write some data
- YangInstanceIdentifier nodePath = TestModel.TEST_PATH;
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- readWriteTx.write(nodePath, nodeToWrite );
+ YangInstanceIdentifier nodePath = TestModel.TEST_PATH;
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ readWriteTx.write(nodePath, nodeToWrite);
- // 3. Read the data from Tx
+ // 3. Read the data from Tx
- Boolean exists = readWriteTx.exists(nodePath).checkedGet(5, TimeUnit.SECONDS);
- assertEquals("exists", true, exists);
+ Boolean exists = readWriteTx.exists(nodePath).checkedGet(5, TimeUnit.SECONDS);
+ assertEquals("exists", true, exists);
- Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", nodeToWrite, optional.get());
+ Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", nodeToWrite, optional.get());
- // 4. Ready the Tx for commit
+ // 4. Ready the Tx for commit
- DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
+ DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
- // 5. Commit the Tx
+ // 5. Commit the Tx
- doCommit(cohort);
+ doCommit(cohort);
- // 6. Verify the data in the store
+ // 6. Verify the data in the store
- DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
+ DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", nodeToWrite, optional.get());
+ optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", nodeToWrite, optional.get());
+ }
}
- }};
+ };
}
@Test
- public void testReadWriteTransactionWithMultipleShards() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("testReadWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
+ public void testReadWriteTransactionWithMultipleShards() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testReadWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
- DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
- assertNotNull("newReadWriteTransaction returned null", readWriteTx);
+ DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
+ assertNotNull("newReadWriteTransaction returned null", readWriteTx);
- readWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
- readWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
+ readWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
+ readWriteTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
- doCommit(readWriteTx.ready());
+ doCommit(readWriteTx.ready());
- readWriteTx = dataStore.newReadWriteTransaction();
+ readWriteTx = dataStore.newReadWriteTransaction();
- readWriteTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
- readWriteTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
+ readWriteTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
+ readWriteTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
- doCommit(readWriteTx.ready());
+ doCommit(readWriteTx.ready());
- readWriteTx = dataStore.newReadWriteTransaction();
+ readWriteTx = dataStore.newReadWriteTransaction();
- MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
- YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
- readWriteTx.write(carPath, car);
+ MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
+ YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
+ readWriteTx.write(carPath, car);
- MapEntryNode person = PeopleModel.newPersonEntry("jack");
- YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
- readWriteTx.write(personPath, person);
+ MapEntryNode person = PeopleModel.newPersonEntry("jack");
+ YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
+ readWriteTx.write(personPath, person);
- Boolean exists = readWriteTx.exists(carPath).checkedGet(5, TimeUnit.SECONDS);
- assertEquals("exists", true, exists);
+ Boolean exists = readWriteTx.exists(carPath).checkedGet(5, TimeUnit.SECONDS);
+ assertEquals("exists", true, exists);
- Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", car, optional.get());
+ Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", car, optional.get());
- doCommit(readWriteTx.ready());
+ doCommit(readWriteTx.ready());
- // Verify the data in the store
+ // Verify the data in the store
- DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
+ DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", car, optional.get());
+ optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", car, optional.get());
- optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", person, optional.get());
+ }
}
- }};
+ };
}
@Test
- public void testSingleTransactionsWritesInQuickSuccession() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testSingleTransactionsWritesInQuickSuccession", "cars-1")) {
+ public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testSingleTransactionsWritesInQuickSuccession", "cars-1")) {
- DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
- writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
- doCommit(writeTx.ready());
+ DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
+ writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
+ doCommit(writeTx.ready());
- writeTx = txChain.newWriteOnlyTransaction();
+ writeTx = txChain.newWriteOnlyTransaction();
- int nCars = 5;
- for(int i = 0; i < nCars; i++) {
- writeTx.write(CarsModel.newCarPath("car" + i),
- CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
- }
+ int numCars = 5;
+ for (int i = 0; i < numCars; i++) {
+ writeTx.write(CarsModel.newCarPath("car" + i),
+ CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
+ }
- doCommit(writeTx.ready());
+ doCommit(writeTx.ready());
- Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction().read(
- CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("# cars", nCars, ((Collection<?>)optional.get().getValue()).size());
+ Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
+ .read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
+ }
}
- }};
+ };
}
- private void testTransactionWritesWithShardNotInitiallyReady(final String testName,
- final boolean writeOnly) throws Exception {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- String shardName = "test-1";
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ private void testTransactionWritesWithShardNotInitiallyReady(final String testName, final boolean writeOnly)
+ throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ String shardName = "test-1";
- // Setup the InMemoryJournal to block shard recovery to ensure the shard isn't
- // initialized until we create and submit the write the Tx.
- String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
- CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
- InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
+ // Setup the InMemoryJournal to block shard recovery to ensure
+ // the shard isn't
+ // initialized until we create and submit the write the Tx.
+ String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
+ CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
+ InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
- try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
- // Create the write Tx
+ // Create the write Tx
- final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction() :
- dataStore.newReadWriteTransaction();
- assertNotNull("newReadWriteTransaction returned null", writeTx);
+ final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction()
+ : dataStore.newReadWriteTransaction();
+ assertNotNull("newReadWriteTransaction returned null", writeTx);
- // Do some modification operations and ready the Tx on a separate thread.
+ // Do some modification operations and ready the Tx on a
+ // separate thread.
- final YangInstanceIdentifier listEntryPath = YangInstanceIdentifier.builder(
- TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME,
- TestModel.ID_QNAME, 1).build();
+ final YangInstanceIdentifier listEntryPath = YangInstanceIdentifier
+ .builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
- final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
- final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch txReady = new CountDownLatch(1);
- Thread txThread = new Thread() {
- @Override
- public void run() {
- try {
- writeTx.write(TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
+ final AtomicReference<Exception> caughtEx = new AtomicReference<>();
+ final CountDownLatch txReady = new CountDownLatch(1);
+ Thread txThread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- writeTx.merge(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(
- TestModel.OUTER_LIST_QNAME).build());
+ writeTx.merge(TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
- writeTx.write(listEntryPath, ImmutableNodes.mapEntry(
- TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
+ writeTx.write(listEntryPath,
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
- writeTx.delete(listEntryPath);
+ writeTx.delete(listEntryPath);
- txCohort.set(writeTx.ready());
- } catch(Exception e) {
- caughtEx.set(e);
- return;
- } finally {
- txReady.countDown();
+ txCohort.set(writeTx.ready());
+ } catch (Exception e) {
+ caughtEx.set(e);
+ return;
+ } finally {
+ txReady.countDown();
+ }
}
- }
- };
+ };
- txThread.start();
+ txThread.start();
- // Wait for the Tx operations to complete.
+ // Wait for the Tx operations to complete.
- boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
- throw caughtEx.get();
- }
+ boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
+ if (caughtEx.get() != null) {
+ throw caughtEx.get();
+ }
- assertEquals("Tx ready", true, done);
+ assertEquals("Tx ready", true, done);
- // At this point the Tx operations should be waiting for the shard to initialize so
- // trigger the latch to let the shard recovery to continue.
+ // At this point the Tx operations should be waiting for the
+ // shard to initialize so
+ // trigger the latch to let the shard recovery to continue.
- blockRecoveryLatch.countDown();
+ blockRecoveryLatch.countDown();
- // Wait for the Tx commit to complete.
+ // Wait for the Tx commit to complete.
- doCommit(txCohort.get());
+ doCommit(txCohort.get());
- // Verify the data in the store
+ // Verify the data in the store
- DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
+ DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).
- get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
+ Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
- optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
+ optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
- optional = readTx.read(listEntryPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", false, optional.isPresent());
+ optional = readTx.read(listEntryPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", false, optional.isPresent());
+ }
}
- }};
+ };
}
@Test
}
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void testTransactionReadsWithShardNotInitiallyReady() throws Exception {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- String testName = "testTransactionReadsWithShardNotInitiallyReady";
- String shardName = "test-1";
-
- // Setup the InMemoryJournal to block shard recovery to ensure the shard isn't
- // initialized until we create the Tx.
- String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
- CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
- InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
-
- try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
-
- // Create the read-write Tx
-
- final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
- assertNotNull("newReadWriteTransaction returned null", readWriteTx);
-
- // Do some reads on the Tx on a separate thread.
-
- final AtomicReference<CheckedFuture<Boolean, ReadFailedException>> txExistsFuture =
- new AtomicReference<>();
- final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
- txReadFuture = new AtomicReference<>();
- final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch txReadsDone = new CountDownLatch(1);
- Thread txThread = new Thread() {
- @Override
- public void run() {
- try {
- readWriteTx.write(TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- txExistsFuture.set(readWriteTx.exists(TestModel.TEST_PATH));
-
- txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
- } catch(Exception e) {
- caughtEx.set(e);
- return;
- } finally {
- txReadsDone.countDown();
- }
- }
- };
-
- txThread.start();
-
- // Wait for the Tx operations to complete.
-
- boolean done = Uninterruptibles.awaitUninterruptibly(txReadsDone, 5, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
- throw caughtEx.get();
- }
-
- assertEquals("Tx reads done", true, done);
-
- // At this point the Tx operations should be waiting for the shard to initialize so
- // trigger the latch to let the shard recovery to continue.
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ String testName = "testTransactionReadsWithShardNotInitiallyReady";
+ String shardName = "test-1";
- blockRecoveryLatch.countDown();
+ // Setup the InMemoryJournal to block shard recovery to ensure
+ // the shard isn't
+ // initialized until we create the Tx.
+ String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
+ CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
+ InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
- // Wait for the reads to complete and verify.
+ try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
- assertEquals("exists", true, txExistsFuture.get().checkedGet(5, TimeUnit.SECONDS));
- assertEquals("read", true, txReadFuture.get().checkedGet(5, TimeUnit.SECONDS).isPresent());
-
- readWriteTx.close();
- }
- }};
- }
+ // Create the read-write Tx
- @Test(expected=NotInitializedException.class)
- public void testTransactionCommitFailureWithShardNotInitialized() throws Throwable{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- String testName = "testTransactionCommitFailureWithShardNotInitialized";
- String shardName = "test-1";
+ final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
+ assertNotNull("newReadWriteTransaction returned null", readWriteTx);
- // Set the shard initialization timeout low for the test.
+ // Do some reads on the Tx on a separate thread.
- datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
-
- // Setup the InMemoryJournal to block shard recovery indefinitely.
-
- String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
- CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
- InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
-
- InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
+ final AtomicReference<CheckedFuture<Boolean, ReadFailedException>> txExistsFuture =
+ new AtomicReference<>();
+ final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
+ txReadFuture = new AtomicReference<>();
+ final AtomicReference<Exception> caughtEx = new AtomicReference<>();
+ final CountDownLatch txReadsDone = new CountDownLatch(1);
+ Thread txThread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ readWriteTx.write(TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
+ txExistsFuture.set(readWriteTx.exists(TestModel.TEST_PATH));
- // Create the write Tx
+ txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
+ } catch (Exception e) {
+ caughtEx.set(e);
+ return;
+ } finally {
+ txReadsDone.countDown();
+ }
+ }
+ };
- final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
- assertNotNull("newReadWriteTransaction returned null", writeTx);
+ txThread.start();
- // Do some modifications and ready the Tx on a separate thread.
+ // Wait for the Tx operations to complete.
- final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
- final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch txReady = new CountDownLatch(1);
- Thread txThread = new Thread() {
- @Override
- public void run() {
- try {
- writeTx.write(TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- txCohort.set(writeTx.ready());
- } catch(Exception e) {
- caughtEx.set(e);
- return;
- } finally {
- txReady.countDown();
- }
+ boolean done = Uninterruptibles.awaitUninterruptibly(txReadsDone, 5, TimeUnit.SECONDS);
+ if (caughtEx.get() != null) {
+ throw caughtEx.get();
}
- };
- txThread.start();
+ assertEquals("Tx reads done", true, done);
- // Wait for the Tx operations to complete.
+ // At this point the Tx operations should be waiting for the
+ // shard to initialize so
+ // trigger the latch to let the shard recovery to continue.
- boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
- throw caughtEx.get();
- }
+ blockRecoveryLatch.countDown();
- assertEquals("Tx ready", true, done);
+ // Wait for the reads to complete and verify.
- // Wait for the commit to complete. Since the shard never initialized, the Tx should
- // have timed out and throw an appropriate exception cause.
+ assertEquals("exists", true, txExistsFuture.get().checkedGet(5, TimeUnit.SECONDS));
+ assertEquals("read", true, txReadFuture.get().checkedGet(5, TimeUnit.SECONDS).isPresent());
- try {
- txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
- } catch(ExecutionException e) {
- throw e.getCause();
- } finally {
- blockRecoveryLatch.countDown();
+ readWriteTx.close();
}
}
- }};
+ };
}
- @Test(expected=NotInitializedException.class)
- public void testTransactionReadFailureWithShardNotInitialized() throws Throwable{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- String testName = "testTransactionReadFailureWithShardNotInitialized";
- String shardName = "test-1";
+ @Test(expected = NotInitializedException.class)
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public void testTransactionCommitFailureWithShardNotInitialized() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ String testName = "testTransactionCommitFailureWithShardNotInitialized";
+ String shardName = "test-1";
- // Set the shard initialization timeout low for the test.
+ // Set the shard initialization timeout low for the test.
- datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
+ datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
- // Setup the InMemoryJournal to block shard recovery indefinitely.
+ // Setup the InMemoryJournal to block shard recovery
+ // indefinitely.
- String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
- CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
- InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
+ String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
+ CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
+ InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
- InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
+ InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
- try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
- // Create the read-write Tx
+ // Create the write Tx
- final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
- assertNotNull("newReadWriteTransaction returned null", readWriteTx);
+ final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
+ assertNotNull("newReadWriteTransaction returned null", writeTx);
- // Do a read on the Tx on a separate thread.
+ // Do some modifications and ready the Tx on a separate
+ // thread.
- final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
- txReadFuture = new AtomicReference<>();
- final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch txReadDone = new CountDownLatch(1);
- Thread txThread = new Thread() {
- @Override
- public void run() {
- try {
- readWriteTx.write(TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
+ final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
+ final AtomicReference<Exception> caughtEx = new AtomicReference<>();
+ final CountDownLatch txReady = new CountDownLatch(1);
+ Thread txThread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- readWriteTx.close();
- } catch(Exception e) {
- caughtEx.set(e);
- return;
- } finally {
- txReadDone.countDown();
+ txCohort.set(writeTx.ready());
+ } catch (Exception e) {
+ caughtEx.set(e);
+ return;
+ } finally {
+ txReady.countDown();
+ }
}
- }
- };
+ };
- txThread.start();
+ txThread.start();
- // Wait for the Tx operations to complete.
+ // Wait for the Tx operations to complete.
- boolean done = Uninterruptibles.awaitUninterruptibly(txReadDone, 5, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
- throw caughtEx.get();
- }
+ boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
+ if (caughtEx.get() != null) {
+ throw caughtEx.get();
+ }
- assertEquals("Tx read done", true, done);
+ assertEquals("Tx ready", true, done);
- // Wait for the read to complete. Since the shard never initialized, the Tx should
- // have timed out and throw an appropriate exception cause.
+ // Wait for the commit to complete. Since the shard never
+ // initialized, the Tx should
+ // have timed out and throw an appropriate exception cause.
- try {
- txReadFuture.get().checkedGet(5, TimeUnit.SECONDS);
- } catch(ReadFailedException e) {
- throw e.getCause();
- } finally {
- blockRecoveryLatch.countDown();
+ try {
+ txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
+ } catch (ExecutionException e) {
+ Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
+ Throwables.propagate(e.getCause());
+ } finally {
+ blockRecoveryLatch.countDown();
+ }
}
}
- }};
+ };
}
- private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName) throws Throwable {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- String shardName = "default";
+ @Test(expected = NotInitializedException.class)
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public void testTransactionReadFailureWithShardNotInitialized() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ String testName = "testTransactionReadFailureWithShardNotInitialized";
+ String shardName = "test-1";
- // We don't want the shard to become the leader so prevent shard elections.
- datastoreContextBuilder.customRaftPolicyImplementation(
- "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
+ // Set the shard initialization timeout low for the test.
- // The ShardManager uses the election timeout for FindPrimary so reset it low so it will timeout quickly.
- datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1).
- shardInitializationTimeout(200, TimeUnit.MILLISECONDS);
+ datastoreContextBuilder.shardInitializationTimeout(300, TimeUnit.MILLISECONDS);
- try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
+ // Setup the InMemoryJournal to block shard recovery
+ // indefinitely.
- Object result = dataStore.getActorContext().executeOperation(
- dataStore.getActorContext().getShardManager(), new FindLocalShard(shardName, true));
- assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
+ String persistentID = String.format("member-1-shard-%s-%s", shardName, testName);
+ CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
+ InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
- // Create the write Tx.
+ InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
- try (final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction() :
- dataStore.newReadWriteTransaction()) {
- assertNotNull("newReadWriteTransaction returned null", writeTx);
+ try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
- // Do some modifications and ready the Tx on a separate thread.
+ // Create the read-write Tx
- final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
+ final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
+ assertNotNull("newReadWriteTransaction returned null", readWriteTx);
+
+ // Do a read on the Tx on a separate thread.
+
+ final AtomicReference<CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>>
+ txReadFuture = new AtomicReference<>();
final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch txReady = new CountDownLatch(1);
+ final CountDownLatch txReadDone = new CountDownLatch(1);
Thread txThread = new Thread() {
@Override
public void run() {
try {
- writeTx.write(TestModel.JUNK_PATH,
- ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
+ readWriteTx.write(TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- txCohort.set(writeTx.ready());
- } catch(Exception e) {
+ txReadFuture.set(readWriteTx.read(TestModel.TEST_PATH));
+
+ readWriteTx.close();
+ } catch (Exception e) {
caughtEx.set(e);
return;
} finally {
- txReady.countDown();
+ txReadDone.countDown();
}
}
};
// Wait for the Tx operations to complete.
- boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
+ boolean done = Uninterruptibles.awaitUninterruptibly(txReadDone, 5, TimeUnit.SECONDS);
+ if (caughtEx.get() != null) {
throw caughtEx.get();
}
- assertEquals("Tx ready", true, done);
+ assertEquals("Tx read done", true, done);
- // Wait for the commit to complete. Since no shard leader was elected in time, the Tx
- // should have timed out and throw an appropriate exception cause.
+ // Wait for the read to complete. Since the shard never
+ // initialized, the Tx should
+ // have timed out and throw an appropriate exception cause.
try {
- txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
- } catch(ExecutionException e) {
- throw e.getCause();
+ txReadFuture.get().checkedGet(5, TimeUnit.SECONDS);
+ } catch (ReadFailedException e) {
+ Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
+ Throwables.propagate(e.getCause());
+ } finally {
+ blockRecoveryLatch.countDown();
}
}
}
- }};
+ };
}
- @Test(expected=NoShardLeaderException.class)
- public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Throwable {
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName)
+ throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ String shardName = "default";
+
+ // We don't want the shard to become the leader so prevent shard
+ // elections.
+ datastoreContextBuilder.customRaftPolicyImplementation(
+ "org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
+
+ // The ShardManager uses the election timeout for FindPrimary so
+ // reset it low so it will timeout quickly.
+ datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1)
+ .shardInitializationTimeout(200, TimeUnit.MILLISECONDS);
+
+ try (DistributedDataStore dataStore = setupDistributedDataStore(testName, false, shardName)) {
+
+ Object result = dataStore.getActorContext().executeOperation(
+ dataStore.getActorContext().getShardManager(), new FindLocalShard(shardName, true));
+ assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
+
+ // Create the write Tx.
+
+ try (final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction()
+ : dataStore.newReadWriteTransaction()) {
+ assertNotNull("newReadWriteTransaction returned null", writeTx);
+
+ // Do some modifications and ready the Tx on a separate
+ // thread.
+
+ final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
+ final AtomicReference<Exception> caughtEx = new AtomicReference<>();
+ final CountDownLatch txReady = new CountDownLatch(1);
+ Thread txThread = new Thread() {
+ @Override
+ public void run() {
+ try {
+ writeTx.write(TestModel.JUNK_PATH,
+ ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
+
+ txCohort.set(writeTx.ready());
+ } catch (Exception e) {
+ caughtEx.set(e);
+ return;
+ } finally {
+ txReady.countDown();
+ }
+ }
+ };
+
+ txThread.start();
+
+ // Wait for the Tx operations to complete.
+
+ boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
+ if (caughtEx.get() != null) {
+ throw caughtEx.get();
+ }
+
+ assertEquals("Tx ready", true, done);
+
+ // Wait for the commit to complete. Since no shard
+ // leader was elected in time, the Tx
+ // should have timed out and throw an appropriate
+ // exception cause.
+
+ try {
+ txCohort.get().canCommit().get(5, TimeUnit.SECONDS);
+ } catch (ExecutionException e) {
+ Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
+ Throwables.propagate(e.getCause());
+ }
+ }
+ }
+ }
+ };
+ }
+
+ @Test(expected = NoShardLeaderException.class)
+ public void testWriteOnlyTransactionCommitFailureWithNoShardLeader() throws Exception {
datastoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
testTransactionCommitFailureWithNoShardLeader(true, "testWriteOnlyTransactionCommitFailureWithNoShardLeader");
}
- @Test(expected=NoShardLeaderException.class)
- public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Throwable {
+ @Test(expected = NoShardLeaderException.class)
+ public void testReadWriteTransactionCommitFailureWithNoShardLeader() throws Exception {
testTransactionCommitFailureWithNoShardLeader(false, "testReadWriteTransactionCommitFailureWithNoShardLeader");
}
@Test
- public void testTransactionAbort() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("transactionAbortIntegrationTest", "test-1")) {
+ public void testTransactionAbort() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore("transactionAbortIntegrationTest",
+ "test-1")) {
- DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
- assertNotNull("newWriteOnlyTransaction returned null", writeTx);
+ DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
+ assertNotNull("newWriteOnlyTransaction returned null", writeTx);
- writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
+ DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
- cohort.canCommit().get(5, TimeUnit.SECONDS);
+ cohort.canCommit().get(5, TimeUnit.SECONDS);
- cohort.abort().get(5, TimeUnit.SECONDS);
+ cohort.abort().get(5, TimeUnit.SECONDS);
- testWriteTransaction(dataStore, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ testWriteTransaction(dataStore, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ }
}
- }};
+ };
}
@Test
- public void testTransactionChainWithSingleShard() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("testTransactionChainWithSingleShard", "test-1")) {
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public void testTransactionChainWithSingleShard() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore("testTransactionChainWithSingleShard",
+ "test-1")) {
- // 1. Create a Tx chain and write-only Tx
+ // 1. Create a Tx chain and write-only Tx
- DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- assertNotNull("newWriteOnlyTransaction returned null", writeTx);
+ DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ assertNotNull("newWriteOnlyTransaction returned null", writeTx);
- // 2. Write some data
+ // 2. Write some data
- NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- writeTx.write(TestModel.TEST_PATH, testNode);
+ NormalizedNode<?, ?> testNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ writeTx.write(TestModel.TEST_PATH, testNode);
- // 3. Ready the Tx for commit
+ // 3. Ready the Tx for commit
- final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
+ final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
- // 4. Commit the Tx on another thread that first waits for the second read Tx.
+ // 4. Commit the Tx on another thread that first waits for
+ // the second read Tx.
- final CountDownLatch continueCommit1 = new CountDownLatch(1);
- final CountDownLatch commit1Done = new CountDownLatch(1);
- final AtomicReference<Exception> commit1Error = new AtomicReference<>();
- new Thread() {
- @Override
- public void run() {
- try {
- continueCommit1.await();
- doCommit(cohort1);
- } catch (Exception e) {
- commit1Error.set(e);
- } finally {
- commit1Done.countDown();
+ final CountDownLatch continueCommit1 = new CountDownLatch(1);
+ final CountDownLatch commit1Done = new CountDownLatch(1);
+ final AtomicReference<Exception> commit1Error = new AtomicReference<>();
+ new Thread() {
+ @Override
+ public void run() {
+ try {
+ continueCommit1.await();
+ doCommit(cohort1);
+ } catch (Exception e) {
+ commit1Error.set(e);
+ } finally {
+ commit1Done.countDown();
+ }
}
- }
- }.start();
+ }.start();
- // 5. Create a new read Tx from the chain to read and verify the data from the first
- // Tx is visible after being readied.
+ // 5. Create a new read Tx from the chain to read and verify
+ // the data from the first
+ // Tx is visible after being readied.
- DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
- Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", testNode, optional.get());
+ DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
+ Optional<NormalizedNode<?, ?>> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", testNode, optional.get());
- // 6. Create a new RW Tx from the chain, write more data, and ready it
+ // 6. Create a new RW Tx from the chain, write more data,
+ // and ready it
- DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
- MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
- rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
+ DOMStoreReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
+ MapNode outerNode = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
+ rwTx.write(TestModel.OUTER_LIST_PATH, outerNode);
- DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
+ final DOMStoreThreePhaseCommitCohort cohort2 = rwTx.ready();
- // 7. Create a new read Tx from the chain to read the data from the last RW Tx to
- // verify it is visible.
+ // 7. Create a new read Tx from the chain to read the data
+ // from the last RW Tx to
+ // verify it is visible.
- readTx = txChain.newReadWriteTransaction();
- optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", outerNode, optional.get());
+ readTx = txChain.newReadWriteTransaction();
+ optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", outerNode, optional.get());
- // 8. Wait for the 2 commits to complete and close the chain.
+ // 8. Wait for the 2 commits to complete and close the
+ // chain.
- continueCommit1.countDown();
- Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
+ continueCommit1.countDown();
+ Uninterruptibles.awaitUninterruptibly(commit1Done, 5, TimeUnit.SECONDS);
- if(commit1Error.get() != null) {
- throw commit1Error.get();
- }
+ if (commit1Error.get() != null) {
+ throw commit1Error.get();
+ }
- doCommit(cohort2);
+ doCommit(cohort2);
- txChain.close();
+ txChain.close();
- // 9. Create a new read Tx from the data store and verify committed data.
+ // 9. Create a new read Tx from the data store and verify
+ // committed data.
- readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", outerNode, optional.get());
+ readTx = dataStore.newReadOnlyTransaction();
+ optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", outerNode, optional.get());
+ }
}
- }};
+ };
}
@Test
- public void testTransactionChainWithMultipleShards() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore("testTransactionChainWithMultipleShards",
- "cars-1", "people-1")) {
+ public void testTransactionChainWithMultipleShards() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testTransactionChainWithMultipleShards", "cars-1", "people-1")) {
- DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- assertNotNull("newWriteOnlyTransaction returned null", writeTx);
+ DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ assertNotNull("newWriteOnlyTransaction returned null", writeTx);
- writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
- writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
+ writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
+ writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
- writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
- writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
+ writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
+ writeTx.write(PeopleModel.PERSON_LIST_PATH, PeopleModel.newPersonMapNode());
- DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
+ final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
- DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
+ DOMStoreReadWriteTransaction readWriteTx = txChain.newReadWriteTransaction();
- MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
- YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
- readWriteTx.write(carPath, car);
+ MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
+ YangInstanceIdentifier carPath = CarsModel.newCarPath("optima");
+ readWriteTx.write(carPath, car);
- MapEntryNode person = PeopleModel.newPersonEntry("jack");
- YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
- readWriteTx.merge(personPath, person);
+ MapEntryNode person = PeopleModel.newPersonEntry("jack");
+ YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
+ readWriteTx.merge(personPath, person);
- Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", car, optional.get());
+ Optional<NormalizedNode<?, ?>> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", car, optional.get());
- optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", person, optional.get());
- DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
+ DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
- writeTx = txChain.newWriteOnlyTransaction();
+ writeTx = txChain.newWriteOnlyTransaction();
- writeTx.delete(carPath);
+ writeTx.delete(carPath);
- DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
+ DOMStoreThreePhaseCommitCohort cohort3 = writeTx.ready();
- ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
- ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
+ ListenableFuture<Boolean> canCommit1 = cohort1.canCommit();
+ ListenableFuture<Boolean> canCommit2 = cohort2.canCommit();
- doCommit(canCommit1, cohort1);
- doCommit(canCommit2, cohort2);
- doCommit(cohort3);
+ doCommit(canCommit1, cohort1);
+ doCommit(canCommit2, cohort2);
+ doCommit(cohort3);
- txChain.close();
+ txChain.close();
- DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
+ DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", false, optional.isPresent());
+ optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", false, optional.isPresent());
- optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", person, optional.get());
+ }
}
- }};
+ };
}
@Test
- public void testCreateChainedTransactionsInQuickSuccession() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
+ public void testCreateChainedTransactionsInQuickSuccession() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
- ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
- ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
- LogicalDatastoreType.CONFIGURATION, dataStore).build(), MoreExecutors.directExecutor());
+ ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
+ ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
+ .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
+ MoreExecutors.directExecutor());
- TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
- DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
+ DOMTransactionChain txChain = broker.createTransactionChain(listener);
- List<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
+ List<CheckedFuture<Void, TransactionCommitFailedException>> futures = new ArrayList<>();
- DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
- writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
- futures.add(writeTx.submit());
+ DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, CarsModel.emptyContainer());
+ writeTx.put(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
+ futures.add(writeTx.submit());
- int nCars = 100;
- for(int i = 0; i < nCars; i++) {
- DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
+ int numCars = 100;
+ for (int i = 0; i < numCars; i++) {
+ DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
- rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
- CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
+ rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.newCarPath("car" + i),
+ CarsModel.newCarEntry("car" + i, BigInteger.valueOf(20000)));
- futures.add(rwTx.submit());
- }
+ futures.add(rwTx.submit());
+ }
- for(CheckedFuture<Void, TransactionCommitFailedException> f: futures) {
- f.checkedGet();
- }
+ for (CheckedFuture<Void, TransactionCommitFailedException> f : futures) {
+ f.checkedGet();
+ }
- Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction().read(
- LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("# cars", nCars, ((Collection<?>)optional.get().getValue()).size());
+ Optional<NormalizedNode<?, ?>> optional = txChain.newReadOnlyTransaction()
+ .read(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("# cars", numCars, ((Collection<?>) optional.get().getValue()).size());
- txChain.close();
+ txChain.close();
- broker.close();
+ broker.close();
+ }
}
- }};
+ };
}
@Test
- public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
+ public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
- DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
+ DOMStoreReadWriteTransaction rwTx1 = txChain.newReadWriteTransaction();
- rwTx1.ready();
+ rwTx1.ready();
- DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
+ DOMStoreReadWriteTransaction rwTx2 = txChain.newReadWriteTransaction();
- Optional<NormalizedNode<?, ?>> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", false, optional.isPresent());
+ Optional<NormalizedNode<?, ?>> optional = rwTx2.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", false, optional.isPresent());
- txChain.close();
+ txChain.close();
+ }
}
- }};
+ };
}
@Test
- public void testCreateChainedTransactionWhenPreviousNotReady() throws Throwable {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
+ public void testCreateChainedTransactionWhenPreviousNotReady() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
- final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- assertNotNull("newWriteOnlyTransaction returned null", writeTx);
+ DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ assertNotNull("newWriteOnlyTransaction returned null", writeTx);
- writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- // Try to create another Tx of each type - each should fail b/c the previous Tx wasn't
- // readied.
+ // Try to create another Tx of each type - each should fail
+ // b/c the previous Tx wasn't
+ // readied.
- assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
+ assertExceptionOnTxChainCreates(txChain, IllegalStateException.class);
+ }
}
- }};
+ };
}
@Test
- public void testCreateChainedTransactionAfterClose() throws Throwable {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testCreateChainedTransactionAfterClose", "test-1")) {
+ public void testCreateChainedTransactionAfterClose() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testCreateChainedTransactionAfterClose", "test-1")) {
- DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- txChain.close();
+ txChain.close();
- // Try to create another Tx of each type - should fail b/c the previous Tx was closed.
+ // Try to create another Tx of each type - should fail b/c
+ // the previous Tx was closed.
- assertExceptionOnTxChainCreates(txChain, TransactionChainClosedException.class);
+ assertExceptionOnTxChainCreates(txChain, TransactionChainClosedException.class);
+ }
}
- }};
+ };
}
@Test
- public void testChainWithReadOnlyTxAfterPreviousReady() throws Throwable {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
+ public void testChainWithReadOnlyTxAfterPreviousReady() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
- final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
- // Create a write tx and submit.
+ // Create a write tx and submit.
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
+ DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
- // Create read-only tx's and issue a read.
+ // Create read-only tx's and issue a read.
- CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture1 =
- txChain.newReadOnlyTransaction().read(TestModel.TEST_PATH);
+ CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture1 = txChain
+ .newReadOnlyTransaction().read(TestModel.TEST_PATH);
- CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture2 =
- txChain.newReadOnlyTransaction().read(TestModel.TEST_PATH);
+ CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture2 = txChain
+ .newReadOnlyTransaction().read(TestModel.TEST_PATH);
- // Create another write tx and issue the write.
+ // Create another write tx and issue the write.
- DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
- writeTx2.write(TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ DOMStoreWriteTransaction writeTx2 = txChain.newWriteOnlyTransaction();
+ writeTx2.write(TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
- // Ensure the reads succeed.
+ // Ensure the reads succeed.
- assertEquals("isPresent", true, readFuture1.checkedGet(5, TimeUnit.SECONDS).isPresent());
- assertEquals("isPresent", true, readFuture2.checkedGet(5, TimeUnit.SECONDS).isPresent());
+ assertEquals("isPresent", true, readFuture1.checkedGet(5, TimeUnit.SECONDS).isPresent());
+ assertEquals("isPresent", true, readFuture2.checkedGet(5, TimeUnit.SECONDS).isPresent());
- // Ensure the writes succeed.
+ // Ensure the writes succeed.
- DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
+ DOMStoreThreePhaseCommitCohort cohort2 = writeTx2.ready();
- doCommit(cohort1);
- doCommit(cohort2);
+ doCommit(cohort1);
+ doCommit(cohort2);
- assertEquals("isPresent", true, txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH).
- checkedGet(5, TimeUnit.SECONDS).isPresent());
+ assertEquals("isPresent", true, txChain.newReadOnlyTransaction().read(TestModel.OUTER_LIST_PATH)
+ .checkedGet(5, TimeUnit.SECONDS).isPresent());
+ }
}
- }};
+ };
}
@Test
- public void testChainedTransactionFailureWithSingleShard() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testChainedTransactionFailureWithSingleShard", "cars-1")) {
+ public void testChainedTransactionFailureWithSingleShard() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testChainedTransactionFailureWithSingleShard", "cars-1")) {
- ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
- ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
- LogicalDatastoreType.CONFIGURATION, dataStore).build(), MoreExecutors.directExecutor());
+ ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
+ ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
+ .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
+ MoreExecutors.directExecutor());
- TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
- DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
+ DOMTransactionChain txChain = broker.createTransactionChain(listener);
- DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
+ DOMDataReadWriteTransaction rwTx = txChain.newReadWriteTransaction();
- ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
+ ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
- rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
+ rwTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
- try {
- rwTx.submit().checkedGet(5, TimeUnit.SECONDS);
- fail("Expected TransactionCommitFailedException");
- } catch (TransactionCommitFailedException e) {
- // Expected
- }
+ try {
+ rwTx.submit().checkedGet(5, TimeUnit.SECONDS);
+ fail("Expected TransactionCommitFailedException");
+ } catch (TransactionCommitFailedException e) {
+ // Expected
+ }
- verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(rwTx), any(Throwable.class));
+ verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(rwTx),
+ any(Throwable.class));
- txChain.close();
- broker.close();
+ txChain.close();
+ broker.close();
+ }
}
- }};
+ };
}
@Test
- public void testChainedTransactionFailureWithMultipleShards() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore = setupDistributedDataStore(
- "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
+ public void testChainedTransactionFailureWithMultipleShards() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore(
+ "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
- ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
- ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
- LogicalDatastoreType.CONFIGURATION, dataStore).build(), MoreExecutors.directExecutor());
+ ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
+ ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
+ .put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
+ MoreExecutors.directExecutor());
- TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
- DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ TransactionChainListener listener = Mockito.mock(TransactionChainListener.class);
+ DOMTransactionChain txChain = broker.createTransactionChain(listener);
- DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
+ writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
+ PeopleModel.emptyContainer());
- ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
+ ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
- // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
- // done for put for performance reasons.
- writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
+ // Note that merge will validate the data and fail but put
+ // succeeds b/c deep validation is not
+ // done for put for performance reasons.
+ writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
- try {
- writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
- fail("Expected TransactionCommitFailedException");
- } catch (TransactionCommitFailedException e) {
- // Expected
- }
+ try {
+ writeTx.submit().checkedGet(5, TimeUnit.SECONDS);
+ fail("Expected TransactionCommitFailedException");
+ } catch (TransactionCommitFailedException e) {
+ // Expected
+ }
- verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
+ verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
+ any(Throwable.class));
- txChain.close();
- broker.close();
+ txChain.close();
+ broker.close();
+ }
}
- }};
+ };
}
@Test
- public void testChangeListenerRegistration() throws Exception{
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- try (DistributedDataStore dataStore =
- setupDistributedDataStore("testChangeListenerRegistration", "test-1")) {
+ public void testChangeListenerRegistration() throws Exception {
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ try (DistributedDataStore dataStore = setupDistributedDataStore("testChangeListenerRegistration",
+ "test-1")) {
- testWriteTransaction(dataStore, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ testWriteTransaction(dataStore, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- MockDataChangeListener listener = new MockDataChangeListener(1);
+ MockDataChangeListener listener = new MockDataChangeListener(1);
- ListenerRegistration<MockDataChangeListener>
- listenerReg = dataStore.registerChangeListener(TestModel.TEST_PATH, listener,
- DataChangeScope.SUBTREE);
+ ListenerRegistration<MockDataChangeListener> listenerReg = dataStore
+ .registerChangeListener(TestModel.TEST_PATH, listener, DataChangeScope.SUBTREE);
- assertNotNull("registerChangeListener returned null", listenerReg);
+ assertNotNull("registerChangeListener returned null", listenerReg);
- // Wait for the initial notification
+ // Wait for the initial notification
- listener.waitForChangeEvents(TestModel.TEST_PATH);
+ listener.waitForChangeEvents(TestModel.TEST_PATH);
- listener.reset(2);
+ listener.reset(2);
- // Write 2 updates.
+ // Write 2 updates.
- testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
- YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH).
- nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
- testWriteTransaction(dataStore, listPath,
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
+ YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build();
+ testWriteTransaction(dataStore, listPath,
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1));
- // Wait for the 2 updates.
+ // Wait for the 2 updates.
- listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
+ listener.waitForChangeEvents(TestModel.OUTER_LIST_PATH, listPath);
- listenerReg.close();
+ listenerReg.close();
- testWriteTransaction(dataStore, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH).
- nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
+ testWriteTransaction(dataStore,
+ YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build(),
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2));
- listener.expectNoMoreChanges("Received unexpected change after close");
+ listener.expectNoMoreChanges("Received unexpected change after close");
+ }
}
- }};
+ };
}
@Test
public void testRestoreFromDatastoreSnapshot() throws Exception {
- new IntegrationTestKit(getSystem(), datastoreContextBuilder) {{
- String name = "transactionIntegrationTest";
-
- ContainerNode carsNode = CarsModel.newCarsNode(CarsModel.newCarsMapNode(
- CarsModel.newCarEntry("optima", BigInteger.valueOf(20000L)),
- CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000L))));
-
- DataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
- dataTree.setSchemaContext(SchemaContextHelper.full());
- AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
- NormalizedNode<?, ?> root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
-
- Snapshot carsSnapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
- Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1");
-
- NormalizedNode<?, ?> peopleNode = PeopleModel.create();
- dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
- dataTree.setSchemaContext(SchemaContextHelper.full());
- AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
- root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
-
- Snapshot peopleSnapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
- Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1");
-
- restoreFromSnapshot = new DatastoreSnapshot(name, null, Arrays.asList(
- new DatastoreSnapshot.ShardSnapshot("cars",
- org.apache.commons.lang3.SerializationUtils.serialize(carsSnapshot)),
- new DatastoreSnapshot.ShardSnapshot("people",
- org.apache.commons.lang3.SerializationUtils.serialize(peopleSnapshot))));
-
- try (DistributedDataStore dataStore = setupDistributedDataStore(name, "module-shards-member1.conf",
- true, "cars", "people")) {
-
- DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
-
- Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", carsNode, optional.get());
-
- optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
- assertEquals("isPresent", true, optional.isPresent());
- assertEquals("Data node", peopleNode, optional.get());
+ new IntegrationTestKit(getSystem(), datastoreContextBuilder) {
+ {
+ final String name = "transactionIntegrationTest";
+
+ ContainerNode carsNode = CarsModel.newCarsNode(
+ CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", BigInteger.valueOf(20000L)),
+ CarsModel.newCarEntry("sportage", BigInteger.valueOf(30000L))));
+
+ DataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
+ dataTree.setSchemaContext(SchemaContextHelper.full());
+ AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
+ NormalizedNode<?, ?> root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
+
+ final Snapshot carsSnapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
+ Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1");
+
+ NormalizedNode<?, ?> peopleNode = PeopleModel.create();
+ dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
+ dataTree.setSchemaContext(SchemaContextHelper.full());
+ AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
+ root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.EMPTY);
+
+ Snapshot peopleSnapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
+ Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1");
+
+ restoreFromSnapshot = new DatastoreSnapshot(name, null,
+ Arrays.asList(
+ new DatastoreSnapshot.ShardSnapshot("cars",
+ org.apache.commons.lang3.SerializationUtils.serialize(carsSnapshot)),
+ new DatastoreSnapshot.ShardSnapshot("people",
+ org.apache.commons.lang3.SerializationUtils.serialize(peopleSnapshot))));
+
+ try (DistributedDataStore dataStore = setupDistributedDataStore(name, "module-shards-member1.conf",
+ true, "cars", "people")) {
+
+ DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
+
+ Optional<NormalizedNode<?, ?>> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", carsNode, optional.get());
+
+ optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
+ assertEquals("isPresent", true, optional.isPresent());
+ assertEquals("Data node", peopleNode, optional.get());
+ }
}
- }};
+ };
}
}
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.testkit.JavaTestKit;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
+import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
private static final String[] CARS_AND_PEOPLE = {"cars", "people"};
private static final String[] CARS = {"cars"};
- private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558");
- private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2559");
+ private static final Address MEMBER_1_ADDRESS = AddressFromURIString.parse(
+ "akka.tcp://cluster-test@127.0.0.1:2558");
+ private static final Address MEMBER_2_ADDRESS = AddressFromURIString.parse(
+ "akka.tcp://cluster-test@127.0.0.1:2559");
private static final String MODULE_SHARDS_CARS_ONLY_1_2 = "module-shards-cars-member-1-and-2.conf";
private static final String MODULE_SHARDS_CARS_PEOPLE_1_2 = "module-shards-member1-and-2.conf";
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
private final DatastoreContext.Builder followerDatastoreContextBuilder =
- DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5).
- customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
+ DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
+ .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
private final TransactionIdentifier tx1 = nextTransactionId();
private final TransactionIdentifier tx2 = nextTransactionId();
leaderDistributedDataStore = leaderTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
followerTestKit = new IntegrationTestKit(followerSystem, followerDatastoreContextBuilder);
- followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false, shards);
+ followerDistributedDataStore = followerTestKit.setupDistributedDataStore(type, moduleShardsConfig, false,
+ shards);
leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorContext(), shards);
}
assertEquals("isPresent", true, optional.isPresent());
CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME);
- for(NormalizedNode<?, ?> entry: entries) {
+ for (NormalizedNode<?, ?> entry: entries) {
listBuilder.withChild((MapEntryNode) entry);
}
assertEquals("Car list node", listBuilder.build(), optional.get());
}
- private static void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path, NormalizedNode<?, ?> expNode)
- throws Exception {
+ private static void verifyNode(DOMStoreReadTransaction readTx, YangInstanceIdentifier path,
+ NormalizedNode<?, ?> expNode) throws Exception {
Optional<NormalizedNode<?, ?>> optional = readTx.read(path).get(5, TimeUnit.SECONDS);
assertEquals("isPresent", true, optional.isPresent());
assertEquals("Data node", expNode, optional.get());
ActorSystem newSystem = ActorSystem.create("reinstated-member2", ConfigFactory.load().getConfig("Member2"));
- try (DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder).
- setupDistributedDataStore(testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
+ try (DistributedDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder)
+ .setupDistributedDataStore(testName, "module-shards-member2", true, CARS_AND_PEOPLE)) {
verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
}
}
@Test
- public void testTransactionChainWithMultipleShards() throws Exception{
+ public void testTransactionChainWithMultipleShards() throws Exception {
initDatastoresWithCarsAndPeople("testTransactionChainWithMultipleShards");
DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
DOMDataWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
+ new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
+ new YangInstanceIdentifier.NodeIdentifier(CarsModel.BASE_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
// Note that merge will validate the data and fail but put succeeds b/c deep validation is not
// done for put for performance reasons.
// Switch the leader to the follower
- sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
- shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
+ sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
+ .shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
JavaTestKit.shutdownActorSystem(leaderSystem, null, true);
Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
leaderSystem = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1"));
Cluster.get(leaderSystem).join(MEMBER_2_ADDRESS);
- DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder().
- shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
+ DatastoreContext.Builder newMember1Builder = DatastoreContext.newBuilder()
+ .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder);
try (DistributedDataStore ds =
carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
Object resp = followerTestKit.expectMsgClass(Object.class);
- if(resp instanceof akka.actor.Status.Failure) {
+ if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
}
carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
resp = followerTestKit.expectMsgClass(Object.class);
- if(resp instanceof akka.actor.Status.Failure) {
+ if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
}
carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
Object resp = followerTestKit.expectMsgClass(Object.class);
- if(resp instanceof akka.actor.Status.Failure) {
+ if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
}
carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
resp = followerTestKit.expectMsgClass(Object.class);
- if(resp instanceof akka.actor.Status.Failure) {
+ if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
}
// Wait for the commit to be replicated to the follower.
MemberNode.verifyRaftState(followerDistributedDataStore, "cars",
- raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
+ raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
MemberNode.verifyRaftState(followerDistributedDataStore, "people",
- raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
+ raftState -> assertEquals("getLastApplied", 0, raftState.getLastApplied()));
// Prepare, ready and canCommit a WO tx that writes to 2 shards. This will become the current tx in
// the leader shard.
carIndex++;
NormalizedNode<?, ?> people = PeopleModel.newPersonMapNode();
writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
- DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
+ final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
// Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
// tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
// sent on ready.
DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
- for(int i = 1; i <= 5; i++, carIndex++) {
+ for (int i = 1; i <= 5; i++, carIndex++) {
cars.add(CarsModel.newCarEntry("car" + carIndex, BigInteger.valueOf(carIndex)));
writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
}
readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
- stats -> assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount()));
+ stats -> assertEquals("getReadWriteTransactionCount", 1, stats.getReadWriteTransactionCount()));
// Disable elections on the leader so it switches to follower.
- sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
- customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
- shardElectionTimeoutFactor(10));
+ sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
+ .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
+ .shardElectionTimeoutFactor(10));
Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
leaderTestKit.waitUntilNoLeader(leaderDistributedDataStore.getActorContext(), "cars");
// Submit all tx's - the messages should get queued for retry.
ListenableFuture<Boolean> writeTx2CanCommit = writeTx2Cohort.canCommit();
- DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
- DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
- DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
+ final DOMStoreThreePhaseCommitCohort writeTx3Cohort = writeTx3.ready();
+ final DOMStoreThreePhaseCommitCohort writeTx4Cohort = writeTx4.ready();
+ final DOMStoreThreePhaseCommitCohort rwTxCohort = readWriteTx.ready();
// Enable elections on the other follower so it becomes the leader, at which point the
// tx's should get forwarded from the previous leader to the new leader to complete the commits.
- sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
- customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
+ sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
+ .customRaftPolicyImplementation(null).shardElectionTimeoutFactor(1));
followerTestKit.doCommit(writeTx1CanCommit, writeTx1Cohort);
followerTestKit.doCommit(writeTx2CanCommit, writeTx2Cohort);
writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
- DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
+ final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
- stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
+ stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
writeTx.write(CarsModel.newCarPath("optima"), car);
- DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
+ final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
- stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
+ stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
// Gracefully stop the leader via a Shutdown message.
- sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
- shardElectionTimeoutFactor(100));
+ sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
+ .shardElectionTimeoutFactor(100));
FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
}
@Test
- public void testTransactionWithIsolatedLeader() throws Throwable {
+ public void testTransactionWithIsolatedLeader() throws Exception {
// Set the isolated leader check interval high so we can control the switch to IsolatedLeader.
leaderDatastoreContextBuilder.shardIsolatedLeaderCheckIntervalInMillis(10000000);
String testName = "testTransactionWithIsolatedLeader";
followerTestKit.expectTerminated(followerDistributedDataStore.getActorContext().getShardManager());
// Submit the preIsolatedLeaderWriteTx so it's pending
- DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
+ final DOMStoreThreePhaseCommitCohort preIsolatedLeaderTxCohort = preIsolatedLeaderWriteTx.ready();
// Change the isolated leader check interval low so it changes to IsolatedLeader.
- sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
- shardIsolatedLeaderCheckIntervalInMillis(200));
+ sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
+ .shardIsolatedLeaderCheckIntervalInMillis(200));
MemberNode.verifyRaftState(leaderDistributedDataStore, "cars",
- raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
+ raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
try {
leaderTestKit.doCommit(noShardLeaderWriteTx.ready());
assertEquals("getCause", NoShardLeaderException.class, e.getCause().getClass());
}
- sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder.
- shardElectionTimeoutFactor(100));
+ sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
+ .shardElectionTimeoutFactor(100));
DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
leaderTestKit.doCommit(successTxCohort);
}
- @Test(expected=AskTimeoutException.class)
- public void testTransactionWithShardLeaderNotResponding() throws Throwable {
+ @Test(expected = AskTimeoutException.class)
+ public void testTransactionWithShardLeaderNotResponding() throws Exception {
initDatastoresWithCars("testTransactionWithShardLeaderNotResponding");
// Do an initial read to get the primary shard info cached.
assertTrue("Expected ShardLeaderNotRespondingException cause. Actual: " + e.getCause(),
e.getCause() instanceof ShardLeaderNotRespondingException);
assertNotNull("Expected a nested cause", e.getCause().getCause());
- throw e.getCause().getCause();
+ Throwables.propagateIfInstanceOf(e.getCause().getCause(), Exception.class);
+ Throwables.propagate(e.getCause().getCause());
}
}
- @Test(expected=NoShardLeaderException.class)
- public void testTransactionWithCreateTxFailureDueToNoLeader() throws Throwable {
+ @Test(expected = NoShardLeaderException.class)
+ public void testTransactionWithCreateTxFailureDueToNoLeader() throws Exception {
initDatastoresWithCars("testTransactionWithCreateTxFailureDueToNoLeader");
// Do an initial read to get the primary shard info cached.
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
- sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
- operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
+ sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
+ .operationTimeoutInMillis(10).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
try {
followerTestKit.doCommit(rwTx.ready());
} catch (ExecutionException e) {
- throw e.getCause();
+ Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
+ Throwables.propagate(e.getCause());
}
}
String testName = "testTransactionRetryWithInitialAskTimeoutExOnCreateTx";
initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS);
- DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder().
- shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
+ DatastoreContext.Builder follower2DatastoreContextBuilder = DatastoreContext.newBuilder()
+ .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System, follower2DatastoreContextBuilder);
try (DistributedDataStore ds =
Cluster.get(followerSystem).leave(MEMBER_1_ADDRESS);
- sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder.
- operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
+ sendDatastoreContextUpdate(followerDistributedDataStore, followerDatastoreContextBuilder
+ .operationTimeoutInMillis(500).shardElectionTimeoutFactor(1).customRaftPolicyImplementation(null));
DOMStoreReadWriteTransaction rwTx = followerDistributedDataStore.newReadWriteTransaction();
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import akka.util.Timeout;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.Executors;
}
@Test
- public void testRateLimitingUsedInReadWriteTxCreation(){
+ public void testRateLimitingUsedInReadWriteTxCreation() {
try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorContext, UNKNOWN_ID)) {
distributedDataStore.newReadWriteTransaction();
}
@Test
- public void testRateLimitingUsedInWriteOnlyTxCreation(){
+ public void testRateLimitingUsedInWriteOnlyTxCreation() {
try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorContext, UNKNOWN_ID)) {
distributedDataStore.newWriteOnlyTransaction();
}
@Test
- public void testRateLimitingNotUsedInReadOnlyTxCreation(){
+ public void testRateLimitingNotUsedInReadOnlyTxCreation() {
try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorContext, UNKNOWN_ID)) {
distributedDataStore.newReadOnlyTransaction();
}
@Test
- public void testWaitTillReadyBlocking(){
+ public void testWaitTillReadyBlocking() {
doReturn(datastoreContext).when(actorContext).getDatastoreContext();
doReturn(shardElectionTimeout).when(datastoreContext).getShardLeaderElectionTimeout();
doReturn(FiniteDuration.apply(50, TimeUnit.MILLISECONDS)).when(shardElectionTimeout).duration();
long end = System.currentTimeMillis();
- assertTrue("Expected to be blocked for 50 millis", (end - start) >= 50);
+ assertTrue("Expected to be blocked for 50 millis", end - start >= 50);
}
}
@Test
- public void testWaitTillReadyCountDown(){
+ public void testWaitTillReadyCountDown() {
try (final DistributedDataStore distributedDataStore = new DistributedDataStore(actorContext, UNKNOWN_ID)) {
doReturn(datastoreContext).when(actorContext).getDatastoreContext();
doReturn(shardElectionTimeout).when(datastoreContext).getShardLeaderElectionTimeout();
long end = System.currentTimeMillis();
- assertTrue("Expected to be released in 500 millis", (end - start) < 5000);
+ assertTrue("Expected to be released in 500 millis", end - start < 5000);
}
}
-
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
+
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.cluster.Cluster;
public DistributedDataStore setupDistributedDataStore(String typeName, String moduleShardsConfig,
boolean waitUntilLeader, SchemaContext schemaContext, String... shardNames) {
- ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
- Configuration config = new ConfigurationImpl(moduleShardsConfig, "modules.conf");
+ final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
+ final Configuration config = new ConfigurationImpl(moduleShardsConfig, "modules.conf");
datastoreContextBuilder.dataStoreName(typeName);
dataStore.onGlobalContextUpdated(schemaContext);
- if(waitUntilLeader) {
+ if (waitUntilLeader) {
waitUntilLeader(dataStore.getActorContext(), shardNames);
}
}
public void waitUntilLeader(ActorContext actorContext, String... shardNames) {
- for(String shardName: shardNames) {
+ for (String shardName: shardNames) {
ActorRef shard = findLocalShard(actorContext, shardName);
assertNotNull("Shard was not created for " + shardName, shard);
}
public void waitUntilNoLeader(ActorContext actorContext, String... shardNames) {
- for(String shardName: shardNames) {
+ for (String shardName: shardNames) {
ActorRef shard = findLocalShard(actorContext, shardName);
assertNotNull("No local shard found for " + shardName, shard);
public void waitForMembersUp(String... otherMembers) {
Set<String> otherMembersSet = Sets.newHashSet(otherMembers);
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 10) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
CurrentClusterState state = Cluster.get(getSystem()).state();
- for(Member m: state.getMembers()) {
- if(m.status() == MemberStatus.up() && otherMembersSet.remove(m.getRoles().iterator().next()) &&
- otherMembersSet.isEmpty()) {
+ for (Member m: state.getMembers()) {
+ if (m.status() == MemberStatus.up() && otherMembersSet.remove(m.getRoles().iterator().next())
+ && otherMembersSet.isEmpty()) {
return;
}
}
public static ActorRef findLocalShard(ActorContext actorContext, String shardName) {
ActorRef shard = null;
- for(int i = 0; i < 20 * 5 && shard == null; i++) {
+ for (int i = 0; i < 20 * 5 && shard == null; i++) {
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
Optional<ActorRef> shardReply = actorContext.findLocalShard(shardName);
- if(shardReply.isPresent()) {
+ if (shardReply.isPresent()) {
shard = shardReply.get();
}
}
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
- ShardStats shardStats = (ShardStats)actorContext.
- executeOperation(shardActor, Shard.GET_SHARD_MBEAN_MESSAGE);
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ ShardStats shardStats = (ShardStats)actorContext
+ .executeOperation(shardActor, Shard.GET_SHARD_MBEAN_MESSAGE);
try {
verifier.verify(shardStats);
cohort.commit().get(5, TimeUnit.SECONDS);
}
- void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort) throws Exception {
+ void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
+ throws Exception {
Boolean canCommit = canCommitFuture.get(7, TimeUnit.SECONDS);
assertEquals("canCommit", true, canCommit);
cohort.preCommit().get(5, TimeUnit.SECONDS);
cohort.commit().get(5, TimeUnit.SECONDS);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
void assertExceptionOnCall(Callable<Void> callable, Class<? extends Exception> expType)
throws Exception {
try {
callable.call();
fail("Expected " + expType.getSimpleName());
- } catch(Exception e) {
+ } catch (Exception e) {
assertEquals("Exception type", expType, e.getClass());
}
}
void assertExceptionOnTxChainCreates(final DOMStoreTransactionChain txChain,
Class<? extends Exception> expType) throws Exception {
- assertExceptionOnCall(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- txChain.newWriteOnlyTransaction();
- return null;
- }
+ assertExceptionOnCall(() -> {
+ txChain.newWriteOnlyTransaction();
+ return null;
}, expType);
- assertExceptionOnCall(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- txChain.newReadWriteTransaction();
- return null;
- }
+ assertExceptionOnCall(() -> {
+ txChain.newReadWriteTransaction();
+ return null;
}, expType);
- assertExceptionOnCall(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- txChain.newReadOnlyTransaction();
- return null;
- }
+ assertExceptionOnCall(() -> {
+ txChain.newReadOnlyTransaction();
+ return null;
}, expType);
}
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorSelection;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.Futures;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- localTransactionContext = new LocalTransactionContext(readWriteTransaction, limiter.getIdentifier(), mockReadySupport) {
+ localTransactionContext = new LocalTransactionContext(readWriteTransaction, limiter.getIdentifier(),
+ mockReadySupport) {
@Override
protected DOMStoreWriteTransaction getWriteDelegate() {
return readWriteTransaction;
public void testRead() {
YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.EMPTY;
NormalizedNode<?, ?> normalizedNode = mock(NormalizedNode.class);
- doReturn(Futures.immediateCheckedFuture(Optional.of(normalizedNode))).when(readWriteTransaction).read(yangInstanceIdentifier);
+ doReturn(Futures.immediateCheckedFuture(Optional.of(normalizedNode))).when(readWriteTransaction)
+ .read(yangInstanceIdentifier);
localTransactionContext.executeRead(new ReadData(yangInstanceIdentifier, DataStoreVersions.CURRENT_VERSION),
SettableFuture.<Optional<NormalizedNode<?,?>>>create());
verify(readWriteTransaction).read(yangInstanceIdentifier);
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Address;
public void waitForMemberDown(String member) {
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 10) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
CurrentClusterState state = Cluster.get(kit.getSystem()).state();
- for(Member m: state.getUnreachable()) {
- if(member.equals(m.getRoles().iterator().next())) {
+ for (Member m : state.getUnreachable()) {
+ if (member.equals(m.getRoles().iterator().next())) {
return;
}
}
- for(Member m: state.getMembers()) {
- if(m.status() != MemberStatus.up() && member.equals(m.getRoles().iterator().next())) {
+ for (Member m : state.getMembers()) {
+ if (m.status() != MemberStatus.up() && member.equals(m.getRoles().iterator().next())) {
return;
}
}
}
public void cleanup() {
- if(!cleanedUp) {
+ if (!cleanedUp) {
cleanedUp = true;
if (configDataStore != null) {
configDataStore.close();
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
- OnDemandRaftState raftState = (OnDemandRaftState)actorContext.
- executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ OnDemandRaftState raftState = (OnDemandRaftState)actorContext
+ .executeOperation(shardActor, GetOnDemandRaftState.INSTANCE);
try {
verifier.verify(raftState);
public static void verifyRaftPeersPresent(DistributedDataStore datastore, final String shardName,
String... peerMemberNames) throws Exception {
final Set<String> peerIds = Sets.newHashSet();
- for(String p: peerMemberNames) {
+ for (String p: peerMemberNames) {
peerIds.add(ShardIdentifier.create(shardName, MemberName.forName(p),
datastore.getActorContext().getDataStoreName()).toString());
}
public static void verifyNoShardPresent(DistributedDataStore datastore, String shardName) {
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
Optional<ActorRef> shardReply = datastore.getActorContext().findLocalShard(shardName);
- if(!shardReply.isPresent()) {
+ if (!shardReply.isPresent()) {
return;
}
private String testName;
private SchemaContext schemaContext;
private boolean createOperDatastore = true;
- private DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder().
- shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(30);
+ private DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder()
+ .shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(30);
Builder(List<MemberNode> members) {
this.members = members;
*
* @return this Builder
*/
- public Builder moduleShardsConfig(String moduleShardsConfig) {
- this.moduleShardsConfig = moduleShardsConfig;
+ public Builder moduleShardsConfig(String newModuleShardsConfig) {
+ this.moduleShardsConfig = newModuleShardsConfig;
return this;
}
*
* @return this Builder
*/
- public Builder akkaConfig(String akkaConfig) {
- this.akkaConfig = akkaConfig;
+ public Builder akkaConfig(String newAkkaConfig) {
+ this.akkaConfig = newAkkaConfig;
return this;
}
*
* @return this Builder
*/
- public Builder testName(String testName) {
- this.testName = testName;
+ public Builder testName(String newTestName) {
+ this.testName = newTestName;
return this;
}
*
* @return this Builder
*/
- public Builder schemaContext(SchemaContext schemaContext) {
- this.schemaContext = schemaContext;
+ public Builder schemaContext(SchemaContext newSchemaContext) {
+ this.schemaContext = newSchemaContext;
return this;
}
Preconditions.checkNotNull(akkaConfig, "akkaConfig must be specified");
Preconditions.checkNotNull(testName, "testName must be specified");
- if(schemaContext == null) {
+ if (schemaContext == null) {
schemaContext = SchemaContextHelper.full();
}
node.configDataStore = node.kit.setupDistributedDataStore("config_" + testName, moduleShardsConfig,
true, schemaContext, waitForshardLeader);
- if(createOperDatastore) {
+ if (createOperDatastore) {
node.kit.getDatastoreContextBuilder().shardManagerPersistenceId("shard-manager-oper-" + memberName);
node.operDataStore = node.kit.setupDistributedDataStore("oper_" + testName, moduleShardsConfig,
true, schemaContext, waitForshardLeader);
public interface RaftStateVerifier {
void verify(OnDemandRaftState raftState);
}
-}
\ No newline at end of file
+}
package org.opendaylight.controller.cluster.datastore;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
package org.opendaylight.controller.cluster.datastore;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.testkit.JavaTestKit;
import org.opendaylight.controller.cluster.raft.RaftState;
import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
-public class RoleChangeNotifierTest extends AbstractActorTest {
+public class RoleChangeNotifierTest extends AbstractActorTest {
@Test
public void testHandleRegisterRoleChangeListener() throws Exception {
- new JavaTestKit(getSystem()) {{
- String memberId = "testHandleRegisterRoleChangeListener";
- ActorRef listenerActor = getSystem().actorOf(Props.create(MessageCollectorActor.class));
-
- TestActorRef<RoleChangeNotifier> notifierTestActorRef = TestActorRef.create(
- getSystem(), RoleChangeNotifier.getProps(memberId), memberId);
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "testHandleRegisterRoleChangeListener";
+ ActorRef listenerActor = getSystem().actorOf(Props.create(MessageCollectorActor.class));
- notifierTestActorRef.tell(new RegisterRoleChangeListener(), listenerActor);
+ TestActorRef<RoleChangeNotifier> notifierTestActorRef = TestActorRef.create(getSystem(),
+ RoleChangeNotifier.getProps(memberId), memberId);
- RegisterRoleChangeListenerReply reply =
- MessageCollectorActor.getFirstMatching(listenerActor, RegisterRoleChangeListenerReply.class);
- assertNotNull(reply);
+ notifierTestActorRef.tell(new RegisterRoleChangeListener(), listenerActor);
- RoleChangeNotification notification =
- MessageCollectorActor.getFirstMatching(listenerActor, RoleChangeNotification.class);
- assertNull(notification);
- }};
+ RegisterRoleChangeListenerReply reply = MessageCollectorActor.getFirstMatching(listenerActor,
+ RegisterRoleChangeListenerReply.class);
+ assertNotNull(reply);
+ RoleChangeNotification notification = MessageCollectorActor.getFirstMatching(listenerActor,
+ RoleChangeNotification.class);
+ assertNull(notification);
+ }
+ };
}
@Test
public void testHandleRaftRoleChanged() throws Exception {
- new JavaTestKit(getSystem()) {{
- String memberId = "testHandleRegisterRoleChangeListenerWithNotificationSet";
- ActorRef listenerActor = getSystem().actorOf(Props.create(MessageCollectorActor.class));
- ActorRef shardActor = getTestActor();
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "testHandleRegisterRoleChangeListenerWithNotificationSet";
+ ActorRef listenerActor = getSystem().actorOf(Props.create(MessageCollectorActor.class));
+ ActorRef shardActor = getTestActor();
- TestActorRef<RoleChangeNotifier> notifierTestActorRef = TestActorRef.create(
- getSystem(), RoleChangeNotifier.getProps(memberId), memberId);
+ TestActorRef<RoleChangeNotifier> notifierTestActorRef = TestActorRef.create(getSystem(),
+ RoleChangeNotifier.getProps(memberId), memberId);
- notifierTestActorRef.tell(new RoleChanged(memberId, RaftState.Candidate.name(), RaftState.Leader.name()), shardActor);
+ notifierTestActorRef.tell(
+ new RoleChanged(memberId, RaftState.Candidate.name(), RaftState.Leader.name()), shardActor);
- // no notification should be sent as listener has not yet registered
- assertNull(MessageCollectorActor.getFirstMatching(listenerActor, RoleChangeNotification.class));
+ // no notification should be sent as listener has not yet
+ // registered
+ assertNull(MessageCollectorActor.getFirstMatching(listenerActor, RoleChangeNotification.class));
- // listener registers after role has been changed, ensure we sent the latest role change after a reply
- notifierTestActorRef.tell(new RegisterRoleChangeListener(), listenerActor);
+ // listener registers after role has been changed, ensure we
+ // sent the latest role change after a reply
+ notifierTestActorRef.tell(new RegisterRoleChangeListener(), listenerActor);
- RegisterRoleChangeListenerReply reply =
- MessageCollectorActor.getFirstMatching(listenerActor, RegisterRoleChangeListenerReply.class);
- assertNotNull(reply);
+ RegisterRoleChangeListenerReply reply = MessageCollectorActor.getFirstMatching(listenerActor,
+ RegisterRoleChangeListenerReply.class);
+ assertNotNull(reply);
- RoleChangeNotification notification =
- MessageCollectorActor.getFirstMatching(listenerActor, RoleChangeNotification.class);
- assertNotNull(notification);
- assertEquals(RaftState.Candidate.name(), notification.getOldRole());
- assertEquals(RaftState.Leader.name(), notification.getNewRole());
+ RoleChangeNotification notification = MessageCollectorActor.getFirstMatching(listenerActor,
+ RoleChangeNotification.class);
+ assertNotNull(notification);
+ assertEquals(RaftState.Candidate.name(), notification.getOldRole());
+ assertEquals(RaftState.Leader.name(), notification.getNewRole());
- }};
+ }
+ };
}
@Test
public void testHandleLeaderStateChanged() throws Exception {
- new JavaTestKit(getSystem()) {{
- String actorId = "testHandleLeaderStateChanged";
- TestActorRef<RoleChangeNotifier> notifierTestActorRef = TestActorRef.create(
- getSystem(), RoleChangeNotifier.getProps(actorId), actorId);
+ new JavaTestKit(getSystem()) {
+ {
+ String actorId = "testHandleLeaderStateChanged";
+ TestActorRef<RoleChangeNotifier> notifierTestActorRef = TestActorRef.create(getSystem(),
+ RoleChangeNotifier.getProps(actorId), actorId);
- notifierTestActorRef.tell(new LeaderStateChanged("member1", "leader1", (short)5), ActorRef.noSender());
+ notifierTestActorRef.tell(new LeaderStateChanged("member1", "leader1", (short) 5), ActorRef.noSender());
- // listener registers after the sate has been changed, ensure we sent the latest state change after a reply
- notifierTestActorRef.tell(new RegisterRoleChangeListener(), getRef());
+ // listener registers after the sate has been changed, ensure we
+ // sent the latest state change after a reply
+ notifierTestActorRef.tell(new RegisterRoleChangeListener(), getRef());
- expectMsgClass(RegisterRoleChangeListenerReply.class);
+ expectMsgClass(RegisterRoleChangeListenerReply.class);
- LeaderStateChanged leaderStateChanged = expectMsgClass(LeaderStateChanged.class);
- assertEquals("getMemberId", "member1", leaderStateChanged.getMemberId());
- assertEquals("getLeaderId", "leader1", leaderStateChanged.getLeaderId());
- assertEquals("getLeaderPayloadVersion", 5, leaderStateChanged.getLeaderPayloadVersion());
+ LeaderStateChanged leaderStateChanged = expectMsgClass(LeaderStateChanged.class);
+ assertEquals("getMemberId", "member1", leaderStateChanged.getMemberId());
+ assertEquals("getLeaderId", "leader1", leaderStateChanged.getLeaderId());
+ assertEquals("getLeaderPayloadVersion", 5, leaderStateChanged.getLeaderPayloadVersion());
- notifierTestActorRef.tell(new LeaderStateChanged("member1", "leader2", (short)6), ActorRef.noSender());
+ notifierTestActorRef.tell(new LeaderStateChanged("member1", "leader2", (short) 6), ActorRef.noSender());
- leaderStateChanged = expectMsgClass(LeaderStateChanged.class);
- assertEquals("getMemberId", "member1", leaderStateChanged.getMemberId());
- assertEquals("getLeaderId", "leader2", leaderStateChanged.getLeaderId());
- assertEquals("getLeaderPayloadVersion", 6, leaderStateChanged.getLeaderPayloadVersion());
- }};
+ leaderStateChanged = expectMsgClass(LeaderStateChanged.class);
+ assertEquals("getMemberId", "member1", leaderStateChanged.getMemberId());
+ assertEquals("getLeaderId", "leader2", leaderStateChanged.getLeaderId());
+ assertEquals("getLeaderPayloadVersion", 6, leaderStateChanged.getLeaderPayloadVersion());
+ }
+ };
}
}
-
-
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+
import com.google.common.primitives.UnsignedLong;
import com.google.common.util.concurrent.FutureCallback;
import org.mockito.InOrder;
}
@SuppressWarnings("unchecked")
- public static ShardDataTreeCohort successfulPreCommit(final ShardDataTreeCohort mock, final DataTreeCandidate candidate) {
+ public static ShardDataTreeCohort successfulPreCommit(final ShardDataTreeCohort mock,
+ final DataTreeCandidate candidate) {
doAnswer(invocation -> {
return invokeSuccess(invocation, candidate);
}).when(mock).preCommit(any(FutureCallback.class));
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
+import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.immediateCanCommit;
import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.immediateCommit;
import static org.opendaylight.controller.cluster.datastore.ShardDataTreeMocking.immediatePreCommit;
+
import com.google.common.base.Optional;
import com.google.common.base.Ticker;
import com.google.common.collect.Maps;
}
- private void modify(final ShardDataTree shardDataTree, final boolean merge, final boolean expectedCarsPresent, final boolean expectedPeoplePresent) throws ExecutionException, InterruptedException {
+ private void modify(final ShardDataTree shardDataTree, final boolean merge, final boolean expectedCarsPresent,
+ final boolean expectedPeoplePresent) throws ExecutionException, InterruptedException {
assertEquals(fullSchema, shardDataTree.getSchemaContext());
- final ReadWriteShardDataTreeTransaction transaction = shardDataTree.newReadWriteTransaction(nextTransactionId());
+ final ReadWriteShardDataTreeTransaction transaction =
+ shardDataTree.newReadWriteTransaction(nextTransactionId());
final DataTreeModification snapshot = transaction.getSnapshot();
assertNotNull(snapshot);
- if(merge){
+ if (merge) {
snapshot.merge(CarsModel.BASE_PATH, CarsModel.create());
snapshot.merge(PeopleModel.BASE_PATH, PeopleModel.create());
} else {
immediatePreCommit(cohort);
immediateCommit(cohort);
- final ReadOnlyShardDataTreeTransaction readOnlyShardDataTreeTransaction = shardDataTree.newReadOnlyTransaction(nextTransactionId());
+ final ReadOnlyShardDataTreeTransaction readOnlyShardDataTreeTransaction =
+ shardDataTree.newReadOnlyTransaction(nextTransactionId());
final DataTreeSnapshot snapshot1 = readOnlyShardDataTreeTransaction.getSnapshot();
assertEquals("getModificationType", expType, dtc.getRootNode().getModificationType());
});
- if(!expChanges.isEmpty()) {
+ if (!expChanges.isEmpty()) {
fail("Missing change notifications: " + expChanges);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
- private static void verifyOnDataTreeChanged(DOMDataTreeChangeListener listener, Consumer<DataTreeCandidate> callback) {
+ private static void verifyOnDataTreeChanged(DOMDataTreeChangeListener listener,
+ Consumer<DataTreeCandidate> callback) {
ArgumentCaptor<Collection> changes = ArgumentCaptor.forClass(Collection.class);
verify(listener, atLeastOnce()).onDataTreeChanged(changes.capture());
- for(Collection list: changes.getAllValues()) {
- for(Object dtc: list) {
+ for (Collection list : changes.getAllValues()) {
+ for (Object dtc : list) {
callback.accept((DataTreeCandidate)dtc);
}
}
}
private static NormalizedNode<?, ?> getCars(final ShardDataTree shardDataTree) {
- final ReadOnlyShardDataTreeTransaction readOnlyShardDataTreeTransaction = shardDataTree.newReadOnlyTransaction(nextTransactionId());
+ final ReadOnlyShardDataTreeTransaction readOnlyShardDataTreeTransaction =
+ shardDataTree.newReadOnlyTransaction(nextTransactionId());
final DataTreeSnapshot snapshot1 = readOnlyShardDataTreeTransaction.getSnapshot();
final Optional<NormalizedNode<?, ?>> optional = snapshot1.readNode(CarsModel.BASE_PATH);
return optional.get();
}
- private static DataTreeCandidateTip addCar(final ShardDataTree shardDataTree) throws ExecutionException, InterruptedException {
+ private static DataTreeCandidateTip addCar(final ShardDataTree shardDataTree)
+ throws ExecutionException, InterruptedException {
return addCar(shardDataTree, "altima");
}
- private static DataTreeCandidateTip addCar(final ShardDataTree shardDataTree, String name) throws ExecutionException, InterruptedException {
+ private static DataTreeCandidateTip addCar(final ShardDataTree shardDataTree, String name)
+ throws ExecutionException, InterruptedException {
return doTransaction(shardDataTree, snapshot -> {
- snapshot.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
- snapshot.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
- snapshot.write(CarsModel.newCarPath(name), CarsModel.newCarEntry(name, new BigInteger("100")));
- });
+ snapshot.merge(CarsModel.BASE_PATH, CarsModel.emptyContainer());
+ snapshot.merge(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
+ snapshot.write(CarsModel.newCarPath(name), CarsModel.newCarEntry(name, new BigInteger("100")));
+ });
}
- private static DataTreeCandidateTip removeCar(final ShardDataTree shardDataTree) throws ExecutionException, InterruptedException {
+ private static DataTreeCandidateTip removeCar(final ShardDataTree shardDataTree)
+ throws ExecutionException, InterruptedException {
return doTransaction(shardDataTree, snapshot -> snapshot.delete(CarsModel.newCarPath("altima")));
}
void execute(DataTreeModification snapshot);
}
- private static DataTreeCandidateTip doTransaction(final ShardDataTree shardDataTree, final DataTreeOperation operation)
- throws ExecutionException, InterruptedException {
- final ReadWriteShardDataTreeTransaction transaction = shardDataTree.newReadWriteTransaction(nextTransactionId());
+ private static DataTreeCandidateTip doTransaction(final ShardDataTree shardDataTree,
+ final DataTreeOperation operation) throws ExecutionException, InterruptedException {
+ final ReadWriteShardDataTreeTransaction transaction =
+ shardDataTree.newReadWriteTransaction(nextTransactionId());
final DataTreeModification snapshot = transaction.getSnapshot();
operation.execute(snapshot);
final ShardDataTreeCohort cohort = shardDataTree.finishTransaction(transaction);
return candidate;
}
- private static DataTreeCandidateTip applyCandidates(final ShardDataTree shardDataTree, final List<DataTreeCandidateTip> candidates)
- throws ExecutionException, InterruptedException {
- final ReadWriteShardDataTreeTransaction transaction = shardDataTree.newReadWriteTransaction(nextTransactionId());
+ private static DataTreeCandidateTip applyCandidates(final ShardDataTree shardDataTree,
+ final List<DataTreeCandidateTip> candidates) throws ExecutionException, InterruptedException {
+ final ReadWriteShardDataTreeTransaction transaction =
+ shardDataTree.newReadWriteTransaction(nextTransactionId());
final DataTreeModification snapshot = transaction.getSnapshot();
- for(final DataTreeCandidateTip candidateTip : candidates){
+ for (final DataTreeCandidateTip candidateTip : candidates) {
DataTreeCandidates.applyToModification(snapshot, candidateTip);
}
final ShardDataTreeCohort cohort = shardDataTree.finishTransaction(transaction);
return candidate;
}
-
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
+
import com.google.common.base.Optional;
import java.io.IOException;
import org.junit.Before;
private SchemaContext carsSchemaContext;
@Before
- public void setUp(){
+ public void setUp() {
peopleSchemaContext = SchemaContextHelper.select(SchemaContextHelper.PEOPLE_YANG);
carsSchemaContext = SchemaContextHelper.select(SchemaContextHelper.CARS_YANG);
@Deprecated
@Test
- public void testAppendRecoveredLogEntryDataTreeCandidatePayload(){
+ public void testAppendRecoveredLogEntryDataTreeCandidatePayload() {
final ShardRecoveryCoordinator coordinator = new ShardRecoveryCoordinator(peopleDataTree,
null, "foobar", LoggerFactory.getLogger("foo"));
coordinator.startLogRecoveryBatch(10);
try {
coordinator.appendRecoveredLogEntry(DataTreeCandidatePayload.create(createCar()));
- } catch(final SchemaValidationFailedException e){
+ } catch (final SchemaValidationFailedException e) {
fail("SchemaValidationFailedException should not happen if pruning is done");
}
coordinator.startLogRecoveryBatch(10);
try {
coordinator.appendRecoveredLogEntry(CommitTransactionPayload.create(nextTransactionId(), createCar()));
- } catch(final SchemaValidationFailedException e){
+ } catch (final SchemaValidationFailedException e) {
fail("SchemaValidationFailedException should not happen if pruning is done");
}
}
@Test
- public void testApplyRecoverySnapshot(){
+ public void testApplyRecoverySnapshot() {
final ShardRecoveryCoordinator coordinator = new ShardRecoveryCoordinator(peopleDataTree,
null, "foobar", LoggerFactory.getLogger("foo"));
coordinator.startLogRecoveryBatch(10);
@Test
- public void testApplyCurrentLogRecoveryBatch(){
+ public void testApplyCurrentLogRecoveryBatch() {
final ShardRecoveryCoordinator coordinator = new ShardRecoveryCoordinator(peopleDataTree,
null, "foobar", LoggerFactory.getLogger("foo"));
coordinator.startLogRecoveryBatch(10);
try {
coordinator.applyCurrentLogRecoveryBatch();
- } catch(final IllegalArgumentException e){
+ } catch (final IllegalArgumentException e) {
fail("IllegalArgumentException should not happen - if the pruning modification delegate is passed");
}
}
- private DataTreeCandidateTip createCar(){
+ private DataTreeCandidateTip createCar() {
final TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
dataTree.setSchemaContext(carsSchemaContext);
return dataTree.prepare(modification);
}
- private Optional<NormalizedNode<?,?>> readCars(final ShardDataTree shardDataTree){
+ private Optional<NormalizedNode<?,?>> readCars(final ShardDataTree shardDataTree) {
final TipProducingDataTree dataTree = shardDataTree.getDataTree();
// FIXME: this should not be called here
dataTree.setSchemaContext(peopleSchemaContext);
return shardDataTree.readNode(CarsModel.BASE_PATH);
}
- private Optional<NormalizedNode<?,?>> readPeople(final ShardDataTree shardDataTree){
+ private Optional<NormalizedNode<?,?>> readPeople(final ShardDataTree shardDataTree) {
final TipProducingDataTree dataTree = shardDataTree.getDataTree();
// FIXME: this should not be called here
dataTree.setSchemaContext(peopleSchemaContext);
return shardDataTree.readNode(PeopleModel.BASE_PATH);
}
- private static byte[] createSnapshot(){
+ private static byte[] createSnapshot() {
final TipProducingDataTree dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL);
- dataTree.setSchemaContext(SchemaContextHelper.select(SchemaContextHelper.CARS_YANG, SchemaContextHelper.PEOPLE_YANG));
+ dataTree.setSchemaContext(SchemaContextHelper.select(SchemaContextHelper.CARS_YANG,
+ SchemaContextHelper.PEOPLE_YANG));
DataTreeSnapshot snapshot = dataTree.takeSnapshot();
return new PreBoronShardDataTreeSnapshot(dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY).get())
.serialize();
}
-}
\ No newline at end of file
+}
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
+
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.Props;
import akka.testkit.TestActorRef;
import akka.util.Timeout;
import com.google.common.base.Stopwatch;
+import com.google.common.base.Throwables;
import com.google.common.primitives.UnsignedLong;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.IOException;
import scala.concurrent.duration.FiniteDuration;
public class ShardTest extends AbstractShardTest {
- private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in InMemorySnapshotStore and journal recovery seq number will start from 1";
+ private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
+ + "InMemorySnapshotStore and journal recovery seq number will start from 1";
@Test
public void testRegisterChangeListener() throws Exception {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterChangeListener");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testRegisterChangeListener");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
+ shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
- final MockDataChangeListener listener = new MockDataChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
- "testRegisterChangeListener-DataChangeListener");
+ final MockDataChangeListener listener = new MockDataChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
+ "testRegisterChangeListener-DataChangeListener");
- shard.tell(new RegisterChangeListener(TestModel.TEST_PATH,
- dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
+ shard.tell(new RegisterChangeListener(TestModel.TEST_PATH, dclActor,
+ AsyncDataBroker.DataChangeScope.BASE, true), getRef());
- final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
- RegisterChangeListenerReply.class);
- final String replyPath = reply.getListenerRegistrationPath().toString();
- assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
- "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
+ final RegisterChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
+ RegisterChangeListenerReply.class);
+ final String replyPath = reply.getListenerRegistrationPath().toString();
+ assertTrue("Incorrect reply path: " + replyPath,
+ replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
- writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- listener.waitForChangeEvents(path);
- }};
+ listener.waitForChangeEvents(path);
+ }
+ };
}
@SuppressWarnings("serial")
// This test tests the timing window in which a change listener is registered before the
// shard becomes the leader. We verify that the listener is registered and notified of the
// existing data when the shard becomes the leader.
- new ShardTestKit(getSystem()) {{
- // For this test, we want to send the RegisterChangeListener message after the shard
- // has recovered from persistence and before it becomes the leader. So we subclass
- // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
- // we know that the shard has been initialized to a follower and has started the
- // election process. The following 2 CountDownLatches are used to coordinate the
- // ElectionTimeout with the sending of the RegisterChangeListener message.
- final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
- final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
- final Creator<Shard> creator = new Creator<Shard>() {
- boolean firstElectionTimeout = true;
-
- @Override
- public Shard create() throws Exception {
- // Use a non persistent provider because this test actually invokes persist on the journal
- // this will cause all other messages to not be queued properly after that.
- // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
- // it does do a persist)
- return new Shard(newShardBuilder()) {
- @Override
- public void handleCommand(final Object message) {
- if(message instanceof ElectionTimeout && firstElectionTimeout) {
- // Got the first ElectionTimeout. We don't forward it to the
- // base Shard yet until we've sent the RegisterChangeListener
- // message. So we signal the onFirstElectionTimeout latch to tell
- // the main thread to send the RegisterChangeListener message and
- // start a thread to wait on the onChangeListenerRegistered latch,
- // which the main thread signals after it has sent the message.
- // After the onChangeListenerRegistered is triggered, we send the
- // original ElectionTimeout message to proceed with the election.
- firstElectionTimeout = false;
- final ActorRef self = getSelf();
- new Thread() {
- @Override
- public void run() {
- Uninterruptibles.awaitUninterruptibly(
- onChangeListenerRegistered, 5, TimeUnit.SECONDS);
- self.tell(message, self);
- }
- }.start();
-
- onFirstElectionTimeout.countDown();
- } else {
- super.handleCommand(message);
- }
- }
- };
- }
- };
-
- setupInMemorySnapshotStore();
+ // For this test, we want to send the RegisterChangeListener message after the shard
+ // has recovered from persistence and before it becomes the leader. So we subclass
+ // Shard to override onReceiveCommand and, when the first ElectionTimeout is received,
+ // we know that the shard has been initialized to a follower and has started the
+ // election process. The following 2 CountDownLatches are used to coordinate the
+ // ElectionTimeout with the sending of the RegisterChangeListener message.
+ final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
+ final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
+ final Creator<Shard> creator = new Creator<Shard>() {
+ boolean firstElectionTimeout = true;
- final MockDataChangeListener listener = new MockDataChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
- "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
-
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testRegisterChangeListenerWhenNotLeaderInitially");
-
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
-
- // Wait until the shard receives the first ElectionTimeout message.
- assertEquals("Got first ElectionTimeout", true,
- onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
-
- // Now send the RegisterChangeListener and wait for the reply.
- shard.tell(new RegisterChangeListener(path, dclActor,
- AsyncDataBroker.DataChangeScope.SUBTREE, false), getRef());
+ @Override
+ public Shard create() throws Exception {
+ // Use a non persistent provider because this test actually invokes persist on the journal
+ // this will cause all other messages to not be queued properly after that.
+ // The basic issue is that you cannot use TestActorRef with a persistent actor (at least when
+ // it does do a persist)
+ return new Shard(newShardBuilder()) {
+ @Override
+ public void handleCommand(final Object message) {
+ if (message instanceof ElectionTimeout && firstElectionTimeout) {
+ // Got the first ElectionTimeout. We don't forward it to the
+ // base Shard yet until we've sent the RegisterChangeListener
+ // message. So we signal the onFirstElectionTimeout latch to tell
+ // the main thread to send the RegisterChangeListener message and
+ // start a thread to wait on the onChangeListenerRegistered latch,
+ // which the main thread signals after it has sent the message.
+ // After the onChangeListenerRegistered is triggered, we send the
+ // original ElectionTimeout message to proceed with the election.
+ firstElectionTimeout = false;
+ final ActorRef self = getSelf();
+ new Thread() {
+ @Override
+ public void run() {
+ Uninterruptibles.awaitUninterruptibly(
+ onChangeListenerRegistered, 5, TimeUnit.SECONDS);
+ self.tell(message, self);
+ }
+ }.start();
+
+ onFirstElectionTimeout.countDown();
+ } else {
+ super.handleCommand(message);
+ }
+ }
+ };
+ }
+ };
- final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
- RegisterChangeListenerReply.class);
- assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
+ setupInMemorySnapshotStore();
- // Sanity check - verify the shard is not the leader yet.
- shard.tell(FindLeader.INSTANCE, getRef());
- final FindLeaderReply findLeadeReply =
- expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
- assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
+ final MockDataChangeListener listener = new MockDataChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
+ "testRegisterChangeListenerWhenNotLeaderInitially-DataChangeListener");
- // Signal the onChangeListenerRegistered latch to tell the thread above to proceed
- // with the election process.
- onChangeListenerRegistered.countDown();
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testRegisterChangeListenerWhenNotLeaderInitially");
- // Wait for the shard to become the leader and notify our listener with the existing
- // data in the store.
- listener.waitForChangeEvents(path);
- }};
+ new ShardTestKit(getSystem()) {
+ {
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
+
+ // Wait until the shard receives the first ElectionTimeout
+ // message.
+ assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
+
+ // Now send the RegisterChangeListener and wait for the reply.
+ shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.SUBTREE, false),
+ getRef());
+
+ final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
+ RegisterChangeListenerReply.class);
+ assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
+
+ // Sanity check - verify the shard is not the leader yet.
+ shard.tell(FindLeader.INSTANCE, getRef());
+ final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
+ assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
+
+ // Signal the onChangeListenerRegistered latch to tell the
+ // thread above to proceed
+ // with the election process.
+ onChangeListenerRegistered.countDown();
+
+ // Wait for the shard to become the leader and notify our
+ // listener with the existing
+ // data in the store.
+ listener.waitForChangeEvents(path);
+ }
+ };
}
@Test
public void testRegisterDataTreeChangeListener() throws Exception {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testRegisterDataTreeChangeListener");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testRegisterDataTreeChangeListener");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
+ shard.tell(new UpdateSchemaContext(SchemaContextHelper.full()), ActorRef.noSender());
- final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
- "testRegisterDataTreeChangeListener-DataTreeChangeListener");
+ final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
+ "testRegisterDataTreeChangeListener-DataTreeChangeListener");
- shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
+ shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, false), getRef());
- final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
- RegisterDataTreeChangeListenerReply.class);
- final String replyPath = reply.getListenerRegistrationPath().toString();
- assertTrue("Incorrect reply path: " + replyPath, replyPath.matches(
- "akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
+ final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("3 seconds"),
+ RegisterDataTreeChangeListenerReply.class);
+ final String replyPath = reply.getListenerRegistrationPath().toString();
+ assertTrue("Incorrect reply path: " + replyPath,
+ replyPath.matches("akka:\\/\\/test\\/user\\/testRegisterDataTreeChangeListener\\/\\$.*"));
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
- writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ writeToStore(shard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- listener.waitForChangeEvents();
- }};
+ listener.waitForChangeEvents();
+ }
+ };
}
@SuppressWarnings("serial")
@Test
public void testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration() throws Exception {
- new ShardTestKit(getSystem()) {{
- final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
- final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
- final Creator<Shard> creator = new Creator<Shard>() {
- boolean firstElectionTimeout = true;
-
- @Override
- public Shard create() throws Exception {
- return new Shard(newShardBuilder()) {
- @Override
- public void handleCommand(final Object message) {
- if(message instanceof ElectionTimeout && firstElectionTimeout) {
- firstElectionTimeout = false;
- final ActorRef self = getSelf();
- new Thread() {
- @Override
- public void run() {
- Uninterruptibles.awaitUninterruptibly(
- onChangeListenerRegistered, 5, TimeUnit.SECONDS);
- self.tell(message, self);
- }
- }.start();
-
- onFirstElectionTimeout.countDown();
- } else {
- super.handleCommand(message);
- }
- }
- };
- }
- };
+ final CountDownLatch onFirstElectionTimeout = new CountDownLatch(1);
+ final CountDownLatch onChangeListenerRegistered = new CountDownLatch(1);
+ final Creator<Shard> creator = new Creator<Shard>() {
+ boolean firstElectionTimeout = true;
- setupInMemorySnapshotStore();
+ @Override
+ public Shard create() throws Exception {
+ return new Shard(newShardBuilder()) {
+ @Override
+ public void handleCommand(final Object message) {
+ if (message instanceof ElectionTimeout && firstElectionTimeout) {
+ firstElectionTimeout = false;
+ final ActorRef self = getSelf();
+ new Thread() {
+ @Override
+ public void run() {
+ Uninterruptibles.awaitUninterruptibly(
+ onChangeListenerRegistered, 5, TimeUnit.SECONDS);
+ self.tell(message, self);
+ }
+ }.start();
+
+ onFirstElectionTimeout.countDown();
+ } else {
+ super.handleCommand(message);
+ }
+ }
+ };
+ }
+ };
- final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
- "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
+ setupInMemorySnapshotStore();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
+ final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
+ "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration-DataChangeListener");
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testDataTreeChangeListenerNotifiedWhenNotTheLeaderOnRegistration");
- assertEquals("Got first ElectionTimeout", true,
- onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
- shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
- final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
- RegisterDataTreeChangeListenerReply.class);
- assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
+ new ShardTestKit(getSystem()) {
+ {
+ assertEquals("Got first ElectionTimeout", true, onFirstElectionTimeout.await(5, TimeUnit.SECONDS));
- shard.tell(FindLeader.INSTANCE, getRef());
- final FindLeaderReply findLeadeReply =
- expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
- assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
+ shard.tell(new RegisterDataTreeChangeListener(path, dclActor, false), getRef());
+ final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
+ RegisterDataTreeChangeListenerReply.class);
+ assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
+ shard.tell(FindLeader.INSTANCE, getRef());
+ final FindLeaderReply findLeadeReply = expectMsgClass(duration("5 seconds"), FindLeaderReply.class);
+ assertFalse("Expected the shard not to be the leader", findLeadeReply.getLeaderActor().isPresent());
- onChangeListenerRegistered.countDown();
+ onChangeListenerRegistered.countDown();
- // TODO: investigate why we do not receive data chage events
- listener.waitForChangeEvents();
- }};
+ // TODO: investigate why we do not receive data chage events
+ listener.waitForChangeEvents();
+ }
+ };
}
@Test
- public void testCreateTransaction(){
- new ShardTestKit(getSystem()) {{
- final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
+ public void testCreateTransaction() {
+ new ShardTestKit(getSystem()) {
+ {
+ final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransaction");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shard.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
- DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
+ shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
+ DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
- final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
- CreateTransactionReply.class);
+ final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
+ CreateTransactionReply.class);
- final String path = reply.getTransactionPath().toString();
- assertTrue("Unexpected transaction path " + path,
- path.startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
- }};
+ final String path = reply.getTransactionPath().toString();
+ assertTrue("Unexpected transaction path " + path, path
+ .startsWith("akka://test/user/testCreateTransaction/shard-member-1:ShardTransactionTest@0:"));
+ }
+ };
}
@Test
- public void testCreateTransactionOnChain(){
- new ShardTestKit(getSystem()) {{
- final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
+ public void testCreateTransactionOnChain() {
+ new ShardTestKit(getSystem()) {
+ {
+ final ActorRef shard = actorFactory.createActor(newShardProps(), "testCreateTransactionOnChain");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- shard.tell(new CreateTransaction(nextTransactionId(),TransactionType.READ_ONLY.ordinal(),
- DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
+ shard.tell(new CreateTransaction(nextTransactionId(), TransactionType.READ_ONLY.ordinal(),
+ DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
- final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
- CreateTransactionReply.class);
+ final CreateTransactionReply reply = expectMsgClass(duration("3 seconds"),
+ CreateTransactionReply.class);
- final String path = reply.getTransactionPath().toString();
- assertTrue("Unexpected transaction path " + path,
- path.startsWith("akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
- }};
+ final String path = reply.getTransactionPath().toString();
+ assertTrue("Unexpected transaction path " + path, path.startsWith(
+ "akka://test/user/testCreateTransactionOnChain/shard-member-1:ShardTransactionTest@0:"));
+ }
+ };
}
@Test
public void testPeerAddressResolved() throws Exception {
- new ShardTestKit(getSystem()) {{
- final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"), "config");
- final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder().
- peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null)).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
-
- final String address = "akka://foobar";
- shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
-
- shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
- final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
- assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
- }};
+ new ShardTestKit(getSystem()) {
+ {
+ final ShardIdentifier peerID = ShardIdentifier.create("inventory", MemberName.forName("member-2"),
+ "config");
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardBuilder()
+ .peerAddresses(Collections.<String, String>singletonMap(peerID.toString(), null))
+ .props().withDispatcher(Dispatchers.DefaultDispatcherId()), "testPeerAddressResolved");
+
+ final String address = "akka://foobar";
+ shard.tell(new PeerAddressResolved(peerID.toString(), address), ActorRef.noSender());
+
+ shard.tell(GetOnDemandRaftState.INSTANCE, getRef());
+ final OnDemandRaftState state = expectMsgClass(OnDemandRaftState.class);
+ assertEquals("getPeerAddress", address, state.getPeerAddresses().get(peerID.toString()));
+ }
+ };
}
@Test
public void testApplySnapshot() throws Exception {
- final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps().
- withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()), "testApplySnapshot");
ShardTestKit.waitUntilLeader(shard);
store.setSchemaContext(SCHEMA_CONTEXT);
final ContainerNode container = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
+ new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).addChild(
ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)).build()).build();
writeToStore(store, TestModel.TEST_PATH, container);
shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
final Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
try {
assertEquals("Root node", expected, readStore(shard, root));
return;
- } catch(final AssertionError e) {
+ } catch (final AssertionError e) {
// try again
}
}
final NormalizedNode<?, ?> root = readStore(store, YangInstanceIdentifier.EMPTY);
final Snapshot snapshot = Snapshot.create(new MetadataShardDataTreeSnapshot(root).serialize(),
- Collections.<ReplicatedLogEntry> emptyList(), 1, 2, 3, 4);
+ Collections.<ReplicatedLogEntry>emptyList(), 1, 2, 3, 4);
shard.tell(new ApplySnapshot(snapshot), ActorRef.noSender());
shard.tell(applyState, shard);
final Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
Uninterruptibles.sleepUninterruptibly(75, TimeUnit.MILLISECONDS);
final NormalizedNode<?,?> actual = readStore(shard, TestModel.TEST_PATH);
- if(actual != null) {
+ if (actual != null) {
assertEquals("Applied state", node, actual);
return;
}
mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
mod.ready();
- InMemoryJournal.addEntry(shardID.toString(), i+1, new ReplicatedLogImplEntry(i, 1,
+ InMemoryJournal.addEntry(shardID.toString(), i + 1, new ReplicatedLogImplEntry(i, 1,
payloadForModification(source, mod, nextTransactionId())));
}
}
@Test
- public void testConcurrentThreePhaseCommits() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testConcurrentThreePhaseCommits");
-
- waitUntilLeader(shard);
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public void testConcurrentThreePhaseCommits() throws Exception {
+ final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
+ final CountDownLatch commitLatch = new CountDownLatch(2);
- final TransactionIdentifier transactionID1 = nextTransactionId();
- final TransactionIdentifier transactionID2 = nextTransactionId();
- final TransactionIdentifier transactionID3 = nextTransactionId();
+ final long timeoutSec = 5;
+ final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
+ final Timeout timeout = new Timeout(duration);
- final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
- shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
- final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
- final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
- final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testConcurrentThreePhaseCommits");
- final long timeoutSec = 5;
- final FiniteDuration duration = FiniteDuration.create(timeoutSec, TimeUnit.SECONDS);
- final Timeout timeout = new Timeout(duration);
+ class OnFutureComplete extends OnComplete<Object> {
+ private final Class<?> expRespType;
- shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
- final ReadyTransactionReply readyReply = ReadyTransactionReply.fromSerializable(
- expectMsgClass(duration, ReadyTransactionReply.class));
- assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
+ OnFutureComplete(final Class<?> expRespType) {
+ this.expRespType = expRespType;
+ }
- // Send the CanCommitTransaction message for the first Tx.
+ @Override
+ public void onComplete(final Throwable error, final Object resp) {
+ if (error != null) {
+ caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
+ } else {
+ try {
+ assertEquals("Commit response type", expRespType, resp.getClass());
+ onSuccess(resp);
+ } catch (final Exception e) {
+ caughtEx.set(e);
+ }
+ }
+ }
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ void onSuccess(final Object resp) throws Exception {
+ }
+ }
- // Ready 2 more Tx's.
+ class OnCommitFutureComplete extends OnFutureComplete {
+ OnCommitFutureComplete() {
+ super(CommitTransactionReply.class);
+ }
- shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ @Override
+ public void onComplete(final Throwable error, final Object resp) {
+ super.onComplete(error, resp);
+ commitLatch.countDown();
+ }
+ }
- shard.tell(prepareBatchedModifications(transactionID3, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
- .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ class OnCanCommitFutureComplete extends OnFutureComplete {
+ private final TransactionIdentifier transactionID;
- // Send the CanCommitTransaction message for the next 2 Tx's. These should get queued and
- // processed after the first Tx completes.
+ OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
+ super(CanCommitTransactionReply.class);
+ this.transactionID = transactionID;
+ }
- final Future<Object> canCommitFuture1 = Patterns.ask(shard,
- new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
+ @Override
+ void onSuccess(final Object resp) throws Exception {
+ final CanCommitTransactionReply canCommitReply =
+ CanCommitTransactionReply.fromSerializable(resp);
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
+
+ final Future<Object> commitFuture = Patterns.ask(shard,
+ new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
+ commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
+ }
+ }
- final Future<Object> canCommitFuture2 = Patterns.ask(shard,
- new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
+ new ShardTestKit(getSystem()) {
+ {
+ waitUntilLeader(shard);
- // Send the CommitTransaction message for the first Tx. After it completes, it should
- // trigger the 2nd Tx to proceed which should in turn then trigger the 3rd.
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ final TransactionIdentifier transactionID3 = nextTransactionId();
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ final Map<TransactionIdentifier, CapturingShardDataTreeCohort> cohortMap = setupCohortDecorator(
+ shard.underlyingActor(), transactionID1, transactionID2, transactionID3);
+ final CapturingShardDataTreeCohort cohort1 = cohortMap.get(transactionID1);
+ final CapturingShardDataTreeCohort cohort2 = cohortMap.get(transactionID2);
+ final CapturingShardDataTreeCohort cohort3 = cohortMap.get(transactionID3);
- // Wait for the next 2 Tx's to complete.
+ shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
+ final ReadyTransactionReply readyReply = ReadyTransactionReply
+ .fromSerializable(expectMsgClass(duration, ReadyTransactionReply.class));
+ assertEquals("Cohort path", shard.path().toString(), readyReply.getCohortPath());
- final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
- final CountDownLatch commitLatch = new CountDownLatch(2);
+ // Send the CanCommitTransaction message for the first Tx.
- class OnFutureComplete extends OnComplete<Object> {
- private final Class<?> expRespType;
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- OnFutureComplete(final Class<?> expRespType) {
- this.expRespType = expRespType;
- }
+ // Ready 2 more Tx's.
- @Override
- public void onComplete(final Throwable error, final Object resp) {
- if(error != null) {
- caughtEx.set(new AssertionError(getClass().getSimpleName() + " failure", error));
- } else {
- try {
- assertEquals("Commit response type", expRespType, resp.getClass());
- onSuccess(resp);
- } catch (final Exception e) {
- caughtEx.set(e);
- }
- }
- }
+ shard.tell(prepareBatchedModifications(transactionID2, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- void onSuccess(final Object resp) throws Exception {
- }
- }
+ shard.tell(
+ prepareBatchedModifications(transactionID3,
+ YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
+ getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- class OnCommitFutureComplete extends OnFutureComplete {
- OnCommitFutureComplete() {
- super(CommitTransactionReply.class);
- }
+ // Send the CanCommitTransaction message for the next 2 Tx's.
+ // These should get queued and
+ // processed after the first Tx completes.
- @Override
- public void onComplete(final Throwable error, final Object resp) {
- super.onComplete(error, resp);
- commitLatch.countDown();
- }
- }
+ final Future<Object> canCommitFuture1 = Patterns.ask(shard,
+ new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
- class OnCanCommitFutureComplete extends OnFutureComplete {
- private final TransactionIdentifier transactionID;
+ final Future<Object> canCommitFuture2 = Patterns.ask(shard,
+ new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), timeout);
- OnCanCommitFutureComplete(final TransactionIdentifier transactionID) {
- super(CanCommitTransactionReply.class);
- this.transactionID = transactionID;
- }
+ // Send the CommitTransaction message for the first Tx. After it
+ // completes, it should
+ // trigger the 2nd Tx to proceed which should in turn then
+ // trigger the 3rd.
- @Override
- void onSuccess(final Object resp) throws Exception {
- final CanCommitTransactionReply canCommitReply =
- CanCommitTransactionReply.fromSerializable(resp);
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- final Future<Object> commitFuture = Patterns.ask(shard,
- new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), timeout);
- commitFuture.onComplete(new OnCommitFutureComplete(), getSystem().dispatcher());
- }
- }
+ // Wait for the next 2 Tx's to complete.
- canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2),
- getSystem().dispatcher());
+ canCommitFuture1.onComplete(new OnCanCommitFutureComplete(transactionID2), getSystem().dispatcher());
- canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3),
- getSystem().dispatcher());
+ canCommitFuture2.onComplete(new OnCanCommitFutureComplete(transactionID3), getSystem().dispatcher());
- final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
+ final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
- throw caughtEx.get();
- }
+ if (caughtEx.get() != null) {
+ Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class);
+ Throwables.propagate(caughtEx.get());
+ }
- assertEquals("Commits complete", true, done);
+ assertEquals("Commits complete", true, done);
- final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
- cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
- cohort3.getPreCommit(), cohort3.getCommit());
- inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
- inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
- inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
- inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
- inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
- inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
- inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
- inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
- inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
+ final InOrder inOrder = inOrder(cohort1.getCanCommit(), cohort1.getPreCommit(), cohort1.getCommit(),
+ cohort2.getCanCommit(), cohort2.getPreCommit(), cohort2.getCommit(), cohort3.getCanCommit(),
+ cohort3.getPreCommit(), cohort3.getCommit());
+ inOrder.verify(cohort1.getCanCommit()).onSuccess(any(Void.class));
+ inOrder.verify(cohort1.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
+ inOrder.verify(cohort1.getCommit()).onSuccess(any(UnsignedLong.class));
+ inOrder.verify(cohort2.getCanCommit()).onSuccess(any(Void.class));
+ inOrder.verify(cohort2.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
+ inOrder.verify(cohort2.getCommit()).onSuccess(any(UnsignedLong.class));
+ inOrder.verify(cohort3.getCanCommit()).onSuccess(any(Void.class));
+ inOrder.verify(cohort3.getPreCommit()).onSuccess(any(DataTreeCandidate.class));
+ inOrder.verify(cohort3.getCommit()).onSuccess(any(UnsignedLong.class));
- // Verify data in the data store.
+ // Verify data in the data store.
- verifyOuterListEntry(shard, 1);
+ verifyOuterListEntry(shard, 1);
- verifyLastApplied(shard, 2);
- }};
+ verifyLastApplied(shard, 2);
+ }
+ };
}
@Test
- public void testBatchedModificationsWithNoCommitOnReady() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testBatchedModificationsWithNoCommitOnReady");
+ public void testBatchedModificationsWithNoCommitOnReady() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testBatchedModificationsWithNoCommitOnReady");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final TransactionIdentifier transactionID = nextTransactionId();
- final FiniteDuration duration = duration("5 seconds");
+ final TransactionIdentifier transactionID = nextTransactionId();
+ final FiniteDuration duration = duration("5 seconds");
- // Send a BatchedModifications to start a transaction.
+ // Send a BatchedModifications to start a transaction.
- shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
- expectMsgClass(duration, BatchedModificationsReply.class);
+ shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
+ expectMsgClass(duration, BatchedModificationsReply.class);
- // Send a couple more BatchedModifications.
+ // Send a couple more BatchedModifications.
- shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
- expectMsgClass(duration, BatchedModificationsReply.class);
+ shard.tell(
+ newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
+ getRef());
+ expectMsgClass(duration, BatchedModificationsReply.class);
- shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
- TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ shard.tell(newBatchedModifications(transactionID,
+ YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, false, 3),
+ getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- // Send the CommitTransaction message.
+ // Send the CommitTransaction message.
- shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- // Verify data in the data store.
+ // Verify data in the data store.
- verifyOuterListEntry(shard, 1);
- }};
+ verifyOuterListEntry(shard, 1);
+ }
+ };
}
@Test
- public void testBatchedModificationsWithCommitOnReady() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testBatchedModificationsWithCommitOnReady");
+ public void testBatchedModificationsWithCommitOnReady() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testBatchedModificationsWithCommitOnReady");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final TransactionIdentifier transactionID = nextTransactionId();
- final FiniteDuration duration = duration("5 seconds");
+ final TransactionIdentifier transactionID = nextTransactionId();
+ final FiniteDuration duration = duration("5 seconds");
- // Send a BatchedModifications to start a transaction.
+ // Send a BatchedModifications to start a transaction.
- shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
- expectMsgClass(duration, BatchedModificationsReply.class);
+ shard.tell(newBatchedModifications(transactionID, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false, false, 1), getRef());
+ expectMsgClass(duration, BatchedModificationsReply.class);
- // Send a couple more BatchedModifications.
+ // Send a couple more BatchedModifications.
- shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2), getRef());
- expectMsgClass(duration, BatchedModificationsReply.class);
+ shard.tell(newBatchedModifications(transactionID, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), false, false, 2),
+ getRef());
+ expectMsgClass(duration, BatchedModificationsReply.class);
- shard.tell(newBatchedModifications(transactionID, YangInstanceIdentifier.builder(
- TestModel.OUTER_LIST_PATH).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3), getRef());
+ shard.tell(newBatchedModifications(transactionID,
+ YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), true, true, 3),
+ getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ expectMsgClass(duration, CommitTransactionReply.class);
- // Verify data in the data store.
+ // Verify data in the data store.
- verifyOuterListEntry(shard, 1);
- }};
+ verifyOuterListEntry(shard, 1);
+ }
+ };
}
- @Test(expected=IllegalStateException.class)
- public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
+ @Test(expected = IllegalStateException.class)
+ public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testBatchedModificationsReadyWithIncorrectTotalMessageCount");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final TransactionIdentifier transactionID = nextTransactionId();
- final BatchedModifications batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
- batched.setReady(true);
- batched.setTotalMessagesSent(2);
+ final TransactionIdentifier transactionID = nextTransactionId();
+ final BatchedModifications batched = new BatchedModifications(transactionID,
+ DataStoreVersions.CURRENT_VERSION);
+ batched.setReady(true);
+ batched.setTotalMessagesSent(2);
- shard.tell(batched, getRef());
+ shard.tell(batched, getRef());
- final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- if(failure != null) {
- throw failure.cause();
+ if (failure != null) {
+ Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
+ Throwables.propagate(failure.cause());
+ }
}
- }};
+ };
}
@Test
- public void testBatchedModificationsWithOperationFailure() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testBatchedModificationsWithOperationFailure");
+ public void testBatchedModificationsWithOperationFailure() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testBatchedModificationsWithOperationFailure");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- // Test merge with invalid data. An exception should occur when the merge is applied. Note that
- // write will not validate the children for performance reasons.
+ // Test merge with invalid data. An exception should occur when
+ // the merge is applied. Note that
+ // write will not validate the children for performance reasons.
- final TransactionIdentifier transactionID = nextTransactionId();
+ final TransactionIdentifier transactionID = nextTransactionId();
- final ContainerNode invalidData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
+ final ContainerNode invalidData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk")).build();
- BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
- batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
- shard.tell(batched, getRef());
- Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ BatchedModifications batched = new BatchedModifications(transactionID, CURRENT_VERSION);
+ batched.addModification(new MergeModification(TestModel.TEST_PATH, invalidData));
+ shard.tell(batched, getRef());
+ Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- final Throwable cause = failure.cause();
+ final Throwable cause = failure.cause();
- batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
- batched.setReady(true);
- batched.setTotalMessagesSent(2);
+ batched = new BatchedModifications(transactionID, DataStoreVersions.CURRENT_VERSION);
+ batched.setReady(true);
+ batched.setTotalMessagesSent(2);
- shard.tell(batched, getRef());
+ shard.tell(batched, getRef());
- failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- assertEquals("Failure cause", cause, failure.cause());
- }};
+ failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ assertEquals("Failure cause", cause, failure.cause());
+ }
+ };
}
@Test
- public void testBatchedModificationsOnTransactionChain() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testBatchedModificationsOnTransactionChain");
+ public void testBatchedModificationsOnTransactionChain() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testBatchedModificationsOnTransactionChain");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final LocalHistoryIdentifier historyId = nextHistoryId();
- final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
- final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
+ final LocalHistoryIdentifier historyId = nextHistoryId();
+ final TransactionIdentifier transactionID1 = new TransactionIdentifier(historyId, 0);
+ final TransactionIdentifier transactionID2 = new TransactionIdentifier(historyId, 1);
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- // Send a BatchedModifications to start a chained write transaction and ready it.
+ // Send a BatchedModifications to start a chained write
+ // transaction and ready it.
- final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
- shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final ContainerNode containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ shard.tell(newBatchedModifications(transactionID1, path, containerNode, true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Create a read Tx on the same chain.
+ // Create a read Tx on the same chain.
- shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
- DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
+ shard.tell(new CreateTransaction(transactionID2, TransactionType.READ_ONLY.ordinal(),
+ DataStoreVersions.CURRENT_VERSION).toSerializable(), getRef());
- final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"), CreateTransactionReply.class);
+ final CreateTransactionReply createReply = expectMsgClass(duration("3 seconds"),
+ CreateTransactionReply.class);
- getSystem().actorSelection(createReply.getTransactionPath()).tell(
- new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
- final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
- assertEquals("Read node", containerNode, readReply.getNormalizedNode());
+ getSystem().actorSelection(createReply.getTransactionPath())
+ .tell(new ReadData(path, DataStoreVersions.CURRENT_VERSION), getRef());
+ final ReadDataReply readReply = expectMsgClass(duration("3 seconds"), ReadDataReply.class);
+ assertEquals("Read node", containerNode, readReply.getNormalizedNode());
- // Commit the write transaction.
+ // Commit the write transaction.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- // Verify data in the data store.
+ // Verify data in the data store.
- final NormalizedNode<?, ?> actualNode = readStore(shard, path);
- assertEquals("Stored node", containerNode, actualNode);
- }};
+ final NormalizedNode<?, ?> actualNode = readStore(shard, path);
+ assertEquals("Stored node", containerNode, actualNode);
+ }
+ };
}
@Test
public void testOnBatchedModificationsWhenNotLeader() {
final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
- new ShardTestKit(getSystem()) {{
- final Creator<Shard> creator = new Creator<Shard>() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public Shard create() throws Exception {
- return new Shard(newShardBuilder()) {
- @Override
- protected boolean isLeader() {
- return overrideLeaderCalls.get() ? false : super.isLeader();
- }
+ new ShardTestKit(getSystem()) {
+ {
+ final Creator<Shard> creator = new Creator<Shard>() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Shard create() throws Exception {
+ return new Shard(newShardBuilder()) {
+ @Override
+ protected boolean isLeader() {
+ return overrideLeaderCalls.get() ? false : super.isLeader();
+ }
- @Override
- public ActorSelection getLeader() {
- return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path()) :
- super.getLeader();
- }
- };
- }
- };
+ @Override
+ public ActorSelection getLeader() {
+ return overrideLeaderCalls.get() ? getSystem().actorSelection(getRef().path())
+ : super.getLeader();
+ }
+ };
+ }
+ };
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- Props.create(new DelegatingShardCreator(creator)).
- withDispatcher(Dispatchers.DefaultDispatcherId()), "testOnBatchedModificationsWhenNotLeader");
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
+ .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testOnBatchedModificationsWhenNotLeader");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- overrideLeaderCalls.set(true);
+ overrideLeaderCalls.set(true);
- final BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
+ final BatchedModifications batched = new BatchedModifications(nextTransactionId(),
+ DataStoreVersions.CURRENT_VERSION);
- shard.tell(batched, ActorRef.noSender());
+ shard.tell(batched, ActorRef.noSender());
- expectMsgEquals(batched);
- }};
+ expectMsgEquals(batched);
+ }
+ };
}
@Test
public void testTransactionMessagesWithNoLeader() {
- new ShardTestKit(getSystem()) {{
- dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).
- shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testTransactionMessagesWithNoLeader");
-
- waitUntilNoLeader(shard);
-
- final TransactionIdentifier txId = nextTransactionId();
- shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
- Failure failure = expectMsgClass(Failure.class);
- assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
-
- shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
- failure = expectMsgClass(Failure.class);
- assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
-
- shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
- failure = expectMsgClass(Failure.class);
- assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
- }};
+ new ShardTestKit(getSystem()) {
+ {
+ dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
+ .shardHeartbeatIntervalInMillis(50).shardElectionTimeoutFactor(1);
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testTransactionMessagesWithNoLeader");
+
+ waitUntilNoLeader(shard);
+
+ final TransactionIdentifier txId = nextTransactionId();
+ shard.tell(new BatchedModifications(txId, DataStoreVersions.CURRENT_VERSION), getRef());
+ Failure failure = expectMsgClass(Failure.class);
+ assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
+
+ shard.tell(prepareForwardedReadyTransaction(shard, txId, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
+ failure = expectMsgClass(Failure.class);
+ assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
+
+ shard.tell(new ReadyLocalTransaction(txId, mock(DataTreeModification.class), true), getRef());
+ failure = expectMsgClass(Failure.class);
+ assertEquals("Failure cause type", NoShardLeaderException.class, failure.cause().getClass());
+ }
+ };
}
@Test
- public void testReadyWithReadWriteImmediateCommit() throws Exception{
+ public void testReadyWithReadWriteImmediateCommit() throws Exception {
testReadyWithImmediateCommit(true);
}
@Test
- public void testReadyWithWriteOnlyImmediateCommit() throws Exception{
+ public void testReadyWithWriteOnlyImmediateCommit() throws Exception {
testReadyWithImmediateCommit(false);
}
- private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception{
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testReadyWithImmediateCommit-" + readWrite);
-
- waitUntilLeader(shard);
-
- final TransactionIdentifier transactionID = nextTransactionId();
- final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- if(readWrite) {
- shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
- containerNode, true), getRef());
- } else {
- shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true), getRef());
- }
+ private void testReadyWithImmediateCommit(final boolean readWrite) throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testReadyWithImmediateCommit-" + readWrite);
- expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
+ waitUntilLeader(shard);
- final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
- assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
- }};
+ final TransactionIdentifier transactionID = nextTransactionId();
+ final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ if (readWrite) {
+ shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
+ containerNode, true), getRef());
+ } else {
+ shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, true),
+ getRef());
+ }
+
+ expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
+
+ final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
+ assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
+ }
+ };
}
@Test
- public void testReadyLocalTransactionWithImmediateCommit() throws Exception{
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testReadyLocalTransactionWithImmediateCommit");
+ public void testReadyLocalTransactionWithImmediateCommit() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testReadyLocalTransactionWithImmediateCommit");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
+ final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
- final DataTreeModification modification = dataStore.newModification();
+ final DataTreeModification modification = dataStore.newModification();
- final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
- final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
- new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
+ final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
+ final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
+ new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
- final TransactionIdentifier txId = nextTransactionId();
- modification.ready();
- final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
+ final TransactionIdentifier txId = nextTransactionId();
+ modification.ready();
+ final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, true);
- shard.tell(readyMessage, getRef());
+ shard.tell(readyMessage, getRef());
- expectMsgClass(CommitTransactionReply.class);
+ expectMsgClass(CommitTransactionReply.class);
- final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
- assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
- }};
+ final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
+ assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
+ }
+ };
}
@Test
- public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception{
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testReadyLocalTransactionWithThreePhaseCommit");
+ public void testReadyLocalTransactionWithThreePhaseCommit() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testReadyLocalTransactionWithThreePhaseCommit");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
+ final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
- final DataTreeModification modification = dataStore.newModification();
+ final DataTreeModification modification = dataStore.newModification();
- final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
- final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
- new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
+ final ContainerNode writeData = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ new WriteModification(TestModel.TEST_PATH, writeData).apply(modification);
+ final MapNode mergeData = ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build();
+ new MergeModification(TestModel.OUTER_LIST_PATH, mergeData).apply(modification);
- final TransactionIdentifier txId = nextTransactionId();
- modification.ready();
- final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
+ final TransactionIdentifier txId = nextTransactionId();
+ modification.ready();
+ final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(txId, modification, false);
- shard.tell(readyMessage, getRef());
+ shard.tell(readyMessage, getRef());
- expectMsgClass(ReadyTransactionReply.class);
+ expectMsgClass(ReadyTransactionReply.class);
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(txId, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(CommitTransactionReply.class);
- final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
- assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
- }};
+ final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.OUTER_LIST_PATH);
+ assertEquals(TestModel.OUTER_LIST_QNAME.getLocalName(), mergeData, actualNode);
+ }
+ };
}
@Test
- public void testReadWriteCommitWithPersistenceDisabled() throws Throwable {
+ public void testReadWriteCommitWithPersistenceDisabled() throws Exception {
dataStoreContextBuilder.persistent(false);
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testCommitWithPersistenceDisabled");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testCommitWithPersistenceDisabled");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- // Setup a simulated transactions with a mock cohort.
+ // Setup a simulated transactions with a mock cohort.
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID = nextTransactionId();
- final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID = nextTransactionId();
+ final NormalizedNode<?, ?> containerNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH, containerNode, false),
+ getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
- assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
- }};
+ final NormalizedNode<?, ?> actualNode = readStore(shard, TestModel.TEST_PATH);
+ assertEquals(TestModel.TEST_QNAME.getLocalName(), containerNode, actualNode);
+ }
+ };
}
@Test
testCommitWhenTransactionHasNoModifications(false);
}
- private void testCommitWhenTransactionHasNoModifications(final boolean readWrite){
- // Note that persistence is enabled which would normally result in the entry getting written to the journal
+ private void testCommitWhenTransactionHasNoModifications(final boolean readWrite) {
+ // Note that persistence is enabled which would normally result in the
+ // entry getting written to the journal
// but here that need not happen
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testCommitWhenTransactionHasNoModifications-" + readWrite);
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testCommitWhenTransactionHasNoModifications-" + readWrite);
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final TransactionIdentifier transactionID = nextTransactionId();
+ final TransactionIdentifier transactionID = nextTransactionId();
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- if(readWrite) {
- final ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore().
- newReadWriteTransaction(transactionID);
- shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, false), getRef());
- } else {
- shard.tell(prepareBatchedModifications(transactionID, new MutableCompositeModification()), getRef());
- }
+ if (readWrite) {
+ final ReadWriteShardDataTreeTransaction rwTx = shard.underlyingActor().getDataStore()
+ .newReadWriteTransaction(transactionID);
+ shard.tell(new ForwardedReadyTransaction(transactionID, CURRENT_VERSION, rwTx, false), getRef());
+ } else {
+ shard.tell(prepareBatchedModifications(transactionID, new MutableCompositeModification()),
+ getRef());
+ }
- expectMsgClass(duration, ReadyTransactionReply.class);
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
- final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
+ shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
+ final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
- // Use MBean for verification
- // Committed transaction count should increase as usual
- assertEquals(1,shardStats.getCommittedTransactionsCount());
+ // Use MBean for verification
+ // Committed transaction count should increase as usual
+ assertEquals(1, shardStats.getCommittedTransactionsCount());
- // Commit index should not advance because this does not go into the journal
- assertEquals(-1, shardStats.getCommitIndex());
- }};
+ // Commit index should not advance because this does not go into
+ // the journal
+ assertEquals(-1, shardStats.getCommitIndex());
+ }
+ };
}
@Test
}
private void testCommitWhenTransactionHasModifications(final boolean readWrite) throws Exception {
- new ShardTestKit(getSystem()) {{
- final TipProducingDataTree dataTree = createDelegatingMockDataTree();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testCommitWhenTransactionHasModifications-" + readWrite);
+ new ShardTestKit(getSystem()) {
+ {
+ final TipProducingDataTree dataTree = createDelegatingMockDataTree();
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testCommitWhenTransactionHasModifications-" + readWrite);
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID = nextTransactionId();
+ final FiniteDuration duration = duration("5 seconds");
+ final TransactionIdentifier transactionID = nextTransactionId();
- if(readWrite) {
- shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
- } else {
- shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
- }
+ if (readWrite) {
+ shard.tell(prepareForwardedReadyTransaction(shard, transactionID, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
+ } else {
+ shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
+ }
- expectMsgClass(duration, ReadyTransactionReply.class);
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- final InOrder inOrder = inOrder(dataTree);
- inOrder.verify(dataTree).validate(any(DataTreeModification.class));
- inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
- inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
+ final InOrder inOrder = inOrder(dataTree);
+ inOrder.verify(dataTree).validate(any(DataTreeModification.class));
+ inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
+ inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
- shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
- final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
+ shard.tell(Shard.GET_SHARD_MBEAN_MESSAGE, getRef());
+ final ShardStats shardStats = expectMsgClass(duration, ShardStats.class);
- // Use MBean for verification
- // Committed transaction count should increase as usual
- assertEquals(1, shardStats.getCommittedTransactionsCount());
+ // Use MBean for verification
+ // Committed transaction count should increase as usual
+ assertEquals(1, shardStats.getCommittedTransactionsCount());
- // Commit index should advance as we do not have an empty modification
- assertEquals(0, shardStats.getCommitIndex());
- }};
+ // Commit index should advance as we do not have an empty
+ // modification
+ assertEquals(0, shardStats.getCommitIndex());
+ }
+ };
}
@Test
- public void testCommitPhaseFailure() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TipProducingDataTree dataTree = createDelegatingMockDataTree();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testCommitPhaseFailure");
+ public void testCommitPhaseFailure() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TipProducingDataTree dataTree = createDelegatingMockDataTree();
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testCommitPhaseFailure");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
- final Timeout timeout = new Timeout(duration);
+ final FiniteDuration duration = duration("5 seconds");
+ final Timeout timeout = new Timeout(duration);
- // Setup 2 simulated transactions with mock cohorts. The first one fails in the
- // commit phase.
+ // Setup 2 simulated transactions with mock cohorts. The first
+ // one fails in the
+ // commit phase.
- doThrow(new RuntimeException("mock commit failure")).when(dataTree).commit(any(DataTreeCandidate.class));
+ doThrow(new RuntimeException("mock commit failure")).when(dataTree)
+ .commit(any(DataTreeCandidate.class));
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message for the first Tx.
+ // Send the CanCommitTransaction message for the first Tx.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
- // processed after the first Tx completes.
+ // Send the CanCommitTransaction message for the 2nd Tx. This
+ // should get queued and
+ // processed after the first Tx completes.
- final Future<Object> canCommitFuture = Patterns.ask(shard,
- new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
+ final Future<Object> canCommitFuture = Patterns.ask(shard,
+ new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
- // Send the CommitTransaction message for the first Tx. This should send back an error
- // and trigger the 2nd Tx to proceed.
+ // Send the CommitTransaction message for the first Tx. This
+ // should send back an error
+ // and trigger the 2nd Tx to proceed.
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, akka.actor.Status.Failure.class);
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, akka.actor.Status.Failure.class);
- // Wait for the 2nd Tx to complete the canCommit phase.
+ // Wait for the 2nd Tx to complete the canCommit phase.
- final CountDownLatch latch = new CountDownLatch(1);
- canCommitFuture.onComplete(new OnComplete<Object>() {
- @Override
- public void onComplete(final Throwable t, final Object resp) {
- latch.countDown();
- }
- }, getSystem().dispatcher());
+ final CountDownLatch latch = new CountDownLatch(1);
+ canCommitFuture.onComplete(new OnComplete<Object>() {
+ @Override
+ public void onComplete(final Throwable failure, final Object resp) {
+ latch.countDown();
+ }
+ }, getSystem().dispatcher());
- assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
+ assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
- final InOrder inOrder = inOrder(dataTree);
- inOrder.verify(dataTree).validate(any(DataTreeModification.class));
- inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
- inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
- inOrder.verify(dataTree).validate(any(DataTreeModification.class));
- }};
+ final InOrder inOrder = inOrder(dataTree);
+ inOrder.verify(dataTree).validate(any(DataTreeModification.class));
+ inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
+ inOrder.verify(dataTree).commit(any(DataTreeCandidate.class));
+ inOrder.verify(dataTree).validate(any(DataTreeModification.class));
+ }
+ };
}
@Test
- public void testPreCommitPhaseFailure() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TipProducingDataTree dataTree = createDelegatingMockDataTree();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testPreCommitPhaseFailure");
+ public void testPreCommitPhaseFailure() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TipProducingDataTree dataTree = createDelegatingMockDataTree();
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testPreCommitPhaseFailure");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
- final Timeout timeout = new Timeout(duration);
+ final FiniteDuration duration = duration("5 seconds");
+ final Timeout timeout = new Timeout(duration);
- doThrow(new RuntimeException("mock preCommit failure")).when(dataTree).prepare(any(DataTreeModification.class));
+ doThrow(new RuntimeException("mock preCommit failure")).when(dataTree)
+ .prepare(any(DataTreeModification.class));
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message for the first Tx.
+ // Send the CanCommitTransaction message for the first Tx.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
- // processed after the first Tx completes.
+ // Send the CanCommitTransaction message for the 2nd Tx. This
+ // should get queued and
+ // processed after the first Tx completes.
- final Future<Object> canCommitFuture = Patterns.ask(shard,
- new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
+ final Future<Object> canCommitFuture = Patterns.ask(shard,
+ new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
- // Send the CommitTransaction message for the first Tx. This should send back an error
- // and trigger the 2nd Tx to proceed.
+ // Send the CommitTransaction message for the first Tx. This
+ // should send back an error
+ // and trigger the 2nd Tx to proceed.
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, akka.actor.Status.Failure.class);
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, akka.actor.Status.Failure.class);
- // Wait for the 2nd Tx to complete the canCommit phase.
+ // Wait for the 2nd Tx to complete the canCommit phase.
- final CountDownLatch latch = new CountDownLatch(1);
- canCommitFuture.onComplete(new OnComplete<Object>() {
- @Override
- public void onComplete(final Throwable t, final Object resp) {
- latch.countDown();
- }
- }, getSystem().dispatcher());
+ final CountDownLatch latch = new CountDownLatch(1);
+ canCommitFuture.onComplete(new OnComplete<Object>() {
+ @Override
+ public void onComplete(final Throwable failure, final Object resp) {
+ latch.countDown();
+ }
+ }, getSystem().dispatcher());
- assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
+ assertEquals("2nd CanCommit complete", true, latch.await(5, TimeUnit.SECONDS));
- final InOrder inOrder = inOrder(dataTree);
- inOrder.verify(dataTree).validate(any(DataTreeModification.class));
- inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
- inOrder.verify(dataTree).validate(any(DataTreeModification.class));
- }};
+ final InOrder inOrder = inOrder(dataTree);
+ inOrder.verify(dataTree).validate(any(DataTreeModification.class));
+ inOrder.verify(dataTree).prepare(any(DataTreeModification.class));
+ inOrder.verify(dataTree).validate(any(DataTreeModification.class));
+ }
+ };
}
@Test
- public void testCanCommitPhaseFailure() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TipProducingDataTree dataTree = createDelegatingMockDataTree();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testCanCommitPhaseFailure");
+ public void testCanCommitPhaseFailure() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TipProducingDataTree dataTree = createDelegatingMockDataTree();
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testCanCommitPhaseFailure");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID1 = nextTransactionId();
+ final FiniteDuration duration = duration("5 seconds");
+ final TransactionIdentifier transactionID1 = nextTransactionId();
- doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure")).
- doNothing().when(dataTree).validate(any(DataTreeModification.class));
+ doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
+ .doNothing().when(dataTree).validate(any(DataTreeModification.class));
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message.
+ // Send the CanCommitTransaction message.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, akka.actor.Status.Failure.class);
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, akka.actor.Status.Failure.class);
- // Send another can commit to ensure the failed one got cleaned up.
+ // Send another can commit to ensure the failed one got cleaned
+ // up.
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
- final CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(CanCommitTransactionReply.class));
- assertEquals("getCanCommit", true, reply.getCanCommit());
- }};
+ shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
+ final CanCommitTransactionReply reply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(CanCommitTransactionReply.class));
+ assertEquals("getCanCommit", true, reply.getCanCommit());
+ }
+ };
}
@Test
- public void testImmediateCommitWithCanCommitPhaseFailure() throws Throwable {
+ public void testImmediateCommitWithCanCommitPhaseFailure() throws Exception {
testImmediateCommitWithCanCommitPhaseFailure(true);
testImmediateCommitWithCanCommitPhaseFailure(false);
}
- private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TipProducingDataTree dataTree = createDelegatingMockDataTree();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
+ private void testImmediateCommitWithCanCommitPhaseFailure(final boolean readWrite) throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TipProducingDataTree dataTree = createDelegatingMockDataTree();
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().dataTree(dataTree).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testImmediateCommitWithCanCommitPhaseFailure-" + readWrite);
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure")).
- doNothing().when(dataTree).validate(any(DataTreeModification.class));
+ doThrow(new DataValidationFailedException(YangInstanceIdentifier.EMPTY, "mock canCommit failure"))
+ .doNothing().when(dataTree).validate(any(DataTreeModification.class));
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID1 = nextTransactionId();
+ final TransactionIdentifier transactionID1 = nextTransactionId();
- if(readWrite) {
- shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
- } else {
- shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
- }
+ if (readWrite) {
+ shard.tell(prepareForwardedReadyTransaction(shard, transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
+ } else {
+ shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
+ }
- expectMsgClass(duration, akka.actor.Status.Failure.class);
+ expectMsgClass(duration, akka.actor.Status.Failure.class);
- // Send another can commit to ensure the failed one got cleaned up.
+ // Send another can commit to ensure the failed one got cleaned
+ // up.
- final TransactionIdentifier transactionID2 = nextTransactionId();
- if(readWrite) {
- shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
- } else {
- shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
- }
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ if (readWrite) {
+ shard.tell(prepareForwardedReadyTransaction(shard, transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
+ } else {
+ shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true), getRef());
+ }
- expectMsgClass(duration, CommitTransactionReply.class);
- }};
+ expectMsgClass(duration, CommitTransactionReply.class);
+ }
+ };
}
- @SuppressWarnings("serial")
@Test
- public void testAbortWithCommitPending() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
- @Override
- void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
- // Simulate an AbortTransaction message occurring during replication, after
- // persisting and before finishing the commit to the in-memory store.
-
- doAbortTransaction(transactionId, null);
- super.persistPayload(transactionId, payload);
- }
- };
+ public void testAbortWithCommitPending() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final Creator<Shard> creator = () -> new Shard(newShardBuilder()) {
+ @Override
+ void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
+ // Simulate an AbortTransaction message occurring during
+ // replication, after
+ // persisting and before finishing the commit to the
+ // in-memory store.
+
+ doAbortTransaction(transactionId, null);
+ super.persistPayload(transactionId, payload);
+ }
+ };
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- Props.create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testAbortWithCommitPending");
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
+ .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testAbortWithCommitPending");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID = nextTransactionId();
+ final TransactionIdentifier transactionID = nextTransactionId();
- shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ shard.tell(prepareBatchedModifications(transactionID, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
+ shard.tell(new CanCommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
- shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
+ final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST_PATH);
- // Since we're simulating an abort occurring during replication and before finish commit,
- // the data should still get written to the in-memory store since we've gotten past
- // canCommit and preCommit and persisted the data.
- assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
- }};
+ // Since we're simulating an abort occurring during replication
+ // and before finish commit,
+ // the data should still get written to the in-memory store
+ // since we've gotten past
+ // canCommit and preCommit and persisted the data.
+ assertNotNull(TestModel.TEST_QNAME.getLocalName() + " not found", node);
+ }
+ };
}
@Test
- public void testTransactionCommitTimeout() throws Throwable {
+ public void testTransactionCommitTimeout() throws Exception {
dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testTransactionCommitTimeout");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testTransactionCommitTimeout");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- writeToStore(shard, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ writeToStore(shard, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
- // Ready 2 Tx's - the first will timeout
+ // Ready 2 Tx's - the first will timeout
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(prepareBatchedModifications(transactionID1, YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
- .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(
+ prepareBatchedModifications(transactionID1,
+ YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(),
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1), false),
+ getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID2 = nextTransactionId();
- final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
- .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
- shard.tell(prepareBatchedModifications(transactionID2, listNodePath,
- ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ final YangInstanceIdentifier listNodePath = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2).build();
+ shard.tell(
+ prepareBatchedModifications(transactionID2, listNodePath,
+ ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 2), false),
+ getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // canCommit 1st Tx. We don't send the commit so it should timeout.
+ // canCommit 1st Tx. We don't send the commit so it should
+ // timeout.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
- // canCommit the 2nd Tx - it should complete after the 1st Tx times out.
+ // canCommit the 2nd Tx - it should complete after the 1st Tx
+ // times out.
- shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
+ shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
- // Try to commit the 1st Tx - should fail as it's not the current Tx.
+ // Try to commit the 1st Tx - should fail as it's not the
+ // current Tx.
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, akka.actor.Status.Failure.class);
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, akka.actor.Status.Failure.class);
- // Commit the 2nd Tx.
+ // Commit the 2nd Tx.
- shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
- assertNotNull(listNodePath + " not found", node);
- }};
+ final NormalizedNode<?, ?> node = readStore(shard, listNodePath);
+ assertNotNull(listNodePath + " not found", node);
+ }
+ };
}
// @Test
//
// // Ready the Tx's
//
-// shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1, modification1), getRef());
+// shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort1, transactionID1,
+// modification1), getRef());
// expectMsgClass(duration, ReadyTransactionReply.class);
//
-// shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2, modification2), getRef());
+// shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort2, transactionID2,
+// modification2), getRef());
// expectMsgClass(duration, ReadyTransactionReply.class);
//
// // The 3rd Tx should exceed queue capacity and fail.
//
-// shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3, modification3), getRef());
+// shard.tell(prepareReadyTransactionMessage(false, shard.underlyingActor(), cohort3, transactionID3,
+// modification3), getRef());
// expectMsgClass(duration, akka.actor.Status.Failure.class);
//
// // canCommit 1st Tx.
// }
@Test
- public void testTransactionCommitWithPriorExpiredCohortEntries() throws Throwable {
+ public void testTransactionCommitWithPriorExpiredCohortEntries() throws Exception {
dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testTransactionCommitWithPriorExpiredCohortEntries");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testTransactionCommitWithPriorExpiredCohortEntries");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID3 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID3 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID3, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // All Tx's are readied. We'll send canCommit for the last one but not the others. The others
- // should expire from the queue and the last one should be processed.
+ // All Tx's are readied. We'll send canCommit for the last one
+ // but not the others. The others
+ // should expire from the queue and the last one should be
+ // processed.
- shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
- }};
+ shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
+ }
+ };
}
@Test
- public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Throwable {
+ public void testTransactionCommitWithSubsequentExpiredCohortEntry() throws Exception {
dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testTransactionCommitWithSubsequentExpiredCohortEntry");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testTransactionCommitWithSubsequentExpiredCohortEntry");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
+ final ShardDataTree dataStore = shard.underlyingActor().getDataStore();
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(prepareBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // CanCommit the first Tx so it's the current in-progress Tx.
+ // CanCommit the first Tx so it's the current in-progress Tx.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
- // Ready the second Tx.
+ // Ready the second Tx.
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(prepareBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), false), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Ready the third Tx.
+ // Ready the third Tx.
- final TransactionIdentifier transactionID3 = nextTransactionId();
- final DataTreeModification modification3 = dataStore.newModification();
- new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
- .apply(modification3);
- modification3.ready();
- final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3, true);
- shard.tell(readyMessage, getRef());
+ final TransactionIdentifier transactionID3 = nextTransactionId();
+ final DataTreeModification modification3 = dataStore.newModification();
+ new WriteModification(TestModel.TEST2_PATH, ImmutableNodes.containerNode(TestModel.TEST2_QNAME))
+ .apply(modification3);
+ modification3.ready();
+ final ReadyLocalTransaction readyMessage = new ReadyLocalTransaction(transactionID3, modification3,
+ true);
+ shard.tell(readyMessage, getRef());
- // Commit the first Tx. After completing, the second should expire from the queue and the third
- // Tx committed.
+ // Commit the first Tx. After completing, the second should
+ // expire from the queue and the third
+ // Tx committed.
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- // Expect commit reply from the third Tx.
+ // Expect commit reply from the third Tx.
- expectMsgClass(duration, CommitTransactionReply.class);
+ expectMsgClass(duration, CommitTransactionReply.class);
- final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
- assertNotNull(TestModel.TEST2_PATH + " not found", node);
- }};
+ final NormalizedNode<?, ?> node = readStore(shard, TestModel.TEST2_PATH);
+ assertNotNull(TestModel.TEST2_PATH + " not found", node);
+ }
+ };
}
@Test
- public void testCanCommitBeforeReadyFailure() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testCanCommitBeforeReadyFailure");
-
- shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- }};
+ public void testCanCommitBeforeReadyFailure() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ "testCanCommitBeforeReadyFailure");
+
+ shard.tell(new CanCommitTransaction(nextTransactionId(), CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ }
+ };
}
@Test
- public void testAbortAfterCanCommit() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
- "testAbortAfterCanCommit");
+ public void testAbortAfterCanCommit() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterCanCommit");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
- final Timeout timeout = new Timeout(duration);
+ final FiniteDuration duration = duration("5 seconds");
+ final Timeout timeout = new Timeout(duration);
- // Ready 2 transactions - the first one will be aborted.
+ // Ready 2 transactions - the first one will be aborted.
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the CanCommitTransaction message for the first Tx.
+ // Send the CanCommitTransaction message for the first Tx.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- CanCommitTransactionReply canCommitReply = CanCommitTransactionReply.fromSerializable(
- expectMsgClass(duration, CanCommitTransactionReply.class));
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ CanCommitTransactionReply canCommitReply = CanCommitTransactionReply
+ .fromSerializable(expectMsgClass(duration, CanCommitTransactionReply.class));
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
- // Send the CanCommitTransaction message for the 2nd Tx. This should get queued and
- // processed after the first Tx completes.
+ // Send the CanCommitTransaction message for the 2nd Tx. This
+ // should get queued and
+ // processed after the first Tx completes.
- final Future<Object> canCommitFuture = Patterns.ask(shard,
- new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
+ final Future<Object> canCommitFuture = Patterns.ask(shard,
+ new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), timeout);
- // Send the AbortTransaction message for the first Tx. This should trigger the 2nd
- // Tx to proceed.
+ // Send the AbortTransaction message for the first Tx. This
+ // should trigger the 2nd
+ // Tx to proceed.
- shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, AbortTransactionReply.class);
+ shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, AbortTransactionReply.class);
- // Wait for the 2nd Tx to complete the canCommit phase.
+ // Wait for the 2nd Tx to complete the canCommit phase.
- canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
- assertEquals("Can commit", true, canCommitReply.getCanCommit());
- }};
+ canCommitReply = (CanCommitTransactionReply) Await.result(canCommitFuture, duration);
+ assertEquals("Can commit", true, canCommitReply.getCanCommit());
+ }
+ };
}
@Test
- public void testAbortAfterReady() throws Throwable {
+ public void testAbortAfterReady() throws Exception {
dataStoreContextBuilder.shardTransactionCommitTimeoutInSeconds(1);
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- final FiniteDuration duration = duration("5 seconds");
+ final FiniteDuration duration = duration("5 seconds");
- // Ready a tx.
+ // Ready a tx.
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Send the AbortTransaction message.
+ // Send the AbortTransaction message.
- shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, AbortTransactionReply.class);
+ shard.tell(new AbortTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, AbortTransactionReply.class);
- assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
+ assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
- // Now send CanCommitTransaction - should fail.
+ // Now send CanCommitTransaction - should fail.
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
- assertTrue("Failure type", failure instanceof IllegalStateException);
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ final Throwable failure = expectMsgClass(duration, akka.actor.Status.Failure.class).cause();
+ assertTrue("Failure type", failure instanceof IllegalStateException);
- // Ready and CanCommit another and verify success.
+ // Ready and CanCommit another and verify success.
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
- }};
+ shard.tell(new CanCommitTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
+ }
+ };
}
@Test
- public void testAbortQueuedTransaction() throws Throwable {
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
-
- waitUntilLeader(shard);
+ public void testAbortQueuedTransaction() throws Exception {
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()), "testAbortAfterReady");
- final FiniteDuration duration = duration("5 seconds");
+ waitUntilLeader(shard);
- // Ready 3 tx's.
+ final FiniteDuration duration = duration("5 seconds");
- final TransactionIdentifier transactionID1 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ // Ready 3 tx's.
- final TransactionIdentifier transactionID2 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
- ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID1 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- final TransactionIdentifier transactionID3 = nextTransactionId();
- shard.tell(newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1), getRef());
- expectMsgClass(duration, ReadyTransactionReply.class);
+ final TransactionIdentifier transactionID2 = nextTransactionId();
+ shard.tell(newBatchedModifications(transactionID2, TestModel.TEST_PATH,
+ ImmutableNodes.containerNode(TestModel.TEST_QNAME), true, false, 1), getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- // Abort the second tx while it's queued.
+ final TransactionIdentifier transactionID3 = nextTransactionId();
+ shard.tell(
+ newBatchedModifications(transactionID3, TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build(), true, false, 1),
+ getRef());
+ expectMsgClass(duration, ReadyTransactionReply.class);
- shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, AbortTransactionReply.class);
+ // Abort the second tx while it's queued.
- // Commit the other 2.
+ shard.tell(new AbortTransaction(transactionID2, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, AbortTransactionReply.class);
- shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
+ // Commit the other 2.
- shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CanCommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
- shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CanCommitTransactionReply.class);
+ shard.tell(new CommitTransaction(transactionID1, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
- expectMsgClass(duration, CommitTransactionReply.class);
+ shard.tell(new CanCommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CanCommitTransactionReply.class);
- assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
- }};
- }
+ shard.tell(new CommitTransaction(transactionID3, CURRENT_VERSION).toSerializable(), getRef());
+ expectMsgClass(duration, CommitTransactionReply.class);
- @Test
- public void testCreateSnapshot() throws Exception {
- testCreateSnapshot(true, "testCreateSnapshot");
+ assertEquals("getPendingTxCommitQueueSize", 0, shard.underlyingActor().getPendingTxCommitQueueSize());
+ }
+ };
}
@Test
testCreateSnapshot(false, "testCreateSnapshotWithNonPersistentData");
}
- private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception{
+ @Test
+ public void testCreateSnapshot() throws Exception {
+ testCreateSnapshot(true, "testCreateSnapshot");
+ }
+ private void testCreateSnapshot(final boolean persistent, final String shardActorName) throws Exception {
final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
final AtomicReference<Object> savedSnapshot = new AtomicReference<>();
}
@Override
- public void saveSnapshot(final Object o) {
- savedSnapshot.set(o);
- super.saveSnapshot(o);
+ public void saveSnapshot(final Object obj) {
+ savedSnapshot.set(obj);
+ super.saveSnapshot(obj);
}
}
dataStoreContextBuilder.persistent(persistent);
- new ShardTestKit(getSystem()) {{
- class TestShard extends Shard {
+ class TestShard extends Shard {
- protected TestShard(final AbstractBuilder<?, ?> builder) {
- super(builder);
- setPersistence(new TestPersistentDataProvider(super.persistence()));
- }
+ protected TestShard(final AbstractBuilder<?, ?> builder) {
+ super(builder);
+ setPersistence(new TestPersistentDataProvider(super.persistence()));
+ }
- @Override
- public void handleCommand(final Object message) {
- super.handleCommand(message);
+ @Override
+ public void handleCommand(final Object message) {
+ super.handleCommand(message);
- // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
- if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
- latch.get().countDown();
- }
+ // XXX: commit_snapshot equality check references RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT
+ if (message instanceof SaveSnapshotSuccess || "commit_snapshot".equals(message.toString())) {
+ latch.get().countDown();
}
+ }
- @Override
- public RaftActorContext getRaftActorContext() {
- return super.getRaftActorContext();
- }
+ @Override
+ public RaftActorContext getRaftActorContext() {
+ return super.getRaftActorContext();
}
+ }
- final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
+ new ShardTestKit(getSystem()) {
+ {
+ final Creator<Shard> creator = () -> new TestShard(newShardBuilder());
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- Props.create(new DelegatingShardCreator(creator)).
- withDispatcher(Dispatchers.DefaultDispatcherId()), shardActorName);
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(Props
+ .create(new DelegatingShardCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ shardActorName);
- waitUntilLeader(shard);
- writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+ waitUntilLeader(shard);
+ writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- final NormalizedNode<?,?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
+ final NormalizedNode<?, ?> expectedRoot = readStore(shard, YangInstanceIdentifier.EMPTY);
- // Trigger creation of a snapshot by ensuring
- final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
- raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
- awaitAndValidateSnapshot(expectedRoot);
+ // Trigger creation of a snapshot by ensuring
+ final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
+ raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
+ awaitAndValidateSnapshot(expectedRoot);
- raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
- awaitAndValidateSnapshot(expectedRoot);
- }
+ raftActorContext.getSnapshotManager().capture(mock(ReplicatedLogEntry.class), -1);
+ awaitAndValidateSnapshot(expectedRoot);
+ }
- private void awaitAndValidateSnapshot(final NormalizedNode<?,?> expectedRoot) throws InterruptedException, IOException {
- assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
+ private void awaitAndValidateSnapshot(final NormalizedNode<?, ?> expectedRoot)
+ throws InterruptedException, IOException {
+ assertEquals("Snapshot saved", true, latch.get().await(5, TimeUnit.SECONDS));
- assertTrue("Invalid saved snapshot " + savedSnapshot.get(),
- savedSnapshot.get() instanceof Snapshot);
+ assertTrue("Invalid saved snapshot " + savedSnapshot.get(), savedSnapshot.get() instanceof Snapshot);
- verifySnapshot((Snapshot)savedSnapshot.get(), expectedRoot);
+ verifySnapshot((Snapshot) savedSnapshot.get(), expectedRoot);
- latch.set(new CountDownLatch(1));
- savedSnapshot.set(null);
- }
+ latch.set(new CountDownLatch(1));
+ savedSnapshot.set(null);
+ }
- private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?,?> expectedRoot) throws IOException {
- final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode().get();
- assertEquals("Root node", expectedRoot, actual);
- }};
+ private void verifySnapshot(final Snapshot snapshot, final NormalizedNode<?, ?> expectedRoot)
+ throws IOException {
+ final NormalizedNode<?, ?> actual = ShardDataTreeSnapshot.deserialize(snapshot.getState()).getRootNode()
+ .get();
+ assertEquals("Root node", expectedRoot, actual);
+ }
+ };
}
/**
- * This test simply verifies that the applySnapShot logic will work
- * @throws ReadFailedException
- * @throws DataValidationFailedException
+ * This test simply verifies that the applySnapShot logic will work.
*/
@Test
public void testInMemoryDataTreeRestore() throws ReadFailedException, DataValidationFailedException {
}
@Test
- public void testRecoveryApplicable(){
+ public void testRecoveryApplicable() {
- final DatastoreContext persistentContext = DatastoreContext.newBuilder().
- shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
+ final DatastoreContext persistentContext = DatastoreContext.newBuilder()
+ .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(true).build();
- final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext).
- schemaContext(SCHEMA_CONTEXT).props();
+ final Props persistentProps = Shard.builder().id(shardID).datastoreContext(persistentContext)
+ .schemaContext(SCHEMA_CONTEXT).props();
- final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder().
- shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
+ final DatastoreContext nonPersistentContext = DatastoreContext.newBuilder()
+ .shardJournalRecoveryLogBatchSize(3).shardSnapshotBatchCount(5000).persistent(false).build();
- final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext).
- schemaContext(SCHEMA_CONTEXT).props();
+ final Props nonPersistentProps = Shard.builder().id(shardID).datastoreContext(nonPersistentContext)
+ .schemaContext(SCHEMA_CONTEXT).props();
- new ShardTestKit(getSystem()) {{
- final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
+ new ShardTestKit(getSystem()) {
+ {
+ final TestActorRef<Shard> shard1 = actorFactory.createTestActor(persistentProps, "testPersistence1");
- assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
+ assertTrue("Recovery Applicable", shard1.underlyingActor().persistence().isRecoveryApplicable());
- final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
+ final TestActorRef<Shard> shard2 = actorFactory.createTestActor(nonPersistentProps, "testPersistence2");
- assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
- }};
+ assertFalse("Recovery Not Applicable", shard2.underlyingActor().persistence().isRecoveryApplicable());
+ }
+ };
}
@Test
public void testOnDatastoreContext() {
- new ShardTestKit(getSystem()) {{
- dataStoreContextBuilder.persistent(true);
+ new ShardTestKit(getSystem()) {
+ {
+ dataStoreContextBuilder.persistent(true);
- final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(), "testOnDatastoreContext");
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(newShardProps(),
+ "testOnDatastoreContext");
- assertEquals("isRecoveryApplicable", true,
- shard.underlyingActor().persistence().isRecoveryApplicable());
+ assertEquals("isRecoveryApplicable", true,
+ shard.underlyingActor().persistence().isRecoveryApplicable());
- waitUntilLeader(shard);
+ waitUntilLeader(shard);
- shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
+ shard.tell(dataStoreContextBuilder.persistent(false).build(), ActorRef.noSender());
- assertEquals("isRecoveryApplicable", false,
- shard.underlyingActor().persistence().isRecoveryApplicable());
+ assertEquals("isRecoveryApplicable", false,
+ shard.underlyingActor().persistence().isRecoveryApplicable());
- shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
+ shard.tell(dataStoreContextBuilder.persistent(true).build(), ActorRef.noSender());
- assertEquals("isRecoveryApplicable", true,
- shard.underlyingActor().persistence().isRecoveryApplicable());
- }};
+ assertEquals("isRecoveryApplicable", true,
+ shard.underlyingActor().persistence().isRecoveryApplicable());
+ }
+ };
}
@Test
newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
"testFollowerInitialSyncStatus");
- shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false, "member-1-shard-inventory-operational"));
+ shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(false,
+ "member-1-shard-inventory-operational"));
assertEquals(false, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
- shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true, "member-1-shard-inventory-operational"));
+ shard.underlyingActor().handleNonRaftCommand(new FollowerInitialSyncUpStatus(true,
+ "member-1-shard-inventory-operational"));
assertEquals(true, shard.underlyingActor().getShardMBean().getFollowerInitialSyncStatus());
}
@Test
public void testClusteredDataChangeListenerDelayedRegistration() throws Exception {
- new ShardTestKit(getSystem()) {{
- final String testName = "testClusteredDataChangeListenerDelayedRegistration";
- dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
- customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
+ new ShardTestKit(getSystem()) {
+ {
+ final String testName = "testClusteredDataChangeListenerDelayedRegistration";
+ dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
+ .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
- final MockDataChangeListener listener = new MockDataChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
- actorFactory.generateActorId(testName + "-DataChangeListener"));
+ final MockDataChangeListener listener = new MockDataChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
+ actorFactory.generateActorId(testName + "-DataChangeListener"));
- setupInMemorySnapshotStore();
+ setupInMemorySnapshotStore();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- actorFactory.generateActorId(testName + "-shard"));
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ actorFactory.generateActorId(testName + "-shard"));
- waitUntilNoLeader(shard);
+ waitUntilNoLeader(shard);
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
- shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
- final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
- RegisterChangeListenerReply.class);
- assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
+ shard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
+ getRef());
+ final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
+ RegisterChangeListenerReply.class);
+ assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
- shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
- customRaftPolicyImplementation(null).build(), ActorRef.noSender());
+ shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
+ .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
- listener.waitForChangeEvents();
- }};
+ listener.waitForChangeEvents();
+ }
+ };
}
@Test
public void testClusteredDataChangeListenerRegistration() throws Exception {
- new ShardTestKit(getSystem()) {{
- final String testName = "testClusteredDataChangeListenerRegistration";
- final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
- MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
-
- final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
- MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
-
- final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
- Shard.builder().id(followerShardID).
- datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
- peerAddresses(Collections.singletonMap(leaderShardID.toString(),
- "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
-
- final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
- Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
- peerAddresses(Collections.singletonMap(followerShardID.toString(),
- "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
-
- leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
- final String leaderPath = waitUntilLeader(followerShard);
- assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
-
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
- final MockDataChangeListener listener = new MockDataChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
- actorFactory.generateActorId(testName + "-DataChangeListener"));
-
- followerShard.tell(new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true), getRef());
- final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
- RegisterChangeListenerReply.class);
- assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
-
- writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- listener.waitForChangeEvents();
- }};
+ new ShardTestKit(getSystem()) {
+ {
+ final String testName = "testClusteredDataChangeListenerRegistration";
+ final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
+ MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
+
+ final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
+ MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
+
+ final TestActorRef<Shard> followerShard = actorFactory
+ .createTestActor(Shard.builder().id(followerShardID)
+ .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
+ .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
+ "akka://test/user/" + leaderShardID.toString()))
+ .schemaContext(SCHEMA_CONTEXT).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
+
+ final TestActorRef<Shard> leaderShard = actorFactory
+ .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
+ .peerAddresses(Collections.singletonMap(followerShardID.toString(),
+ "akka://test/user/" + followerShardID.toString()))
+ .schemaContext(SCHEMA_CONTEXT).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
+
+ leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
+ final String leaderPath = waitUntilLeader(followerShard);
+ assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
+
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ final MockDataChangeListener listener = new MockDataChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener),
+ actorFactory.generateActorId(testName + "-DataChangeListener"));
+
+ followerShard.tell(
+ new RegisterChangeListener(path, dclActor, AsyncDataBroker.DataChangeScope.BASE, true),
+ getRef());
+ final RegisterChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
+ RegisterChangeListenerReply.class);
+ assertNotNull("getListenerRegistratioznPath", reply.getListenerRegistrationPath());
+
+ writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+
+ listener.waitForChangeEvents();
+ }
+ };
}
@Test
public void testClusteredDataTreeChangeListenerDelayedRegistration() throws Exception {
- new ShardTestKit(getSystem()) {{
- final String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
- dataStoreContextBuilder.shardElectionTimeoutFactor(1000).
- customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
+ new ShardTestKit(getSystem()) {
+ {
+ final String testName = "testClusteredDataTreeChangeListenerDelayedRegistration";
+ dataStoreContextBuilder.shardElectionTimeoutFactor(1000)
+ .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
- final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
- actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
+ final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
+ actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
- setupInMemorySnapshotStore();
+ setupInMemorySnapshotStore();
- final TestActorRef<Shard> shard = actorFactory.createTestActor(
- newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- actorFactory.generateActorId(testName + "-shard"));
+ final TestActorRef<Shard> shard = actorFactory.createTestActor(
+ newShardBuilder().props().withDispatcher(Dispatchers.DefaultDispatcherId()),
+ actorFactory.generateActorId(testName + "-shard"));
- waitUntilNoLeader(shard);
+ waitUntilNoLeader(shard);
- shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
- final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
- RegisterDataTreeChangeListenerReply.class);
- assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
+ shard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
+ final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
+ RegisterDataTreeChangeListenerReply.class);
+ assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
- shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
- customRaftPolicyImplementation(null).build(), ActorRef.noSender());
+ shard.tell(DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
+ .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
- listener.waitForChangeEvents();
- }};
+ listener.waitForChangeEvents();
+ }
+ };
}
@Test
public void testClusteredDataTreeChangeListenerRegistration() throws Exception {
- new ShardTestKit(getSystem()) {{
- final String testName = "testClusteredDataTreeChangeListenerRegistration";
- final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
- MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
-
- final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
- MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
-
- final TestActorRef<Shard> followerShard = actorFactory.createTestActor(
- Shard.builder().id(followerShardID).
- datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build()).
- peerAddresses(Collections.singletonMap(leaderShardID.toString(),
- "akka://test/user/" + leaderShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
-
- final TestActorRef<Shard> leaderShard = actorFactory.createTestActor(
- Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext()).
- peerAddresses(Collections.singletonMap(followerShardID.toString(),
- "akka://test/user/" + followerShardID.toString())).schemaContext(SCHEMA_CONTEXT).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
-
- leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
- final String leaderPath = waitUntilLeader(followerShard);
- assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
-
- final YangInstanceIdentifier path = TestModel.TEST_PATH;
- final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
- final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
- actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
-
- followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
- final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
- RegisterDataTreeChangeListenerReply.class);
- assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
-
- writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- listener.waitForChangeEvents();
- }};
+ new ShardTestKit(getSystem()) {
+ {
+ final String testName = "testClusteredDataTreeChangeListenerRegistration";
+ final ShardIdentifier followerShardID = ShardIdentifier.create("inventory",
+ MemberName.forName(actorFactory.generateActorId(testName + "-follower")), "config");
+
+ final ShardIdentifier leaderShardID = ShardIdentifier.create("inventory",
+ MemberName.forName(actorFactory.generateActorId(testName + "-leader")), "config");
+
+ final TestActorRef<Shard> followerShard = actorFactory
+ .createTestActor(Shard.builder().id(followerShardID)
+ .datastoreContext(dataStoreContextBuilder.shardElectionTimeoutFactor(1000).build())
+ .peerAddresses(Collections.singletonMap(leaderShardID.toString(),
+ "akka://test/user/" + leaderShardID.toString()))
+ .schemaContext(SCHEMA_CONTEXT).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()), followerShardID.toString());
+
+ final TestActorRef<Shard> leaderShard = actorFactory
+ .createTestActor(Shard.builder().id(leaderShardID).datastoreContext(newDatastoreContext())
+ .peerAddresses(Collections.singletonMap(followerShardID.toString(),
+ "akka://test/user/" + followerShardID.toString()))
+ .schemaContext(SCHEMA_CONTEXT).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()), leaderShardID.toString());
+
+ leaderShard.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
+ final String leaderPath = waitUntilLeader(followerShard);
+ assertEquals("Shard leader path", leaderShard.path().toString(), leaderPath);
+
+ final YangInstanceIdentifier path = TestModel.TEST_PATH;
+ final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
+ final ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener),
+ actorFactory.generateActorId(testName + "-DataTreeChangeListener"));
+
+ followerShard.tell(new RegisterDataTreeChangeListener(TestModel.TEST_PATH, dclActor, true), getRef());
+ final RegisterDataTreeChangeListenerReply reply = expectMsgClass(duration("5 seconds"),
+ RegisterDataTreeChangeListenerReply.class);
+ assertNotNull("getListenerRegistrationPath", reply.getListenerRegistrationPath());
+
+ writeToStore(followerShard, path, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+
+ listener.waitForChangeEvents();
+ }
+ };
}
@Test
super(actorSystem);
}
- public void waitForLogMessage(final Class<?> logLevel, ActorRef subject, String logMessage){
+ public void waitForLogMessage(final Class<?> logLevel, ActorRef subject, String logMessage) {
// Wait for a specific log message to show up
final boolean result =
new JavaTestKit.EventFilter<Boolean>(logLevel
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static String waitUntilLeader(ActorRef shard) {
FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS);
- for(int i = 0; i < 20 * 5; i++) {
+ for (int i = 0; i < 20 * 5; i++) {
Future<Object> future = Patterns.ask(shard, FindLeader.INSTANCE, new Timeout(duration));
try {
- final Optional<String> maybeLeader = ((FindLeaderReply)Await.result(future, duration)).getLeaderActor();
+ final Optional<String> maybeLeader = ((FindLeaderReply) Await.result(future, duration))
+ .getLeaderActor();
if (maybeLeader.isPresent()) {
return maybeLeader.get();
}
- } catch(TimeoutException e) {
+ } catch (TimeoutException e) {
LOG.trace("FindLeader timed out", e);
- } catch(Exception e) {
+ } catch (Exception e) {
LOG.error("FindLeader failed", e);
}
return null;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void waitUntilNoLeader(ActorRef shard) {
FiniteDuration duration = Duration.create(100, TimeUnit.MILLISECONDS);
Object lastResponse = null;
- for(int i = 0; i < 20 * 5; i++) {
+ for (int i = 0; i < 20 * 5; i++) {
Future<Object> future = Patterns.ask(shard, FindLeader.INSTANCE, new Timeout(duration));
try {
- final Optional<String> maybeLeader = ((FindLeaderReply)Await.result(future, duration)).getLeaderActor();
+ final Optional<String> maybeLeader = ((FindLeaderReply) Await.result(future, duration))
+ .getLeaderActor();
if (!maybeLeader.isPresent()) {
return;
}
lastResponse = maybeLeader.get();
- } catch(TimeoutException e) {
+ } catch (TimeoutException e) {
lastResponse = e;
- } catch(Exception e) {
+ } catch (Exception e) {
LOG.error("FindLeader failed", e);
lastResponse = e;
}
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
}
- if(lastResponse instanceof Throwable) {
+ if (lastResponse instanceof Throwable) {
throw (AssertionError)new AssertionError(
- String.format("Unexpected error occurred from FindLeader for shard %s", shard.path())).
- initCause((Throwable)lastResponse);
+ String.format("Unexpected error occurred from FindLeader for shard %s", shard.path()))
+ .initCause((Throwable)lastResponse);
}
Assert.fail(String.format("Unexpected leader %s found for shard %s", lastResponse, shard.path()));
}
-}
\ No newline at end of file
+}
import scala.concurrent.duration.Duration;
/**
- * Covers negative test cases
+ * Covers negative test cases.
*
- * @author Basheeruddin Ahmed <syedbahm@cisco.com>
+ * @author Basheeruddin Ahmed
*/
public class ShardTransactionFailureTest extends AbstractActorTest {
- private static final SchemaContext testSchemaContext =
- TestModel.createTestContext();
+ private static final SchemaContext TEST_SCHEMA_CONTEXT = TestModel.createTestContext();
private static final TransactionType RO = TransactionType.READ_ONLY;
private static final TransactionType RW = TransactionType.READ_WRITE;
- private static final TransactionType WO = TransactionType.WRITE_ONLY;
- private static final Shard mockShard = Mockito.mock(Shard.class);
+ private static final Shard MOCK_SHARD = Mockito.mock(Shard.class);
- private static final ShardDataTree store = new ShardDataTree(mockShard, testSchemaContext, TreeType.OPERATIONAL);
+ private static final ShardDataTree STORE = new ShardDataTree(MOCK_SHARD, TEST_SCHEMA_CONTEXT, TreeType.OPERATIONAL);
private static final ShardIdentifier SHARD_IDENTIFIER =
ShardIdentifier.create("inventory", MemberName.forName("member-1"), "operational");
private final ShardStats shardStats = new ShardStats(SHARD_IDENTIFIER.toString(), "DataStore");
- private ActorRef createShard(){
- ActorRef shard = getSystem().actorOf(Shard.builder().id(SHARD_IDENTIFIER).datastoreContext(datastoreContext).
- schemaContext(TestModel.createTestContext()).props());
+ private ActorRef createShard() {
+ ActorRef shard = getSystem().actorOf(Shard.builder().id(SHARD_IDENTIFIER).datastoreContext(datastoreContext)
+ .schemaContext(TestModel.createTestContext()).props());
ShardTestKit.waitUntilLeader(shard);
return shard;
}
@Test(expected = ReadFailedException.class)
- public void testNegativeReadWithReadOnlyTransactionClosed() throws Throwable {
+ public void testNegativeReadWithReadOnlyTransactionClosed() throws Exception {
final ActorRef shard = createShard();
- final Props props = ShardTransaction.props(RO, store.newReadOnlyTransaction(nextTransactionId()), shard,
+ final Props props = ShardTransaction.props(RO, STORE.newReadOnlyTransaction(nextTransactionId()), shard,
datastoreContext, shardStats);
final TestActorRef<ShardTransaction> subject = TestActorRef.create(getSystem(), props,
@Test(expected = ReadFailedException.class)
- public void testNegativeReadWithReadWriteTransactionClosed() throws Throwable {
+ public void testNegativeReadWithReadWriteTransactionClosed() throws Exception {
final ActorRef shard = createShard();
- final Props props = ShardTransaction.props(RW, store.newReadWriteTransaction(nextTransactionId()), shard,
+ final Props props = ShardTransaction.props(RW, STORE.newReadWriteTransaction(nextTransactionId()), shard,
datastoreContext, shardStats);
final TestActorRef<ShardTransaction> subject = TestActorRef.create(getSystem(), props,
}
@Test(expected = ReadFailedException.class)
- public void testNegativeExistsWithReadWriteTransactionClosed() throws Throwable {
+ public void testNegativeExistsWithReadWriteTransactionClosed() throws Exception {
final ActorRef shard = createShard();
- final Props props = ShardTransaction.props(RW, store.newReadWriteTransaction(nextTransactionId()), shard,
+ final Props props = ShardTransaction.props(RW, STORE.newReadWriteTransaction(nextTransactionId()), shard,
datastoreContext, shardStats);
final TestActorRef<ShardTransaction> subject = TestActorRef.create(getSystem(), props,
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
+
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.Status.Failure;
import akka.dispatch.Dispatchers;
import akka.testkit.JavaTestKit;
import akka.testkit.TestActorRef;
+import com.google.common.base.Throwables;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
@Before
public void setUp() {
- shard = actorFactory.createTestActor(Shard.builder().id(SHARD_IDENTIFIER).datastoreContext(datastoreContext).
- schemaContext(TestModel.createTestContext()).props().withDispatcher(Dispatchers.DefaultDispatcherId()));
+ shard = actorFactory.createTestActor(Shard.builder().id(SHARD_IDENTIFIER).datastoreContext(datastoreContext)
+ .schemaContext(TestModel.createTestContext()).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()));
ShardTestKit.waitUntilLeader(shard);
store = shard.underlyingActor().getDataStore();
}
- private ActorRef newTransactionActor(final TransactionType type, final AbstractShardDataTreeTransaction<?> transaction, final String name) {
- Props props = ShardTransaction.props(type, transaction, shard, datastoreContext, shard.underlyingActor().getShardMBean());
+ private ActorRef newTransactionActor(final TransactionType type,
+ final AbstractShardDataTreeTransaction<?> transaction, final String name) {
+ Props props = ShardTransaction.props(type, transaction, shard, datastoreContext,
+ shard.underlyingActor().getShardMBean());
return actorFactory.createActor(props, name);
}
@Test
public void testOnReceiveReadData() throws Exception {
- new JavaTestKit(getSystem()) {{
- testOnReceiveReadData(newTransactionActor(RO, readOnlyTransaction(), "testReadDataRO"));
+ new JavaTestKit(getSystem()) {
+ {
+ testOnReceiveReadData(newTransactionActor(RO, readOnlyTransaction(), "testReadDataRO"));
- testOnReceiveReadData(newTransactionActor(RW, readWriteTransaction(), "testReadDataRW"));
- }
+ testOnReceiveReadData(newTransactionActor(RW, readWriteTransaction(), "testReadDataRW"));
+ }
- private void testOnReceiveReadData(final ActorRef transaction) {
- transaction.tell(new ReadData(YangInstanceIdentifier.EMPTY,
- DataStoreVersions.CURRENT_VERSION), getRef());
+ private void testOnReceiveReadData(final ActorRef transaction) {
+ transaction.tell(new ReadData(YangInstanceIdentifier.EMPTY, DataStoreVersions.CURRENT_VERSION),
+ getRef());
- ReadDataReply reply = expectMsgClass(duration("5 seconds"), ReadDataReply.class);
+ ReadDataReply reply = expectMsgClass(duration("5 seconds"), ReadDataReply.class);
- assertNotNull(reply.getNormalizedNode());
- }};
+ assertNotNull(reply.getNormalizedNode());
+ }
+ };
}
@Test
public void testOnReceiveReadDataWhenDataNotFound() throws Exception {
- new JavaTestKit(getSystem()) {{
- testOnReceiveReadDataWhenDataNotFound(newTransactionActor(
- RO, readOnlyTransaction(), "testReadDataWhenDataNotFoundRO"));
+ new JavaTestKit(getSystem()) {
+ {
+ testOnReceiveReadDataWhenDataNotFound(
+ newTransactionActor(RO, readOnlyTransaction(), "testReadDataWhenDataNotFoundRO"));
- testOnReceiveReadDataWhenDataNotFound(newTransactionActor(
- RW, readWriteTransaction(), "testReadDataWhenDataNotFoundRW"));
- }
+ testOnReceiveReadDataWhenDataNotFound(
+ newTransactionActor(RW, readWriteTransaction(), "testReadDataWhenDataNotFoundRW"));
+ }
- private void testOnReceiveReadDataWhenDataNotFound(final ActorRef transaction) {
- transaction.tell(new ReadData(TestModel.TEST_PATH, DataStoreVersions.CURRENT_VERSION),getRef());
+ private void testOnReceiveReadDataWhenDataNotFound(final ActorRef transaction) {
+ transaction.tell(new ReadData(TestModel.TEST_PATH, DataStoreVersions.CURRENT_VERSION), getRef());
- ReadDataReply reply = expectMsgClass(duration("5 seconds"), ReadDataReply.class);
+ ReadDataReply reply = expectMsgClass(duration("5 seconds"), ReadDataReply.class);
- assertTrue(reply.getNormalizedNode() == null);
- }};
+ assertTrue(reply.getNormalizedNode() == null);
+ }
+ };
}
@Test
public void testOnReceiveDataExistsPositive() throws Exception {
- new JavaTestKit(getSystem()) {{
- testOnReceiveDataExistsPositive(newTransactionActor(RO, readOnlyTransaction(),
- "testDataExistsPositiveRO"));
+ new JavaTestKit(getSystem()) {
+ {
+ testOnReceiveDataExistsPositive(
+ newTransactionActor(RO, readOnlyTransaction(), "testDataExistsPositiveRO"));
- testOnReceiveDataExistsPositive(newTransactionActor(RW, readWriteTransaction(),
- "testDataExistsPositiveRW"));
- }
+ testOnReceiveDataExistsPositive(
+ newTransactionActor(RW, readWriteTransaction(), "testDataExistsPositiveRW"));
+ }
- private void testOnReceiveDataExistsPositive(final ActorRef transaction) {
- transaction.tell(new DataExists(YangInstanceIdentifier.EMPTY,
- DataStoreVersions.CURRENT_VERSION), getRef());
+ private void testOnReceiveDataExistsPositive(final ActorRef transaction) {
+ transaction.tell(new DataExists(YangInstanceIdentifier.EMPTY, DataStoreVersions.CURRENT_VERSION),
+ getRef());
- DataExistsReply reply = expectMsgClass(duration("5 seconds"), DataExistsReply.class);
+ DataExistsReply reply = expectMsgClass(duration("5 seconds"), DataExistsReply.class);
- assertTrue(reply.exists());
- }};
+ assertTrue(reply.exists());
+ }
+ };
}
@Test
public void testOnReceiveDataExistsNegative() throws Exception {
- new JavaTestKit(getSystem()) {{
- testOnReceiveDataExistsNegative(newTransactionActor(RO, readOnlyTransaction(),
- "testDataExistsNegativeRO"));
+ new JavaTestKit(getSystem()) {
+ {
+ testOnReceiveDataExistsNegative(
+ newTransactionActor(RO, readOnlyTransaction(), "testDataExistsNegativeRO"));
- testOnReceiveDataExistsNegative(newTransactionActor(RW, readWriteTransaction(),
- "testDataExistsNegativeRW"));
- }
+ testOnReceiveDataExistsNegative(
+ newTransactionActor(RW, readWriteTransaction(), "testDataExistsNegativeRW"));
+ }
- private void testOnReceiveDataExistsNegative(final ActorRef transaction) {
- transaction.tell(new DataExists(TestModel.TEST_PATH, DataStoreVersions.CURRENT_VERSION),getRef());
+ private void testOnReceiveDataExistsNegative(final ActorRef transaction) {
+ transaction.tell(new DataExists(TestModel.TEST_PATH, DataStoreVersions.CURRENT_VERSION), getRef());
- DataExistsReply reply = expectMsgClass(duration("5 seconds"), DataExistsReply.class);
+ DataExistsReply reply = expectMsgClass(duration("5 seconds"), DataExistsReply.class);
- assertFalse(reply.exists());
- }};
+ assertFalse(reply.exists());
+ }
+ };
}
@Test
public void testOnReceiveBatchedModifications() throws Exception {
- new JavaTestKit(getSystem()) {{
-
- ShardDataTreeTransactionParent parent = Mockito.mock(ShardDataTreeTransactionParent.class);
- DataTreeModification mockModification = Mockito.mock(DataTreeModification.class);
- ReadWriteShardDataTreeTransaction mockWriteTx = new ReadWriteShardDataTreeTransaction(parent,
- nextTransactionId(), mockModification);
- final ActorRef transaction = newTransactionActor(RW, mockWriteTx, "testOnReceiveBatchedModifications");
-
- YangInstanceIdentifier writePath = TestModel.TEST_PATH;
- NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
-
- YangInstanceIdentifier mergePath = TestModel.OUTER_LIST_PATH;
- NormalizedNode<?, ?> mergeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.OUTER_LIST_QNAME)).build();
-
- YangInstanceIdentifier deletePath = TestModel.TEST_PATH;
-
- BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
- batched.addModification(new WriteModification(writePath, writeData));
- batched.addModification(new MergeModification(mergePath, mergeData));
- batched.addModification(new DeleteModification(deletePath));
-
- transaction.tell(batched, getRef());
-
- BatchedModificationsReply reply = expectMsgClass(duration("5 seconds"), BatchedModificationsReply.class);
- assertEquals("getNumBatched", 3, reply.getNumBatched());
-
- InOrder inOrder = Mockito.inOrder(mockModification);
- inOrder.verify(mockModification).write(writePath, writeData);
- inOrder.verify(mockModification).merge(mergePath, mergeData);
- inOrder.verify(mockModification).delete(deletePath);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ ShardDataTreeTransactionParent parent = Mockito.mock(ShardDataTreeTransactionParent.class);
+ DataTreeModification mockModification = Mockito.mock(DataTreeModification.class);
+ ReadWriteShardDataTreeTransaction mockWriteTx = new ReadWriteShardDataTreeTransaction(parent,
+ nextTransactionId(), mockModification);
+ final ActorRef transaction = newTransactionActor(RW, mockWriteTx, "testOnReceiveBatchedModifications");
+
+ YangInstanceIdentifier writePath = TestModel.TEST_PATH;
+ NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+
+ YangInstanceIdentifier mergePath = TestModel.OUTER_LIST_PATH;
+ NormalizedNode<?, ?> mergeData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.OUTER_LIST_QNAME))
+ .build();
+
+ YangInstanceIdentifier deletePath = TestModel.TEST_PATH;
+
+ BatchedModifications batched = new BatchedModifications(nextTransactionId(),
+ DataStoreVersions.CURRENT_VERSION);
+ batched.addModification(new WriteModification(writePath, writeData));
+ batched.addModification(new MergeModification(mergePath, mergeData));
+ batched.addModification(new DeleteModification(deletePath));
+
+ transaction.tell(batched, getRef());
+
+ BatchedModificationsReply reply = expectMsgClass(duration("5 seconds"),
+ BatchedModificationsReply.class);
+ assertEquals("getNumBatched", 3, reply.getNumBatched());
+
+ InOrder inOrder = Mockito.inOrder(mockModification);
+ inOrder.verify(mockModification).write(writePath, writeData);
+ inOrder.verify(mockModification).merge(mergePath, mergeData);
+ inOrder.verify(mockModification).delete(deletePath);
+ }
+ };
}
@Test
public void testOnReceiveBatchedModificationsReadyWithoutImmediateCommit() throws Exception {
- new JavaTestKit(getSystem()) {{
-
- final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
- "testOnReceiveBatchedModificationsReadyWithoutImmediateCommit");
-
- JavaTestKit watcher = new JavaTestKit(getSystem());
- watcher.watch(transaction);
-
- YangInstanceIdentifier writePath = TestModel.TEST_PATH;
- NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
-
- final TransactionIdentifier tx1 = nextTransactionId();
- BatchedModifications batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
- batched.addModification(new WriteModification(writePath, writeData));
-
- transaction.tell(batched, getRef());
- BatchedModificationsReply reply = expectMsgClass(duration("5 seconds"), BatchedModificationsReply.class);
- assertEquals("getNumBatched", 1, reply.getNumBatched());
-
- batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
- batched.setReady(true);
- batched.setTotalMessagesSent(2);
-
- transaction.tell(batched, getRef());
- expectMsgClass(duration("5 seconds"), ReadyTransactionReply.class);
- watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
+ "testOnReceiveBatchedModificationsReadyWithoutImmediateCommit");
+
+ JavaTestKit watcher = new JavaTestKit(getSystem());
+ watcher.watch(transaction);
+
+ YangInstanceIdentifier writePath = TestModel.TEST_PATH;
+ NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+
+ final TransactionIdentifier tx1 = nextTransactionId();
+ BatchedModifications batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
+ batched.addModification(new WriteModification(writePath, writeData));
+
+ transaction.tell(batched, getRef());
+ BatchedModificationsReply reply = expectMsgClass(duration("5 seconds"),
+ BatchedModificationsReply.class);
+ assertEquals("getNumBatched", 1, reply.getNumBatched());
+
+ batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
+ batched.setReady(true);
+ batched.setTotalMessagesSent(2);
+
+ transaction.tell(batched, getRef());
+ expectMsgClass(duration("5 seconds"), ReadyTransactionReply.class);
+ watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
+ }
+ };
}
@Test
public void testOnReceiveBatchedModificationsReadyWithImmediateCommit() throws Exception {
- new JavaTestKit(getSystem()) {{
-
- final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
- "testOnReceiveBatchedModificationsReadyWithImmediateCommit");
-
- JavaTestKit watcher = new JavaTestKit(getSystem());
- watcher.watch(transaction);
-
- YangInstanceIdentifier writePath = TestModel.TEST_PATH;
- NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
-
- BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
- batched.addModification(new WriteModification(writePath, writeData));
- batched.setReady(true);
- batched.setDoCommitOnReady(true);
- batched.setTotalMessagesSent(1);
-
- transaction.tell(batched, getRef());
- expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
- watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
+ "testOnReceiveBatchedModificationsReadyWithImmediateCommit");
+
+ JavaTestKit watcher = new JavaTestKit(getSystem());
+ watcher.watch(transaction);
+
+ YangInstanceIdentifier writePath = TestModel.TEST_PATH;
+ NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+
+ BatchedModifications batched = new BatchedModifications(nextTransactionId(),
+ DataStoreVersions.CURRENT_VERSION);
+ batched.addModification(new WriteModification(writePath, writeData));
+ batched.setReady(true);
+ batched.setDoCommitOnReady(true);
+ batched.setTotalMessagesSent(1);
+
+ transaction.tell(batched, getRef());
+ expectMsgClass(duration("5 seconds"), CommitTransactionReply.class);
+ watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
+ }
+ };
}
- @Test(expected=TestException.class)
- public void testOnReceiveBatchedModificationsFailure() throws Throwable {
- new JavaTestKit(getSystem()) {{
+ @Test(expected = TestException.class)
+ public void testOnReceiveBatchedModificationsFailure() throws Exception {
+ new JavaTestKit(getSystem()) {
+ {
- ShardDataTreeTransactionParent parent = Mockito.mock(ShardDataTreeTransactionParent.class);
- DataTreeModification mockModification = Mockito.mock(DataTreeModification.class);
- ReadWriteShardDataTreeTransaction mockWriteTx = new ReadWriteShardDataTreeTransaction(parent,
- nextTransactionId(), mockModification);
- final ActorRef transaction = newTransactionActor(RW, mockWriteTx,
- "testOnReceiveBatchedModificationsFailure");
+ ShardDataTreeTransactionParent parent = Mockito.mock(ShardDataTreeTransactionParent.class);
+ DataTreeModification mockModification = Mockito.mock(DataTreeModification.class);
+ ReadWriteShardDataTreeTransaction mockWriteTx = new ReadWriteShardDataTreeTransaction(parent,
+ nextTransactionId(), mockModification);
+ final ActorRef transaction = newTransactionActor(RW, mockWriteTx,
+ "testOnReceiveBatchedModificationsFailure");
- JavaTestKit watcher = new JavaTestKit(getSystem());
- watcher.watch(transaction);
+ JavaTestKit watcher = new JavaTestKit(getSystem());
+ watcher.watch(transaction);
- YangInstanceIdentifier path = TestModel.TEST_PATH;
- ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ YangInstanceIdentifier path = TestModel.TEST_PATH;
+ ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- doThrow(new TestException()).when(mockModification).write(path, node);
+ doThrow(new TestException()).when(mockModification).write(path, node);
- final TransactionIdentifier tx1 = nextTransactionId();
- BatchedModifications batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
- batched.addModification(new WriteModification(path, node));
+ final TransactionIdentifier tx1 = nextTransactionId();
+ BatchedModifications batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
+ batched.addModification(new WriteModification(path, node));
- transaction.tell(batched, getRef());
- expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ transaction.tell(batched, getRef());
+ expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
- batched.setReady(true);
- batched.setTotalMessagesSent(2);
+ batched = new BatchedModifications(tx1, DataStoreVersions.CURRENT_VERSION);
+ batched.setReady(true);
+ batched.setTotalMessagesSent(2);
- transaction.tell(batched, getRef());
- Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
+ transaction.tell(batched, getRef());
+ Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
- if(failure != null) {
- throw failure.cause();
+ if (failure != null) {
+ Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
+ Throwables.propagate(failure.cause());
+ }
}
- }};
+ };
}
- @Test(expected=IllegalStateException.class)
- public void testOnReceiveBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Throwable {
- new JavaTestKit(getSystem()) {{
+ @Test(expected = IllegalStateException.class)
+ public void testOnReceiveBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
+ new JavaTestKit(getSystem()) {
+ {
- final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
- "testOnReceiveBatchedModificationsReadyWithIncorrectTotalMessageCount");
+ final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
+ "testOnReceiveBatchedModificationsReadyWithIncorrectTotalMessageCount");
- JavaTestKit watcher = new JavaTestKit(getSystem());
- watcher.watch(transaction);
+ JavaTestKit watcher = new JavaTestKit(getSystem());
+ watcher.watch(transaction);
- BatchedModifications batched = new BatchedModifications(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
- batched.setReady(true);
- batched.setTotalMessagesSent(2);
+ BatchedModifications batched = new BatchedModifications(nextTransactionId(),
+ DataStoreVersions.CURRENT_VERSION);
+ batched.setReady(true);
+ batched.setTotalMessagesSent(2);
- transaction.tell(batched, getRef());
+ transaction.tell(batched, getRef());
- Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
- watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
+ Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class);
+ watcher.expectMsgClass(duration("5 seconds"), Terminated.class);
- if(failure != null) {
- throw failure.cause();
+ if (failure != null) {
+ Throwables.propagateIfInstanceOf(failure.cause(), Exception.class);
+ Throwables.propagate(failure.cause());
+ }
}
- }};
+ };
}
@Test
public void testReadWriteTxOnReceiveCloseTransaction() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef transaction = newTransactionActor(RW, readWriteTransaction(),
- "testReadWriteTxOnReceiveCloseTransaction");
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef transaction = newTransactionActor(RW, readWriteTransaction(),
+ "testReadWriteTxOnReceiveCloseTransaction");
- watch(transaction);
+ watch(transaction);
- transaction.tell(new CloseTransaction().toSerializable(), getRef());
+ transaction.tell(new CloseTransaction().toSerializable(), getRef());
- expectMsgClass(duration("3 seconds"), CloseTransactionReply.class);
- expectTerminated(duration("3 seconds"), transaction);
- }};
+ expectMsgClass(duration("3 seconds"), CloseTransactionReply.class);
+ expectTerminated(duration("3 seconds"), transaction);
+ }
+ };
}
@Test
public void testWriteOnlyTxOnReceiveCloseTransaction() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
- "testWriteTxOnReceiveCloseTransaction");
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef transaction = newTransactionActor(WO, readWriteTransaction(),
+ "testWriteTxOnReceiveCloseTransaction");
- watch(transaction);
+ watch(transaction);
- transaction.tell(new CloseTransaction().toSerializable(), getRef());
+ transaction.tell(new CloseTransaction().toSerializable(), getRef());
- expectMsgClass(duration("3 seconds"), CloseTransactionReply.class);
- expectTerminated(duration("3 seconds"), transaction);
- }};
+ expectMsgClass(duration("3 seconds"), CloseTransactionReply.class);
+ expectTerminated(duration("3 seconds"), transaction);
+ }
+ };
}
@Test
public void testReadOnlyTxOnReceiveCloseTransaction() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef transaction = newTransactionActor(TransactionType.READ_ONLY, readOnlyTransaction(),
- "testReadOnlyTxOnReceiveCloseTransaction");
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef transaction = newTransactionActor(TransactionType.READ_ONLY, readOnlyTransaction(),
+ "testReadOnlyTxOnReceiveCloseTransaction");
- watch(transaction);
+ watch(transaction);
- transaction.tell(new CloseTransaction().toSerializable(), getRef());
+ transaction.tell(new CloseTransaction().toSerializable(), getRef());
- expectMsgClass(duration("3 seconds"), Terminated.class);
- }};
+ expectMsgClass(duration("3 seconds"), Terminated.class);
+ }
+ };
}
@Test
public void testShardTransactionInactivity() {
-
datastoreContext = DatastoreContext.newBuilder().shardTransactionIdleTimeout(
500, TimeUnit.MILLISECONDS).build();
- new JavaTestKit(getSystem()) {{
- final ActorRef transaction = newTransactionActor(RW, readWriteTransaction(),
- "testShardTransactionInactivity");
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef transaction = newTransactionActor(RW, readWriteTransaction(),
+ "testShardTransactionInactivity");
- watch(transaction);
+ watch(transaction);
- expectMsgClass(duration("3 seconds"), Terminated.class);
- }};
+ expectMsgClass(duration("3 seconds"), Terminated.class);
+ }
+ };
}
+
public static class TestException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+
import com.google.common.primitives.UnsignedLong;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
}).when(mockShardDataTree).startCommit(cohort, candidate);
@SuppressWarnings("unchecked")
- final
- FutureCallback<UnsignedLong> mockCommitCallback = mock(FutureCallback.class);
+ final FutureCallback<UnsignedLong> mockCommitCallback = mock(FutureCallback.class);
cohort.commit(mockCommitCallback);
verify(mockCommitCallback).onSuccess(any(UnsignedLong.class));
}
@Test
- public void testPreCommitWithIllegalArgumentEx() throws Throwable {
+ public void testPreCommitWithIllegalArgumentEx() throws Exception {
canCommitSuccess();
final Exception cause = new IllegalArgumentException("mock");
}
@Test
- public void testPreCommitWithReportedFailure() throws Throwable {
+ public void testPreCommitWithReportedFailure() throws Exception {
canCommitSuccess();
final Exception cause = new IllegalArgumentException("mock");
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.opendaylight.controller.cluster.datastore.DataStoreVersions.CURRENT_VERSION;
+
import akka.actor.ActorSelection;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
+import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.Arrays;
MockitoAnnotations.initMocks(this);
actorContext = new ActorContext(getSystem(), actorFactory.createActor(Props.create(DoNothingActor.class)),
- new MockClusterWrapper(), new MockConfiguration(),
- DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache()) {
- @Override
- public Timer getOperationTimer(String operationName) {
- return commitTimer;
- }
-
- @Override
- public double getTxCreationLimit() {
- return 10.0;
- }
- };
+ new MockClusterWrapper(), new MockConfiguration(), DatastoreContext.newBuilder().build(),
+ new PrimaryShardInfoFutureCache()) {
+ @Override
+ public Timer getOperationTimer(String operationName) {
+ return commitTimer;
+ }
+
+ @Override
+ public double getTxCreationLimit() {
+ return 10.0;
+ }
+ };
doReturn(commitTimerContext).when(commitTimer).time();
doReturn(commitSnapshot).when(commitTimer).getSnapshot();
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(i) * 1D).when(commitSnapshot).getValue(i * 0.1);
}
@Test(expected = TestException.class)
- public void testCanCommitWithExceptionFailure() throws Throwable {
+ public void testCanCommitWithExceptionFailure() throws Exception {
ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext, Arrays.asList(
newCohortInfo(new CohortActor.Builder(tx).expectCanCommit(new TestException()))), tx);
}
@Test(expected = IllegalArgumentException.class)
- public void testCanCommitWithInvalidResponseType() throws Throwable {
+ public void testCanCommitWithInvalidResponseType() throws Exception {
ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext, Arrays.asList(
newCohortInfo(new CohortActor.Builder(tx).expectCanCommit("invalid"))), tx);
}
@Test(expected = TestException.class)
- public void testCanCommitWithFailedCohortFuture() throws Throwable {
+ public void testCanCommitWithFailedCohortFuture() throws Exception {
List<CohortInfo> cohorts = Arrays.asList(
newCohortInfo(new CohortActor.Builder(tx)),
newCohortInfoWithFailedFuture(new TestException()),
@Test
public void testAllThreePhasesSuccessful() throws Exception {
List<CohortInfo> cohorts = Arrays.asList(
- newCohortInfo(new CohortActor.Builder(tx).
- expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION)).
- expectCommit(CommitTransactionReply.instance(CURRENT_VERSION))),
- newCohortInfo(new CohortActor.Builder(tx).
- expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION)).
- expectCommit(CommitTransactionReply.instance(CURRENT_VERSION))));
+ newCohortInfo(
+ new CohortActor.Builder(tx).expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION))
+ .expectCommit(CommitTransactionReply.instance(CURRENT_VERSION))),
+ newCohortInfo(
+ new CohortActor.Builder(tx).expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION))
+ .expectCommit(CommitTransactionReply.instance(CURRENT_VERSION))));
ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext, cohorts, tx);
verifyCanCommit(proxy.canCommit(), true);
}
@Test(expected = TestException.class)
- public void testCommitWithExceptionFailure() throws Throwable {
+ public void testCommitWithExceptionFailure() throws Exception {
List<CohortInfo> cohorts = Arrays.asList(
- newCohortInfo(new CohortActor.Builder(tx).
- expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION)).
- expectCommit(CommitTransactionReply.instance(CURRENT_VERSION))),
- newCohortInfo(new CohortActor.Builder(tx).
- expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION)).
- expectCommit(new TestException())));
+ newCohortInfo(
+ new CohortActor.Builder(tx).expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION))
+ .expectCommit(CommitTransactionReply.instance(CURRENT_VERSION))),
+ newCohortInfo(
+ new CohortActor.Builder(tx).expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION))
+ .expectCommit(new TestException())));
ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext, cohorts, tx);
verifyCanCommit(proxy.canCommit(), true);
}
@Test(expected = IllegalArgumentException.class)
- public void testCommitWithInvalidResponseType() throws Throwable {
- ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext, Arrays.asList(
- newCohortInfo(new CohortActor.Builder(tx).
- expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION)).
- expectCommit("invalid"))), tx);
+ public void testCommitWithInvalidResponseType() throws Exception {
+ ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext,
+ Arrays.asList(newCohortInfo(new CohortActor.Builder(tx)
+ .expectCanCommit(CanCommitTransactionReply.yes(CURRENT_VERSION)).expectCommit("invalid"))), tx);
verifyCanCommit(proxy.canCommit(), true);
verifySuccessfulFuture(proxy.preCommit());
}
@Test
- public void testAbortWithFailedCohortFuture() throws Throwable {
+ public void testAbortWithFailedCohortFuture() throws Exception {
List<CohortInfo> cohorts = Arrays.asList(
newCohortInfoWithFailedFuture(new TestException()), newCohortInfo(new CohortActor.Builder(tx)));
ThreePhaseCommitCohortProxy proxy = new ThreePhaseCommitCohortProxy(actorContext, cohorts, tx);
verifyCohortActors();
}
- private void propagateExecutionExceptionCause(ListenableFuture<?> future) throws Throwable {
+ private void propagateExecutionExceptionCause(ListenableFuture<?> future) throws Exception {
try {
future.get(5, TimeUnit.SECONDS);
fail("Expected ExecutionException");
- } catch(ExecutionException e) {
+ } catch (ExecutionException e) {
verifyCohortActors();
- throw e.getCause();
+ Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
+ Throwables.propagate(e.getCause());
}
}
private CohortInfo newCohortInfo(CohortActor.Builder builder, final short version) {
- TestActorRef<CohortActor> actor = actorFactory.createTestActor(builder.props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId("cohort"));
+ TestActorRef<CohortActor> actor = actorFactory.createTestActor(builder.props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId("cohort"));
cohortActors.add(actor);
- return new CohortInfo(Futures.successful(getSystem().actorSelection(actor.path())), new Supplier<Short>() {
- @Override
- public Short get() {
- return version;
- }
- });
- }
-
- private static CohortInfo newCohortInfoWithFailedFuture(Exception failure) {
- return new CohortInfo(Futures.<ActorSelection>failed(failure), new Supplier<Short>() {
- @Override
- public Short get() {
- return CURRENT_VERSION;
- }
- });
+ return new CohortInfo(Futures.successful(getSystem().actorSelection(actor.path())), () -> version);
}
private CohortInfo newCohortInfo(CohortActor.Builder builder) {
return newCohortInfo(builder, CURRENT_VERSION);
}
+ private static CohortInfo newCohortInfoWithFailedFuture(Exception failure) {
+ return new CohortInfo(Futures.<ActorSelection>failed(failure), () -> CURRENT_VERSION);
+ }
+
private void verifyCohortActors() {
- for(TestActorRef<CohortActor> actor: cohortActors) {
+ for (TestActorRef<CohortActor> actor: cohortActors) {
actor.underlyingActor().verify();
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private <T> T verifySuccessfulFuture(ListenableFuture<T> future) throws Exception {
try {
return future.get(5, TimeUnit.SECONDS);
- } catch(Exception e) {
+ } catch (Exception e) {
verifyCohortActors();
throw e;
}
@Override
public void onReceive(Object message) {
- if(CanCommitTransaction.isSerializedType(message)) {
+ if (CanCommitTransaction.isSerializedType(message)) {
canCommitCount.incrementAndGet();
onMessage("CanCommitTransaction", message, CanCommitTransaction.fromSerializable(message),
builder.expCanCommitType, builder.canCommitReply);
- } else if(CommitTransaction.isSerializedType(message)) {
+ } else if (CommitTransaction.isSerializedType(message)) {
commitCount.incrementAndGet();
onMessage("CommitTransaction", message, CommitTransaction.fromSerializable(message),
builder.expCommitType, builder.commitReply);
- } else if(AbortTransaction.isSerializedType(message)) {
+ } else if (AbortTransaction.isSerializedType(message)) {
abortCount.incrementAndGet();
onMessage("AbortTransaction", message, AbortTransaction.fromSerializable(message),
builder.expAbortType, builder.abortReply);
assertEquals(name + " type", expType, rawMessage.getClass());
assertEquals(name + " transactionId", builder.transactionId, actualMessage.getTransactionID());
- if(reply instanceof Throwable) {
+ if (reply instanceof Throwable) {
getSender().tell(new akka.actor.Status.Failure((Throwable)reply), self());
} else {
getSender().tell(reply, self());
}
- } catch(AssertionError e) {
+ } catch (AssertionError e) {
assertionError = e;
}
}
void verify() {
- if(assertionError != null) {
+ if (assertionError != null) {
throw assertionError;
}
- if(builder.expCanCommitType != null) {
+ if (builder.expCanCommitType != null) {
assertEquals("CanCommitTransaction count", 1, canCommitCount.get());
}
- if(builder.expCommitType != null) {
+ if (builder.expCommitType != null) {
assertEquals("CommitTransaction count", 1, commitCount.get());
}
- if(builder.expAbortType != null) {
+ if (builder.expAbortType != null) {
assertEquals("AbortTransaction count", 1, abortCount.get());
}
}
this.transactionId = Preconditions.checkNotNull(transactionId);
}
- Builder expectCanCommit(Class<?> expCanCommitType, Object canCommitReply) {
- this.expCanCommitType = expCanCommitType;
- this.canCommitReply = canCommitReply;
+ Builder expectCanCommit(Class<?> newExpCanCommitType, Object newCanCommitReply) {
+ this.expCanCommitType = newExpCanCommitType;
+ this.canCommitReply = newCanCommitReply;
return this;
}
- Builder expectCanCommit(Object canCommitReply) {
- return expectCanCommit(CanCommitTransaction.class, canCommitReply);
+ Builder expectCanCommit(Object newCanCommitReply) {
+ return expectCanCommit(CanCommitTransaction.class, newCanCommitReply);
}
- Builder expectCommit(Class<?> expCommitType, Object commitReply) {
- this.expCommitType = expCommitType;
- this.commitReply = commitReply;
+ Builder expectCommit(Class<?> newExpCommitType, Object newCommitReply) {
+ this.expCommitType = newExpCommitType;
+ this.commitReply = newCommitReply;
return this;
}
- Builder expectCommit(Object commitReply) {
- return expectCommit(CommitTransaction.class, commitReply);
+ Builder expectCommit(Object newCommitReply) {
+ return expectCommit(CommitTransaction.class, newCommitReply);
}
- Builder expectAbort(Class<?> expAbortType, Object abortReply) {
- this.expAbortType = expAbortType;
- this.abortReply = abortReply;
+ Builder expectAbort(Class<?> newExpAbortType, Object newAbortReply) {
+ this.expAbortType = newExpAbortType;
+ this.abortReply = newAbortReply;
return this;
}
- Builder expectAbort(Object abortReply) {
- return expectAbort(AbortTransaction.class, abortReply);
+ Builder expectAbort(Object newAbortReply) {
+ return expectAbort(AbortTransaction.class, newAbortReply);
}
Props props() {
import static org.mockito.Mockito.verify;
import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
+
import akka.actor.ActorRef;
import akka.util.Timeout;
import java.util.concurrent.CountDownLatch;
}
+ @SuppressWarnings("unchecked")
@Test
public void testClose() {
new TransactionChainProxy(mockComponentFactory, historyId).close();
* initiated until the first one completes its read future.
*/
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void testChainedWriteOnlyTransactions() throws Exception {
dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
* initiated until the first one completes its read future.
*/
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void testChainedReadWriteTransactions() throws Exception {
try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
NormalizedNode<?, ?> writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
writeTx1.write(TestModel.TEST_PATH, writeNode1);
- NormalizedNode<?, ?> writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
-
txChainProxy.newWriteOnlyTransaction();
}
}
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
private TransactionContextWrapper transactionContextWrapper;
@Before
- public void setUp(){
+ public void setUp() {
MockitoAnnotations.initMocks(this);
doReturn(DatastoreContext.newBuilder().build()).when(actorContext).getDatastoreContext();
transactionContextWrapper = new TransactionContextWrapper(MockIdentifiers.transactionIdentifier(
}
@Test
- public void testExecutePriorTransactionOperations(){
- for(int i=0;i<100;i++) {
+ public void testExecutePriorTransactionOperations() {
+ for (int i = 0; i < 100; i++) {
transactionContextWrapper.maybeExecuteTransactionOperation(mock(TransactionOperation.class));
}
assertEquals(901, transactionContextWrapper.getLimiter().availablePermits());
assertEquals(1001, transactionContextWrapper.getLimiter().availablePermits());
}
-}
\ No newline at end of file
+}
import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_ONLY;
import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
+
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import akka.dispatch.Futures;
import akka.util.Timeout;
import com.google.common.base.Optional;
+import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
public void testReadWithInvalidReplyMessageType() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
- doReturn(Futures.successful(new Object())).when(mockActorContext).
- executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
+ doReturn(Futures.successful(new Object())).when(mockActorContext)
+ .executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
}
@Test(expected = TestException.class)
- public void testReadWithAsyncRemoteOperatonFailure() throws Throwable {
+ public void testReadWithAsyncRemoteOperatonFailure() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
- doReturn(Futures.failed(new TestException())).when(mockActorContext).
- executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
+ doReturn(Futures.failed(new TestException())).when(mockActorContext)
+ .executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH));
}
- private void testExceptionOnInitialCreateTransaction(Exception exToThrow, Invoker invoker)
- throws Throwable {
+ private void testExceptionOnInitialCreateTransaction(Exception exToThrow, Invoker invoker) throws Exception {
ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
if (exToThrow instanceof PrimaryNotFoundException) {
doReturn(Futures.failed(exToThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
} else {
- doReturn(primaryShardInfoReply(getSystem(), actorRef)).
- when(mockActorContext).findPrimaryShardAsync(anyString());
+ doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
+ .findPrimaryShardAsync(anyString());
}
doReturn(Futures.failed(exToThrow)).when(mockActorContext).executeOperationAsync(
propagateReadFailedExceptionCause(invoker.invoke(transactionProxy));
}
- private void testReadWithExceptionOnInitialCreateTransaction(Exception exToThrow) throws Throwable {
- testExceptionOnInitialCreateTransaction(exToThrow, new Invoker() {
- @Override
- public CheckedFuture<?, ReadFailedException> invoke(TransactionProxy proxy) throws Exception {
- return proxy.read(TestModel.TEST_PATH);
- }
- });
+ private void testReadWithExceptionOnInitialCreateTransaction(Exception exToThrow) throws Exception {
+ testExceptionOnInitialCreateTransaction(exToThrow, proxy -> proxy.read(TestModel.TEST_PATH));
}
@Test(expected = PrimaryNotFoundException.class)
- public void testReadWhenAPrimaryNotFoundExceptionIsThrown() throws Throwable {
+ public void testReadWhenAPrimaryNotFoundExceptionIsThrown() throws Exception {
testReadWithExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"));
}
@Test(expected = TimeoutException.class)
- public void testReadWhenATimeoutExceptionIsThrown() throws Throwable {
+ public void testReadWhenATimeoutExceptionIsThrown() throws Exception {
testReadWithExceptionOnInitialCreateTransaction(new TimeoutException("test",
new Exception("reason")));
}
@Test(expected = TestException.class)
- public void testReadWhenAnyOtherExceptionIsThrown() throws Throwable {
+ public void testReadWhenAnyOtherExceptionIsThrown() throws Exception {
testReadWithExceptionOnInitialCreateTransaction(new TestException());
}
@Test
- public void testReadWithPriorRecordingOperationSuccessful() throws Throwable {
+ public void testReadWithPriorRecordingOperationSuccessful() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
NormalizedNode<?, ?> expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
}
- @Test(expected=IllegalStateException.class)
+ @Test(expected = IllegalStateException.class)
public void testReadPreConditionCheck() {
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
transactionProxy.read(TestModel.TEST_PATH);
}
- @Test(expected=IllegalArgumentException.class)
- public void testInvalidCreateTransactionReply() throws Throwable {
+ @Test(expected = IllegalArgumentException.class)
+ public void testInvalidCreateTransactionReply() throws Exception {
ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
- doReturn(getSystem().actorSelection(actorRef.path())).when(mockActorContext).
- actorSelection(actorRef.path().toString());
+ doReturn(getSystem().actorSelection(actorRef.path())).when(mockActorContext)
+ .actorSelection(actorRef.path().toString());
- doReturn(primaryShardInfoReply(getSystem(), actorRef)).
- when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
eq(getSystem().actorSelection(actorRef.path())), eqCreateTransaction(memberName, READ_ONLY),
}
@Test(expected = PrimaryNotFoundException.class)
- public void testExistsWhenAPrimaryNotFoundExceptionIsThrown() throws Throwable {
- testExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"), new Invoker() {
- @Override
- public CheckedFuture<?, ReadFailedException> invoke(TransactionProxy proxy) throws Exception {
- return proxy.exists(TestModel.TEST_PATH);
- }
- });
+ public void testExistsWhenAPrimaryNotFoundExceptionIsThrown() throws Exception {
+ testExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"),
+ proxy -> proxy.exists(TestModel.TEST_PATH));
}
@Test(expected = ReadFailedException.class)
public void testExistsWithInvalidReplyMessageType() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
- doReturn(Futures.successful(new Object())).when(mockActorContext).
- executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
+ doReturn(Futures.successful(new Object())).when(mockActorContext)
+ .executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
}
@Test(expected = TestException.class)
- public void testExistsWithAsyncRemoteOperatonFailure() throws Throwable {
+ public void testExistsWithAsyncRemoteOperatonFailure() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
- doReturn(Futures.failed(new TestException())).when(mockActorContext).
- executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
+ doReturn(Futures.failed(new TestException())).when(mockActorContext)
+ .executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
}
@Test
- public void testExistsWithPriorRecordingOperationSuccessful() throws Throwable {
+ public void testExistsWithPriorRecordingOperationSuccessful() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
}
- @Test(expected=IllegalStateException.class)
+ @Test(expected = IllegalStateException.class)
public void testExistsPreConditionCheck() {
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
transactionProxy.exists(TestModel.TEST_PATH);
}
@Test
- public void testWriteAfterAsyncRead() throws Throwable {
- ActorRef actorRef = setupActorContextWithoutInitialCreateTransaction(getSystem(), DefaultShardStrategy.DEFAULT_SHARD);
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public void testWriteAfterAsyncRead() throws Exception {
+ ActorRef actorRef = setupActorContextWithoutInitialCreateTransaction(getSystem(),
+ DefaultShardStrategy.DEFAULT_SHARD);
Promise<Object> createTxPromise = akka.dispatch.Futures.promise();
doReturn(createTxPromise).when(mockActorContext).executeOperationAsync(
}
@Override
- public void onFailure(Throwable t) {
- caughtEx.set(t);
+ public void onFailure(Throwable failure) {
+ caughtEx.set(failure);
readComplete.countDown();
}
});
Uninterruptibles.awaitUninterruptibly(readComplete, 5, TimeUnit.SECONDS);
- if(caughtEx.get() != null) {
- throw caughtEx.get();
+ if (caughtEx.get() != null) {
+ Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class);
+ Throwables.propagate(caughtEx.get());
}
// This sends the batched modification.
verifyOneBatchedModification(actorRef, new WriteModification(TestModel.TEST_PATH, nodeToWrite), true);
}
- @Test(expected=IllegalStateException.class)
+ @Test(expected = IllegalStateException.class)
public void testWritePreConditionCheck() {
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
}
- @Test(expected=IllegalStateException.class)
+ @Test(expected = IllegalStateException.class)
public void testWriteAfterReadyPreConditionCheck() {
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
public void testReadWrite() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ final NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
public void testReadyWithReadWrite() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ final NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
public void testReadyWithLocalTransaction() throws Exception {
ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
- doReturn(getSystem().actorSelection(shardActorRef.path())).
- when(mockActorContext).actorSelection(shardActorRef.path().toString());
+ doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
+ .actorSelection(shardActorRef.path().toString());
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, createDataTree()))).
- when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, createDataTree()))).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
public void testReadyWithLocalTransactionWithFailure() throws Exception {
ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
- doReturn(getSystem().actorSelection(shardActorRef.path())).
- when(mockActorContext).actorSelection(shardActorRef.path().toString());
+ doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
+ .actorSelection(shardActorRef.path().toString());
DataTree mockDataTree = createDataTree();
DataTreeModification mockModification = mockDataTree.takeSnapshot().newModification();
doThrow(new RuntimeException("mock")).when(mockModification).ready();
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, mockDataTree))).
- when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, mockDataTree))).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
ActorRef actorRef2 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY, "junk");
- doReturn(Futures.successful(new Object())).when(mockActorContext).
- executeOperationAsync(eq(actorSelection(actorRef1)), isA(BatchedModifications.class),
- any(Timeout.class));
+ doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
+ eq(actorSelection(actorRef1)), isA(BatchedModifications.class), any(Timeout.class));
expectBatchedModificationsReady(actorRef2);
}
@Test
- public void testClose() throws Exception{
+ public void testClose() throws Exception {
ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
void run(TransactionProxy transactionProxy);
}
- private void throttleOperation(TransactionProxyOperation operation) {
- throttleOperation(operation, 1, true);
- }
-
- private void throttleOperation(TransactionProxyOperation operation, int outstandingOpsLimit, boolean shardFound){
- throttleOperation(operation, outstandingOpsLimit, shardFound, TimeUnit.MILLISECONDS.toNanos(
- mockActorContext.getDatastoreContext().getOperationTimeoutInMillis()));
- }
-
- private PrimaryShardInfo newPrimaryShardInfo(ActorRef actorRef){
+ private PrimaryShardInfo newPrimaryShardInfo(ActorRef actorRef) {
return new PrimaryShardInfo(getSystem().actorSelection(actorRef.path()), DataStoreVersions.CURRENT_VERSION);
}
- private PrimaryShardInfo newPrimaryShardInfo(ActorRef actorRef, DataTree dataTree){
+ private PrimaryShardInfo newPrimaryShardInfo(ActorRef actorRef, DataTree dataTree) {
return new PrimaryShardInfo(getSystem().actorSelection(actorRef.path()), DataStoreVersions.CURRENT_VERSION,
dataTree);
}
+ private void throttleOperation(TransactionProxyOperation operation) {
+ throttleOperation(operation, 1, true);
+ }
+
+ private void throttleOperation(TransactionProxyOperation operation, int outstandingOpsLimit, boolean shardFound) {
+ throttleOperation(operation, outstandingOpsLimit, shardFound, TimeUnit.MILLISECONDS.toNanos(
+ mockActorContext.getDatastoreContext().getOperationTimeoutInMillis()));
+ }
- private void throttleOperation(TransactionProxyOperation operation, int outstandingOpsLimit, boolean shardFound, long expectedCompletionTime){
+ private void throttleOperation(TransactionProxyOperation operation, int outstandingOpsLimit, boolean shardFound,
+ long expectedCompletionTime) {
ActorSystem actorSystem = getSystem();
ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
// Note that we setting batchedModificationCount to one less than what we need because in TransactionProxy
// we now allow one extra permit to be allowed for ready
- doReturn(dataStoreContextBuilder.operationTimeoutInSeconds(2).
- shardBatchedModificationCount(outstandingOpsLimit-1).build()).when(mockActorContext).getDatastoreContext();
+ doReturn(dataStoreContextBuilder.operationTimeoutInSeconds(2)
+ .shardBatchedModificationCount(outstandingOpsLimit - 1).build()).when(mockActorContext)
+ .getDatastoreContext();
- doReturn(actorSystem.actorSelection(shardActorRef.path())).
- when(mockActorContext).actorSelection(shardActorRef.path().toString());
+ doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
+ .actorSelection(shardActorRef.path().toString());
- if(shardFound) {
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).
- when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).
- when(mockActorContext).findPrimaryShardAsync(eq("cars"));
+ if (shardFound) {
+ doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
+ .findPrimaryShardAsync(eq("cars"));
} else {
doReturn(Futures.failed(new Exception("not found")))
.when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
}
- String actorPath = "akka.tcp://system@127.0.0.1:2550/user/tx-actor";
-
- doReturn(incompleteFuture()).when(mockActorContext).
- executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
- eqCreateTransaction(memberName, READ_WRITE), any(Timeout.class));
+ doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
+ eq(actorSystem.actorSelection(shardActorRef.path())), eqCreateTransaction(memberName, READ_WRITE),
+ any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
long end = System.nanoTime();
Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
- expectedCompletionTime, (end-start)),
- ((end - start) > expectedCompletionTime) && ((end - start) < expectedCompletionTime*2));
+ expectedCompletionTime, end - start),
+ end - start > expectedCompletionTime && end - start < expectedCompletionTime * 2);
}
- private void completeOperation(TransactionProxyOperation operation){
+ private void completeOperation(TransactionProxyOperation operation) {
completeOperation(operation, true);
}
- private void completeOperation(TransactionProxyOperation operation, boolean shardFound){
+ private void completeOperation(TransactionProxyOperation operation, boolean shardFound) {
ActorSystem actorSystem = getSystem();
ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
- doReturn(actorSystem.actorSelection(shardActorRef.path())).
- when(mockActorContext).actorSelection(shardActorRef.path().toString());
+ doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
+ .actorSelection(shardActorRef.path().toString());
- if(shardFound) {
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).
- when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ if (shardFound) {
+ doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
} else {
- doReturn(Futures.failed(new PrimaryNotFoundException("test")))
- .when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ doReturn(Futures.failed(new PrimaryNotFoundException("test"))).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
}
ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
doReturn(actorSystem.actorSelection(actorPath)).when(mockActorContext).actorSelection(actorPath);
- doReturn(Futures.successful(createTransactionReply)).when(mockActorContext).
- executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
- eqCreateTransaction(memberName, READ_WRITE), any(Timeout.class));
+ doReturn(Futures.successful(createTransactionReply)).when(mockActorContext).executeOperationAsync(
+ eq(actorSystem.actorSelection(shardActorRef.path())), eqCreateTransaction(memberName, READ_WRITE),
+ any(Timeout.class));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
long end = System.nanoTime();
- long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext().getOperationTimeoutInMillis());
+ long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
+ .getOperationTimeoutInMillis());
Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
- expected, (end-start)), (end - start) <= expected);
+ expected, end - start), end - start <= expected);
}
- private void completeOperationLocal(TransactionProxyOperation operation, DataTree dataTree){
+ private void completeOperationLocal(TransactionProxyOperation operation, DataTree dataTree) {
ActorSystem actorSystem = getSystem();
ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
- doReturn(actorSystem.actorSelection(shardActorRef.path())).
- when(mockActorContext).actorSelection(shardActorRef.path().toString());
+ doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
+ .actorSelection(shardActorRef.path().toString());
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, dataTree))).
- when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
+ doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, dataTree))).when(mockActorContext)
+ .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
long end = System.nanoTime();
- long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext().getOperationTimeoutInMillis());
- Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
- expected, (end-start)), (end - start) <= expected);
+ long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
+ .getOperationTimeoutInMillis());
+ Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s", expected, end - start),
+ end - start <= expected);
}
- private static DataTree createDataTree(){
+ private static DataTree createDataTree() {
DataTree dataTree = mock(DataTree.class);
DataTreeSnapshot dataTreeSnapshot = mock(DataTreeSnapshot.class);
DataTreeModification dataTreeModification = mock(DataTreeModification.class);
return dataTree;
}
- private static DataTree createDataTree(NormalizedNode<?, ?> readResponse){
+ private static DataTree createDataTree(NormalizedNode<?, ?> readResponse) {
DataTree dataTree = mock(DataTree.class);
DataTreeSnapshot dataTreeSnapshot = mock(DataTreeSnapshot.class);
DataTreeModification dataTreeModification = mock(DataTreeModification.class);
@Test
- public void testWriteCompletionForLocalShard(){
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testWriteCompletionForLocalShard() {
+ completeOperationLocal(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- }
}, createDataTree());
}
@Test
- public void testWriteThrottlingWhenShardFound(){
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testWriteThrottlingWhenShardFound() {
+ throttleOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectIncompleteBatchedModifications();
+ expectIncompleteBatchedModifications();
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- }
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
});
}
@Test
- public void testWriteThrottlingWhenShardNotFound(){
+ public void testWriteThrottlingWhenShardNotFound() {
// Confirm that there is no throttling when the Shard is not found
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ completeOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectBatchedModifications(2);
+ expectBatchedModifications(2);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- }
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
}, false);
}
@Test
- public void testWriteCompletion(){
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testWriteCompletion() {
+ completeOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectBatchedModifications(2);
+ expectBatchedModifications(2);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- }
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
});
}
@Test
- public void testMergeThrottlingWhenShardFound(){
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testMergeThrottlingWhenShardFound() {
+ throttleOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectIncompleteBatchedModifications();
+ expectIncompleteBatchedModifications();
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- }
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
});
}
@Test
- public void testMergeThrottlingWhenShardNotFound(){
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testMergeThrottlingWhenShardNotFound() {
+ completeOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectBatchedModifications(2);
+ expectBatchedModifications(2);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- }
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
}, false);
}
@Test
- public void testMergeCompletion(){
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testMergeCompletion() {
+ completeOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectBatchedModifications(2);
+ expectBatchedModifications(2);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- }
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
});
}
@Test
- public void testMergeCompletionForLocalShard(){
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testMergeCompletionForLocalShard() {
+ completeOperationLocal(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
- }
}, createDataTree());
}
@Test
- public void testDeleteThrottlingWhenShardFound(){
+ public void testDeleteThrottlingWhenShardFound() {
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- expectIncompleteBatchedModifications();
+ throttleOperation(transactionProxy -> {
+ expectIncompleteBatchedModifications();
- transactionProxy.delete(TestModel.TEST_PATH);
+ transactionProxy.delete(TestModel.TEST_PATH);
- transactionProxy.delete(TestModel.TEST_PATH);
- }
+ transactionProxy.delete(TestModel.TEST_PATH);
});
}
@Test
- public void testDeleteThrottlingWhenShardNotFound(){
+ public void testDeleteThrottlingWhenShardNotFound() {
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- expectBatchedModifications(2);
+ completeOperation(transactionProxy -> {
+ expectBatchedModifications(2);
- transactionProxy.delete(TestModel.TEST_PATH);
+ transactionProxy.delete(TestModel.TEST_PATH);
- transactionProxy.delete(TestModel.TEST_PATH);
- }
+ transactionProxy.delete(TestModel.TEST_PATH);
}, false);
}
@Test
- public void testDeleteCompletionForLocalShard(){
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
+ public void testDeleteCompletionForLocalShard() {
+ completeOperationLocal(transactionProxy -> {
- transactionProxy.delete(TestModel.TEST_PATH);
+ transactionProxy.delete(TestModel.TEST_PATH);
- transactionProxy.delete(TestModel.TEST_PATH);
- }
+ transactionProxy.delete(TestModel.TEST_PATH);
}, createDataTree());
}
@Test
- public void testDeleteCompletion(){
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- expectBatchedModifications(2);
+ public void testDeleteCompletion() {
+ completeOperation(transactionProxy -> {
+ expectBatchedModifications(2);
- transactionProxy.delete(TestModel.TEST_PATH);
+ transactionProxy.delete(TestModel.TEST_PATH);
- transactionProxy.delete(TestModel.TEST_PATH);
- }
+ transactionProxy.delete(TestModel.TEST_PATH);
});
}
@Test
- public void testReadThrottlingWhenShardFound(){
+ public void testReadThrottlingWhenShardFound() {
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqReadData());
+ throttleOperation(transactionProxy -> {
+ doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), eqReadData());
- transactionProxy.read(TestModel.TEST_PATH);
+ transactionProxy.read(TestModel.TEST_PATH);
- transactionProxy.read(TestModel.TEST_PATH);
- }
+ transactionProxy.read(TestModel.TEST_PATH);
});
}
@Test
- public void testReadThrottlingWhenShardNotFound(){
+ public void testReadThrottlingWhenShardNotFound() {
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqReadData());
+ completeOperation(transactionProxy -> {
+ doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), eqReadData());
- transactionProxy.read(TestModel.TEST_PATH);
+ transactionProxy.read(TestModel.TEST_PATH);
- transactionProxy.read(TestModel.TEST_PATH);
- }
+ transactionProxy.read(TestModel.TEST_PATH);
}, false);
}
@Test
- public void testReadCompletion(){
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ public void testReadCompletion() {
+ completeOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- doReturn(readDataReply(nodeToRead)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqReadData(), any(Timeout.class));
+ doReturn(readDataReply(nodeToRead)).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), eqReadData(), any(Timeout.class));
- transactionProxy.read(TestModel.TEST_PATH);
+ transactionProxy.read(TestModel.TEST_PATH);
- transactionProxy.read(TestModel.TEST_PATH);
- }
+ transactionProxy.read(TestModel.TEST_PATH);
});
}
@Test
- public void testReadCompletionForLocalShard(){
+ public void testReadCompletionForLocalShard() {
final NormalizedNode<?, ?> nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- transactionProxy.read(TestModel.TEST_PATH);
+ completeOperationLocal(transactionProxy -> {
+ transactionProxy.read(TestModel.TEST_PATH);
- transactionProxy.read(TestModel.TEST_PATH);
- }
+ transactionProxy.read(TestModel.TEST_PATH);
}, createDataTree(nodeToRead));
}
@Test
- public void testReadCompletionForLocalShardWhenExceptionOccurs(){
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
- }
+ public void testReadCompletionForLocalShardWhenExceptionOccurs() {
+ completeOperationLocal(transactionProxy -> {
+ transactionProxy.read(TestModel.TEST_PATH);
+
+ transactionProxy.read(TestModel.TEST_PATH);
}, createDataTree());
}
@Test
- public void testExistsThrottlingWhenShardFound(){
+ public void testExistsThrottlingWhenShardFound() {
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqDataExists());
+ throttleOperation(transactionProxy -> {
+ doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), eqDataExists());
- transactionProxy.exists(TestModel.TEST_PATH);
+ transactionProxy.exists(TestModel.TEST_PATH);
- transactionProxy.exists(TestModel.TEST_PATH);
- }
+ transactionProxy.exists(TestModel.TEST_PATH);
});
}
@Test
- public void testExistsThrottlingWhenShardNotFound(){
+ public void testExistsThrottlingWhenShardNotFound() {
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqDataExists());
+ completeOperation(transactionProxy -> {
+ doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), eqDataExists());
- transactionProxy.exists(TestModel.TEST_PATH);
+ transactionProxy.exists(TestModel.TEST_PATH);
- transactionProxy.exists(TestModel.TEST_PATH);
- }
+ transactionProxy.exists(TestModel.TEST_PATH);
}, false);
}
@Test
- public void testExistsCompletion(){
- completeOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqDataExists(), any(Timeout.class));
+ public void testExistsCompletion() {
+ completeOperation(transactionProxy -> {
+ doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
+ any(ActorSelection.class), eqDataExists(), any(Timeout.class));
- transactionProxy.exists(TestModel.TEST_PATH);
+ transactionProxy.exists(TestModel.TEST_PATH);
- transactionProxy.exists(TestModel.TEST_PATH);
- }
+ transactionProxy.exists(TestModel.TEST_PATH);
});
}
@Test
- public void testExistsCompletionForLocalShard(){
+ public void testExistsCompletionForLocalShard() {
final NormalizedNode<?, ?> nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- transactionProxy.exists(TestModel.TEST_PATH);
+ completeOperationLocal(transactionProxy -> {
+ transactionProxy.exists(TestModel.TEST_PATH);
- transactionProxy.exists(TestModel.TEST_PATH);
- }
+ transactionProxy.exists(TestModel.TEST_PATH);
}, createDataTree(nodeToRead));
}
@Test
- public void testExistsCompletionForLocalShardWhenExceptionOccurs(){
- completeOperationLocal(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- transactionProxy.exists(TestModel.TEST_PATH);
-
- transactionProxy.exists(TestModel.TEST_PATH);
- }
+ public void testExistsCompletionForLocalShardWhenExceptionOccurs() {
+ completeOperationLocal(transactionProxy -> {
+ transactionProxy.exists(TestModel.TEST_PATH);
+
+ transactionProxy.exists(TestModel.TEST_PATH);
}, createDataTree());
}
+
@Test
- public void testReadyThrottling(){
+ public void testReadyThrottling() {
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ throttleOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- expectBatchedModifications(1);
+ expectBatchedModifications(1);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- transactionProxy.ready();
- }
+ transactionProxy.ready();
});
}
@Test
- public void testReadyThrottlingWithTwoTransactionContexts(){
- throttleOperation(new TransactionProxyOperation() {
- @Override
- public void run(TransactionProxy transactionProxy) {
- NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- NormalizedNode<?, ?> carsNode = ImmutableNodes.containerNode(CarsModel.BASE_QNAME);
+ public void testReadyThrottlingWithTwoTransactionContexts() {
+ throttleOperation(transactionProxy -> {
+ NormalizedNode<?, ?> nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ NormalizedNode<?, ?> carsNode = ImmutableNodes.containerNode(CarsModel.BASE_QNAME);
- expectBatchedModifications(2);
+ expectBatchedModifications(2);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
+ transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- // Trying to write to Cars will cause another transaction context to get created
- transactionProxy.write(CarsModel.BASE_PATH, carsNode);
+ // Trying to write to Cars will cause another transaction context to get created
+ transactionProxy.write(CarsModel.BASE_PATH, carsNode);
- // Now ready should block for both transaction contexts
- transactionProxy.ready();
- }
- }, 1, true, TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext().getOperationTimeoutInMillis()) * 2);
+ // Now ready should block for both transaction contexts
+ transactionProxy.ready();
+ }, 1, true, TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
+ .getOperationTimeoutInMillis()) * 2);
}
private void testModificationOperationBatching(TransactionType type) throws Exception {
}
@Test
- public void testReadWriteModificationOperationBatching() throws Throwable {
+ public void testReadWriteModificationOperationBatching() throws Exception {
testModificationOperationBatching(READ_WRITE);
}
@Test
- public void testWriteOnlyModificationOperationBatching() throws Throwable {
+ public void testWriteOnlyModificationOperationBatching() throws Exception {
testModificationOperationBatching(WRITE_ONLY);
}
@Test
- public void testOptimizedWriteOnlyModificationOperationBatching() throws Throwable {
+ public void testOptimizedWriteOnlyModificationOperationBatching() throws Exception {
dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
testModificationOperationBatching(WRITE_ONLY);
}
@Test
- public void testModificationOperationBatchingWithInterleavedReads() throws Throwable {
+ public void testModificationOperationBatchingWithInterleavedReads() throws Exception {
int shardBatchedModificationCount = 10;
dataStoreContextBuilder.shardBatchedModificationCount(shardBatchedModificationCount);
expectBatchedModifications(actorRef, shardBatchedModificationCount);
- YangInstanceIdentifier writePath1 = TestModel.TEST_PATH;
- NormalizedNode<?, ?> writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ final YangInstanceIdentifier writePath1 = TestModel.TEST_PATH;
+ final NormalizedNode<?, ?> writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
YangInstanceIdentifier writePath2 = TestModel.OUTER_LIST_PATH;
NormalizedNode<?, ?> writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
- YangInstanceIdentifier mergePath1 = TestModel.TEST_PATH;
- NormalizedNode<?, ?> mergeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ final YangInstanceIdentifier mergePath1 = TestModel.TEST_PATH;
+ final NormalizedNode<?, ?> mergeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
YangInstanceIdentifier mergePath2 = TestModel.INNER_LIST_PATH;
NormalizedNode<?, ?> mergeNode2 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
- YangInstanceIdentifier deletePath = TestModel.OUTER_LIST_PATH;
+ final YangInstanceIdentifier deletePath = TestModel.OUTER_LIST_PATH;
doReturn(readDataReply(writeNode2)).when(mockActorContext).executeOperationAsync(
eq(actorSelection(actorRef)), eqReadData(writePath2), any(Timeout.class));
transactionProxy.write(writePath1, writeNode1);
transactionProxy.write(writePath2, writeNode2);
- Optional<NormalizedNode<?, ?>> readOptional = transactionProxy.read(writePath2).
- get(5, TimeUnit.SECONDS);
+ Optional<NormalizedNode<?, ?>> readOptional = transactionProxy.read(writePath2).get(5, TimeUnit.SECONDS);
assertEquals("NormalizedNode isPresent", true, readOptional.isPresent());
assertEquals("Response NormalizedNode", writeNode2, readOptional.get());
}
@Test
- public void testReadRoot() throws ReadFailedException, InterruptedException, ExecutionException, java.util.concurrent.TimeoutException {
-
+ public void testReadRoot() throws ReadFailedException, InterruptedException, ExecutionException,
+ java.util.concurrent.TimeoutException {
SchemaContext schemaContext = SchemaContextHelper.full();
Configuration configuration = mock(Configuration.class);
doReturn(configuration).when(mockActorContext).getConfiguration();
@SuppressWarnings("unchecked")
Collection<NormalizedNode<?,?>> collection = (Collection<NormalizedNode<?,?>>) normalizedNode.getValue();
- for(NormalizedNode<?,?> node : collection){
+ for (NormalizedNode<?,?> node : collection) {
assertTrue("Expected " + node + " to be a ContainerNode", node instanceof ContainerNode);
}
ActorSystem actorSystem = getSystem();
ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
- doReturn(getSystem().actorSelection(shardActorRef.path())).
- when(mockActorContext).actorSelection(shardActorRef.path().toString());
+ doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
+ .actorSelection(shardActorRef.path().toString());
- doReturn(primaryShardInfoReply(getSystem(), shardActorRef)).
- when(mockActorContext).findPrimaryShardAsync(eq(shardName));
+ doReturn(primaryShardInfoReply(getSystem(), shardActorRef)).when(mockActorContext)
+ .findPrimaryShardAsync(eq(shardName));
ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
- doReturn(actorSystem.actorSelection(txActorRef.path())).
- when(mockActorContext).actorSelection(txActorRef.path().toString());
+ doReturn(actorSystem.actorSelection(txActorRef.path())).when(mockActorContext)
+ .actorSelection(txActorRef.path().toString());
- doReturn(Futures.successful(createTransactionReply(txActorRef, DataStoreVersions.CURRENT_VERSION))).when(mockActorContext).
- executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
+ doReturn(Futures.successful(createTransactionReply(txActorRef, DataStoreVersions.CURRENT_VERSION)))
+ .when(mockActorContext).executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
eqCreateTransaction(memberName, TransactionType.READ_ONLY), any(Timeout.class));
doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
+
import com.codahale.metrics.Timer;
import com.google.common.base.Ticker;
import java.util.concurrent.TimeUnit;
TransactionRateLimitingCallback callback;
@Before
- public void setUp(){
+ public void setUp() {
MockitoAnnotations.initMocks(this);
doReturn(mockTimer).when(mockContext).getOperationTimer(ActorContext.COMMIT);
callback = new TransactionRateLimitingCallback(mockContext);
}
@Test
- public void testSuccessWithoutRun(){
+ public void testSuccessWithoutRun() {
try {
callback.success();
fail("Expected IllegalStateException");
- } catch(IllegalStateException e){
-
+ } catch (IllegalStateException e) {
+ // expected
}
verify(mockTimer, never()).update(anyLong(), any(TimeUnit.class));
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+
import akka.actor.ActorRef;
import akka.testkit.JavaTestKit;
import java.util.Optional;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
-import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
import org.opendaylight.controller.cluster.datastore.persisted.PreBoronShardDataTreeSnapshot;
+import org.opendaylight.controller.cluster.datastore.persisted.ShardDataTreeSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
private static void testSerializeSnapshot(final String testName, final ShardDataTreeSnapshot snapshot)
throws Exception {
- new JavaTestKit(getSystem()) {{
+ new JavaTestKit(getSystem()) {
+ {
- final ActorRef snapshotActor = getSystem().actorOf(ShardSnapshotActor.props(), testName);
- watch(snapshotActor);
+ final ActorRef snapshotActor = getSystem().actorOf(ShardSnapshotActor.props(), testName);
+ watch(snapshotActor);
- final NormalizedNode<?, ?> expectedRoot = snapshot.getRootNode().get();
+ final NormalizedNode<?, ?> expectedRoot = snapshot.getRootNode().get();
- ShardSnapshotActor.requestSnapshot(snapshotActor, snapshot, getRef());
+ ShardSnapshotActor.requestSnapshot(snapshotActor, snapshot, getRef());
- final CaptureSnapshotReply reply = expectMsgClass(duration("3 seconds"), CaptureSnapshotReply.class);
- assertNotNull("getSnapshot is null", reply.getSnapshot());
+ final CaptureSnapshotReply reply = expectMsgClass(duration("3 seconds"), CaptureSnapshotReply.class);
+ assertNotNull("getSnapshot is null", reply.getSnapshot());
- final ShardDataTreeSnapshot actual = ShardDataTreeSnapshot.deserialize(reply.getSnapshot());
- assertNotNull(actual);
- assertEquals(snapshot.getClass(), actual.getClass());
+ final ShardDataTreeSnapshot actual = ShardDataTreeSnapshot.deserialize(reply.getSnapshot());
+ assertNotNull(actual);
+ assertEquals(snapshot.getClass(), actual.getClass());
- final Optional<NormalizedNode<?, ?>> maybeNode = actual.getRootNode();
- assertTrue(maybeNode.isPresent());
+ final Optional<NormalizedNode<?, ?>> maybeNode = actual.getRootNode();
+ assertTrue(maybeNode.isPresent());
- assertEquals("Root node", expectedRoot, maybeNode.get());
- }};
+ assertEquals("Root node", expectedRoot, maybeNode.get());
+ }
+ };
}
@Test
package org.opendaylight.controller.cluster.datastore.compat;
import static org.junit.Assert.assertEquals;
+
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.testkit.TestActorRef;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.net.URI;
private ConfigurationImpl configuration;
@Before
- public void setup(){
+ public void setup() {
configuration = new ConfigurationImpl("module-shards.conf", "modules.conf");
}
@Test
- public void testConstructor(){
+ public void testConstructor() {
Assert.assertNotNull(configuration);
}
@Test
- public void testGetMemberShardNames(){
+ public void testGetMemberShardNames() {
Collection<String> memberShardNames = configuration.getMemberShardNames(MEMBER_1);
assertEquals("getMemberShardNames", ImmutableSortedSet.of("people-1", "cars-1", "test-1", "default"),
ImmutableSortedSet.copyOf(memberShardNames));
}
@Test
- public void testGetMembersFromShardName(){
+ public void testGetMembersFromShardName() {
Collection<MemberName> members = configuration.getMembersFromShardName("default");
assertEquals("getMembersFromShardName", ImmutableSortedSet.of(MEMBER_1, MEMBER_2, MEMBER_3),
ImmutableSortedSet.copyOf(members));
}
@Test
- public void testGetAllShardNames(){
+ public void testGetAllShardNames() {
Set<String> allShardNames = configuration.getAllShardNames();
assertEquals("getAllShardNames", ImmutableSortedSet.of("people-1", "cars-1", "test-1", "default"),
ImmutableSortedSet.copyOf(allShardNames));
entityId, true);
getMapEntryNodeChild(entityEntry, Candidate.QNAME, CANDIDATE_NAME_QNAME, candidateName, expectPresent);
- } catch(AssertionError e) {
+ } catch (AssertionError e) {
throw new AssertionError("Verification of entity candidate failed - returned data was: " + node, e);
}
}
Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader, boolean expectPresent) {
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
+ while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
NormalizedNode<?, ?> node = reader.apply(ENTITY_OWNERS_PATH);
try {
verifyEntityCandidate(node, entityType, entityId, candidateName, expectPresent);
MapNode entityTypeMapNode = (MapNode) childNode.get();
Optional<MapEntryNode> entityTypeEntry = entityTypeMapNode.getChild(new NodeIdentifierWithPredicates(
childMap, child, key));
- if(expectPresent && !entityTypeEntry.isPresent()) {
+ if (expectPresent && !entityTypeEntry.isPresent()) {
fail("Missing " + childMap.toString() + " entry for " + key + ". Actual: " + entityTypeMapNode.getValue());
- } else if(!expectPresent && entityTypeEntry.isPresent()) {
+ } else if (!expectPresent && entityTypeEntry.isPresent()) {
fail("Found unexpected " + childMap.toString() + " entry for " + key);
}
AssertionError lastError = null;
YangInstanceIdentifier entityPath = entityPath(entityType, entityId).node(ENTITY_OWNER_QNAME);
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
+ while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
try {
NormalizedNode<?, ?> node = reader.apply(entityPath);
Assert.assertNotNull("Owner was not set for entityId: " + entityId, node);
Assert.assertEquals("Entity owner", expected, node.getValue().toString());
return;
- } catch(AssertionError e) {
+ } catch (AssertionError e) {
lastError = e;
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
throw lastError;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ static void verifyOwner(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
+ YangInstanceIdentifier entityId, String localMemberName) {
+ verifyOwner(localMemberName, entityType, entityId, path -> {
+ try {
+ return AbstractShardTest.readStore(shard, path);
+ } catch (Exception e) {
+ return null;
+ }
+ });
+ }
+
protected void verifyNodeRemoved(YangInstanceIdentifier path,
Function<YangInstanceIdentifier,NormalizedNode<?,?>> reader) {
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
+ while (sw.elapsed(TimeUnit.MILLISECONDS) <= 5000) {
try {
NormalizedNode<?, ?> node = reader.apply(path);
Assert.assertNull("Node was not removed at path: " + path, node);
return;
- } catch(AssertionError e) {
+ } catch (AssertionError e) {
lastError = e;
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
}
@Override
public boolean matches(Object argument) {
DOMEntityOwnershipChange change = (DOMEntityOwnershipChange) argument;
- return expEntity.equals(change.getEntity()) && expWasOwner == change.getState().wasOwner() &&
- expIsOwner == change.getState().isOwner() && expHasOwner == change.getState().hasOwner() &&
- expInJeopardy == change.inJeopardy();
+ return expEntity.equals(change.getEntity()) && expWasOwner == change.getState().wasOwner()
+ && expIsOwner == change.getState().isOwner() && expHasOwner == change.getState().hasOwner()
+ && expInJeopardy == change.inJeopardy();
}
@Override
});
}
- static void verifyOwner(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
- YangInstanceIdentifier entityId, String localMemberName) {
- verifyOwner(localMemberName, entityType, entityId, path -> {
- try {
- return AbstractShardTest.readStore(shard, path);
- } catch(Exception e) {
- return null;
- }
- });
- }
-
+ @SuppressWarnings("checkstyle:IllegalCatch")
static void verifyNoOwnerSet(TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
YangInstanceIdentifier entityId) {
YangInstanceIdentifier entityPath = entityPath(entityType, entityId).node(ENTITY_OWNER_QNAME);
try {
NormalizedNode<?, ?> node = AbstractShardTest.readStore(shard, entityPath);
- if(node != null) {
+ if (node != null) {
Assert.fail("Owner " + node.getValue() + " was set for " + entityPath);
}
}
}
- static void verifyRaftState(final TestActorRef<? extends EntityOwnershipShard> shard, Consumer<OnDemandRaftState> verifier)
+ static void verifyRaftState(final TestActorRef<? extends EntityOwnershipShard> shard,
+ Consumer<OnDemandRaftState> verifier)
throws Exception {
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
Future<Object> future = Patterns.ask(shard, GetOnDemandRaftState.INSTANCE, new Timeout(operationDuration));
OnDemandRaftState raftState = (OnDemandRaftState)Await.result(future, operationDuration);
"operational" + NEXT_SHARD_NUM.getAndIncrement());
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
void verifyEntityCandidateRemoved(final TestActorRef<EntityOwnershipShard> shard, String entityType,
YangInstanceIdentifier entityId, String candidateName) {
- verifyNodeRemoved(candidatePath(entityType, entityId, candidateName),
- path -> {
- try {
- return AbstractShardTest.readStore(shard, path);
- } catch(Exception e) {
- throw new AssertionError("Failed to read " + path, e);
- }
- });
+ verifyNodeRemoved(candidatePath(entityType, entityId, candidateName), path -> {
+ try {
+ return AbstractShardTest.readStore(shard, path);
+ } catch (Exception e) {
+ throw new AssertionError("Failed to read " + path, e);
+ }
+ });
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
void verifyCommittedEntityCandidate(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
YangInstanceIdentifier entityId, String candidateName) {
verifyEntityCandidate(entityType, entityId, candidateName, path -> {
try {
return AbstractShardTest.readStore(shard, path);
- } catch(Exception e) {
+ } catch (Exception e) {
throw new AssertionError("Failed to read " + path, e);
}
});
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
void verifyNoEntityCandidate(final TestActorRef<? extends EntityOwnershipShard> shard, String entityType,
YangInstanceIdentifier entityId, String candidateName) {
verifyEntityCandidate(entityType, entityId, candidateName, path -> {
try {
return AbstractShardTest.readStore(shard, path);
- } catch(Exception e) {
+ } catch (Exception e) {
throw new AssertionError("Failed to read " + path, e);
}
}, false);
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.candidatePath;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
+
import akka.testkit.JavaTestKit;
import com.google.common.collect.ImmutableSet;
import java.util.concurrent.TimeUnit;
ImmutableSet.copyOf(candidateRemoved.getRemainingCandidates()));
}
- private void writeNode(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node) throws DataValidationFailedException {
+ private void writeNode(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node)
+ throws DataValidationFailedException {
AbstractEntityOwnershipTest.writeNode(path, node, shardDataTree);
}
import static org.opendaylight.controller.cluster.datastore.entityownership.DistributedEntityOwnershipService.ENTITY_OWNERSHIP_SHARD_NAME;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.CANDIDATE_NAME_NODE_ID;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
+
import akka.actor.ActorRef;
import akka.actor.Status.Failure;
import akka.actor.Status.Success;
private static final SchemaContext SCHEMA_CONTEXT = SchemaContextHelper.entityOwners();
private final DatastoreContext.Builder leaderDatastoreContextBuilder =
- DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5).
- shardIsolatedLeaderCheckIntervalInMillis(1000000);
+ DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5)
+ .shardIsolatedLeaderCheckIntervalInMillis(1000000);
private final DatastoreContext.Builder followerDatastoreContextBuilder =
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10000);
@Test
public void testFunctionalityWithThreeNodes() throws Exception {
String name = "test";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(leaderDatastoreContextBuilder).build();
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
follower1Node.configDataStore().waitTillReady();
follower2Node.configDataStore().waitTillReady();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
- DOMEntityOwnershipService follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
- DOMEntityOwnershipService follower2EntityOwnershipService = newOwnershipService(follower2Node.configDataStore());
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService follower1EntityOwnershipService =
+ newOwnershipService(follower1Node.configDataStore());
+ final DOMEntityOwnershipService follower2EntityOwnershipService =
+ newOwnershipService(follower2Node.configDataStore());
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
// Register follower1 candidate for entity2 and verify it becomes owner
- DOMEntityOwnershipCandidateRegistration follower1Entity2Reg = follower1EntityOwnershipService.registerCandidate(ENTITY2);
+ final DOMEntityOwnershipCandidateRegistration follower1Entity2Reg =
+ follower1EntityOwnershipService.registerCandidate(ENTITY2);
verify(follower1MockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, true, true));
verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, false, true));
reset(leaderMockListener, follower1MockListener);
// Register leader candidate for entity2 and verify it becomes owner
- DOMEntityOwnershipCandidateRegistration leaderEntity2Reg = leaderEntityOwnershipService.registerCandidate(ENTITY2);
+ DOMEntityOwnershipCandidateRegistration leaderEntity2Reg =
+ leaderEntityOwnershipService.registerCandidate(ENTITY2);
verifyOwner(leaderDistributedDataStore, ENTITY2, "member-1");
verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY2, false, true, true));
@Test
public void testLeaderEntityOwnersReassignedAfterShutdown() throws Exception {
- followerDatastoreContextBuilder.shardElectionTimeoutFactor(5).
- customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
+ followerDatastoreContextBuilder.shardElectionTimeoutFactor(5)
+ .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
String name = "test";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(leaderDatastoreContextBuilder).build();
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
follower1Node.configDataStore().waitTillReady();
follower2Node.configDataStore().waitTillReady();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
- DOMEntityOwnershipService follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
- DOMEntityOwnershipService follower2EntityOwnershipService = newOwnershipService(follower2Node.configDataStore());
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService follower1EntityOwnershipService =
+ newOwnershipService(follower1Node.configDataStore());
+ final DOMEntityOwnershipService follower2EntityOwnershipService =
+ newOwnershipService(follower2Node.configDataStore());
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
// Re-enable elections on follower1 so it becomes the leader
- ActorRef follower1Shard = IntegrationTestKit.findLocalShard(follower1Node.configDataStore().
- getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
- follower1Shard.tell(DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).
- customRaftPolicyImplementation(null).build(), ActorRef.noSender());
+ ActorRef follower1Shard = IntegrationTestKit.findLocalShard(follower1Node.configDataStore().getActorContext(),
+ ENTITY_OWNERSHIP_SHARD_NAME);
+ follower1Shard.tell(DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build())
+ .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
MemberNode.verifyRaftState(follower1Node.configDataStore(), ENTITY_OWNERSHIP_SHARD_NAME,
raftState -> assertEquals("Raft state", RaftState.Leader.toString(), raftState.getRaftState()));
@Test
public void testLeaderAndFollowerEntityOwnersReassignedAfterShutdown() throws Exception {
- followerDatastoreContextBuilder.shardElectionTimeoutFactor(5).
- customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
+ followerDatastoreContextBuilder.shardElectionTimeoutFactor(5)
+ .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
String name = "test";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ final MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT)
+ .createOperDatastore(false).datastoreContextBuilder(leaderDatastoreContextBuilder).build();
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ final MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT)
+ .createOperDatastore(false).datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ final MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT)
+ .createOperDatastore(false).datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower3Node = MemberNode.builder(memberNodes).akkaConfig("Member4").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ final MemberNode follower3Node = MemberNode.builder(memberNodes).akkaConfig("Member4").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT)
+ .createOperDatastore(false).datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower4Node = MemberNode.builder(memberNodes).akkaConfig("Member5").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ final MemberNode follower4Node = MemberNode.builder(memberNodes).akkaConfig("Member5").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_5_NODE_CONFIG).schemaContext(SCHEMA_CONTEXT)
+ .createOperDatastore(false).datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
follower1Node.configDataStore().waitTillReady();
follower2Node.configDataStore().waitTillReady();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
- DOMEntityOwnershipService follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
- DOMEntityOwnershipService follower2EntityOwnershipService = newOwnershipService(follower2Node.configDataStore());
- DOMEntityOwnershipService follower3EntityOwnershipService = newOwnershipService(follower3Node.configDataStore());
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService follower1EntityOwnershipService =
+ newOwnershipService(follower1Node.configDataStore());
+ final DOMEntityOwnershipService follower2EntityOwnershipService =
+ newOwnershipService(follower2Node.configDataStore());
+ final DOMEntityOwnershipService follower3EntityOwnershipService =
+ newOwnershipService(follower3Node.configDataStore());
newOwnershipService(follower4Node.configDataStore());
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
// Re-enable elections on follower1 so it becomes the leader
- ActorRef follower1Shard = IntegrationTestKit.findLocalShard(follower1Node.configDataStore().
- getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
- follower1Shard.tell(DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).
- customRaftPolicyImplementation(null).build(), ActorRef.noSender());
+ ActorRef follower1Shard = IntegrationTestKit.findLocalShard(follower1Node.configDataStore().getActorContext(),
+ ENTITY_OWNERSHIP_SHARD_NAME);
+ follower1Shard.tell(DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build())
+ .customRaftPolicyImplementation(null).build(), ActorRef.noSender());
MemberNode.verifyRaftState(follower1Node.configDataStore(), ENTITY_OWNERSHIP_SHARD_NAME,
- raftState -> assertEquals("Raft state", RaftState.Leader.toString(), raftState.getRaftState()));
+ raftState -> assertEquals("Raft state", RaftState.Leader.toString(), raftState.getRaftState()));
// Verify the prior leader's and follower3 entity owners are re-assigned.
}
/**
- * Reproduces bug <a href="https://bugs.opendaylight.org/show_bug.cgi?id=4554">4554</a>
- *
- * @throws CandidateAlreadyRegisteredException
+ * Reproduces bug <a href="https://bugs.opendaylight.org/show_bug.cgi?id=4554">4554</a>.
*/
@Test
public void testCloseCandidateRegistrationInQuickSuccession() throws CandidateAlreadyRegisteredException {
String name = "testCloseCandidateRegistrationInQuickSuccession";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(leaderDatastoreContextBuilder).build();
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
follower1Node.configDataStore().waitTillReady();
follower2Node.configDataStore().waitTillReady();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
- DOMEntityOwnershipService follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
- DOMEntityOwnershipService follower2EntityOwnershipService = newOwnershipService(follower2Node.configDataStore());
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService follower1EntityOwnershipService =
+ newOwnershipService(follower1Node.configDataStore());
+ final DOMEntityOwnershipService follower2EntityOwnershipService =
+ newOwnershipService(follower2Node.configDataStore());
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
follower1EntityOwnershipService.registerListener(ENTITY_TYPE1, follower1MockListener);
follower2EntityOwnershipService.registerListener(ENTITY_TYPE1, follower2MockListener);
- final DOMEntityOwnershipCandidateRegistration candidate1 = leaderEntityOwnershipService.registerCandidate(ENTITY1);
+ final DOMEntityOwnershipCandidateRegistration candidate1 =
+ leaderEntityOwnershipService.registerCandidate(ENTITY1);
verify(leaderMockListener, timeout(5000)).ownershipChanged(ownershipChange(ENTITY1, false, true, true));
- final DOMEntityOwnershipCandidateRegistration candidate2 = follower1EntityOwnershipService.registerCandidate(ENTITY1);
- final DOMEntityOwnershipCandidateRegistration candidate3 = follower2EntityOwnershipService.registerCandidate(ENTITY1);
+ final DOMEntityOwnershipCandidateRegistration candidate2 =
+ follower1EntityOwnershipService.registerCandidate(ENTITY1);
+ final DOMEntityOwnershipCandidateRegistration candidate3 =
+ follower2EntityOwnershipService.registerCandidate(ENTITY1);
Mockito.reset(leaderMockListener);
- ArgumentCaptor<DOMEntityOwnershipChange> leaderChangeCaptor = ArgumentCaptor.forClass(DOMEntityOwnershipChange.class);
- ArgumentCaptor<DOMEntityOwnershipChange> follower1ChangeCaptor = ArgumentCaptor.forClass(DOMEntityOwnershipChange.class);
- ArgumentCaptor<DOMEntityOwnershipChange> follower2ChangeCaptor = ArgumentCaptor.forClass(DOMEntityOwnershipChange.class);
+ ArgumentCaptor<DOMEntityOwnershipChange> leaderChangeCaptor =
+ ArgumentCaptor.forClass(DOMEntityOwnershipChange.class);
+ ArgumentCaptor<DOMEntityOwnershipChange> follower1ChangeCaptor =
+ ArgumentCaptor.forClass(DOMEntityOwnershipChange.class);
+ ArgumentCaptor<DOMEntityOwnershipChange> follower2ChangeCaptor =
+ ArgumentCaptor.forClass(DOMEntityOwnershipChange.class);
doNothing().when(leaderMockListener).ownershipChanged(leaderChangeCaptor.capture());
doNothing().when(follower1MockListener).ownershipChanged(follower1ChangeCaptor.capture());
doNothing().when(follower2MockListener).ownershipChanged(follower2ChangeCaptor.capture());
candidate3.close();
boolean passed = false;
- for(int i=0;i<100;i++) {
+ for (int i = 0; i < 100; i++) {
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
- if(!leaderEntityOwnershipService.getOwnershipState(ENTITY1).isPresent() ||
- leaderEntityOwnershipService.getOwnershipState(ENTITY1).get() == EntityOwnershipState.NO_OWNER &&
- follower1EntityOwnershipService.getOwnershipState(ENTITY1).isPresent() &&
- follower1EntityOwnershipService.getOwnershipState(ENTITY1).get() == EntityOwnershipState.NO_OWNER &&
- follower2EntityOwnershipService.getOwnershipState(ENTITY1).isPresent() &&
- follower2EntityOwnershipService.getOwnershipState(ENTITY1).get() == EntityOwnershipState.NO_OWNER &&
- leaderChangeCaptor.getAllValues().size() > 0 && !leaderChangeCaptor.getValue().getState().hasOwner() &&
- leaderChangeCaptor.getAllValues().size() > 0 && !follower1ChangeCaptor.getValue().getState().hasOwner() &&
- leaderChangeCaptor.getAllValues().size() > 0 && !follower2ChangeCaptor.getValue().getState().hasOwner()) {
+ if (!leaderEntityOwnershipService.getOwnershipState(ENTITY1).isPresent()
+ || leaderEntityOwnershipService.getOwnershipState(ENTITY1).get() == EntityOwnershipState.NO_OWNER
+ && follower1EntityOwnershipService.getOwnershipState(ENTITY1).isPresent()
+ && follower1EntityOwnershipService.getOwnershipState(ENTITY1)
+ .get() == EntityOwnershipState.NO_OWNER
+ && follower2EntityOwnershipService.getOwnershipState(ENTITY1).isPresent()
+ && follower2EntityOwnershipService.getOwnershipState(ENTITY1)
+ .get() == EntityOwnershipState.NO_OWNER
+ && leaderChangeCaptor.getAllValues().size() > 0
+ && !leaderChangeCaptor.getValue().getState().hasOwner()
+ && leaderChangeCaptor.getAllValues().size() > 0
+ && !follower1ChangeCaptor.getValue().getState().hasOwner()
+ && leaderChangeCaptor.getAllValues().size() > 0
+ && !follower2ChangeCaptor.getValue().getState().hasOwner()) {
passed = true;
break;
}
* an AddShardReplica request to join it to an existing leader.
*/
@Test
- public void testEntityOwnershipShardBootstrapping() throws Throwable {
+ public void testEntityOwnershipShardBootstrapping() throws Exception {
String name = "testEntityOwnershipShardBootstrapping";
String moduleShardsConfig = MODULE_SHARDS_MEMBER_1_CONFIG;
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(moduleShardsConfig).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(moduleShardsConfig).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(leaderDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(moduleShardsConfig).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(moduleShardsConfig).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore follower1DistributedDataStore = follower1Node.configDataStore();
follower1DistributedDataStore.waitTillReady();
leaderEntityOwnershipService.registerListener(ENTITY_TYPE1, leaderMockListener);
// Register a candidate for follower1 - should get queued since follower1 has no leader
- DOMEntityOwnershipCandidateRegistration candidateReg = follower1EntityOwnershipService.registerCandidate(ENTITY1);
+ final DOMEntityOwnershipCandidateRegistration candidateReg =
+ follower1EntityOwnershipService.registerCandidate(ENTITY1);
Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS);
verify(leaderMockListener, never()).ownershipChanged(ownershipChange(ENTITY1));
// Add replica in follower1
AddShardReplica addReplica = new AddShardReplica(ENTITY_OWNERSHIP_SHARD_NAME);
- follower1DistributedDataStore.getActorContext().getShardManager().tell(addReplica , follower1Node.kit().getRef());
- Object reply = follower1Node.kit().expectMsgAnyClassOf(JavaTestKit.duration("5 sec"), Success.class, Failure.class);
- if(reply instanceof Failure) {
+ follower1DistributedDataStore.getActorContext().getShardManager().tell(addReplica,
+ follower1Node.kit().getRef());
+ Object reply = follower1Node.kit().expectMsgAnyClassOf(JavaTestKit.duration("5 sec"),
+ Success.class, Failure.class);
+ if (reply instanceof Failure) {
throw new AssertionError("AddShardReplica failed", ((Failure)reply).cause());
}
Cluster.get(leaderNode.kit().getSystem()).down(Cluster.get(follower1Node.kit().getSystem()).selfAddress());
follower1Node.cleanup();
- follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(moduleShardsConfig).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(moduleShardsConfig).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
follower1EntityOwnershipService.registerCandidate(ENTITY1);
@Test
public void testOwnerSelectedOnRapidUnregisteringAndRegisteringOfCandidates() throws Exception {
String name = "test";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(leaderDatastoreContextBuilder).build();
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
follower1Node.configDataStore().waitTillReady();
follower2Node.configDataStore().waitTillReady();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
- DOMEntityOwnershipService follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
- DOMEntityOwnershipService follower2EntityOwnershipService = newOwnershipService(follower2Node.configDataStore());
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService follower1EntityOwnershipService =
+ newOwnershipService(follower1Node.configDataStore());
+ newOwnershipService(follower2Node.configDataStore());
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
// Register leader candidate for entity1 and verify it becomes owner
- DOMEntityOwnershipCandidateRegistration leaderEntity1Reg = leaderEntityOwnershipService.registerCandidate(ENTITY1);
+ DOMEntityOwnershipCandidateRegistration leaderEntity1Reg =
+ leaderEntityOwnershipService.registerCandidate(ENTITY1);
verifyCandidates(leaderDistributedDataStore, ENTITY1, "member-1");
verifyOwner(leaderDistributedDataStore, ENTITY1, "member-1");
@Test
public void testOwnerSelectedOnRapidRegisteringAndUnregisteringOfCandidates() throws Exception {
String name = "test";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(leaderDatastoreContextBuilder).build();
+ MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(leaderDatastoreContextBuilder).build();
- MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower1Node = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
- MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name ).
- moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false).
- datastoreContextBuilder(followerDatastoreContextBuilder).build();
+ MemberNode follower2Node = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ .moduleShardsConfig(MODULE_SHARDS_CONFIG).schemaContext(SCHEMA_CONTEXT).createOperDatastore(false)
+ .datastoreContextBuilder(followerDatastoreContextBuilder).build();
DistributedDataStore leaderDistributedDataStore = leaderNode.configDataStore();
follower1Node.configDataStore().waitTillReady();
follower2Node.configDataStore().waitTillReady();
- DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
- DOMEntityOwnershipService follower1EntityOwnershipService = newOwnershipService(follower1Node.configDataStore());
- DOMEntityOwnershipService follower2EntityOwnershipService = newOwnershipService(follower2Node.configDataStore());
+ final DOMEntityOwnershipService leaderEntityOwnershipService = newOwnershipService(leaderDistributedDataStore);
+ final DOMEntityOwnershipService follower1EntityOwnershipService =
+ newOwnershipService(follower1Node.configDataStore());
+ newOwnershipService(follower2Node.configDataStore());
leaderNode.kit().waitUntilLeader(leaderNode.configDataStore().getActorContext(), ENTITY_OWNERSHIP_SHARD_NAME);
// Register leader candidate for entity1 and verify it becomes owner
- DOMEntityOwnershipCandidateRegistration leaderEntity1Reg = leaderEntityOwnershipService.registerCandidate(ENTITY1);
+ final DOMEntityOwnershipCandidateRegistration leaderEntity1Reg =
+ leaderEntityOwnershipService.registerCandidate(ENTITY1);
verifyCandidates(leaderDistributedDataStore, ENTITY1, "member-1");
verifyOwner(leaderDistributedDataStore, ENTITY1, "member-1");
assertEquals("EntityOwnershipState", expState, state.get());
}
- private static void verifyCandidates(final DistributedDataStore dataStore, final DOMEntity entity, final String... expCandidates) throws Exception {
+ private static void verifyCandidates(final DistributedDataStore dataStore, final DOMEntity entity,
+ final String... expCandidates) throws Exception {
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.MILLISECONDS) <= 10000) {
- Optional<NormalizedNode<?, ?>> possible = dataStore.newReadOnlyTransaction().read(
- entityPath(entity.getType(), entity.getIdentifier()).node(Candidate.QNAME)).get(5, TimeUnit.SECONDS);
+ while (sw.elapsed(TimeUnit.MILLISECONDS) <= 10000) {
+ Optional<NormalizedNode<?, ?>> possible = dataStore.newReadOnlyTransaction()
+ .read(entityPath(entity.getType(), entity.getIdentifier()).node(Candidate.QNAME))
+ .get(5, TimeUnit.SECONDS);
try {
assertEquals("Candidates not found for " + entity, true, possible.isPresent());
Collection<String> actual = new ArrayList<>();
- for(MapEntryNode candidate: ((MapNode)possible.get()).getValue()) {
+ for (MapEntryNode candidate: ((MapNode)possible.get()).getValue()) {
actual.add(candidate.getChild(CANDIDATE_NAME_NODE_ID).get().getValue().toString());
}
throw lastError;
}
- private static void verifyOwner(final DistributedDataStore dataStore, final DOMEntity entity, final String expOwner) {
- AbstractEntityOwnershipTest.verifyOwner(expOwner, entity.getType(), entity.getIdentifier(),
- path -> {
- try {
- return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
- } catch (Exception e) {
- return null;
- }
- });
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ private static void verifyOwner(final DistributedDataStore dataStore, final DOMEntity entity,
+ final String expOwner) {
+ AbstractEntityOwnershipTest.verifyOwner(expOwner, entity.getType(), entity.getIdentifier(), path -> {
+ try {
+ return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
+ } catch (Exception e) {
+ return null;
+ }
+ });
}
}
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithEntityTypeEntry;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityTypeEntryWithEntityEntry;
+
import akka.actor.ActorRef;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
@Before
public void setUp() {
- DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreName(dataStoreName).
- shardInitializationTimeout(10, TimeUnit.SECONDS).build();
+ DatastoreContext datastoreContext = DatastoreContext.newBuilder().dataStoreName(dataStoreName)
+ .shardInitializationTimeout(10, TimeUnit.SECONDS).build();
Configuration configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider()) {
@Override
Mockito.doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
Mockito.doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(Mockito.anyString());
- dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration, mockContextFactory, null);
+ dataStore = new DistributedDataStore(getSystem(), new MockClusterWrapper(), configuration,
+ mockContextFactory, null);
dataStore.onGlobalContextUpdated(SchemaContextHelper.entityOwners());
}
try {
service.registerCandidate(entity);
fail("Expected CandidateAlreadyRegisteredException");
- } catch(CandidateAlreadyRegisteredException e) {
+ } catch (CandidateAlreadyRegisteredException e) {
// expected
assertEquals("getEntity", entity, e.getEntity());
}
when(service.getLocalEntityOwnershipShardDataTree()).thenReturn(shardDataTree.getDataTree());
DOMEntity entity1 = new DOMEntity(ENTITY_TYPE, "one");
- writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity1.getIdentifier(), "member-1"), shardDataTree);
+ writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, entity1.getIdentifier(), "member-1"),
+ shardDataTree);
writeNode(ENTITY_OWNERS_PATH, entityOwnersWithEntityTypeEntry(entityTypeEntryWithEntityEntry(entity1.getType(),
entityEntryWithOwner(entity1.getIdentifier(), "member-1"))), shardDataTree);
verifyGetOwnershipState(service, entity1, EntityOwnershipState.IS_OWNER);
entityEntryWithOwner(entity1.getIdentifier(), "member-2"), shardDataTree);
verifyGetOwnershipState(service, entity1, EntityOwnershipState.OWNED_BY_OTHER);
- writeNode(entityPath(entity1.getType(), entity1.getIdentifier()), entityEntryWithOwner(entity1.getIdentifier(), ""),
- shardDataTree);
+ writeNode(entityPath(entity1.getType(), entity1.getIdentifier()), entityEntryWithOwner(entity1.getIdentifier(),
+ ""), shardDataTree);
verifyGetOwnershipState(service, entity1, EntityOwnershipState.NO_OWNER);
DOMEntity entity2 = new DOMEntity(ENTITY_TYPE, "two");
assertEquals("EntityOwnershipState", expState, state.get());
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void verifyEntityCandidate(final ActorRef entityOwnershipShard, final String entityType,
final YangInstanceIdentifier entityId, final String candidateName) {
- verifyEntityCandidate(entityType, entityId, candidateName,
- path -> {
- try {
- return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
- } catch (Exception e) {
- return null;
- }
- });
+ verifyEntityCandidate(entityType, entityId, candidateName, path -> {
+ try {
+ return dataStore.newReadOnlyTransaction().read(path).get(5, TimeUnit.SECONDS).get();
+ } catch (Exception e) {
+ return null;
+ }
+ });
}
- private static void verifyRegisterCandidateLocal(final DistributedEntityOwnershipService service, final DOMEntity entity) {
+ private static void verifyRegisterCandidateLocal(final DistributedEntityOwnershipService service,
+ final DOMEntity entity) {
RegisterCandidateLocal regCandidate = verifyMessage(service, RegisterCandidateLocal.class);
assertEquals("getEntity", entity, regCandidate.getEntity());
}
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityEntryWithOwner;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
anyBoolean(), anyBoolean());
}
- private void writeNode(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node) throws DataValidationFailedException {
+ private void writeNode(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node)
+ throws DataValidationFailedException {
AbstractEntityOwnershipTest.writeNode(path, node, shardDataTree);
}
}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorRef;
import akka.testkit.TestActorRef;
import org.junit.After;
DOMEntityOwnershipListener mockListener = mock(DOMEntityOwnershipListener.class);
DOMEntity entity1 = new DOMEntity("test", YangInstanceIdentifier.of(QName.create("test", "id1")));
- doThrow(new RuntimeException("mock")).when(mockListener).ownershipChanged(ownershipChange(entity1, false, true, true));
+ doThrow(new RuntimeException("mock")).when(mockListener).ownershipChanged(
+ ownershipChange(entity1, false, true, true));
DOMEntity entity2 = new DOMEntity("test", YangInstanceIdentifier.of(QName.create("test", "id2")));
doNothing().when(mockListener).ownershipChanged(ownershipChange(entity2, true, false, false));
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorContext;
import akka.actor.ActorRef;
import akka.actor.Props;
DOMEntityOwnershipListener mockListener1 = mock(DOMEntityOwnershipListener.class, "EntityOwnershipListener1");
DOMEntityOwnershipListener mockListener2 = mock(DOMEntityOwnershipListener.class, "EntityOwnershipListener2");
- DOMEntityOwnershipListener mockListener1_2 = mock(DOMEntityOwnershipListener.class, "EntityOwnershipListener1_2");
+ DOMEntityOwnershipListener mockListener12 = mock(DOMEntityOwnershipListener.class,
+ "EntityOwnershipListener1_2");
String entityType1 = "type1";
String entityType2 = "type2";
- DOMEntity entity1 = new DOMEntity(entityType1, YangInstanceIdentifier.of(QName.create("test", "id1")));
- DOMEntity entity2 = new DOMEntity(entityType2, YangInstanceIdentifier.of(QName.create("test", "id2")));
- DOMEntity entity3 = new DOMEntity("noListener", YangInstanceIdentifier.of(QName.create("test", "id5")));
+ final DOMEntity entity1 = new DOMEntity(entityType1, YangInstanceIdentifier.of(QName.create("test", "id1")));
+ final DOMEntity entity2 = new DOMEntity(entityType2, YangInstanceIdentifier.of(QName.create("test", "id2")));
+ final DOMEntity entity3 = new DOMEntity("noListener", YangInstanceIdentifier.of(QName.create("test", "id5")));
// Add EntityOwnershipListener registrations.
support.addEntityOwnershipListener(entityType1, mockListener1);
support.addEntityOwnershipListener(entityType1, mockListener1); // register again - should be noop
- support.addEntityOwnershipListener(entityType1, mockListener1_2);
+ support.addEntityOwnershipListener(entityType1, mockListener12);
support.addEntityOwnershipListener(entityType2, mockListener2);
// Notify entity1 changed and verify appropriate listeners are notified.
support.notifyEntityOwnershipListeners(entity1, false, true, true);
verify(mockListener1, timeout(5000)).ownershipChanged(ownershipChange(entity1, false, true, true));
- verify(mockListener1_2, timeout(5000)).ownershipChanged(ownershipChange(entity1, false, true, true));
+ verify(mockListener12, timeout(5000)).ownershipChanged(ownershipChange(entity1, false, true, true));
Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS);
verify(mockListener2, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
assertEquals("# of listener actors", 2, actorContext.children().size());
- reset(mockListener1, mockListener2, mockListener1_2);
+ reset(mockListener1, mockListener2, mockListener12);
// Notify entity2 changed and verify appropriate listeners are notified.
verify(mockListener2, timeout(5000)).ownershipChanged(ownershipChange(entity2, false, true, true));
Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS);
verify(mockListener1, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
- verify(mockListener1_2, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
+ verify(mockListener12, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
assertEquals("# of listener actors", 3, actorContext.children().size());
- reset(mockListener1, mockListener2, mockListener1_2);
+ reset(mockListener1, mockListener2, mockListener12);
// Notify entity3 changed and verify no listeners are notified.
Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS);
verify(mockListener1, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
verify(mockListener2, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
- verify(mockListener1_2, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
- reset(mockListener1, mockListener2, mockListener1_2);
+ verify(mockListener12, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
+ reset(mockListener1, mockListener2, mockListener12);
Iterable<ActorRef> listenerActors = actorContext.children();
assertEquals("# of listener actors", 3, listenerActors.size());
support.removeEntityOwnershipListener(entityType1, mockListener1);
support.notifyEntityOwnershipListeners(entity1, true, false, true);
- verify(mockListener1_2, timeout(5000)).ownershipChanged(ownershipChange(entity1, true, false, true));
+ verify(mockListener12, timeout(5000)).ownershipChanged(ownershipChange(entity1, true, false, true));
Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS);
verify(mockListener1, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
- reset(mockListener1, mockListener2, mockListener1_2);
+ reset(mockListener1, mockListener2, mockListener12);
// Unregister all listeners and verify their listener actors are destroyed.
List<JavaTestKit> watchers = new ArrayList<>();
- for(Iterator<ActorRef> iter = listenerActors.iterator(); iter.hasNext();) {
+ for (Iterator<ActorRef> iter = listenerActors.iterator(); iter.hasNext();) {
JavaTestKit kit = new JavaTestKit(getSystem());
kit.watch(iter.next());
watchers.add(kit);
}
- support.removeEntityOwnershipListener(entityType1, mockListener1_2);
- support.removeEntityOwnershipListener(entityType1, mockListener1_2); // un-register again - should be noop
+ support.removeEntityOwnershipListener(entityType1, mockListener12);
+ support.removeEntityOwnershipListener(entityType1, mockListener12); // un-register again - should be noop
support.removeEntityOwnershipListener(entityType2, mockListener2);
Iterator<ActorRef> iter = listenerActors.iterator();
- for(JavaTestKit kit: watchers) {
+ for (JavaTestKit kit: watchers) {
kit.expectTerminated(JavaTestKit.duration("3 seconds"), iter.next());
}
support.notifyEntityOwnershipListeners(entity1, false, false, true);
verify(mockListener1, timeout(5000)).ownershipChanged(ownershipChange(entity1, false, false, true));
- verify(mockListener1_2, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
+ verify(mockListener12, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
verify(mockListener2, never()).ownershipChanged(any(DOMEntityOwnershipChange.class));
// Quickly register and unregister mockListener2 - expecting no exceptions.
*/
package org.opendaylight.controller.cluster.datastore.entityownership;
-import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectFirstMatching;
-import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectMatching;
-import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.clearMessages;
import static org.junit.Assert.assertEquals;
import static org.mockito.AdditionalMatchers.or;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
-import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
+import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.clearMessages;
+import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectFirstMatching;
+import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectMatching;
+
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
import org.opendaylight.controller.cluster.raft.messages.RequestVote;
+import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipChange;
public void testOnRegisterCandidateLocalWithNoInitialLeader() throws Exception {
testLog.info("testOnRegisterCandidateLocalWithNoInitialLeader starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
public void testOnRegisterCandidateLocalWithNoInitialConsensus() throws Exception {
testLog.info("testOnRegisterCandidateLocalWithNoInitialConsensus starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
- dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2).
- shardTransactionCommitTimeoutInSeconds(1);
+ dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2)
+ .shardTransactionCommitTimeoutInSeconds(1);
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId = newShardId(PEER_MEMBER_1_NAME);
public void testOnRegisterCandidateLocalWithIsolatedLeader() throws Exception {
testLog.info("testOnRegisterCandidateLocalWithIsolatedLeader starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
- dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2).
- shardIsolatedLeaderCheckIntervalInMillis(50);
+ dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2)
+ .shardIsolatedLeaderCheckIntervalInMillis(50);
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId = newShardId(PEER_MEMBER_1_NAME);
ShardTestKit kit = new ShardTestKit(getSystem());
- dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2).
- shardBatchedModificationCount(5);
+ dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2)
+ .shardBatchedModificationCount(5);
ShardIdentifier leaderId = newShardId(PEER_MEMBER_1_NAME);
ShardIdentifier localId = newShardId(LOCAL_MEMBER_NAME);
TestActorRef<TestEntityOwnershipShard> leader = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(leaderId, peerMap(localId.toString()), PEER_MEMBER_1_NAME),
actorFactory.createTestActor(MessageCollectorActor.props())), leaderId.toString());
- TestEntityOwnershipShard leaderShard = leader.underlyingActor();
+ final TestEntityOwnershipShard leaderShard = leader.underlyingActor();
TestActorRef<TestEntityOwnershipShard> local = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(localId, peerMap(leaderId.toString()),LOCAL_MEMBER_NAME)), localId.toString());
int max = 100;
List<YangInstanceIdentifier> entityIds = new ArrayList<>();
- for(int i = 1; i <= max; i++) {
+ for (int i = 1; i <= max; i++) {
YangInstanceIdentifier id = YangInstanceIdentifier.of(QName.create("test", "2015-08-14", "test" + i));
entityIds.add(id);
local.tell(new RegisterCandidateLocal(new DOMEntity(ENTITY_TYPE, id)), kit.getRef());
}
- for(int i = 0; i < max; i++) {
+ for (int i = 0; i < max; i++) {
verifyCommittedEntityCandidate(local, ENTITY_TYPE, entityIds.get(i), LOCAL_MEMBER_NAME);
}
public void testOwnershipChanges() throws Exception {
testLog.info("testOwnershipChanges starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
public void testOwnerChangesOnPeerAvailabilityChanges() throws Exception {
testLog.info("testOwnerChangesOnPeerAvailabilityChanges starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
- dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(4).
- shardIsolatedLeaderCheckIntervalInMillis(100000);
+ dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(4)
+ .shardIsolatedLeaderCheckIntervalInMillis(100000);
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId1 = newShardId(PEER_MEMBER_1_NAME);
public void testLeaderIsolation() throws Exception {
testLog.info("testLeaderIsolation starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId1 = newShardId(PEER_MEMBER_1_NAME);
ShardIdentifier peerId2 = newShardId(PEER_MEMBER_2_NAME);
- dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(4).
- shardIsolatedLeaderCheckIntervalInMillis(100000);
+ dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(4)
+ .shardIsolatedLeaderCheckIntervalInMillis(100000);
TestActorRef<TestEntityOwnershipShard> peer1 = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(peerId1, peerMap(leaderId.toString(), peerId2.toString()), PEER_MEMBER_1_NAME)),
peerId2.toString());
peer2.underlyingActor().startDroppingMessagesOfType(ElectionTimeout.class);
- dataStoreContextBuilder = DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
- shardIsolatedLeaderCheckIntervalInMillis(500);
+ dataStoreContextBuilder = DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
+ .shardIsolatedLeaderCheckIntervalInMillis(500);
TestActorRef<TestEntityOwnershipShard> leader = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(leaderId, peerMap(peerId1.toString(), peerId2.toString()), LOCAL_MEMBER_NAME)),
DOMEntityOwnershipListener leaderListener = mock(DOMEntityOwnershipListener.class);
leader.tell(new RegisterListenerLocal(leaderListener, ENTITY_TYPE), kit.getRef());
kit.expectMsgClass(SuccessReply.class);
- verify(leaderListener, timeout(5000).times(3)).ownershipChanged(or(or(ownershipChange(entity1, false, true, true),
- ownershipChange(entity2, false, false, true)), ownershipChange(entity3, false, false, true)));
+ verify(leaderListener, timeout(5000).times(3)).ownershipChanged(or(or(
+ ownershipChange(entity1, false, true, true), ownershipChange(entity2, false, false, true)),
+ ownershipChange(entity3, false, false, true)));
reset(leaderListener);
DOMEntityOwnershipListener peer1Listener = mock(DOMEntityOwnershipListener.class);
peer1.tell(new RegisterListenerLocal(peer1Listener, ENTITY_TYPE), kit.getRef());
kit.expectMsgClass(SuccessReply.class);
- verify(peer1Listener, timeout(5000).times(3)).ownershipChanged(or(or(ownershipChange(entity1, false, false, true),
- ownershipChange(entity2, false, true, true)), ownershipChange(entity3, false, false, true)));
+ verify(peer1Listener, timeout(5000).times(3)).ownershipChanged(or(or(
+ ownershipChange(entity1, false, false, true), ownershipChange(entity2, false, true, true)),
+ ownershipChange(entity3, false, false, true)));
reset(peer1Listener);
DOMEntityOwnershipListener peer2Listener = mock(DOMEntityOwnershipListener.class);
peer2.tell(new RegisterListenerLocal(peer2Listener, ENTITY_TYPE), kit.getRef());
kit.expectMsgClass(SuccessReply.class);
- verify(peer2Listener, timeout(5000).times(3)).ownershipChanged(or(or(ownershipChange(entity1, false, false, true),
- ownershipChange(entity2, false, false, true)), ownershipChange(entity3, false, true, true)));
+ verify(peer2Listener, timeout(5000).times(3)).ownershipChanged(or(or(
+ ownershipChange(entity1, false, false, true), ownershipChange(entity2, false, false, true)),
+ ownershipChange(entity3, false, true, true)));
reset(peer2Listener);
// Isolate the leader by dropping AppendEntries to the followers and incoming messages from the followers.
leader.underlyingActor().startDroppingMessagesOfType(AppendEntries.class);
peer2.underlyingActor().startDroppingMessagesOfType(AppendEntries.class,
- ae -> ae.getLeaderId().equals(leaderId.toString()));
+ ae -> ae.getLeaderId().equals(leaderId.toString()));
peer1.underlyingActor().startDroppingMessagesOfType(AppendEntries.class);
// Make peer1 start an election and become leader by enabling the ElectionTimeout message.
// Expect inJeopardy notification on the isolated leader.
- verify(leaderListener, timeout(5000).times(3)).ownershipChanged(or(or(ownershipChange(entity1, true, true, true, true),
- ownershipChange(entity2, false, false, true, true)), ownershipChange(entity3, false, false, true, true)));
+ verify(leaderListener, timeout(5000).times(3)).ownershipChanged(or(or(
+ ownershipChange(entity1, true, true, true, true), ownershipChange(entity2, false, false, true, true)),
+ ownershipChange(entity3, false, false, true, true)));
reset(leaderListener);
verifyRaftState(peer1, state ->
verifyRaftState(leader, state ->
assertEquals("getRaftState", RaftState.Follower.toString(), state.getRaftState()));
- verify(leaderListener, timeout(5000).times(3)).ownershipChanged(or(or(ownershipChange(entity1, true, true, true),
- ownershipChange(entity2, false, false, true)), ownershipChange(entity3, false, false, true)));
+ verify(leaderListener, timeout(5000).times(3)).ownershipChanged(or(or(
+ ownershipChange(entity1, true, true, true), ownershipChange(entity2, false, false, true)),
+ ownershipChange(entity3, false, false, true)));
verifyOwner(leader, entity1.getType(), entity1.getIdentifier(), PEER_MEMBER_1_NAME);
verify(leaderListener, timeout(5000)).ownershipChanged(ownershipChange(entity1, true, false, true));
public void testLeaderIsolationWithPendingCandidateAdded() throws Exception {
testLog.info("testLeaderIsolationWithPendingCandidateAdded starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
+ final ShardTestKit kit = new ShardTestKit(getSystem());
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId1 = newShardId(PEER_MEMBER_1_NAME);
ShardIdentifier peerId2 = newShardId(PEER_MEMBER_2_NAME);
- dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(4).
- shardIsolatedLeaderCheckIntervalInMillis(100000);
+ dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(4)
+ .shardIsolatedLeaderCheckIntervalInMillis(100000);
TestActorRef<TestEntityOwnershipShard> peer1 = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(peerId1, peerMap(leaderId.toString(), peerId2.toString()), PEER_MEMBER_1_NAME),
actorFactory.createTestActor(MessageCollectorActor.props())), peerId2.toString());
peer2.underlyingActor().startDroppingMessagesOfType(ElectionTimeout.class);
- dataStoreContextBuilder = DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build()).
- shardIsolatedLeaderCheckIntervalInMillis(500);
+ dataStoreContextBuilder = DatastoreContext.newBuilderFrom(dataStoreContextBuilder.build())
+ .shardIsolatedLeaderCheckIntervalInMillis(500);
TestActorRef<TestEntityOwnershipShard> leader = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(leaderId, peerMap(peerId1.toString(), peerId2.toString()), LOCAL_MEMBER_NAME),
// Capture the CandidateAdded messages.
- List<CandidateAdded> candidateAdded = expectMatching(leader.underlyingActor().collectorActor(), CandidateAdded.class, 2);
+ final List<CandidateAdded> candidateAdded = expectMatching(leader.underlyingActor().collectorActor(),
+ CandidateAdded.class, 2);
// Drop AppendEntries to the followers containing a log entry, which will be for the owner writes after we
// forward the CandidateAdded messages to the leader. This will leave the pending owner write tx's uncommitted.
leader.tell(candidateAdded.get(0), leader);
leader.tell(candidateAdded.get(1), leader);
- expectMatching(peer1.underlyingActor().collectorActor(), AppendEntries.class, 2, ae -> ae.getEntries().size() > 0);
+ expectMatching(peer1.underlyingActor().collectorActor(), AppendEntries.class, 2,
+ ae -> ae.getEntries().size() > 0);
// Verify no owner assigned.
leader.underlyingActor().startDroppingMessagesOfType(AppendEntries.class);
peer2.underlyingActor().startDroppingMessagesOfType(AppendEntries.class,
- ae -> ae.getLeaderId().equals(leaderId.toString()));
+ ae -> ae.getLeaderId().equals(leaderId.toString()));
peer1.underlyingActor().startDroppingMessagesOfType(AppendEntries.class);
// Send PeerDown to the isolated leader - should be no-op since there's no owned entities.
// Verify the leader transitions to IsolatedLeader.
- verifyRaftState(leader, state -> assertEquals("getRaftState", RaftState.IsolatedLeader.toString(), state.getRaftState()));
+ verifyRaftState(leader, state -> assertEquals("getRaftState", RaftState.IsolatedLeader.toString(),
+ state.getRaftState()));
// Send PeerDown to the new leader peer1.
// Verify the peer1 transitions to Leader.
- verifyRaftState(peer1, state -> assertEquals("getRaftState", RaftState.Leader.toString(), state.getRaftState()));
+ verifyRaftState(peer1, state -> assertEquals("getRaftState", RaftState.Leader.toString(),
+ state.getRaftState()));
verifyNoOwnerSet(peer1, entity1.getType(), entity1.getIdentifier());
verifyNoOwnerSet(peer2, entity1.getType(), entity2.getIdentifier());
// Previous leader should switch to Follower.
- verifyRaftState(leader, state -> assertEquals("getRaftState", RaftState.Follower.toString(), state.getRaftState()));
+ verifyRaftState(leader, state -> assertEquals("getRaftState", RaftState.Follower.toString(),
+ state.getRaftState()));
// Send PeerUp to peer1 and peer2.
// - inJeopardy cleared for entity2 (wasOwner=false, isOwner=false, hasOwner=false, inJeopardy=false)
// - local owner granted for entity1 (wasOwner=false, isOwner=true, hasOwner=true, inJeopardy=false)
// - remote owner for entity2 (wasOwner=false, isOwner=false, hasOwner=true, inJeopardy=false)
- verify(leaderListener, timeout(5000).times(4)).ownershipChanged(or(or(ownershipChange(entity1, false, false, false),
- ownershipChange(entity2, false, false, false)), or(ownershipChange(entity1, false, true, true),
- ownershipChange(entity2, false, false, true))));
+ verify(leaderListener, timeout(5000).times(4)).ownershipChanged(or(
+ or(ownershipChange(entity1, false, false, false), ownershipChange(entity2, false, false, false)),
+ or(ownershipChange(entity1, false, true, true), ownershipChange(entity2, false, false, true))));
verify(peer1Listener, timeout(5000)).ownershipChanged(ownershipChange(entity1, false, false, true));
verify(peer2Listener, timeout(5000)).ownershipChanged(ownershipChange(entity1, false, false, true));
ShardTestKit.waitUntilLeader(leader);
String otherEntityType = "otherEntityType";
- DOMEntity entity1 = new DOMEntity(ENTITY_TYPE, ENTITY_ID1);
- DOMEntity entity2 = new DOMEntity(ENTITY_TYPE, ENTITY_ID2);
- DOMEntity entity3 = new DOMEntity(ENTITY_TYPE, ENTITY_ID3);
- DOMEntity entity4 = new DOMEntity(otherEntityType, ENTITY_ID3);
+ final DOMEntity entity1 = new DOMEntity(ENTITY_TYPE, ENTITY_ID1);
+ final DOMEntity entity2 = new DOMEntity(ENTITY_TYPE, ENTITY_ID2);
+ final DOMEntity entity3 = new DOMEntity(ENTITY_TYPE, ENTITY_ID3);
+ final DOMEntity entity4 = new DOMEntity(otherEntityType, ENTITY_ID3);
DOMEntityOwnershipListener listener = mock(DOMEntityOwnershipListener.class);
// Register listener
testLog.info("testDelayedEntityOwnerSelectionWhenMaxPeerRequestsReceived starting");
ShardTestKit kit = new ShardTestKit(getSystem());
- EntityOwnerSelectionStrategyConfig.Builder builder = EntityOwnerSelectionStrategyConfig.newBuilder().
- addStrategy(ENTITY_TYPE, LastCandidateSelectionStrategy.class, 500);
+ EntityOwnerSelectionStrategyConfig.Builder builder = EntityOwnerSelectionStrategyConfig.newBuilder()
+ .addStrategy(ENTITY_TYPE, LastCandidateSelectionStrategy.class, 500);
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId = newShardId(PEER_MEMBER_1_NAME);
peer.underlyingActor().startDroppingMessagesOfType(ElectionTimeout.class);
TestActorRef<EntityOwnershipShard> leader = actorFactory.createTestActor(
- newShardProps(leaderId, peerMap(peerId.toString()), LOCAL_MEMBER_NAME, builder.build()), leaderId.toString());
+ newShardProps(leaderId, peerMap(peerId.toString()), LOCAL_MEMBER_NAME, builder.build()),
+ leaderId.toString());
ShardTestKit.waitUntilLeader(leader);
public void testDelayedEntityOwnerSelection() throws Exception {
testLog.info("testDelayedEntityOwnerSelection starting");
- ShardTestKit kit = new ShardTestKit(getSystem());
- EntityOwnerSelectionStrategyConfig.Builder builder = EntityOwnerSelectionStrategyConfig.newBuilder().
- addStrategy(ENTITY_TYPE, LastCandidateSelectionStrategy.class, 500);
+ final ShardTestKit kit = new ShardTestKit(getSystem());
+ EntityOwnerSelectionStrategyConfig.Builder builder = EntityOwnerSelectionStrategyConfig.newBuilder()
+ .addStrategy(ENTITY_TYPE, LastCandidateSelectionStrategy.class, 500);
dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2);
peer2.underlyingActor().startDroppingMessagesOfType(ElectionTimeout.class);
TestActorRef<EntityOwnershipShard> leader = actorFactory.createTestActor(
- newShardProps(leaderId, peerMap(peerId1.toString(), peerId2.toString()), LOCAL_MEMBER_NAME, builder.build()),
- leaderId.toString());
+ newShardProps(leaderId, peerMap(peerId1.toString(), peerId2.toString()), LOCAL_MEMBER_NAME,
+ builder.build()), leaderId.toString());
ShardTestKit.waitUntilLeader(leader);
private Map<String, String> peerMap(String... peerIds) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String>builder();
- for(String peerId: peerIds) {
+ for (String peerId: peerIds) {
builder.put(peerId, actorFactory.createTestActorPath(peerId)).build();
}
@Override
public void handleCommand(Object message) {
Predicate drop = dropMessagesOfType.get(message.getClass());
- if(drop == null || !drop.test(message)) {
+ if (drop == null || !drop.test(message)) {
super.handleCommand(message);
}
- if(collectorActor != null) {
+ if (collectorActor != null) {
collectorActor.tell(message, ActorRef.noSender());
}
}
}
static Props props(Builder builder, TestActorRef<MessageCollectorActor> collectorActor) {
- return Props.create(TestEntityOwnershipShard.class, builder, collectorActor).
- withDispatcher(Dispatchers.DefaultDispatcherId());
+ return Props.create(TestEntityOwnershipShard.class, builder, collectorActor)
+ .withDispatcher(Dispatchers.DefaultDispatcherId());
}
}
}
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityEntryWithOwner;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityOwnersWithCandidate;
import static org.opendaylight.controller.cluster.datastore.entityownership.EntityOwnersModel.entityPath;
+
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
@Test
public void testOnDataTreeChanged() throws Exception {
- Map<String, Map<String, Long>> statistics = null;
writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, ENTITY_ID1, LOCAL_MEMBER_NAME));
writeNode(ENTITY_OWNERS_PATH, entityOwnersWithCandidate(ENTITY_TYPE, ENTITY_ID2, LOCAL_MEMBER_NAME));
// Change owner to remote member 1 for entity 1
writeNode(entityPath(ENTITY_TYPE, ENTITY_ID1), entityEntryWithOwner(ENTITY_ID1, REMOTE_MEMBER_NAME1));
- statistics = ownershipStatistics.all();
+ Map<String, Map<String, Long>> statistics = ownershipStatistics.all();
assertStatistics(statistics, LOCAL_MEMBER_NAME, 0L);
assertStatistics(statistics, REMOTE_MEMBER_NAME1, 1L);
}
- private static void assertStatistics(final Map<String, Map<String, Long>> statistics, final String memberName, final long val) {
+ private static void assertStatistics(final Map<String, Map<String, Long>> statistics, final String memberName,
+ final long val) {
assertEquals(val, statistics.get(ENTITY_TYPE).get(memberName).longValue());
}
- private void writeNode(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node) throws DataValidationFailedException {
+ private void writeNode(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node)
+ throws DataValidationFailedException {
AbstractEntityOwnershipTest.writeNode(path, node, shardDataTree);
}
-}
\ No newline at end of file
+}
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
+
import java.io.IOException;
import java.util.Collections;
import java.util.Hashtable;
}
@Test
- public void testReadStrategies(){
+ public void testReadStrategies() {
Hashtable<String, Object> props = new Hashtable<>();
- props.put("entity.type.test", "org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.LastCandidateSelectionStrategy,100");
+ props.put("entity.type.test", "org.opendaylight.controller.cluster.datastore.entityownership."
+ + "selectionstrategy.LastCandidateSelectionStrategy,100");
doReturn(props).when(mockConfig).getProperties();
assertTrue(strategy.toString(), strategy instanceof LastCandidateSelectionStrategy);
assertEquals(100L, strategy.getSelectionDelayInMillis());
- final EntityOwnerSelectionStrategy strategy1 = config.createStrategy("test", Collections.<String, Long>emptyMap());
+ final EntityOwnerSelectionStrategy strategy1 = config.createStrategy("test", Collections.emptyMap());
assertEquals(strategy, strategy1);
config.clearStrategies();
- final EntityOwnerSelectionStrategy strategy2 = config.createStrategy("test", Collections.<String, Long>emptyMap());
+ final EntityOwnerSelectionStrategy strategy2 = config.createStrategy("test", Collections.emptyMap());
assertNotEquals(strategy1, strategy2);
}
@Test
public void testReadStrategiesWithIOException() throws IOException {
- doThrow(IOException.class).when(mockConfigAdmin).getConfiguration(EntityOwnerSelectionStrategyConfigReader.CONFIG_ID);
+ doThrow(IOException.class).when(mockConfigAdmin).getConfiguration(
+ EntityOwnerSelectionStrategyConfigReader.CONFIG_ID);
EntityOwnerSelectionStrategyConfig config = loadStrategyConfig();
}
@Test(expected = IllegalArgumentException.class)
- public void testReadStrategiesInvalidDelay(){
+ public void testReadStrategiesInvalidDelay() {
Hashtable<String, Object> props = new Hashtable<>();
- props.put("entity.type.test", "org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.LastCandidateSelectionStrategy,foo");
+ props.put("entity.type.test", "org.opendaylight.controller.cluster.datastore.entityownership."
+ + "selectionstrategy.LastCandidateSelectionStrategy,foo");
doReturn(props).when(mockConfig).getProperties();
}
@Test(expected = IllegalArgumentException.class)
- public void testReadStrategiesInvalidClassType(){
+ public void testReadStrategiesInvalidClassType() {
Hashtable<String, Object> props = new Hashtable<>();
props.put("entity.type.test", "String,100");
}
@Test
- public void testReadStrategiesMissingDelay(){
+ public void testReadStrategiesMissingDelay() {
Hashtable<String, Object> props = new Hashtable<>();
- props.put("entity.type.test", "org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.LastCandidateSelectionStrategy,100");
- props.put("entity.type.test1", "org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy.LastCandidateSelectionStrategy");
+ props.put("entity.type.test", "org.opendaylight.controller.cluster.datastore.entityownership."
+ + "selectionstrategy.LastCandidateSelectionStrategy,100");
+ props.put("entity.type.test1", "org.opendaylight.controller.cluster.datastore.entityownership."
+ + "selectionstrategy.LastCandidateSelectionStrategy");
doReturn(props).when(mockConfig).getProperties();
EntityOwnerSelectionStrategyConfig config = loadStrategyConfig();
- assertEquals(100, config.createStrategy("test", Collections.<String, Long>emptyMap()).getSelectionDelayInMillis());
- assertEquals(0, config.createStrategy("test2", Collections.<String, Long>emptyMap()).getSelectionDelayInMillis());
+ assertEquals(100, config.createStrategy("test", Collections.emptyMap()).getSelectionDelayInMillis());
+ assertEquals(0, config.createStrategy("test2", Collections.emptyMap()).getSelectionDelayInMillis());
}
-
-}
\ No newline at end of file
+}
package org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy;
import static org.junit.Assert.assertEquals;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class LeastLoadedCandidateSelectionStrategyTest {
@Test
- public void testLeastLoadedStrategy(){
- LeastLoadedCandidateSelectionStrategy strategy = new LeastLoadedCandidateSelectionStrategy(0L, Collections.<String, Long>emptyMap());
+ public void testLeastLoadedStrategy() {
+ LeastLoadedCandidateSelectionStrategy strategy = new LeastLoadedCandidateSelectionStrategy(
+ 0L, Collections.<String, Long>emptyMap());
String owner = strategy.newOwner(null, prepareViableCandidates(3));
assertEquals("member-1", owner);
}
- private static Map<String, Long> prepareStatistics(long... count){
+ private static Map<String, Long> prepareStatistics(long... count) {
Map<String, Long> statistics = new HashMap<>();
- for(int i=0;i<count.length;i++){
- statistics.put("member-" + (i+1), count[i]);
+ for (int i = 0; i < count.length; i++) {
+ statistics.put("member-" + (i + 1), count[i]);
}
return statistics;
}
- private static Collection<String> prepareViableCandidates(int count){
+ private static Collection<String> prepareViableCandidates(int count) {
Collection<String> viableCandidates = new ArrayList<>();
- for(int i=0;i<count;i++){
- viableCandidates.add("member-" + (i+1));
+ for (int i = 0; i < count; i++) {
+ viableCandidates.add("member-" + (i + 1));
}
return viableCandidates;
}
- private static void assertStatistics(Map<String, Long> statistics, long... count){
- for(int i=0;i<count.length;i++){
- assertEquals(count[i], (long) statistics.get("member-" + (i+1)));
+ private static void assertStatistics(Map<String, Long> statistics, long... count) {
+ for (int i = 0; i < count.length; i++) {
+ assertEquals(count[i], (long) statistics.get("member-" + (i + 1)));
}
}
-}
\ No newline at end of file
+}
package org.opendaylight.controller.cluster.datastore.identifiers;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
import org.opendaylight.controller.cluster.access.concepts.MemberName;
public class ShardIdentifierTest {
@Test
- public void testBasic(){
+ public void testBasic() {
ShardIdentifier id = ShardIdentifier.create("inventory", MemberName.forName("member-1"), "config");
assertEquals("member-1-shard-inventory-config", id.toString());
}
@Test
- public void testFromShardIdString(){
+ public void testFromShardIdString() {
String shardIdStr = "member-1-shard-inventory-config";
ShardIdentifier id = ShardIdentifier.fromShardIdString(shardIdStr);
package org.opendaylight.controller.cluster.datastore.identifiers;
-import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
- public class ShardManagerIdentifierTest {
+import org.junit.Test;
+
+public class ShardManagerIdentifierTest {
@Test
- public void testIdentifier(){
- assertEquals("shardmanager-operational", ShardManagerIdentifier.builder().type("operational").build().toString());
+ public void testIdentifier() {
+ assertEquals("shardmanager-operational", ShardManagerIdentifier.builder().type("operational")
+ .build().toString());
}
-
}
*/
package org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard;
+import java.lang.management.ManagementFactory;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-import java.lang.management.ManagementFactory;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
public class ShardStatsTest {
private MBeanServer mbeanServer;
private ShardStats shardStats;
shardStats = new ShardStats("shard-1", "DataStore");
shardStats.registerMBean();
mbeanServer = ManagementFactory.getPlatformMBeanServer();
- String objectName =
- AbstractMXBean.BASE_JMX_PREFIX + "type=" + shardStats
- .getMBeanType() + ",Category=" +
- shardStats.getMBeanCategory() + ",name=" +
- shardStats.getMBeanName();
+ String objectName = AbstractMXBean.BASE_JMX_PREFIX + "type=" + shardStats.getMBeanType() + ",Category="
+ + shardStats.getMBeanCategory() + ",name=" + shardStats.getMBeanName();
testMBeanName = new ObjectName(objectName);
}
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
@Test
public void testSerialization() {
AbortTransaction expected = new AbortTransaction(
- MockIdentifiers.transactionIdentifier(AbortTransactionTest.class, "mock"), DataStoreVersions.CURRENT_VERSION);
+ MockIdentifiers.transactionIdentifier(AbortTransactionTest.class, "mock"),
+ DataStoreVersions.CURRENT_VERSION);
Object serialized = expected.toSerializable();
assertEquals("Serialized type", AbortTransaction.class, serialized.getClass());
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
public void testSerialization() {
YangInstanceIdentifier writePath = TestModel.TEST_PATH;
NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
YangInstanceIdentifier mergePath = TestModel.OUTER_LIST_PATH;
NormalizedNode<?, ?> mergeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
@Test
public void testSerialization() {
- CanCommitTransaction expected = new CanCommitTransaction(nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
+ CanCommitTransaction expected = new CanCommitTransaction(nextTransactionId(),
+ DataStoreVersions.CURRENT_VERSION);
Object serialized = expected.toSerializable();
assertEquals("Serialized type", CanCommitTransaction.class, serialized.getClass());
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
@Test
public void testSerialization() {
- CreateTransactionReply expected = new CreateTransactionReply("txPath", nextTransactionId(), DataStoreVersions.CURRENT_VERSION);
+ CreateTransactionReply expected = new CreateTransactionReply("txPath", nextTransactionId(),
+ DataStoreVersions.CURRENT_VERSION);
Object serialized = expected.toSerializable();
assertEquals("Serialized type", CreateTransactionReply.class, serialized.getClass());
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
@Test
public void testSerialization() {
- DOMImmutableDataChangeEvent change = DOMImmutableDataChangeEvent.builder(DataChangeScope.SUBTREE).
- addCreated(TestModel.TEST_PATH, ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build()).
- addUpdated(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
- ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.NAME_QNAME, "bar")).build())
-.
- addRemoved(TestModel.OUTER_LIST_PATH,
- ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build()).
- setBefore(ImmutableNodes.containerNode(TestModel.TEST_QNAME)).
- setAfter(ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).
- withChild(ImmutableNodes.leafNode(TestModel.NAME_QNAME, "bar")).build()).build();
+ DOMImmutableDataChangeEvent change = DOMImmutableDataChangeEvent.builder(DataChangeScope.SUBTREE)
+ .addCreated(TestModel.TEST_PATH,
+ ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build())
+ .addUpdated(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME),
+ ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.NAME_QNAME, "bar")).build())
+ .addRemoved(TestModel.OUTER_LIST_PATH,
+ ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build())
+ .setBefore(ImmutableNodes.containerNode(TestModel.TEST_QNAME))
+ .setAfter(ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo"))
+ .withChild(ImmutableNodes.leafNode(TestModel.NAME_QNAME, "bar")).build())
+ .build();
DataChanged expected = new DataChanged(change);
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore.messages;
-
-import org.junit.Test;
-
-public class FindPrimaryTest {
-
- @Test
- public void testNewBuilderForType() throws Exception {
-
- }
-
- @Test
- public void testToBuilder() throws Exception {
-
- }
-
- @Test
- public void testGetDefaultInstanceForType() throws Exception {
-
- }
-}
\ No newline at end of file
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
@Test
public void testSerialization() {
- NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
ReadDataReply expected = new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION);
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+
import java.util.List;
import org.junit.Test;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
package org.opendaylight.controller.cluster.datastore.messages;
import static org.junit.Assert.assertEquals;
+
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
public abstract class AbstractModificationTest {
- protected InMemoryDOMDataStore store;
+ protected InMemoryDOMDataStore store;
- @Before
- public void setUp(){
- store = new InMemoryDOMDataStore("test", MoreExecutors.newDirectExecutorService());
- store.onGlobalContextUpdated(TestModel.createTestContext());
- }
+ @Before
+ public void setUp() {
+ store = new InMemoryDOMDataStore("test", MoreExecutors.newDirectExecutorService());
+ store.onGlobalContextUpdated(TestModel.createTestContext());
+ }
- protected void commitTransaction(final DOMStoreWriteTransaction transaction){
- DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
- cohort.preCommit();
- cohort.commit();
- }
+ protected void commitTransaction(final DOMStoreWriteTransaction transaction) {
+ DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
+ cohort.preCommit();
+ cohort.commit();
+ }
- protected Optional<NormalizedNode<?,?>> readData(final YangInstanceIdentifier path) throws Exception{
- DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
- ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
- return future.get();
- }
+ protected Optional<NormalizedNode<?, ?>> readData(final YangInstanceIdentifier path) throws Exception {
+ DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
+ ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
+ return future.get();
+ }
}
package org.opendaylight.controller.cluster.datastore.modification;
import static org.junit.Assert.assertEquals;
+
import com.google.common.base.Optional;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Assert;
package org.opendaylight.controller.cluster.datastore.modification;
import static org.junit.Assert.assertEquals;
+
import com.google.common.base.Optional;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Assert;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
-public class MergeModificationTest extends AbstractModificationTest{
+public class MergeModificationTest extends AbstractModificationTest {
@Test
public void testApply() throws Exception {
@Test
public void testSerialization() {
YangInstanceIdentifier path = TestModel.TEST_PATH;
- NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
MergeModification expected = new MergeModification(path, data);
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+
import com.google.common.base.Optional;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;
@Test
public void testSerialization() {
YangInstanceIdentifier writePath = TestModel.TEST_PATH;
- NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
YangInstanceIdentifier mergePath = TestModel.OUTER_LIST_PATH;
NormalizedNode<?, ?> mergeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
compositeModification.addModification(new MergeModification(mergePath, mergeData));
compositeModification.addModification(new DeleteModification(deletePath));
- MutableCompositeModification clone = (MutableCompositeModification) SerializationUtils.clone(compositeModification);
+ MutableCompositeModification clone = (MutableCompositeModification)
+ SerializationUtils.clone(compositeModification);
assertEquals("getVersion", DataStoreVersions.CURRENT_VERSION, clone.getVersion());
package org.opendaylight.controller.cluster.datastore.modification;
import static org.junit.Assert.assertEquals;
+
import com.google.common.base.Optional;
import org.apache.commons.lang.SerializationUtils;
import org.junit.Assert;
@Test
public void testSerialization() {
YangInstanceIdentifier path = TestModel.TEST_PATH;
- NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> data = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
WriteModification expected = new WriteModification(path, data);
package org.opendaylight.controller.cluster.datastore.persisted;
import static org.junit.Assert.assertEquals;
+
import java.io.IOException;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
+
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.lang3.SerializationUtils;
private DataTreeCandidate candidate;
- private static DataTreeCandidateNode findNode(final Collection<DataTreeCandidateNode> nodes, final PathArgument arg) {
+ private static DataTreeCandidateNode findNode(final Collection<DataTreeCandidateNode> nodes,
+ final PathArgument arg) {
for (DataTreeCandidateNode node : nodes) {
if (arg.equals(node.getIdentifier())) {
return node;
assertEquals("root type", expRoot.getModificationType(), actRoot.getModificationType());
switch (actRoot.getModificationType()) {
- case DELETE:
- case WRITE:
- assertEquals("root data", expRoot.getDataAfter(), actRoot.getDataAfter());
- break;
- case SUBTREE_MODIFIED:
- assertChildrenEquals(expRoot.getChildNodes(), actRoot.getChildNodes());
- break;
- default:
- fail("Unexpect root type " + actRoot.getModificationType());
- break;
+ case DELETE:
+ case WRITE:
+ assertEquals("root data", expRoot.getDataAfter(), actRoot.getDataAfter());
+ break;
+ case SUBTREE_MODIFIED:
+ assertChildrenEquals(expRoot.getChildNodes(), actRoot.getChildNodes());
+ break;
+ default:
+ fail("Unexpect root type " + actRoot.getModificationType());
+ break;
}
assertCandidateNodeEquals(expected.getRootNode(), actual.getRootNode());
}
- private static void assertCandidateNodeEquals(final DataTreeCandidateNode expected, final DataTreeCandidateNode actual) {
+ private static void assertCandidateNodeEquals(final DataTreeCandidateNode expected,
+ final DataTreeCandidateNode actual) {
assertEquals("child type", expected.getModificationType(), actual.getModificationType());
assertEquals("child identifier", expected.getIdentifier(), actual.getIdentifier());
switch (actual.getModificationType()) {
- case DELETE:
- case WRITE:
- assertEquals("child data", expected.getDataAfter(), actual.getDataAfter());
- break;
- case SUBTREE_MODIFIED:
- assertChildrenEquals(expected.getChildNodes(), actual.getChildNodes());
- break;
- default:
- fail("Unexpect root type " + actual.getModificationType());
- break;
+ case DELETE:
+ case WRITE:
+ assertEquals("child data", expected.getDataAfter(), actual.getDataAfter());
+ break;
+ case SUBTREE_MODIFIED:
+ assertChildrenEquals(expected.getChildNodes(), actual.getChildNodes());
+ break;
+ default:
+ fail("Unexpect root type " + actual.getModificationType());
+ break;
}
}
public void setUp() {
setUpStatic();
final YangInstanceIdentifier writePath = TestModel.TEST_PATH;
- final NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ final NormalizedNode<?, ?> writeData = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
candidate = DataTreeCandidates.fromNormalizedNode(writePath, writeData);
}
YangInstanceIdentifier leafSetEntryPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET)
.node(entryPathArg).build();
- NormalizedNode<?, ?> leafSetEntryNode = Builders.leafSetEntryBuilder().
- withNodeIdentifier(entryPathArg).withValue("one").build();
+ NormalizedNode<?, ?> leafSetEntryNode = Builders.leafSetEntryBuilder().withNodeIdentifier(entryPathArg)
+ .withValue("one").build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafSetEntryPath, leafSetEntryNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetEntryPath, leafSetEntryNode);
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
assertCandidateEquals(candidate, payload.getCandidate().getValue());
}
YangInstanceIdentifier.NodeWithValue entryPathArg = new YangInstanceIdentifier.NodeWithValue(LEAF_SET, "one");
YangInstanceIdentifier leafSetPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET).build();
- LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder().
- withNodeIdentifier(entryPathArg).withValue("one").build();
+ LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder().withNodeIdentifier(entryPathArg)
+ .withValue("one").build();
NormalizedNode<?, ?> leafSetNode = Builders.leafSetBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(LEAF_SET)).withChild(leafSetEntryNode).build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, leafSetNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, leafSetNode);
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
assertCandidateEquals(candidate, payload.getCandidate().getValue());
}
YangInstanceIdentifier.NodeWithValue entryPathArg = new YangInstanceIdentifier.NodeWithValue(LEAF_SET, "one");
YangInstanceIdentifier leafSetPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET).build();
- LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder().
- withNodeIdentifier(entryPathArg).withValue("one").build();
+ LeafSetEntryNode leafSetEntryNode = Builders.leafSetEntryBuilder().withNodeIdentifier(entryPathArg)
+ .withValue("one").build();
NormalizedNode<?, ?> leafSetNode = Builders.orderedLeafSetBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(LEAF_SET)).withChild(leafSetEntryNode).build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, leafSetNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, leafSetNode);
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
assertCandidateEquals(candidate, payload.getCandidate().getValue());
}
@Test
public void testLeafNodeCandidate() throws Exception {
- YangInstanceIdentifier leafPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(TestModel.DESC_QNAME).build();
+ YangInstanceIdentifier leafPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH)
+ .node(TestModel.DESC_QNAME).build();
LeafNode<Object> leafNode = Builders.leafBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(TestModel.DESC_QNAME)).withValue("test").build();
- DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(leafPath, leafNode);
+ candidate = DataTreeCandidates.fromNormalizedNode(leafPath, leafNode);
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
assertCandidateEquals(candidate, payload.getCandidate().getValue());
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeSet;
}
private static FrontendShardDataTreeSnapshotMetadata createEmptyMetadataSnapshot() {
- return new FrontendShardDataTreeSnapshotMetadata(Collections.<FrontendClientMetadata> emptyList());
+ return new FrontendShardDataTreeSnapshotMetadata(Collections.<FrontendClientMetadata>emptyList());
}
private static FrontendShardDataTreeSnapshotMetadata createMetadataSnapshot(final int size) {
return new FrontendShardDataTreeSnapshotMetadata(clients);
}
- private static FrontendClientMetadata createFrontedClientMetadata(final long i) {
- final String index = String.valueOf(i);
+ private static FrontendClientMetadata createFrontedClientMetadata(final long num) {
+ final String index = String.valueOf(num);
final String indexName = "test_" + index;
final FrontendIdentifier frontendIdentifier = FrontendIdentifier.create(MemberName.forName(indexName),
FrontendType.forName(index));
- final ClientIdentifier clientIdentifier = ClientIdentifier.create(frontendIdentifier, i);
+ final ClientIdentifier clientIdentifier = ClientIdentifier.create(frontendIdentifier, num);
final RangeSet<UnsignedLong> purgedHistories = TreeRangeSet.create();
purgedHistories.add(Range.closed(UnsignedLong.ZERO, UnsignedLong.ONE));
final Collection<FrontendHistoryMetadata> currentHistories = Collections
- .singleton(new FrontendHistoryMetadata(i, i, i, true));
+ .singleton(new FrontendHistoryMetadata(num, num, num, true));
return new FrontendClientMetadata(clientIdentifier, purgedHistories, currentHistories);
}
- private static final <T> void testObject(final T object, final T equalObject) {
+ private static <T> void testObject(final T object, final T equalObject) {
assertEquals(object.hashCode(), equalObject.hashCode());
assertTrue(object.equals(object));
assertTrue(object.equals(equalObject));
}
@SuppressWarnings("unchecked")
- private static <T> T copy(final T o) throws IOException, ClassNotFoundException {
+ private static <T> T copy(final T obj) throws IOException, ClassNotFoundException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
- oos.writeObject(o);
+ oos.writeObject(obj);
}
try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
package org.opendaylight.controller.cluster.datastore.persisted;
import static org.junit.Assert.assertEquals;
+
import com.google.common.collect.ImmutableMap;
import java.io.Externalizable;
import java.io.IOException;
@Test
public void testShardDataTreeSnapshotWithNoMetadata() throws Exception {
- NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
MetadataShardDataTreeSnapshot snapshot = new MetadataShardDataTreeSnapshot(expectedNode);
byte[] serialized = snapshot.serialize();
@Test
public void testShardDataTreeSnapshotWithMetadata() throws Exception {
- NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> expMetadata =
ImmutableMap.of(TestShardDataTreeSnapshotMetadata.class, new TestShardDataTreeSnapshotMetadata("test"));
@Test
public void testPreBoronShardDataTreeSnapshot() throws Exception {
- NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME)).
- withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
+ NormalizedNode<?, ?> expectedNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
PreBoronShardDataTreeSnapshot snapshot = new PreBoronShardDataTreeSnapshot(expectedNode);
byte[] serialized = snapshot.serialize();
assertEquals("Deserialized type", PreBoronShardDataTreeSnapshot.class, deserialized.getClass());
}
- static class TestShardDataTreeSnapshotMetadata extends ShardDataTreeSnapshotMetadata<TestShardDataTreeSnapshotMetadata> {
+ static class TestShardDataTreeSnapshotMetadata
+ extends ShardDataTreeSnapshotMetadata<TestShardDataTreeSnapshotMetadata> {
private static final long serialVersionUID = 1L;
private final String data;
@Override
public boolean equals(Object obj) {
- return data.equals(((TestShardDataTreeSnapshotMetadata)obj).data);
+ return obj instanceof TestShardDataTreeSnapshotMetadata
+ && data.equals(((TestShardDataTreeSnapshotMetadata)obj).data);
}
private static class Proxy implements Externalizable {
private String data;
+ @SuppressWarnings("checkstyle:RedundantModifier")
public Proxy() {
}
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+
import akka.actor.ActorRef;
import akka.actor.Status.Failure;
import akka.actor.Terminated;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.AddressFromURIString;
@Mock
private static CountDownLatch ready;
- private static TestActorRef<MessageCollectorActor> mockShardActor;
+ private static ShardIdentifier mockShardName = ShardIdentifier.create(Shard.DEFAULT_NAME, MEMBER_1, "config");
- private static ShardIdentifier mockShardName;
+ private static TestActorRef<MessageCollectorActor> mockShardActor = TestActorRef.create(getSystem(),
+ Props.create(MessageCollectorActor.class), mockShardName.toString());
- private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder().
- dataStoreName(shardMrgIDSuffix).shardInitializationTimeout(600, TimeUnit.MILLISECONDS)
- .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(6);
+ private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder()
+ .dataStoreName(shardMrgIDSuffix).shardInitializationTimeout(600, TimeUnit.MILLISECONDS)
+ .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(6);
private final Collection<ActorSystem> actorSystems = new ArrayList<>();
InMemoryJournal.clear();
InMemorySnapshotStore.clear();
- if(mockShardActor == null) {
- mockShardName = ShardIdentifier.create(Shard.DEFAULT_NAME, MEMBER_1, "config");
- mockShardActor = TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class),
- mockShardName.toString());
- }
-
mockShardActor.underlyingActor().clear();
}
InMemoryJournal.clear();
InMemorySnapshotStore.clear();
- for(ActorSystem system: actorSystems) {
+ for (ActorSystem system: actorSystems) {
JavaTestKit.shutdownActorSystem(system, null, Boolean.TRUE);
}
private ActorRef newMockShardActor(ActorSystem system, String shardName, String memberName) {
String name = ShardIdentifier.create(shardName, MemberName.forName(memberName), "config").toString();
- if(system == getSystem()) {
+ if (system == getSystem()) {
return actorFactory.createTestActor(Props.create(MessageCollectorActor.class), name);
}
return newShardMgrProps(new MockConfiguration());
}
+ private Props newShardMgrProps(Configuration config) {
+ return newTestShardMgrBuilder(config).props();
+ }
+
private static DatastoreContextFactory newDatastoreContextFactory(DatastoreContext datastoreContext) {
DatastoreContextFactory mockFactory = mock(DatastoreContextFactory.class);
Mockito.doReturn(datastoreContext).when(mockFactory).getBaseDatastoreContext();
return TestShardManager.builder(datastoreContextBuilder).configuration(config);
}
- private Props newShardMgrProps(Configuration config) {
- return newTestShardMgrBuilder(config).props();
- }
-
private TestShardManager.Builder newTestShardMgrBuilderWithMockShardActor() {
return newTestShardMgrBuilderWithMockShardActor(mockShardActor);
}
private static void waitForShardInitialized(ActorRef shardManager, String shardName, JavaTestKit kit) {
AssertionError last = null;
Stopwatch sw = Stopwatch.createStarted();
- while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
+ while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
try {
shardManager.tell(new FindLocalShard(shardName, true), kit.getRef());
kit.expectMsgClass(LocalShardFound.class);
return;
- } catch(AssertionError e) {
+ } catch (AssertionError e) {
last = e;
}
throw last;
}
+ @SuppressWarnings("unchecked")
private static <T> T expectMsgClassOrFailure(Class<T> msgClass, JavaTestKit kit, String msg) {
Object reply = kit.expectMsgAnyClassOf(JavaTestKit.duration("5 sec"), msgClass, Failure.class);
- if(reply instanceof Failure) {
+ if (reply instanceof Failure) {
throw new AssertionError(msg + " failed", ((Failure)reply).cause());
}
final DatastoreContextFactory mockFactory = newDatastoreContextFactory(
datastoreContextBuilder.shardElectionTimeoutFactor(5).build());
- Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
- shardElectionTimeoutFactor(6).build()).when(mockFactory).getShardDatastoreContext("default");
+ Mockito.doReturn(
+ DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).shardElectionTimeoutFactor(6).build())
+ .when(mockFactory).getShardDatastoreContext("default");
- Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
- shardElectionTimeoutFactor(7).build()).when(mockFactory).getShardDatastoreContext("topology");
+ Mockito.doReturn(
+ DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).shardElectionTimeoutFactor(7).build())
+ .when(mockFactory).getShardDatastoreContext("topology");
final MockConfiguration mockConfig = new MockConfiguration() {
@Override
final PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
final CountDownLatch newShardActorLatch = new CountDownLatch(2);
class LocalShardManager extends ShardManager {
- public LocalShardManager(AbstractShardManagerCreator<?> creator) {
+ LocalShardManager(AbstractShardManagerCreator<?> creator) {
super(creator);
}
protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
Entry<ActorRef, DatastoreContext> entry = shardInfoMap.get(info.getShardName());
ActorRef ref = null;
- if(entry != null) {
+ if (entry != null) {
ref = entry.getKey();
entry.setValue(info.getDatastoreContext());
}
private static final long serialVersionUID = 1L;
@Override
public ShardManager create() throws Exception {
- return new LocalShardManager(new GenericCreator<LocalShardManager>(LocalShardManager.class).
- datastoreContextFactory(mockFactory).primaryShardInfoCache(primaryShardInfoCache).
- configuration(mockConfig));
+ return new LocalShardManager(
+ new GenericCreator<>(LocalShardManager.class).datastoreContextFactory(mockFactory)
+ .primaryShardInfoCache(primaryShardInfoCache).configuration(mockConfig));
}
};
shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), kit.getRef());
assertEquals("Shard actors created", true, newShardActorLatch.await(5, TimeUnit.SECONDS));
- assertEquals("getShardElectionTimeoutFactor", 6, shardInfoMap.get("default").getValue().
- getShardElectionTimeoutFactor());
- assertEquals("getShardElectionTimeoutFactor", 7, shardInfoMap.get("topology").getValue().
- getShardElectionTimeoutFactor());
+ assertEquals("getShardElectionTimeoutFactor", 6,
+ shardInfoMap.get("default").getValue().getShardElectionTimeoutFactor());
+ assertEquals("getShardElectionTimeoutFactor", 7,
+ shardInfoMap.get("topology").getValue().getShardElectionTimeoutFactor());
DatastoreContextFactory newMockFactory = newDatastoreContextFactory(
datastoreContextBuilder.shardElectionTimeoutFactor(5).build());
- Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
- shardElectionTimeoutFactor(66).build()).when(newMockFactory).getShardDatastoreContext("default");
+ Mockito.doReturn(
+ DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).shardElectionTimeoutFactor(66).build())
+ .when(newMockFactory).getShardDatastoreContext("default");
- Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
- shardElectionTimeoutFactor(77).build()).when(newMockFactory).getShardDatastoreContext("topology");
+ Mockito.doReturn(
+ DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).shardElectionTimeoutFactor(77).build())
+ .when(newMockFactory).getShardDatastoreContext("topology");
shardManager.tell(newMockFactory, kit.getRef());
- DatastoreContext newContext = MessageCollectorActor.expectFirstMatching(defaultShardActor, DatastoreContext.class);
+ DatastoreContext newContext = MessageCollectorActor.expectFirstMatching(defaultShardActor,
+ DatastoreContext.class);
assertEquals("getShardElectionTimeoutFactor", 66, newContext.getShardElectionTimeoutFactor());
newContext = MessageCollectorActor.expectFirstMatching(topologyShardActor, DatastoreContext.class);
@Test
public void testOnReceiveFindPrimaryForNonExistentShard() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new FindPrimary("non-existent", false), getRef());
+ shardManager.tell(new FindPrimary("non-existent", false), getRef());
- expectMsgClass(duration("5 seconds"), PrimaryNotFoundException.class);
- }};
+ expectMsgClass(duration("5 seconds"), PrimaryNotFoundException.class);
+ }
+ };
}
@Test
public void testOnReceiveFindPrimaryForLocalLeaderShard() throws Exception {
LOG.info("testOnReceiveFindPrimaryForLocalLeaderShard starting");
- new JavaTestKit(getSystem()) {{
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- DataTree mockDataTree = mock(DataTree.class);
- shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
- DataStoreVersions.CURRENT_VERSION), getRef());
+ DataTree mockDataTree = mock(DataTree.class);
+ shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
+ DataStoreVersions.CURRENT_VERSION), getRef());
- MessageCollectorActor.expectFirstMatching(mockShardActor, RegisterRoleChangeListener.class);
- shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
- RaftState.Leader.name())), mockShardActor);
+ MessageCollectorActor.expectFirstMatching(mockShardActor, RegisterRoleChangeListener.class);
+ shardManager.tell(
+ new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
- LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
- assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
- primaryFound.getPrimaryPath().contains("member-1-shard-default"));
- assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
- }};
+ LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"),
+ LocalPrimaryShardFound.class);
+ assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
+ primaryFound.getPrimaryPath().contains("member-1-shard-default"));
+ assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
+ }
+ };
LOG.info("testOnReceiveFindPrimaryForLocalLeaderShard ending");
}
@Test
public void testOnReceiveFindPrimaryForNonLocalLeaderShardBeforeMemberUp() throws Exception {
LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShardBeforeMemberUp starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
- String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.tell(new RoleChangeNotification(memberId1,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
- shardManager.tell(new LeaderStateChanged(memberId1, memberId2, DataStoreVersions.CURRENT_VERSION), mockShardActor);
+ String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
+ String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.tell(
+ new RoleChangeNotification(memberId1, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor);
+ shardManager.tell(new LeaderStateChanged(memberId1, memberId2, DataStoreVersions.CURRENT_VERSION),
+ mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
- }};
+ expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
+ }
+ };
LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShardBeforeMemberUp ending");
}
@Test
public void testOnReceiveFindPrimaryForNonLocalLeaderShard() throws Exception {
LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShard starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
-
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
-
- String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
- MockClusterWrapper.sendMemberUp(shardManager, "member-2", getRef().path().toString());
-
- String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.tell(new RoleChangeNotification(memberId1,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
- short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
- shardManager.tell(new ShardLeaderStateChanged(memberId1, memberId2, leaderVersion), mockShardActor);
-
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
-
- RemotePrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
- assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
- primaryFound.getPrimaryPath().contains("member-2-shard-default"));
- assertEquals("getPrimaryVersion", leaderVersion, primaryFound.getPrimaryVersion());
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
+
+ String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
+ MockClusterWrapper.sendMemberUp(shardManager, "member-2", getRef().path().toString());
+
+ String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.tell(
+ new RoleChangeNotification(memberId1, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor);
+ short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
+ shardManager.tell(new ShardLeaderStateChanged(memberId1, memberId2, leaderVersion), mockShardActor);
+
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+
+ RemotePrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"),
+ RemotePrimaryShardFound.class);
+ assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
+ primaryFound.getPrimaryPath().contains("member-2-shard-default"));
+ assertEquals("getPrimaryVersion", leaderVersion, primaryFound.getPrimaryVersion());
+ }
+ };
LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShard ending");
}
@Test
public void testOnReceiveFindPrimaryForUninitializedShard() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), NotInitializedException.class);
- }};
+ expectMsgClass(duration("5 seconds"), NotInitializedException.class);
+ }
+ };
}
@Test
public void testOnReceiveFindPrimaryForInitializedShardWithNoRole() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
- }};
+ expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
+ }
+ };
}
@Test
public void testOnReceiveFindPrimaryForFollowerShardWithNoInitialLeaderId() throws Exception {
LOG.info("testOnReceiveFindPrimaryForFollowerShardWithNoInitialLeaderId starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.tell(new RoleChangeNotification(memberId,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.tell(
+ new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
+ expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
- DataTree mockDataTree = mock(DataTree.class);
- shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
- DataStoreVersions.CURRENT_VERSION), mockShardActor);
+ DataTree mockDataTree = mock(DataTree.class);
+ shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
+ DataStoreVersions.CURRENT_VERSION), mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
- LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
- assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
- primaryFound.getPrimaryPath().contains("member-1-shard-default"));
- assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
- }};
+ LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"),
+ LocalPrimaryShardFound.class);
+ assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
+ primaryFound.getPrimaryPath().contains("member-1-shard-default"));
+ assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
+ }
+ };
LOG.info("testOnReceiveFindPrimaryForFollowerShardWithNoInitialLeaderId starting");
}
public void testOnReceiveFindPrimaryWaitForShardLeader() throws Exception {
LOG.info("testOnReceiveFindPrimaryWaitForShardLeader starting");
datastoreContextBuilder.shardInitializationTimeout(10, TimeUnit.SECONDS);
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- // We're passing waitUntilInitialized = true to FindPrimary so the response should be
- // delayed until we send ActorInitialized and RoleChangeNotification.
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
+ // We're passing waitUntilInitialized = true to FindPrimary so
+ // the response should be
+ // delayed until we send ActorInitialized and
+ // RoleChangeNotification.
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
- expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
+ expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
+ expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.tell(new RoleChangeNotification(memberId,
- RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor);
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.tell(
+ new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardActor);
- expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
+ expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
- DataTree mockDataTree = mock(DataTree.class);
- shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
- DataStoreVersions.CURRENT_VERSION), mockShardActor);
+ DataTree mockDataTree = mock(DataTree.class);
+ shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
+ DataStoreVersions.CURRENT_VERSION), mockShardActor);
- LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
- assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
- primaryFound.getPrimaryPath().contains("member-1-shard-default"));
- assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree() );
+ LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"),
+ LocalPrimaryShardFound.class);
+ assertTrue("Unexpected primary path " + primaryFound.getPrimaryPath(),
+ primaryFound.getPrimaryPath().contains("member-1-shard-default"));
+ assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
- expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
- }};
+ expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
+ }
+ };
LOG.info("testOnReceiveFindPrimaryWaitForShardLeader ending");
}
@Test
public void testOnReceiveFindPrimaryWaitForReadyWithUninitializedShard() throws Exception {
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithUninitializedShard starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
- expectMsgClass(duration("2 seconds"), NotInitializedException.class);
+ expectMsgClass(duration("2 seconds"), NotInitializedException.class);
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
- }};
+ expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
+ }
+ };
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithUninitializedShard ending");
}
@Test
public void testOnReceiveFindPrimaryWaitForReadyWithCandidateShard() throws Exception {
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithCandidateShard starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix,
- null, RaftState.Candidate.name()), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix, null,
+ RaftState.Candidate.name()), mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
- expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
- }};
+ expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
+ }
+ };
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithCandidateShard ending");
}
@Test
public void testOnReceiveFindPrimaryWaitForReadyWithIsolatedLeaderShard() throws Exception {
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithIsolatedLeaderShard starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix,
- null, RaftState.IsolatedLeader.name()), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix, null,
+ RaftState.IsolatedLeader.name()), mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
- expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
- }};
+ expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
+ }
+ };
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithIsolatedLeaderShard ending");
}
@Test
public void testOnReceiveFindPrimaryWaitForReadyWithNoRoleShard() throws Exception {
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithNoRoleShard starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
+ shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
- expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
- }};
+ expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
+ }
+ };
LOG.info("testOnReceiveFindPrimaryWaitForReadyWithNoRoleShard ending");
}
final ActorRef mockShardActor2 = newMockShardActor(system2, "astronauts", "member-2");
- MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).
- put("astronauts", Arrays.asList("member-2")).build());
+ MockConfiguration mockConfig2 = new MockConfiguration(
+ ImmutableMap.<String, List<String>>builder().put("default", Arrays.asList("member-1", "member-2"))
+ .put("astronauts", Arrays.asList("member-2")).build());
final TestActorRef<TestShardManager> shardManager2 = TestActorRef.create(system2,
newTestShardMgrBuilder(mockConfig2).shardActor(mockShardActor2).cluster(
new ClusterWrapperImpl(system2)).props().withDispatcher(
Dispatchers.DefaultDispatcherId()), shardManagerID);
- new JavaTestKit(system1) {{
-
- shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ new JavaTestKit(system1) {
+ {
+ shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ shardManager2.tell(new ActorInitialized(), mockShardActor2);
- String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
- short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
- shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2,
- mock(DataTree.class), leaderVersion), mockShardActor2);
- shardManager2.tell(new RoleChangeNotification(memberId2,
- RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor2);
+ String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
+ short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
+ shardManager2.tell(
+ new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class), leaderVersion),
+ mockShardActor2);
+ shardManager2.tell(
+ new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardActor2);
- shardManager1.underlyingActor().waitForMemberUp();
- shardManager1.tell(new FindPrimary("astronauts", false), getRef());
+ shardManager1.underlyingActor().waitForMemberUp();
+ shardManager1.tell(new FindPrimary("astronauts", false), getRef());
- RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
- String path = found.getPrimaryPath();
- assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-astronauts-config"));
- assertEquals("getPrimaryVersion", leaderVersion, found.getPrimaryVersion());
+ RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
+ String path = found.getPrimaryPath();
+ assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-astronauts-config"));
+ assertEquals("getPrimaryVersion", leaderVersion, found.getPrimaryVersion());
- shardManager2.underlyingActor().verifyFindPrimary();
+ shardManager2.underlyingActor().verifyFindPrimary();
- Cluster.get(system2).down(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
+ Cluster.get(system2).down(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
- shardManager1.underlyingActor().waitForMemberRemoved();
+ shardManager1.underlyingActor().waitForMemberRemoved();
- shardManager1.tell(new FindPrimary("astronauts", false), getRef());
+ shardManager1.tell(new FindPrimary("astronauts", false), getRef());
- expectMsgClass(duration("5 seconds"), PrimaryNotFoundException.class);
- }};
+ expectMsgClass(duration("5 seconds"), PrimaryNotFoundException.class);
+ }
+ };
LOG.info("testOnReceiveFindPrimaryForRemoteShard ending");
}
final ActorRef mockShardActor2 = newMockShardActor(system2, Shard.DEFAULT_NAME, "member-2");
- MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).build());
+ MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("default", Arrays.asList("member-1", "member-2")).build());
final TestActorRef<TestShardManager> shardManager2 = TestActorRef.create(system2,
newTestShardMgrBuilder(mockConfig2).shardActor(mockShardActor2).cluster(
new ClusterWrapperImpl(system2)).props().withDispatcher(
Dispatchers.DefaultDispatcherId()), shardManagerID);
- new JavaTestKit(system1) {{
+ new JavaTestKit(system1) {
+ {
+ shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager1.tell(new ActorInitialized(), mockShardActor1);
+ shardManager2.tell(new ActorInitialized(), mockShardActor2);
- shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager1.tell(new ActorInitialized(), mockShardActor1);
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
+ String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId2, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), mockShardActor1);
+ shardManager1.tell(
+ new RoleChangeNotification(memberId1, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor1);
+ shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), mockShardActor2);
+ shardManager2.tell(
+ new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardActor2);
+ shardManager1.underlyingActor().waitForMemberUp();
- String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
- String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId2,
- mock(DataTree.class), DataStoreVersions.CURRENT_VERSION), mockShardActor1);
- shardManager1.tell(new RoleChangeNotification(memberId1,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor1);
- shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION),
- mockShardActor2);
- shardManager2.tell(new RoleChangeNotification(memberId2,
- RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor2);
- shardManager1.underlyingActor().waitForMemberUp();
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
+ String path = found.getPrimaryPath();
+ assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-default-config"));
- RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
- String path = found.getPrimaryPath();
- assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-default-config"));
+ shardManager1.tell(MockClusterWrapper.createUnreachableMember("member-2",
+ "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
- shardManager1.tell(MockClusterWrapper.
- createUnreachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
+ shardManager1.underlyingActor().waitForUnreachableMember();
- shardManager1.underlyingActor().waitForUnreachableMember();
+ PeerDown peerDown = MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerDown.class);
+ assertEquals("getMemberName", MEMBER_2, peerDown.getMemberName());
+ MessageCollectorActor.clearMessages(mockShardActor1);
- PeerDown peerDown = MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerDown.class);
- assertEquals("getMemberName", MEMBER_2, peerDown.getMemberName());
- MessageCollectorActor.clearMessages(mockShardActor1);
+ shardManager1.tell(
+ MockClusterWrapper.createMemberRemoved("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"),
+ getRef());
- shardManager1.tell(MockClusterWrapper.
- createMemberRemoved("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
+ MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerDown.class);
- MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerDown.class);
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
- expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
+ shardManager1.tell(
+ MockClusterWrapper.createReachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"),
+ getRef());
- shardManager1.tell(MockClusterWrapper.
- createReachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
+ shardManager1.underlyingActor().waitForReachableMember();
- shardManager1.underlyingActor().waitForReachableMember();
+ PeerUp peerUp = MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerUp.class);
+ assertEquals("getMemberName", MEMBER_2, peerUp.getMemberName());
+ MessageCollectorActor.clearMessages(mockShardActor1);
- PeerUp peerUp = MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerUp.class);
- assertEquals("getMemberName", MEMBER_2, peerUp.getMemberName());
- MessageCollectorActor.clearMessages(mockShardActor1);
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ RemotePrimaryShardFound found1 = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
+ String path1 = found1.getPrimaryPath();
+ assertTrue("Unexpected primary path " + path1, path1.contains("member-2-shard-default-config"));
- RemotePrimaryShardFound found1 = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
- String path1 = found1.getPrimaryPath();
- assertTrue("Unexpected primary path " + path1, path1.contains("member-2-shard-default-config"));
+ shardManager1.tell(
+ MockClusterWrapper.createMemberUp("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"),
+ getRef());
- shardManager1.tell(MockClusterWrapper.
- createMemberUp("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
+ MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerUp.class);
- MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerUp.class);
+ // Test FindPrimary wait succeeds after reachable member event.
- // Test FindPrimary wait succeeds after reachable member event.
+ shardManager1.tell(MockClusterWrapper.createUnreachableMember("member-2",
+ "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
+ shardManager1.underlyingActor().waitForUnreachableMember();
- shardManager1.tell(MockClusterWrapper.
- createUnreachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
- shardManager1.underlyingActor().waitForUnreachableMember();
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ shardManager1.tell(
+ MockClusterWrapper.createReachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"),
+ getRef());
- shardManager1.tell(MockClusterWrapper.
- createReachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
-
- RemotePrimaryShardFound found2 = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
- String path2 = found2.getPrimaryPath();
- assertTrue("Unexpected primary path " + path2, path2.contains("member-2-shard-default-config"));
- }};
+ RemotePrimaryShardFound found2 = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
+ String path2 = found2.getPrimaryPath();
+ assertTrue("Unexpected primary path " + path2, path2.contains("member-2-shard-default-config"));
+ }
+ };
LOG.info("testShardAvailabilityOnChangeOfMemberReachability ending");
}
final PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
final TestActorRef<TestShardManager> shardManager1 = TestActorRef.create(system1,
- newTestShardMgrBuilder().shardActor(mockShardActor1).cluster(
- new ClusterWrapperImpl(system1)).primaryShardInfoCache(primaryShardInfoCache).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), shardManagerID);
+ newTestShardMgrBuilder().shardActor(mockShardActor1).cluster(new ClusterWrapperImpl(system1))
+ .primaryShardInfoCache(primaryShardInfoCache).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
+ shardManagerID);
// Create an ActorSystem ShardManager actor for member-2.
final ActorRef mockShardActor2 = newMockShardActor(system2, Shard.DEFAULT_NAME, "member-2");
- MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).build());
+ MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("default", Arrays.asList("member-1", "member-2")).build());
final TestActorRef<TestShardManager> shardManager2 = TestActorRef.create(system2,
newTestShardMgrBuilder(mockConfig2).shardActor(mockShardActor2).cluster(
new ClusterWrapperImpl(system2)).props().withDispatcher(
Dispatchers.DefaultDispatcherId()), shardManagerID);
- new JavaTestKit(system1) {{
- shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager1.tell(new ActorInitialized(), mockShardActor1);
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ new JavaTestKit(system1) {
+ {
+ shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager1.tell(new ActorInitialized(), mockShardActor1);
+ shardManager2.tell(new ActorInitialized(), mockShardActor2);
- String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
- String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId2,
- mock(DataTree.class), DataStoreVersions.CURRENT_VERSION), mockShardActor1);
- shardManager1.tell(new RoleChangeNotification(memberId1,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor1);
- shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION),
- mockShardActor2);
- shardManager2.tell(new RoleChangeNotification(memberId2,
- RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor2);
- shardManager1.underlyingActor().waitForMemberUp();
+ String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
+ String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId2, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), mockShardActor1);
+ shardManager1.tell(
+ new RoleChangeNotification(memberId1, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor1);
+ shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), mockShardActor2);
+ shardManager2.tell(
+ new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardActor2);
+ shardManager1.underlyingActor().waitForMemberUp();
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
- String path = found.getPrimaryPath();
- assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-default-config"));
+ RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
+ String path = found.getPrimaryPath();
+ assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-default-config"));
- primaryShardInfoCache.putSuccessful("default", new PrimaryShardInfo(system1.actorSelection(
- mockShardActor1.path()), DataStoreVersions.CURRENT_VERSION));
+ primaryShardInfoCache.putSuccessful("default", new PrimaryShardInfo(
+ system1.actorSelection(mockShardActor1.path()), DataStoreVersions.CURRENT_VERSION));
- shardManager1.tell(MockClusterWrapper.
- createUnreachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
+ shardManager1.tell(MockClusterWrapper.createUnreachableMember("member-2",
+ "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
- shardManager1.underlyingActor().waitForUnreachableMember();
+ shardManager1.underlyingActor().waitForUnreachableMember();
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
+ expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
- assertNull("Expected primaryShardInfoCache entry removed", primaryShardInfoCache.getIfPresent("default"));
+ assertNull("Expected primaryShardInfoCache entry removed",
+ primaryShardInfoCache.getIfPresent("default"));
- shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId1, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION), mockShardActor1);
- shardManager1.tell(new RoleChangeNotification(memberId1,
- RaftState.Follower.name(), RaftState.Leader.name()), mockShardActor1);
+ shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId1, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), mockShardActor1);
+ shardManager1.tell(
+ new RoleChangeNotification(memberId1, RaftState.Follower.name(), RaftState.Leader.name()),
+ mockShardActor1);
- shardManager1.tell(new FindPrimary("default", true), getRef());
+ shardManager1.tell(new FindPrimary("default", true), getRef());
- LocalPrimaryShardFound found1 = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
- String path1 = found1.getPrimaryPath();
- assertTrue("Unexpected primary path " + path1, path1.contains("member-1-shard-default-config"));
+ LocalPrimaryShardFound found1 = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
+ String path1 = found1.getPrimaryPath();
+ assertTrue("Unexpected primary path " + path1, path1.contains("member-1-shard-default-config"));
- }};
+ }
+ };
LOG.info("testShardAvailabilityChangeOnMemberUnreachableAndLeadershipChange ending");
}
@Test
public void testOnReceiveFindLocalShardForNonExistentShard() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new FindLocalShard("non-existent", false), getRef());
+ shardManager.tell(new FindLocalShard("non-existent", false), getRef());
- LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
+ LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
- assertEquals("getShardName", "non-existent", notFound.getShardName());
- }};
+ assertEquals("getShardName", "non-existent", notFound.getShardName());
+ }
+ };
}
@Test
public void testOnReceiveFindLocalShardForExistentShard() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
- LocalShardFound found = expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ LocalShardFound found = expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- assertTrue("Found path contains " + found.getPath().path().toString(),
- found.getPath().path().toString().contains("member-1-shard-default-config"));
- }};
+ assertTrue("Found path contains " + found.getPath().path().toString(),
+ found.getPath().path().toString().contains("member-1-shard-default-config"));
+ }
+ };
}
@Test
public void testOnReceiveFindLocalShardForNotInitializedShard() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
+ shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), NotInitializedException.class);
- }};
+ expectMsgClass(duration("5 seconds"), NotInitializedException.class);
+ }
+ };
}
@Test
public void testOnReceiveFindLocalShardWaitForShardInitialized() throws Exception {
LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- // We're passing waitUntilInitialized = true to FindLocalShard so the response should be
- // delayed until we send ActorInitialized.
- Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true),
- new Timeout(5, TimeUnit.SECONDS));
+ // We're passing waitUntilInitialized = true to FindLocalShard
+ // so the response should be
+ // delayed until we send ActorInitialized.
+ Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true),
+ new Timeout(5, TimeUnit.SECONDS));
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- Object resp = Await.result(future, duration("5 seconds"));
- assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
- }};
+ Object resp = Await.result(future, duration("5 seconds"));
+ assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
+ }
+ };
LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
}
@Test
public void testRoleChangeNotificationToFollowerWithShardLeaderStateChangedReleaseReady() throws Exception {
- new JavaTestKit(getSystem()) {{
- TestShardManager shardManager = newTestShardManager();
+ new JavaTestKit(getSystem()) {
+ {
+ TestShardManager shardManager = newTestShardManager();
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.onReceiveCommand(new RoleChangeNotification(
- memberId, null, RaftState.Follower.name()));
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.onReceiveCommand(new RoleChangeNotification(memberId, null, RaftState.Follower.name()));
- verify(ready, never()).countDown();
+ verify(ready, never()).countDown();
- shardManager.onReceiveCommand(MockClusterWrapper.createMemberUp("member-2", getRef().path().toString()));
+ shardManager
+ .onReceiveCommand(MockClusterWrapper.createMemberUp("member-2", getRef().path().toString()));
- shardManager.onReceiveCommand(new ShardLeaderStateChanged(memberId,
- "member-2-shard-default-" + shardMrgIDSuffix, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION));
+ shardManager.onReceiveCommand(
+ new ShardLeaderStateChanged(memberId, "member-2-shard-default-" + shardMrgIDSuffix,
+ mock(DataTree.class), DataStoreVersions.CURRENT_VERSION));
- verify(ready, times(1)).countDown();
- }};
+ verify(ready, times(1)).countDown();
+ }
+ };
}
@Test
public void testReadyCountDownForMemberUpAfterLeaderStateChanged() throws Exception {
- new JavaTestKit(getSystem()) {{
- TestShardManager shardManager = newTestShardManager();
+ new JavaTestKit(getSystem()) {
+ {
+ TestShardManager shardManager = newTestShardManager();
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.onReceiveCommand(new RoleChangeNotification(memberId, null, RaftState.Follower.name()));
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.onReceiveCommand(new RoleChangeNotification(memberId, null, RaftState.Follower.name()));
- verify(ready, never()).countDown();
+ verify(ready, never()).countDown();
- shardManager.onReceiveCommand(new ShardLeaderStateChanged(memberId,
- "member-2-shard-default-" + shardMrgIDSuffix, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION));
+ shardManager.onReceiveCommand(
+ new ShardLeaderStateChanged(memberId, "member-2-shard-default-" + shardMrgIDSuffix,
+ mock(DataTree.class), DataStoreVersions.CURRENT_VERSION));
- shardManager.onReceiveCommand(MockClusterWrapper.createMemberUp("member-2", getRef().path().toString()));
+ shardManager
+ .onReceiveCommand(MockClusterWrapper.createMemberUp("member-2", getRef().path().toString()));
- verify(ready, times(1)).countDown();
- }};
+ verify(ready, times(1)).countDown();
+ }
+ };
}
@Test
}
@Test
- public void testByDefaultSyncStatusIsFalse() throws Exception{
+ public void testByDefaultSyncStatusIsFalse() throws Exception {
TestShardManager shardManager = newTestShardManager();
assertEquals(false, shardManager.getMBean().getSyncStatus());
}
@Test
- public void testWhenShardIsLeaderSyncStatusIsTrue() throws Exception{
+ public void testWhenShardIsLeaderSyncStatusIsTrue() throws Exception {
TestShardManager shardManager = newTestShardManager();
shardManager.onReceiveCommand(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix,
}
@Test
- public void testWhenShardIsCandidateSyncStatusIsFalse() throws Exception{
+ public void testWhenShardIsCandidateSyncStatusIsFalse() throws Exception {
TestShardManager shardManager = newTestShardManager();
String shardId = "member-1-shard-default-" + shardMrgIDSuffix;
}
@Test
- public void testWhenShardIsFollowerSyncStatusDependsOnFollowerInitialSyncStatus() throws Exception{
+ public void testWhenShardIsFollowerSyncStatusDependsOnFollowerInitialSyncStatus() throws Exception {
TestShardManager shardManager = newTestShardManager();
String shardId = "member-1-shard-default-" + shardMrgIDSuffix;
}
@Test
- public void testWhenMultipleShardsPresentSyncStatusMustBeTrueForAllShards() throws Exception{
+ public void testWhenMultipleShardsPresentSyncStatusMustBeTrueForAllShards() throws Exception {
LOG.info("testWhenMultipleShardsPresentSyncStatusMustBeTrueForAllShards starting");
TestShardManager shardManager = newTestShardManager(newShardMgrProps(new MockConfiguration() {
@Override
@Test
public void testOnReceiveSwitchShardBehavior() throws Exception {
- new JavaTestKit(getSystem()) {{
- final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+ new JavaTestKit(getSystem()) {
+ {
+ final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new SwitchShardBehavior(mockShardName, RaftState.Leader, 1000), getRef());
+ shardManager.tell(new SwitchShardBehavior(mockShardName, RaftState.Leader, 1000), getRef());
- SwitchBehavior switchBehavior = MessageCollectorActor.expectFirstMatching(mockShardActor, SwitchBehavior.class);
+ SwitchBehavior switchBehavior = MessageCollectorActor.expectFirstMatching(mockShardActor,
+ SwitchBehavior.class);
- assertEquals(RaftState.Leader, switchBehavior.getNewState());
- assertEquals(1000, switchBehavior.getNewTerm());
- }};
+ assertEquals(RaftState.Leader, switchBehavior.getNewState());
+ assertEquals(1000, switchBehavior.getNewTerm());
+ }
+ };
}
private static List<MemberName> members(String... names) {
@Test
public void testOnCreateShard() {
LOG.info("testOnCreateShard starting");
- new JavaTestKit(getSystem()) {{
- datastoreContextBuilder.shardInitializationTimeout(1, TimeUnit.MINUTES).persistent(true);
+ new JavaTestKit(getSystem()) {
+ {
+ datastoreContextBuilder.shardInitializationTimeout(1, TimeUnit.MINUTES).persistent(true);
- ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
- new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
+ ActorRef shardManager = actorFactory
+ .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
- SchemaContext schemaContext = TestModel.createTestContext();
- shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
+ SchemaContext schemaContext = TestModel.createTestContext();
+ shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
- DatastoreContext datastoreContext = DatastoreContext.newBuilder().shardElectionTimeoutFactor(100).
- persistent(false).build();
- Shard.Builder shardBuilder = Shard.builder();
+ DatastoreContext datastoreContext = DatastoreContext.newBuilder().shardElectionTimeoutFactor(100)
+ .persistent(false).build();
+ Shard.Builder shardBuilder = Shard.builder();
- ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
- "foo", null, members("member-1", "member-5", "member-6"));
- shardManager.tell(new CreateShard(config, shardBuilder, datastoreContext), getRef());
+ ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
+ "foo", null, members("member-1", "member-5", "member-6"));
+ shardManager.tell(new CreateShard(config, shardBuilder, datastoreContext), getRef());
- expectMsgClass(duration("5 seconds"), Success.class);
+ expectMsgClass(duration("5 seconds"), Success.class);
- shardManager.tell(new FindLocalShard("foo", true), getRef());
+ shardManager.tell(new FindLocalShard("foo", true), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- assertEquals("isRecoveryApplicable", false, shardBuilder.getDatastoreContext().isPersistent());
- assertTrue("Epxected ShardPeerAddressResolver", shardBuilder.getDatastoreContext().getShardRaftConfig().
- getPeerAddressResolver() instanceof ShardPeerAddressResolver);
- assertEquals("peerMembers", Sets.newHashSet(
- ShardIdentifier.create("foo", MemberName.forName("member-5"), shardMrgIDSuffix).toString(),
- ShardIdentifier.create("foo", MemberName.forName("member-6"), shardMrgIDSuffix).toString()),
- shardBuilder.getPeerAddresses().keySet());
- assertEquals("ShardIdentifier", ShardIdentifier.create("foo", MEMBER_1, shardMrgIDSuffix),
- shardBuilder.getId());
- assertSame("schemaContext", schemaContext, shardBuilder.getSchemaContext());
+ assertEquals("isRecoveryApplicable", false, shardBuilder.getDatastoreContext().isPersistent());
+ assertTrue("Epxected ShardPeerAddressResolver", shardBuilder.getDatastoreContext().getShardRaftConfig()
+ .getPeerAddressResolver() instanceof ShardPeerAddressResolver);
+ assertEquals("peerMembers", Sets.newHashSet(
+ ShardIdentifier.create("foo", MemberName.forName("member-5"), shardMrgIDSuffix).toString(),
+ ShardIdentifier.create("foo", MemberName.forName("member-6"), shardMrgIDSuffix).toString()),
+ shardBuilder.getPeerAddresses().keySet());
+ assertEquals("ShardIdentifier", ShardIdentifier.create("foo", MEMBER_1, shardMrgIDSuffix),
+ shardBuilder.getId());
+ assertSame("schemaContext", schemaContext, shardBuilder.getSchemaContext());
- // Send CreateShard with same name - should return Success with a message.
+ // Send CreateShard with same name - should return Success with
+ // a message.
- shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
+ shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
- Success success = expectMsgClass(duration("5 seconds"), Success.class);
- assertNotNull("Success status is null", success.status());
- }};
+ Success success = expectMsgClass(duration("5 seconds"), Success.class);
+ assertNotNull("Success status is null", success.status());
+ }
+ };
LOG.info("testOnCreateShard ending");
}
@Test
public void testOnCreateShardWithLocalMemberNotInShardConfig() {
LOG.info("testOnCreateShardWithLocalMemberNotInShardConfig starting");
- new JavaTestKit(getSystem()) {{
- datastoreContextBuilder.shardInitializationTimeout(1, TimeUnit.MINUTES).persistent(true);
+ new JavaTestKit(getSystem()) {
+ {
+ datastoreContextBuilder.shardInitializationTimeout(1, TimeUnit.MINUTES).persistent(true);
- ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
- new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
+ ActorRef shardManager = actorFactory
+ .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
- Shard.Builder shardBuilder = Shard.builder();
- ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
- "foo", null, members("member-5", "member-6"));
+ Shard.Builder shardBuilder = Shard.builder();
+ ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
+ "foo", null, members("member-5", "member-6"));
- shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
- expectMsgClass(duration("5 seconds"), Success.class);
+ shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
+ expectMsgClass(duration("5 seconds"), Success.class);
- shardManager.tell(new FindLocalShard("foo", true), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ shardManager.tell(new FindLocalShard("foo", true), getRef());
+ expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- assertEquals("peerMembers size", 0, shardBuilder.getPeerAddresses().size());
- assertEquals("schemaContext", DisableElectionsRaftPolicy.class.getName(),
- shardBuilder.getDatastoreContext().getShardRaftConfig().getCustomRaftPolicyImplementationClass());
- }};
+ assertEquals("peerMembers size", 0, shardBuilder.getPeerAddresses().size());
+ assertEquals("schemaContext", DisableElectionsRaftPolicy.class.getName(), shardBuilder
+ .getDatastoreContext().getShardRaftConfig().getCustomRaftPolicyImplementationClass());
+ }
+ };
LOG.info("testOnCreateShardWithLocalMemberNotInShardConfig ending");
}
@Test
public void testOnCreateShardWithNoInitialSchemaContext() {
LOG.info("testOnCreateShardWithNoInitialSchemaContext starting");
- new JavaTestKit(getSystem()) {{
- ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
- new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardManager = actorFactory
+ .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
- Shard.Builder shardBuilder = Shard.builder();
+ Shard.Builder shardBuilder = Shard.builder();
- ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
- "foo", null, members("member-1"));
- shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
+ ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
+ "foo", null, members("member-1"));
+ shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
- expectMsgClass(duration("5 seconds"), Success.class);
+ expectMsgClass(duration("5 seconds"), Success.class);
- SchemaContext schemaContext = TestModel.createTestContext();
- shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
+ SchemaContext schemaContext = TestModel.createTestContext();
+ shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
- shardManager.tell(new FindLocalShard("foo", true), getRef());
+ shardManager.tell(new FindLocalShard("foo", true), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- assertSame("schemaContext", schemaContext, shardBuilder.getSchemaContext());
- assertNotNull("schemaContext is null", shardBuilder.getDatastoreContext());
- }};
+ assertSame("schemaContext", schemaContext, shardBuilder.getSchemaContext());
+ assertNotNull("schemaContext is null", shardBuilder.getDatastoreContext());
+ }
+ };
LOG.info("testOnCreateShardWithNoInitialSchemaContext ending");
}
@Test
- public void testGetSnapshot() throws Throwable {
+ public void testGetSnapshot() throws Exception {
LOG.info("testGetSnapshot starting");
JavaTestKit kit = new JavaTestKit(getSystem());
- MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("shard1", Arrays.asList("member-1")).
- put("shard2", Arrays.asList("member-1")).
- put("astronauts", Collections.<String>emptyList()).build());
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("shard1", Arrays.asList("member-1")).put("shard2", Arrays.asList("member-1"))
+ .put("astronauts", Collections.<String>emptyList()).build());
- TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newShardMgrProps(mockConfig).
- withDispatcher(Dispatchers.DefaultDispatcherId()));
+ TestActorRef<TestShardManager> shardManager = actorFactory
+ .createTestActor(newShardMgrProps(mockConfig).withDispatcher(Dispatchers.DefaultDispatcherId()));
shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
Failure failure = kit.expectMsgClass(Failure.class);
}
@Test
- public void testRestoreFromSnapshot() throws Throwable {
+ public void testRestoreFromSnapshot() throws Exception {
LOG.info("testRestoreFromSnapshot starting");
datastoreContextBuilder.shardInitializationTimeout(3, TimeUnit.SECONDS);
JavaTestKit kit = new JavaTestKit(getSystem());
- MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("shard1", Collections.<String>emptyList()).
- put("shard2", Collections.<String>emptyList()).
- put("astronauts", Collections.<String>emptyList()).build());
-
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("shard1", Collections.<String>emptyList()).put("shard2", Collections.<String>emptyList())
+ .put("astronauts", Collections.<String>emptyList()).build());
ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList("shard1", "shard2", "astronauts"));
DatastoreSnapshot restoreFromSnapshot = new DatastoreSnapshot(shardMrgIDSuffix,
SerializationUtils.serialize(snapshot), Collections.<ShardSnapshot>emptyList());
- TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newTestShardMgrBuilder(mockConfig).
- restoreFromSnapshot(restoreFromSnapshot).props().withDispatcher(Dispatchers.DefaultDispatcherId()));
+ TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newTestShardMgrBuilder(mockConfig)
+ .restoreFromSnapshot(restoreFromSnapshot).props().withDispatcher(Dispatchers.DefaultDispatcherId()));
shardManager.underlyingActor().waitForRecoveryComplete();
@Test
public void testAddShardReplicaForNonExistentShardConfig() throws Exception {
- new JavaTestKit(getSystem()) {{
- ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
- new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardManager = actorFactory
+ .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
- shardManager.tell(new AddShardReplica("model-inventory"), getRef());
- Status.Failure resp = expectMsgClass(duration("2 seconds"), Status.Failure.class);
+ shardManager.tell(new AddShardReplica("model-inventory"), getRef());
+ Status.Failure resp = expectMsgClass(duration("2 seconds"), Status.Failure.class);
- assertEquals("Failure obtained", true,
- (resp.cause() instanceof IllegalArgumentException));
- }};
+ assertEquals("Failure obtained", true, resp.cause() instanceof IllegalArgumentException);
+ }
+ };
}
@Test
public void testAddShardReplica() throws Exception {
LOG.info("testAddShardReplica starting");
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).
- put("astronauts", Arrays.asList("member-2")).build());
+ MockConfiguration mockConfig = new MockConfiguration(
+ ImmutableMap.<String, List<String>>builder().put("default", Arrays.asList("member-1", "member-2"))
+ .put("astronauts", Arrays.asList("member-2")).build());
final String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
datastoreContextBuilder.shardManagerPersistenceId(shardManagerID);
Cluster.get(system1).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
ActorRef mockDefaultShardActor = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
final TestActorRef<TestShardManager> newReplicaShardManager = TestActorRef.create(system1,
- newTestShardMgrBuilder(mockConfig).shardActor(mockDefaultShardActor).cluster(
- new ClusterWrapperImpl(system1)).props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardManagerID);
+ newTestShardMgrBuilder(mockConfig).shardActor(mockDefaultShardActor)
+ .cluster(new ClusterWrapperImpl(system1)).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
+ shardManagerID);
// Create an ActorSystem ShardManager actor for member-2.
final ActorSystem system2 = newActorSystem("Member2");
String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
String name = ShardIdentifier.create("astronauts", MEMBER_2, "config").toString();
- final TestActorRef<MockRespondActor> mockShardLeaderActor =
- TestActorRef.create(system2, Props.create(MockRespondActor.class, AddServer.class,
- new AddServerReply(ServerChangeStatus.OK, memberId2)).
- withDispatcher(Dispatchers.DefaultDispatcherId()), name);
+ final TestActorRef<MockRespondActor> mockShardLeaderActor = TestActorRef.create(system2,
+ Props.create(MockRespondActor.class, AddServer.class,
+ new AddServerReply(ServerChangeStatus.OK, memberId2))
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
+ name);
final TestActorRef<TestShardManager> leaderShardManager = TestActorRef.create(system2,
- newTestShardMgrBuilder(mockConfig).shardActor(mockShardLeaderActor).cluster(
- new ClusterWrapperImpl(system2)).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()), shardManagerID);
-
- new JavaTestKit(system1) {{
-
- newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
-
- leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
-
- short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
- leaderShardManager.tell(new ShardLeaderStateChanged(memberId2, memberId2,
- mock(DataTree.class), leaderVersion), mockShardLeaderActor);
- leaderShardManager.tell(new RoleChangeNotification(memberId2,
- RaftState.Candidate.name(), RaftState.Leader.name()), mockShardLeaderActor);
-
- newReplicaShardManager.underlyingActor().waitForMemberUp();
- leaderShardManager.underlyingActor().waitForMemberUp();
-
- //Have a dummy snapshot to be overwritten by the new data persisted.
- String[] restoredShards = {"default", "people"};
- ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList(restoredShards));
- InMemorySnapshotStore.addSnapshot(shardManagerID, snapshot);
- Uninterruptibles.sleepUninterruptibly(2, TimeUnit.MILLISECONDS);
-
- InMemorySnapshotStore.addSnapshotSavedLatch(shardManagerID);
- InMemorySnapshotStore.addSnapshotDeletedLatch(shardManagerID);
-
- //construct a mock response message
- newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
- AddServer addServerMsg = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
- AddServer.class);
- String addServerId = "member-1-shard-astronauts-" + shardMrgIDSuffix;
- assertEquals("AddServer serverId", addServerId, addServerMsg.getNewServerId());
- expectMsgClass(duration("5 seconds"), Status.Success.class);
-
- InMemorySnapshotStore.waitForSavedSnapshot(shardManagerID, ShardManagerSnapshot.class);
- InMemorySnapshotStore.waitForDeletedSnapshot(shardManagerID);
- List<ShardManagerSnapshot> persistedSnapshots =
- InMemorySnapshotStore.getSnapshots(shardManagerID, ShardManagerSnapshot.class);
- assertEquals("Number of snapshots persisted", 1, persistedSnapshots.size());
- ShardManagerSnapshot shardManagerSnapshot = persistedSnapshots.get(0);
- assertEquals("Persisted local shards", Sets.newHashSet("default", "astronauts"),
- Sets.newHashSet(shardManagerSnapshot.getShardList()));
- }};
+ newTestShardMgrBuilder(mockConfig).shardActor(mockShardLeaderActor)
+ .cluster(new ClusterWrapperImpl(system2)).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
+ shardManagerID);
+
+ new JavaTestKit(system1) {
+ {
+ newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+
+ leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
+
+ short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
+ leaderShardManager.tell(
+ new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class), leaderVersion),
+ mockShardLeaderActor);
+ leaderShardManager.tell(
+ new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardLeaderActor);
+
+ newReplicaShardManager.underlyingActor().waitForMemberUp();
+ leaderShardManager.underlyingActor().waitForMemberUp();
+
+ // Have a dummy snapshot to be overwritten by the new data
+ // persisted.
+ String[] restoredShards = { "default", "people" };
+ ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList(restoredShards));
+ InMemorySnapshotStore.addSnapshot(shardManagerID, snapshot);
+ Uninterruptibles.sleepUninterruptibly(2, TimeUnit.MILLISECONDS);
+
+ InMemorySnapshotStore.addSnapshotSavedLatch(shardManagerID);
+ InMemorySnapshotStore.addSnapshotDeletedLatch(shardManagerID);
+
+ // construct a mock response message
+ newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
+ AddServer addServerMsg = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
+ AddServer.class);
+ String addServerId = "member-1-shard-astronauts-" + shardMrgIDSuffix;
+ assertEquals("AddServer serverId", addServerId, addServerMsg.getNewServerId());
+ expectMsgClass(duration("5 seconds"), Status.Success.class);
+
+ InMemorySnapshotStore.waitForSavedSnapshot(shardManagerID, ShardManagerSnapshot.class);
+ InMemorySnapshotStore.waitForDeletedSnapshot(shardManagerID);
+ List<ShardManagerSnapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(shardManagerID,
+ ShardManagerSnapshot.class);
+ assertEquals("Number of snapshots persisted", 1, persistedSnapshots.size());
+ ShardManagerSnapshot shardManagerSnapshot = persistedSnapshots.get(0);
+ assertEquals("Persisted local shards", Sets.newHashSet("default", "astronauts"),
+ Sets.newHashSet(shardManagerSnapshot.getShardList()));
+ }
+ };
LOG.info("testAddShardReplica ending");
}
@Test
public void testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader() throws Exception {
LOG.info("testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader starting");
- new JavaTestKit(getSystem()) {{
- TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
- newPropsShardMgrWithMockShardActor(), shardMgrID);
+ new JavaTestKit(getSystem()) {
+ {
+ TestActorRef<TestShardManager> shardManager = actorFactory
+ .createTestActor(newPropsShardMgrWithMockShardActor(), shardMgrID);
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
- String leaderId = "leader-member-shard-default-" + shardMrgIDSuffix;
- AddServerReply addServerReply = new AddServerReply(ServerChangeStatus.ALREADY_EXISTS, null);
- ActorRef leaderShardActor = shardManager.underlyingActor().getContext().actorOf(
- Props.create(MockRespondActor.class, AddServer.class, addServerReply), leaderId);
+ String leaderId = "leader-member-shard-default-" + shardMrgIDSuffix;
+ AddServerReply addServerReply = new AddServerReply(ServerChangeStatus.ALREADY_EXISTS, null);
+ ActorRef leaderShardActor = shardManager.underlyingActor().getContext()
+ .actorOf(Props.create(MockRespondActor.class, AddServer.class, addServerReply), leaderId);
- MockClusterWrapper.sendMemberUp(shardManager, "leader-member", leaderShardActor.path().toString());
+ MockClusterWrapper.sendMemberUp(shardManager, "leader-member", leaderShardActor.path().toString());
- String newReplicaId = "member-1-shard-default-" + shardMrgIDSuffix;
- shardManager.tell(new RoleChangeNotification(newReplicaId,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
- shardManager.tell(new ShardLeaderStateChanged(newReplicaId, leaderId,
- DataStoreVersions.CURRENT_VERSION), mockShardActor);
+ String newReplicaId = "member-1-shard-default-" + shardMrgIDSuffix;
+ shardManager.tell(
+ new RoleChangeNotification(newReplicaId, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor);
+ shardManager.tell(
+ new ShardLeaderStateChanged(newReplicaId, leaderId, DataStoreVersions.CURRENT_VERSION),
+ mockShardActor);
- shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
+ shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
- MessageCollectorActor.expectFirstMatching(leaderShardActor, AddServer.class);
+ MessageCollectorActor.expectFirstMatching(leaderShardActor, AddServer.class);
- Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
- assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
+ Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
+ assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
- shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
+ expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- // Send message again to verify previous in progress state is cleared
+ // Send message again to verify previous in progress state is
+ // cleared
- shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
- resp = expectMsgClass(duration("5 seconds"), Failure.class);
- assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
+ shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
+ resp = expectMsgClass(duration("5 seconds"), Failure.class);
+ assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
- // Send message again with an AddServer timeout to verify the pre-existing shard actor isn't terminated.
+ // Send message again with an AddServer timeout to verify the
+ // pre-existing shard actor isn't terminated.
- shardManager.tell(newDatastoreContextFactory(datastoreContextBuilder.
- shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build()), getRef());
- leaderShardActor.tell(MockRespondActor.CLEAR_RESPONSE, ActorRef.noSender());
- shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
- expectMsgClass(duration("5 seconds"), Failure.class);
+ shardManager.tell(
+ newDatastoreContextFactory(
+ datastoreContextBuilder.shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build()),
+ getRef());
+ leaderShardActor.tell(MockRespondActor.CLEAR_RESPONSE, ActorRef.noSender());
+ shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
+ expectMsgClass(duration("5 seconds"), Failure.class);
- shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- }};
+ shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
+ expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ }
+ };
LOG.info("testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader ending");
}
@Test
public void testAddShardReplicaWithPreExistingLocalReplicaLeader() throws Exception {
LOG.info("testAddShardReplicaWithPreExistingLocalReplicaLeader starting");
- new JavaTestKit(getSystem()) {{
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
-
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
- shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION), getRef());
- shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
- RaftState.Leader.name())), mockShardActor);
-
- shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
- Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
- assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
-
- shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardFound.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
+
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), getRef());
+ shardManager.tell(
+ new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardActor);
+
+ shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
+ Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
+ assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
+
+ shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
+ expectMsgClass(duration("5 seconds"), LocalShardFound.class);
+ }
+ };
LOG.info("testAddShardReplicaWithPreExistingLocalReplicaLeader ending");
}
@Test
public void testAddShardReplicaWithAddServerReplyFailure() throws Exception {
LOG.info("testAddShardReplicaWithAddServerReplyFailure starting");
- new JavaTestKit(getSystem()) {{
- JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
+ new JavaTestKit(getSystem()) {
+ {
+ JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("astronauts", Arrays.asList("member-2")).build());
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("astronauts", Arrays.asList("member-2")).build());
- ActorRef mockNewReplicaShardActor = newMockShardActor(getSystem(), "astronauts", "member-1");
- final TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
- newTestShardMgrBuilder(mockConfig).shardActor(mockNewReplicaShardActor).props(), shardMgrID);
- shardManager.underlyingActor().setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
+ ActorRef mockNewReplicaShardActor = newMockShardActor(getSystem(), "astronauts", "member-1");
+ final TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
+ newTestShardMgrBuilder(mockConfig).shardActor(mockNewReplicaShardActor).props(), shardMgrID);
+ shardManager.underlyingActor()
+ .setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- JavaTestKit terminateWatcher = new JavaTestKit(getSystem());
- terminateWatcher.watch(mockNewReplicaShardActor);
+ JavaTestKit terminateWatcher = new JavaTestKit(getSystem());
+ terminateWatcher.watch(mockNewReplicaShardActor);
- shardManager.tell(new AddShardReplica("astronauts"), getRef());
+ shardManager.tell(new AddShardReplica("astronauts"), getRef());
- AddServer addServerMsg = mockShardLeaderKit.expectMsgClass(AddServer.class);
- assertEquals("AddServer serverId", "member-1-shard-astronauts-" + shardMrgIDSuffix,
- addServerMsg.getNewServerId());
- mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.TIMEOUT, null));
+ AddServer addServerMsg = mockShardLeaderKit.expectMsgClass(AddServer.class);
+ assertEquals("AddServer serverId", "member-1-shard-astronauts-" + shardMrgIDSuffix,
+ addServerMsg.getNewServerId());
+ mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.TIMEOUT, null));
- Failure failure = expectMsgClass(duration("5 seconds"), Failure.class);
- assertEquals("Failure cause", TimeoutException.class, failure.cause().getClass());
+ Failure failure = expectMsgClass(duration("5 seconds"), Failure.class);
+ assertEquals("Failure cause", TimeoutException.class, failure.cause().getClass());
- shardManager.tell(new FindLocalShard("astronauts", false), getRef());
- expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
+ shardManager.tell(new FindLocalShard("astronauts", false), getRef());
+ expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
- terminateWatcher.expectTerminated(mockNewReplicaShardActor);
+ terminateWatcher.expectTerminated(mockNewReplicaShardActor);
- shardManager.tell(new AddShardReplica("astronauts"), getRef());
- mockShardLeaderKit.expectMsgClass(AddServer.class);
- mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.NO_LEADER, null));
- failure = expectMsgClass(duration("5 seconds"), Failure.class);
- assertEquals("Failure cause", NoShardLeaderException.class, failure.cause().getClass());
- }};
+ shardManager.tell(new AddShardReplica("astronauts"), getRef());
+ mockShardLeaderKit.expectMsgClass(AddServer.class);
+ mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.NO_LEADER, null));
+ failure = expectMsgClass(duration("5 seconds"), Failure.class);
+ assertEquals("Failure cause", NoShardLeaderException.class, failure.cause().getClass());
+ }
+ };
LOG.info("testAddShardReplicaWithAddServerReplyFailure ending");
}
public void testAddShardReplicaWithFindPrimaryTimeout() throws Exception {
LOG.info("testAddShardReplicaWithFindPrimaryTimeout starting");
datastoreContextBuilder.shardInitializationTimeout(100, TimeUnit.MILLISECONDS);
- new JavaTestKit(getSystem()) {{
- MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("astronauts", Arrays.asList("member-2")).build());
+ new JavaTestKit(getSystem()) {
+ {
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("astronauts", Arrays.asList("member-2")).build());
- final ActorRef newReplicaShardManager = actorFactory.createActor(newTestShardMgrBuilder(mockConfig).
- shardActor(mockShardActor).props(), shardMgrID);
+ final ActorRef newReplicaShardManager = actorFactory
+ .createActor(newTestShardMgrBuilder(mockConfig).shardActor(mockShardActor).props(), shardMgrID);
- newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- MockClusterWrapper.sendMemberUp(newReplicaShardManager, "member-2",
- AddressFromURIString.parse("akka.tcp://non-existent@127.0.0.1:5").toString());
+ newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ MockClusterWrapper.sendMemberUp(newReplicaShardManager, "member-2",
+ AddressFromURIString.parse("akka.tcp://non-existent@127.0.0.1:5").toString());
- newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
- Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
- assertEquals("Failure obtained", true,
- (resp.cause() instanceof RuntimeException));
- }};
+ newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
+ Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
+ assertEquals("Failure obtained", true, resp.cause() instanceof RuntimeException);
+ }
+ };
LOG.info("testAddShardReplicaWithFindPrimaryTimeout ending");
}
@Test
public void testRemoveShardReplicaForNonExistentShard() throws Exception {
- new JavaTestKit(getSystem()) {{
- ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
- new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
-
- shardManager.tell(new RemoveShardReplica("model-inventory", MEMBER_1), getRef());
- Status.Failure resp = expectMsgClass(duration("10 seconds"), Status.Failure.class);
- assertEquals("Failure obtained", true,
- (resp.cause() instanceof PrimaryNotFoundException));
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardManager = actorFactory
+ .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
+
+ shardManager.tell(new RemoveShardReplica("model-inventory", MEMBER_1), getRef());
+ Status.Failure resp = expectMsgClass(duration("10 seconds"), Status.Failure.class);
+ assertEquals("Failure obtained", true, resp.cause() instanceof PrimaryNotFoundException);
+ }
+ };
}
@Test
* Primary is Local
*/
public void testRemoveShardReplicaLocal() throws Exception {
- new JavaTestKit(getSystem()) {{
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
-
- final TestActorRef<MockRespondActor> respondActor =
- actorFactory.createTestActor(Props.create(MockRespondActor.class, RemoveServer.class,
- new RemoveServerReply(ServerChangeStatus.OK, null)), memberId);
-
- ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
-
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), respondActor);
- shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION), getRef());
- shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
- RaftState.Leader.name())), respondActor);
-
- shardManager.tell(new RemoveShardReplica(Shard.DEFAULT_NAME, MEMBER_1), getRef());
- final RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(respondActor, RemoveServer.class);
- assertEquals(ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString(),
- removeServer.getServerId());
- expectMsgClass(duration("5 seconds"), Success.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+
+ final TestActorRef<MockRespondActor> respondActor = actorFactory
+ .createTestActor(Props.create(MockRespondActor.class, RemoveServer.class,
+ new RemoveServerReply(ServerChangeStatus.OK, null)), memberId);
+
+ ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
+
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), respondActor);
+ shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), getRef());
+ shardManager.tell(
+ new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
+ respondActor);
+
+ shardManager.tell(new RemoveShardReplica(Shard.DEFAULT_NAME, MEMBER_1), getRef());
+ final RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(respondActor,
+ RemoveServer.class);
+ assertEquals(ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString(),
+ removeServer.getServerId());
+ expectMsgClass(duration("5 seconds"), Success.class);
+ }
+ };
}
@Test
public void testRemoveShardReplicaRemote() throws Exception {
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).
- put("astronauts", Arrays.asList("member-1")).build());
+ MockConfiguration mockConfig = new MockConfiguration(
+ ImmutableMap.<String, List<String>>builder().put("default", Arrays.asList("member-1", "member-2"))
+ .put("astronauts", Arrays.asList("member-1")).build());
String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
// mockShardLeaderActor. The ForwardingActor simply forwards all messages to the mockShardLeaderActor and every
// thing works as expected
final ActorRef actorRef = leaderShardManager.underlyingActor().context()
- .actorOf(Props.create(ForwardingActor.class, mockShardLeaderActor), "member-2-shard-default-" + shardMrgIDSuffix);
+ .actorOf(Props.create(ForwardingActor.class, mockShardLeaderActor),
+ "member-2-shard-default-" + shardMrgIDSuffix);
LOG.error("Forwarding actor : {}", actorRef);
- new JavaTestKit(system1) {{
-
- newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
-
- leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
- newReplicaShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
-
- short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
- leaderShardManager.tell(new ShardLeaderStateChanged(memberId2, memberId2,
- mock(DataTree.class), leaderVersion), mockShardLeaderActor);
- leaderShardManager.tell(new RoleChangeNotification(memberId2,
- RaftState.Candidate.name(), RaftState.Leader.name()), mockShardLeaderActor);
-
- String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
- newReplicaShardManager.tell(new ShardLeaderStateChanged(memberId1, memberId2,
- mock(DataTree.class), leaderVersion), mockShardActor);
- newReplicaShardManager.tell(new RoleChangeNotification(memberId1,
- RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
-
- newReplicaShardManager.underlyingActor().waitForMemberUp();
- leaderShardManager.underlyingActor().waitForMemberUp();
-
- //construct a mock response message
- newReplicaShardManager.tell(new RemoveShardReplica("default", MEMBER_1), getRef());
- RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
- RemoveServer.class);
- String removeServerId = ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString();
- assertEquals("RemoveServer serverId", removeServerId, removeServer.getServerId());
- expectMsgClass(duration("5 seconds"), Status.Success.class);
- }};
-
+ new JavaTestKit(system1) {
+ {
+ newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+
+ leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
+ newReplicaShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
+
+ short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
+ leaderShardManager.tell(
+ new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class), leaderVersion),
+ mockShardLeaderActor);
+ leaderShardManager.tell(
+ new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
+ mockShardLeaderActor);
+
+ String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
+ newReplicaShardManager.tell(
+ new ShardLeaderStateChanged(memberId1, memberId2, mock(DataTree.class), leaderVersion),
+ mockShardActor);
+ newReplicaShardManager.tell(
+ new RoleChangeNotification(memberId1, RaftState.Candidate.name(), RaftState.Follower.name()),
+ mockShardActor);
+
+ newReplicaShardManager.underlyingActor().waitForMemberUp();
+ leaderShardManager.underlyingActor().waitForMemberUp();
+
+ // construct a mock response message
+ newReplicaShardManager.tell(new RemoveShardReplica("default", MEMBER_1), getRef());
+ RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
+ RemoveServer.class);
+ String removeServerId = ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString();
+ assertEquals("RemoveServer serverId", removeServerId, removeServer.getServerId());
+ expectMsgClass(duration("5 seconds"), Status.Success.class);
+ }
+ };
}
@Test
public void testServerChangeWhenAlreadyInProgress(final String shardName, final Object firstServerChange,
final Class<?> firstForwardedServerChangeClass,
final Object secondServerChange) throws Exception {
- new JavaTestKit(getSystem()) {{
- JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
- JavaTestKit secondRequestKit = new JavaTestKit(getSystem());
+ new JavaTestKit(getSystem()) {
+ {
+ JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
+ final JavaTestKit secondRequestKit = new JavaTestKit(getSystem());
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put(shardName, Arrays.asList("member-2")).build());
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put(shardName, Arrays.asList("member-2")).build());
- final TestActorRef<TestShardManager> shardManager = TestActorRef.create(getSystem(),
- newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockShardActor).cluster(
- new MockClusterWrapper()).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
- shardMgrID);
+ final TestActorRef<TestShardManager> shardManager = TestActorRef.create(getSystem(),
+ newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockShardActor)
+ .cluster(new MockClusterWrapper()).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
+ shardMgrID);
- shardManager.underlyingActor().setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
+ shardManager.underlyingActor()
+ .setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(firstServerChange, getRef());
+ shardManager.tell(firstServerChange, getRef());
- mockShardLeaderKit.expectMsgClass(firstForwardedServerChangeClass);
+ mockShardLeaderKit.expectMsgClass(firstForwardedServerChangeClass);
- shardManager.tell(secondServerChange, secondRequestKit.getRef());
+ shardManager.tell(secondServerChange, secondRequestKit.getRef());
- secondRequestKit.expectMsgClass(duration("5 seconds"), Failure.class);
- }};
+ secondRequestKit.expectMsgClass(duration("5 seconds"), Failure.class);
+ }
+ };
}
@Test
public void testServerRemovedShardActorNotRunning() throws Exception {
LOG.info("testServerRemovedShardActorNotRunning starting");
- new JavaTestKit(getSystem()) {{
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).
- put("astronauts", Arrays.asList("member-2")).
- put("people", Arrays.asList("member-1", "member-2")).build());
-
- TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newShardMgrProps(mockConfig));
-
- shardManager.underlyingActor().waitForRecoveryComplete();
- shardManager.tell(new FindLocalShard("people", false), getRef());
- expectMsgClass(duration("5 seconds"), NotInitializedException.class);
-
- shardManager.tell(new FindLocalShard("default", false), getRef());
- expectMsgClass(duration("5 seconds"), NotInitializedException.class);
-
- // Removed the default shard replica from member-1
- ShardIdentifier.Builder builder = new ShardIdentifier.Builder();
- ShardIdentifier shardId = builder.shardName("default").memberName(MEMBER_1).type(shardMrgIDSuffix).build();
- shardManager.tell(new ServerRemoved(shardId.toString()), getRef());
-
- shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("default", Arrays.asList("member-1", "member-2"))
+ .put("astronauts", Arrays.asList("member-2"))
+ .put("people", Arrays.asList("member-1", "member-2")).build());
+
+ TestActorRef<TestShardManager> shardManager = actorFactory
+ .createTestActor(newShardMgrProps(mockConfig));
+
+ shardManager.underlyingActor().waitForRecoveryComplete();
+ shardManager.tell(new FindLocalShard("people", false), getRef());
+ expectMsgClass(duration("5 seconds"), NotInitializedException.class);
+
+ shardManager.tell(new FindLocalShard("default", false), getRef());
+ expectMsgClass(duration("5 seconds"), NotInitializedException.class);
+
+ // Removed the default shard replica from member-1
+ ShardIdentifier.Builder builder = new ShardIdentifier.Builder();
+ ShardIdentifier shardId = builder.shardName("default").memberName(MEMBER_1).type(shardMrgIDSuffix)
+ .build();
+ shardManager.tell(new ServerRemoved(shardId.toString()), getRef());
+
+ shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
+ }
+ };
LOG.info("testServerRemovedShardActorNotRunning ending");
}
@Test
public void testServerRemovedShardActorRunning() throws Exception {
LOG.info("testServerRemovedShardActorRunning starting");
- new JavaTestKit(getSystem()) {{
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).
- put("astronauts", Arrays.asList("member-2")).
- put("people", Arrays.asList("member-1", "member-2")).build());
+ new JavaTestKit(getSystem()) {
+ {
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("default", Arrays.asList("member-1", "member-2"))
+ .put("astronauts", Arrays.asList("member-2"))
+ .put("people", Arrays.asList("member-1", "member-2")).build());
- String shardId = ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString();
- TestActorRef<MessageCollectorActor> shard = actorFactory.createTestActor(
- MessageCollectorActor.props(), shardId);
+ String shardId = ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString();
+ TestActorRef<MessageCollectorActor> shard = actorFactory.createTestActor(MessageCollectorActor.props(),
+ shardId);
- TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
- newTestShardMgrBuilder(mockConfig).addShardActor("default", shard).props());
+ TestActorRef<TestShardManager> shardManager = actorFactory
+ .createTestActor(newTestShardMgrBuilder(mockConfig).addShardActor("default", shard).props());
- shardManager.underlyingActor().waitForRecoveryComplete();
+ shardManager.underlyingActor().waitForRecoveryComplete();
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), shard);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), shard);
- waitForShardInitialized(shardManager, "people", this);
- waitForShardInitialized(shardManager, "default", this);
+ waitForShardInitialized(shardManager, "people", this);
+ waitForShardInitialized(shardManager, "default", this);
- // Removed the default shard replica from member-1
- shardManager.tell(new ServerRemoved(shardId), getRef());
+ // Removed the default shard replica from member-1
+ shardManager.tell(new ServerRemoved(shardId), getRef());
- shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
+ shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
- MessageCollectorActor.expectFirstMatching(shard, Shutdown.class);
- }};
+ MessageCollectorActor.expectFirstMatching(shard, Shutdown.class);
+ }
+ };
LOG.info("testServerRemovedShardActorRunning ending");
}
-
@Test
public void testShardPersistenceWithRestoredData() throws Exception {
LOG.info("testShardPersistenceWithRestoredData starting");
- new JavaTestKit(getSystem()) {{
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("default", Arrays.asList("member-1", "member-2")).
- put("astronauts", Arrays.asList("member-2")).
- put("people", Arrays.asList("member-1", "member-2")).build());
- String[] restoredShards = {"default", "astronauts"};
- ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList(restoredShards));
- InMemorySnapshotStore.addSnapshot("shard-manager-" + shardMrgIDSuffix, snapshot);
-
- //create shardManager to come up with restored data
- TestActorRef<TestShardManager> newRestoredShardManager = actorFactory.createTestActor(
- newShardMgrProps(mockConfig));
-
- newRestoredShardManager.underlyingActor().waitForRecoveryComplete();
-
- newRestoredShardManager.tell(new FindLocalShard("people", false), getRef());
- LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
- assertEquals("for uninitialized shard", "people", notFound.getShardName());
-
- //Verify a local shard is created for the restored shards,
- //although we expect a NotInitializedException for the shards as the actor initialization
- //message is not sent for them
- newRestoredShardManager.tell(new FindLocalShard("default", false), getRef());
- expectMsgClass(duration("5 seconds"), NotInitializedException.class);
-
- newRestoredShardManager.tell(new FindLocalShard("astronauts", false), getRef());
- expectMsgClass(duration("5 seconds"), NotInitializedException.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("default", Arrays.asList("member-1", "member-2"))
+ .put("astronauts", Arrays.asList("member-2"))
+ .put("people", Arrays.asList("member-1", "member-2")).build());
+ String[] restoredShards = { "default", "astronauts" };
+ ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList(restoredShards));
+ InMemorySnapshotStore.addSnapshot("shard-manager-" + shardMrgIDSuffix, snapshot);
+
+ // create shardManager to come up with restored data
+ TestActorRef<TestShardManager> newRestoredShardManager = actorFactory
+ .createTestActor(newShardMgrProps(mockConfig));
+
+ newRestoredShardManager.underlyingActor().waitForRecoveryComplete();
+
+ newRestoredShardManager.tell(new FindLocalShard("people", false), getRef());
+ LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
+ assertEquals("for uninitialized shard", "people", notFound.getShardName());
+
+ // Verify a local shard is created for the restored shards,
+ // although we expect a NotInitializedException for the shards
+ // as the actor initialization
+ // message is not sent for them
+ newRestoredShardManager.tell(new FindLocalShard("default", false), getRef());
+ expectMsgClass(duration("5 seconds"), NotInitializedException.class);
+
+ newRestoredShardManager.tell(new FindLocalShard("astronauts", false), getRef());
+ expectMsgClass(duration("5 seconds"), NotInitializedException.class);
+ }
+ };
LOG.info("testShardPersistenceWithRestoredData ending");
}
@Test
public void testShutDown() throws Exception {
LOG.info("testShutDown starting");
- new JavaTestKit(getSystem()) {{
- MockConfiguration mockConfig =
- new MockConfiguration(ImmutableMap.<String, List<String>>builder().
- put("shard1", Arrays.asList("member-1")).
- put("shard2", Arrays.asList("member-1")).build());
-
- String shardId1 = ShardIdentifier.create("shard1", MEMBER_1, shardMrgIDSuffix).toString();
- TestActorRef<MessageCollectorActor> shard1 = actorFactory.createTestActor(
- MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId1);
-
- String shardId2 = ShardIdentifier.create("shard2", MEMBER_1, shardMrgIDSuffix).toString();
- TestActorRef<MessageCollectorActor> shard2 = actorFactory.createTestActor(
- MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId2);
-
- TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newTestShardMgrBuilder(
- mockConfig).addShardActor("shard1", shard1).addShardActor("shard2", shard2).props().
- withDispatcher(Dispatchers.DefaultDispatcherId()));
-
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), shard1);
- shardManager.tell(new ActorInitialized(), shard2);
-
- FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
- Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);
+ new JavaTestKit(getSystem()) {
+ {
+ MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
+ .put("shard1", Arrays.asList("member-1")).put("shard2", Arrays.asList("member-1")).build());
+
+ String shardId1 = ShardIdentifier.create("shard1", MEMBER_1, shardMrgIDSuffix).toString();
+ TestActorRef<MessageCollectorActor> shard1 = actorFactory.createTestActor(
+ MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId1);
+
+ String shardId2 = ShardIdentifier.create("shard2", MEMBER_1, shardMrgIDSuffix).toString();
+ TestActorRef<MessageCollectorActor> shard2 = actorFactory.createTestActor(
+ MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId2);
+
+ TestActorRef<TestShardManager> shardManager = actorFactory
+ .createTestActor(newTestShardMgrBuilder(mockConfig).addShardActor("shard1", shard1)
+ .addShardActor("shard2", shard2).props()
+ .withDispatcher(Dispatchers.DefaultDispatcherId()));
+
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), shard1);
+ shardManager.tell(new ActorInitialized(), shard2);
+
+ FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
+ Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);
+
+ MessageCollectorActor.expectFirstMatching(shard1, Shutdown.class);
+ MessageCollectorActor.expectFirstMatching(shard2, Shutdown.class);
+
+ try {
+ Await.ready(stopFuture, FiniteDuration.create(500, TimeUnit.MILLISECONDS));
+ fail("ShardManager actor stopped without waiting for the Shards to be stopped");
+ } catch (TimeoutException e) {
+ // expected
+ }
- MessageCollectorActor.expectFirstMatching(shard1, Shutdown.class);
- MessageCollectorActor.expectFirstMatching(shard2, Shutdown.class);
+ actorFactory.killActor(shard1, this);
+ actorFactory.killActor(shard2, this);
- try {
- Await.ready(stopFuture, FiniteDuration.create(500, TimeUnit.MILLISECONDS));
- fail("ShardManager actor stopped without waiting for the Shards to be stopped");
- } catch(TimeoutException e) {
- // expected
+ Boolean stopped = Await.result(stopFuture, duration);
+ assertEquals("Stopped", Boolean.TRUE, stopped);
}
-
- actorFactory.killActor(shard1, this);
- actorFactory.killActor(shard2, this);
-
- Boolean stopped = Await.result(stopFuture, duration);
- assertEquals("Stopped", Boolean.TRUE, stopped);
- }};
+ };
LOG.info("testShutDown ending");
}
@Test
public void testChangeServersVotingStatus() throws Exception {
- new JavaTestKit(getSystem()) {{
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
-
- TestActorRef<MockRespondActor> respondActor =
- actorFactory.createTestActor(Props.create(MockRespondActor.class, ChangeServersVotingStatus.class,
- new ServerChangeReply(ServerChangeStatus.OK, null)), memberId);
-
- ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
-
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), respondActor);
- shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
- DataStoreVersions.CURRENT_VERSION), getRef());
- shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
- RaftState.Leader.name())), respondActor);
-
- shardManager.tell(new ChangeShardMembersVotingStatus("default",
- ImmutableMap.of("member-2", Boolean.TRUE)), getRef());
-
- ChangeServersVotingStatus actualChangeStatusMsg = MessageCollectorActor.expectFirstMatching(
- respondActor, ChangeServersVotingStatus.class);
- assertEquals("ChangeServersVotingStatus map", actualChangeStatusMsg.getServerVotingStatusMap(),
- ImmutableMap.of(ShardIdentifier.create("default", MemberName.forName("member-2"),
- shardMrgIDSuffix).toString(), Boolean.TRUE));
-
- expectMsgClass(duration("5 seconds"), Success.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+
+ TestActorRef<MockRespondActor> respondActor = actorFactory
+ .createTestActor(Props.create(MockRespondActor.class, ChangeServersVotingStatus.class,
+ new ServerChangeReply(ServerChangeStatus.OK, null)), memberId);
+
+ ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
+
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), respondActor);
+ shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
+ DataStoreVersions.CURRENT_VERSION), getRef());
+ shardManager.tell(
+ new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
+ respondActor);
+
+ shardManager.tell(
+ new ChangeShardMembersVotingStatus("default", ImmutableMap.of("member-2", Boolean.TRUE)),
+ getRef());
+
+ ChangeServersVotingStatus actualChangeStatusMsg = MessageCollectorActor
+ .expectFirstMatching(respondActor, ChangeServersVotingStatus.class);
+ assertEquals("ChangeServersVotingStatus map", actualChangeStatusMsg.getServerVotingStatusMap(),
+ ImmutableMap.of(ShardIdentifier
+ .create("default", MemberName.forName("member-2"), shardMrgIDSuffix).toString(),
+ Boolean.TRUE));
+
+ expectMsgClass(duration("5 seconds"), Success.class);
+ }
+ };
}
@Test
public void testChangeServersVotingStatusWithNoLeader() throws Exception {
- new JavaTestKit(getSystem()) {{
- String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
+ new JavaTestKit(getSystem()) {
+ {
+ String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
- TestActorRef<MockRespondActor> respondActor =
- actorFactory.createTestActor(Props.create(MockRespondActor.class, ChangeServersVotingStatus.class,
- new ServerChangeReply(ServerChangeStatus.NO_LEADER, null)), memberId);
+ TestActorRef<MockRespondActor> respondActor = actorFactory
+ .createTestActor(Props.create(MockRespondActor.class, ChangeServersVotingStatus.class,
+ new ServerChangeReply(ServerChangeStatus.NO_LEADER, null)), memberId);
- ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
+ ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
- shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
- shardManager.tell(new ActorInitialized(), respondActor);
- shardManager.tell((new RoleChangeNotification(memberId, null, RaftState.Follower.name())), respondActor);
+ shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+ shardManager.tell(new ActorInitialized(), respondActor);
+ shardManager.tell(new RoleChangeNotification(memberId, null, RaftState.Follower.name()), respondActor);
- shardManager.tell(new ChangeShardMembersVotingStatus("default",
- ImmutableMap.of("member-2", Boolean.TRUE)), getRef());
+ shardManager.tell(
+ new ChangeShardMembersVotingStatus("default", ImmutableMap.of("member-2", Boolean.TRUE)),
+ getRef());
- MessageCollectorActor.expectFirstMatching(respondActor, ChangeServersVotingStatus.class);
+ MessageCollectorActor.expectFirstMatching(respondActor, ChangeServersVotingStatus.class);
- Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
- assertEquals("Failure resposnse", true, (resp.cause() instanceof NoShardLeaderException));
- }};
+ Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
+ assertEquals("Failure resposnse", true, resp.cause() instanceof NoShardLeaderException);
+ }
+ };
}
private static class TestShardManager extends ShardManager {
try {
super.handleRecover(message);
} finally {
- if(message instanceof RecoveryCompleted) {
+ if (message instanceof RecoveryCompleted) {
recoveryComplete.countDown();
}
}
@Override
public void handleCommand(Object message) throws Exception {
- try{
- if(messageInterceptor != null && messageInterceptor.canIntercept(message)) {
+ try {
+ if (messageInterceptor != null && messageInterceptor.canIntercept(message)) {
getSender().tell(messageInterceptor.apply(message), getSelf());
} else {
super.handleCommand(message);
}
} finally {
- if(message instanceof FindPrimary) {
+ if (message instanceof FindPrimary) {
findPrimaryMessageReceived.countDown();
- } else if(message instanceof ClusterEvent.MemberUp) {
- countDownIfOther(((ClusterEvent.MemberUp)message).member(), memberUpReceived);
- } else if(message instanceof ClusterEvent.MemberRemoved) {
- countDownIfOther(((ClusterEvent.MemberRemoved)message).member(), memberRemovedReceived);
- } else if(message instanceof ClusterEvent.UnreachableMember) {
- countDownIfOther(((ClusterEvent.UnreachableMember)message).member(), memberUnreachableReceived);
- } else if(message instanceof ClusterEvent.ReachableMember) {
- countDownIfOther(((ClusterEvent.ReachableMember)message).member(), memberReachableReceived);
+ } else if (message instanceof ClusterEvent.MemberUp) {
+ countDownIfOther(((ClusterEvent.MemberUp) message).member(), memberUpReceived);
+ } else if (message instanceof ClusterEvent.MemberRemoved) {
+ countDownIfOther(((ClusterEvent.MemberRemoved) message).member(), memberRemovedReceived);
+ } else if (message instanceof ClusterEvent.UnreachableMember) {
+ countDownIfOther(((ClusterEvent.UnreachableMember) message).member(), memberUnreachableReceived);
+ } else if (message instanceof ClusterEvent.ReachableMember) {
+ countDownIfOther(((ClusterEvent.ReachableMember) message).member(), memberReachableReceived);
}
}
}
datastoreContextFactory(newDatastoreContextFactory(datastoreContextBuilder.build()));
}
- Builder shardActor(ActorRef shardActor) {
- this.shardActor = shardActor;
+ Builder shardActor(ActorRef newShardActor) {
+ this.shardActor = newShardActor;
return this;
}
- Builder addShardActor(String shardName, ActorRef actorRef){
+ Builder addShardActor(String shardName, ActorRef actorRef) {
shardActors.put(shardName, actorRef);
return this;
}
@Override
protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
- if(shardActors.get(info.getShardName()) != null){
+ if (shardActors.get(info.getShardName()) != null) {
return shardActors.get(info.getShardName());
}
- if(shardActor != null) {
+ if (shardActor != null) {
return shardActor;
}
}
}
- private static abstract class AbstractGenericCreator<T extends AbstractGenericCreator<T, ?>, C extends ShardManager>
+ private abstract static class AbstractGenericCreator<T extends AbstractGenericCreator<T, ?>, C extends ShardManager>
extends AbstractShardManagerCreator<T> {
private final Class<C> shardManagerClass;
AbstractGenericCreator(Class<C> shardManagerClass) {
this.shardManagerClass = shardManagerClass;
- cluster(new MockClusterWrapper()).configuration(new MockConfiguration()).
- waitTillReadyCountdownLatch(ready).primaryShardInfoCache(new PrimaryShardInfoFutureCache());
+ cluster(new MockClusterWrapper()).configuration(new MockConfiguration()).waitTillReadyCountdownLatch(ready)
+ .primaryShardInfoCache(new PrimaryShardInfoFutureCache());
}
@Override
private static final long serialVersionUID = 1L;
private final Creator<ShardManager> delegate;
- public DelegatingShardManagerCreator(Creator<ShardManager> delegate) {
+ DelegatingShardManagerCreator(Creator<ShardManager> delegate) {
this.delegate = delegate;
}
}
private static MessageInterceptor newFindPrimaryInterceptor(final ActorRef primaryActor) {
- return new MessageInterceptor(){
+ return new MessageInterceptor() {
@Override
public Object apply(Object message) {
return new RemotePrimaryShardFound(Serialization.serializedActorPath(primaryActor), (short) 1);
private final Class<?> requestClass;
@SuppressWarnings("unused")
- public MockRespondActor(Class<?> requestClass, Object responseMsg) {
+ MockRespondActor(Class<?> requestClass, Object responseMsg) {
this.requestClass = requestClass;
this.responseMsg = responseMsg;
}
@Override
public void onReceive(Object message) throws Exception {
- if(message.equals(CLEAR_RESPONSE)) {
+ if (message.equals(CLEAR_RESPONSE)) {
responseMsg = null;
} else {
super.onReceive(message);
package org.opendaylight.controller.cluster.datastore.shardmanager;
import static org.junit.Assert.assertEquals;
+
import akka.actor.Address;
import com.google.common.collect.Sets;
import java.util.Collection;
resolver.addPeerAddress(MEMBER_3, address3);
assertEquals("getPeerAddress", address3, resolver.getPeerAddress(MEMBER_3));
- assertEquals("getShardActorAddress", address2.toString() +
- "/user/shardmanager-config/member-2-shard-default-config",
+ assertEquals("getShardActorAddress",
+ address2.toString() + "/user/shardmanager-config/member-2-shard-default-config",
resolver.getShardActorAddress("default", MEMBER_2));
- assertEquals("getShardActorAddress", address3.toString() +
- "/user/shardmanager-config/member-3-shard-default-config",
+ assertEquals("getShardActorAddress",
+ address3.toString() + "/user/shardmanager-config/member-3-shard-default-config",
resolver.getShardActorAddress("default", MEMBER_3));
- assertEquals("getShardActorAddress", address2.toString() +
- "/user/shardmanager-config/member-2-shard-topology-config",
+ assertEquals("getShardActorAddress",
+ address2.toString() + "/user/shardmanager-config/member-2-shard-topology-config",
resolver.getShardActorAddress("topology", MEMBER_2));
resolver.removePeerAddress(MEMBER_2);
assertEquals("getShardActorAddress", null, resolver.getShardActorAddress("default", MEMBER_2));
assertEquals("getShardActorAddress", null, resolver.getShardActorAddress("topology", MEMBER_2));
- assertEquals("getShardActorAddress", address3.toString() +
- "/user/shardmanager-config/member-3-shard-default-config",
+ assertEquals("getShardActorAddress",
+ address3.toString() + "/user/shardmanager-config/member-3-shard-default-config",
resolver.getShardActorAddress("default", MEMBER_3));
}
resolver.addPeerAddress(memberName, address);
String shardAddress = resolver.getShardActorAddress("default", memberName);
- assertEquals("getShardActorAddress", address.toString() +
- "/user/shardmanager-" + type + "/" + memberName.getName() + "-shard-default-" + type, shardAddress);
+ assertEquals("getShardActorAddress", address.toString() + "/user/shardmanager-" + type + "/"
+ + memberName.getName() + "-shard-default-" + type, shardAddress);
assertEquals("resolve", shardAddress, resolver.resolve(peerId));
}
package org.opendaylight.controller.cluster.datastore.shardstrategy;
import static org.junit.Assert.assertEquals;
+
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
private static Configuration configuration;
@BeforeClass
- public static void setUpClass(){
+ public static void setUpClass() {
configuration = new ConfigurationImpl("module-shards.conf", "modules.conf");
}
@Test
public void testFindShardWhenModuleConfigurationPresentInModulesButMissingInModuleShards() {
+ final QName baseQName = QName.create(
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:missing", "2014-03-13",
+ "missing");
- final QName BASE_QNAME = QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:missing", "2014-03-13",
- "missing");
-
- final YangInstanceIdentifier BASE_PATH = YangInstanceIdentifier.of(BASE_QNAME);
+ final YangInstanceIdentifier BASE_PATH = YangInstanceIdentifier.of(baseQName);
ModuleShardStrategy moduleShardStrategy =
new ModuleShardStrategy("missing", configuration);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
factory.getStrategy(null);
}
-
}
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;
-public class ActorContextTest extends AbstractActorTest{
+public class ActorContextTest extends AbstractActorTest {
- static final Logger log = LoggerFactory.getLogger(ActorContextTest.class);
+ static final Logger LOG = LoggerFactory.getLogger(ActorContextTest.class);
private static class TestMessage {
}
private final ActorRef actorRef;
private final Map<String,Object> findPrimaryResponses = Maps.newHashMap();
- private MockShardManager(final boolean found, final ActorRef actorRef){
+ private MockShardManager(final boolean found, final ActorRef actorRef) {
this.found = found;
this.actorRef = actorRef;
}
@Override public void onReceive(final Object message) throws Exception {
- if(message instanceof FindPrimary) {
+ if (message instanceof FindPrimary) {
FindPrimary fp = (FindPrimary)message;
Object resp = findPrimaryResponses.get(fp.getShardName());
- if(resp == null) {
- log.error("No expected FindPrimary response found for shard name {}", fp.getShardName());
+ if (resp == null) {
+ LOG.error("No expected FindPrimary response found for shard name {}", fp.getShardName());
} else {
getSender().tell(resp, getSelf());
}
return;
}
- if(found){
+ if (found) {
getSender().tell(new LocalShardFound(actorRef), getSelf());
} else {
getSender().tell(new LocalShardNotFound(((FindLocalShard) message).getShardName()), getSelf());
findPrimaryResponses.put(shardName, resp);
}
- private static Props props(final boolean found, final ActorRef actorRef){
+ private static Props props(final boolean found, final ActorRef actorRef) {
return Props.create(new MockShardManagerCreator(found, actorRef) );
}
- private static Props props(){
+ private static Props props() {
return Props.create(new MockShardManagerCreator() );
}
}
@Test
- public void testFindLocalShardWithShardFound(){
- new JavaTestKit(getSystem()) {{
-
- new Within(duration("1 seconds")) {
- @Override
- protected void run() {
-
- ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
+ public void testFindLocalShardWithShardFound() {
+ new JavaTestKit(getSystem()) {
+ {
+ new Within(duration("1 seconds")) {
+ @Override
+ protected void run() {
- ActorRef shardManagerActorRef = getSystem()
- .actorOf(MockShardManager.props(true, shardActorRef));
+ ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
- ActorContext actorContext =
- new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
- mock(Configuration.class));
+ ActorRef shardManagerActorRef = getSystem()
+ .actorOf(MockShardManager.props(true, shardActorRef));
- Optional<ActorRef> out = actorContext.findLocalShard("default");
+ ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
+ mock(ClusterWrapper.class), mock(Configuration.class));
- assertEquals(shardActorRef, out.get());
+ Optional<ActorRef> out = actorContext.findLocalShard("default");
+ assertEquals(shardActorRef, out.get());
- expectNoMsg();
- }
- };
- }};
+ expectNoMsg();
+ }
+ };
+ }
+ };
}
@Test
- public void testFindLocalShardWithShardNotFound(){
- new JavaTestKit(getSystem()) {{
- ActorRef shardManagerActorRef = getSystem()
- .actorOf(MockShardManager.props(false, null));
+ public void testFindLocalShardWithShardNotFound() {
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(false, null));
- ActorContext actorContext =
- new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
- mock(Configuration.class));
+ ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
+ mock(ClusterWrapper.class), mock(Configuration.class));
- Optional<ActorRef> out = actorContext.findLocalShard("default");
- assertTrue(!out.isPresent());
- }};
+ Optional<ActorRef> out = actorContext.findLocalShard("default");
+ assertTrue(!out.isPresent());
+ }
+ };
}
@Test
public void testExecuteRemoteOperation() {
- new JavaTestKit(getSystem()) {{
- ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
- ActorRef shardManagerActorRef = getSystem()
- .actorOf(MockShardManager.props(true, shardActorRef));
+ ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
- ActorContext actorContext =
- new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
- mock(Configuration.class));
+ ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
+ mock(ClusterWrapper.class), mock(Configuration.class));
- ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
+ ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
- Object out = actorContext.executeOperation(actor, "hello");
+ Object out = actorContext.executeOperation(actor, "hello");
- assertEquals("hello", out);
- }};
+ assertEquals("hello", out);
+ }
+ };
}
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void testExecuteRemoteOperationAsync() {
- new JavaTestKit(getSystem()) {{
- ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
- ActorRef shardManagerActorRef = getSystem()
- .actorOf(MockShardManager.props(true, shardActorRef));
+ ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
- ActorContext actorContext =
- new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
- mock(Configuration.class));
+ ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
+ mock(ClusterWrapper.class), mock(Configuration.class));
- ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
+ ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
- Future<Object> future = actorContext.executeOperationAsync(actor, "hello");
+ Future<Object> future = actorContext.executeOperationAsync(actor, "hello");
- try {
- Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS));
- assertEquals("Result", "hello", result);
- } catch(Exception e) {
- throw new AssertionError(e);
+ try {
+ Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS));
+ assertEquals("Result", "hello", result);
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
}
- }};
+ };
}
@Test
}
@Test
- public void testClientDispatcherIsGlobalDispatcher(){
- ActorContext actorContext =
- new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
- mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
+ public void testClientDispatcherIsGlobalDispatcher() {
+ ActorContext actorContext = new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
+ mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
assertEquals(getSystem().dispatchers().defaultGlobalDispatcher(), actorContext.getClientDispatcher());
}
@Test
- public void testClientDispatcherIsNotGlobalDispatcher(){
- ActorSystem actorSystem = ActorSystem.create("with-custom-dispatchers", ConfigFactory.load("application-with-custom-dispatchers.conf"));
+ public void testClientDispatcherIsNotGlobalDispatcher() {
+ ActorSystem actorSystem = ActorSystem.create("with-custom-dispatchers",
+ ConfigFactory.load("application-with-custom-dispatchers.conf"));
- ActorContext actorContext =
- new ActorContext(actorSystem, mock(ActorRef.class), mock(ClusterWrapper.class),
- mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
+ ActorContext actorContext = new ActorContext(actorSystem, mock(ActorRef.class), mock(ClusterWrapper.class),
+ mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
assertNotEquals(actorSystem.dispatchers().defaultGlobalDispatcher(), actorContext.getClientDispatcher());
@Test
public void testSetDatastoreContext() {
- new JavaTestKit(getSystem()) {{
- ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class),
- mock(Configuration.class), DatastoreContext.newBuilder().
- operationTimeoutInSeconds(5).shardTransactionCommitTimeoutInSeconds(7).build(), new PrimaryShardInfoFutureCache());
+ new JavaTestKit(getSystem()) {
+ {
+ ActorContext actorContext = new ActorContext(getSystem(), getRef(),
+ mock(ClusterWrapper.class), mock(Configuration.class), DatastoreContext.newBuilder()
+ .operationTimeoutInSeconds(5).shardTransactionCommitTimeoutInSeconds(7).build(),
+ new PrimaryShardInfoFutureCache());
- assertEquals("getOperationDuration", 5, actorContext.getOperationDuration().toSeconds());
- assertEquals("getTransactionCommitOperationTimeout", 7,
- actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
+ assertEquals("getOperationDuration", 5, actorContext.getOperationDuration().toSeconds());
+ assertEquals("getTransactionCommitOperationTimeout", 7,
+ actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
- DatastoreContext newContext = DatastoreContext.newBuilder().operationTimeoutInSeconds(6).
- shardTransactionCommitTimeoutInSeconds(8).build();
+ DatastoreContext newContext = DatastoreContext.newBuilder().operationTimeoutInSeconds(6)
+ .shardTransactionCommitTimeoutInSeconds(8).build();
- DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
- Mockito.doReturn(newContext).when(mockContextFactory).getBaseDatastoreContext();
+ DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
+ Mockito.doReturn(newContext).when(mockContextFactory).getBaseDatastoreContext();
- actorContext.setDatastoreContext(mockContextFactory);
+ actorContext.setDatastoreContext(mockContextFactory);
- expectMsgClass(duration("5 seconds"), DatastoreContextFactory.class);
+ expectMsgClass(duration("5 seconds"), DatastoreContextFactory.class);
- Assert.assertSame("getDatastoreContext", newContext, actorContext.getDatastoreContext());
+ Assert.assertSame("getDatastoreContext", newContext, actorContext.getDatastoreContext());
- assertEquals("getOperationDuration", 6, actorContext.getOperationDuration().toSeconds());
- assertEquals("getTransactionCommitOperationTimeout", 8,
- actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
- }};
+ assertEquals("getOperationDuration", 6, actorContext.getOperationDuration().toSeconds());
+ assertEquals("getTransactionCommitOperationTimeout", 8,
+ actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
+ }
+ };
}
@Test
public void testFindPrimaryShardAsyncRemotePrimaryFound() throws Exception {
- TestActorRef<MessageCollectorActor> shardManager =
- TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
+ TestActorRef<MessageCollectorActor> shardManager = TestActorRef.create(getSystem(),
+ Props.create(MessageCollectorActor.class));
- DatastoreContext dataStoreContext = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.CONFIGURATION).
- shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
+ DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
+ .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
- final String expPrimaryPath = "akka://test-system/find-primary-shard";
- final short expPrimaryVersion = DataStoreVersions.CURRENT_VERSION;
- ActorContext actorContext =
- new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
- mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
- @Override
- protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
- return Futures.successful((Object) new RemotePrimaryShardFound(expPrimaryPath, expPrimaryVersion));
- }
- };
+ final String expPrimaryPath = "akka://test-system/find-primary-shard";
+ final short expPrimaryVersion = DataStoreVersions.CURRENT_VERSION;
+ ActorContext actorContext = new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
+ mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
+ @Override
+ protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
+ return Futures.successful((Object) new RemotePrimaryShardFound(expPrimaryPath, expPrimaryVersion));
+ }
+ };
- Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
- PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
+ Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
+ PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
- assertNotNull(actual);
- assertEquals("LocalShardDataTree present", false, actual.getLocalShardDataTree().isPresent());
- assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
- expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
- assertEquals("getPrimaryShardVersion", expPrimaryVersion, actual.getPrimaryShardVersion());
+ assertNotNull(actual);
+ assertEquals("LocalShardDataTree present", false, actual.getLocalShardDataTree().isPresent());
+ assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
+ expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
+ assertEquals("getPrimaryShardVersion", expPrimaryVersion, actual.getPrimaryShardVersion());
- Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
+ Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
- PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
+ PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
- assertEquals(cachedInfo, actual);
+ assertEquals(cachedInfo, actual);
- actorContext.getPrimaryShardInfoCache().remove("foobar");
+ actorContext.getPrimaryShardInfoCache().remove("foobar");
- cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
+ cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
- assertNull(cached);
+ assertNull(cached);
}
@Test
public void testFindPrimaryShardAsyncLocalPrimaryFound() throws Exception {
- TestActorRef<MessageCollectorActor> shardManager =
- TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
+ TestActorRef<MessageCollectorActor> shardManager = TestActorRef.create(getSystem(),
+ Props.create(MessageCollectorActor.class));
- DatastoreContext dataStoreContext = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.CONFIGURATION).
- shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
+ DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
+ .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
- final DataTree mockDataTree = Mockito.mock(DataTree.class);
- final String expPrimaryPath = "akka://test-system/find-primary-shard";
- ActorContext actorContext =
- new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
- mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
- @Override
- protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
- return Futures.successful((Object) new LocalPrimaryShardFound(expPrimaryPath, mockDataTree));
- }
- };
+ final DataTree mockDataTree = Mockito.mock(DataTree.class);
+ final String expPrimaryPath = "akka://test-system/find-primary-shard";
+ ActorContext actorContext = new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
+ mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
+ @Override
+ protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
+ return Futures.successful((Object) new LocalPrimaryShardFound(expPrimaryPath, mockDataTree));
+ }
+ };
- Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
- PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
+ Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
+ PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
- assertNotNull(actual);
- assertEquals("LocalShardDataTree present", true, actual.getLocalShardDataTree().isPresent());
- assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get());
- assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
- expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
- assertEquals("getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion());
+ assertNotNull(actual);
+ assertEquals("LocalShardDataTree present", true, actual.getLocalShardDataTree().isPresent());
+ assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get());
+ assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
+ expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
+ assertEquals("getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion());
- Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
+ Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
- PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
+ PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
- assertEquals(cachedInfo, actual);
+ assertEquals(cachedInfo, actual);
- actorContext.getPrimaryShardInfoCache().remove("foobar");
+ actorContext.getPrimaryShardInfoCache().remove("foobar");
- cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
+ cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
- assertNull(cached);
+ assertNull(cached);
}
@Test
testFindPrimaryExceptions(new NotInitializedException("not initialized"));
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private static void testFindPrimaryExceptions(final Object expectedException) throws Exception {
TestActorRef<MessageCollectorActor> shardManager =
TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
- DatastoreContext dataStoreContext = DatastoreContext.newBuilder().
- logicalStoreType(LogicalDatastoreType.CONFIGURATION).
- shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
+ DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
+ .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
+ .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
ActorContext actorContext =
new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
try {
Await.result(foobar, Duration.apply(100, TimeUnit.MILLISECONDS));
fail("Expected" + expectedException.getClass().toString());
- } catch(Exception e){
- if(!expectedException.getClass().isInstance(e)) {
+ } catch (Exception e) {
+ if (!expectedException.getClass().isInstance(e)) {
fail("Expected Exception of type " + expectedException.getClass().toString());
}
}
@Test
public void testBroadcast() {
- new JavaTestKit(getSystem()) {{
- ActorRef shardActorRef1 = getSystem().actorOf(Props.create(MessageCollectorActor.class));
- ActorRef shardActorRef2 = getSystem().actorOf(Props.create(MessageCollectorActor.class));
-
- TestActorRef<MockShardManager> shardManagerActorRef = TestActorRef.create(getSystem(), MockShardManager.props());
- MockShardManager shardManagerActor = shardManagerActorRef.underlyingActor();
- shardManagerActor.addFindPrimaryResp("shard1", new RemotePrimaryShardFound(shardActorRef1.path().toString(),
- DataStoreVersions.CURRENT_VERSION));
- shardManagerActor.addFindPrimaryResp("shard2", new RemotePrimaryShardFound(shardActorRef2.path().toString(),
- DataStoreVersions.CURRENT_VERSION));
- shardManagerActor.addFindPrimaryResp("shard3", new NoShardLeaderException("not found"));
-
- Configuration mockConfig = mock(Configuration.class);
- doReturn(Sets.newLinkedHashSet(Arrays.asList("shard1", "shard2", "shard3"))).
- when(mockConfig).getAllShardNames();
-
- ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
- mock(ClusterWrapper.class), mockConfig,
- DatastoreContext.newBuilder().shardInitializationTimeout(200, TimeUnit.MILLISECONDS).build(), new PrimaryShardInfoFutureCache());
-
- actorContext.broadcast(new Function<Short, Object>() {
- @Override
- public Object apply(final Short v) {
- return new TestMessage();
- }
- }, TestMessage.class);
-
- MessageCollectorActor.expectFirstMatching(shardActorRef1, TestMessage.class);
- MessageCollectorActor.expectFirstMatching(shardActorRef2, TestMessage.class);
- }};
+ new JavaTestKit(getSystem()) {
+ {
+ ActorRef shardActorRef1 = getSystem().actorOf(Props.create(MessageCollectorActor.class));
+ ActorRef shardActorRef2 = getSystem().actorOf(Props.create(MessageCollectorActor.class));
+
+ TestActorRef<MockShardManager> shardManagerActorRef = TestActorRef.create(getSystem(),
+ MockShardManager.props());
+ MockShardManager shardManagerActor = shardManagerActorRef.underlyingActor();
+ shardManagerActor.addFindPrimaryResp("shard1", new RemotePrimaryShardFound(
+ shardActorRef1.path().toString(), DataStoreVersions.CURRENT_VERSION));
+ shardManagerActor.addFindPrimaryResp("shard2", new RemotePrimaryShardFound(
+ shardActorRef2.path().toString(), DataStoreVersions.CURRENT_VERSION));
+ shardManagerActor.addFindPrimaryResp("shard3", new NoShardLeaderException("not found"));
+
+ Configuration mockConfig = mock(Configuration.class);
+ doReturn(Sets.newLinkedHashSet(Arrays.asList("shard1", "shard2", "shard3"))).when(mockConfig)
+ .getAllShardNames();
+
+ ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
+ mock(ClusterWrapper.class), mockConfig,
+ DatastoreContext.newBuilder().shardInitializationTimeout(200, TimeUnit.MILLISECONDS).build(),
+ new PrimaryShardInfoFutureCache());
+
+ actorContext.broadcast(v -> new TestMessage(), TestMessage.class);
+
+ MessageCollectorActor.expectFirstMatching(shardActorRef1, TestMessage.class);
+ MessageCollectorActor.expectFirstMatching(shardActorRef2, TestMessage.class);
+ }
+ };
}
-
}
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+
import akka.dispatch.MessageDispatcher;
import org.junit.Test;
public class DispatchersTest {
@Test
- public void testGetDefaultDispatcherPath(){
+ public void testGetDefaultDispatcherPath() {
akka.dispatch.Dispatchers mockDispatchers = mock(akka.dispatch.Dispatchers.class);
doReturn(false).when(mockDispatchers).hasDispatcher(anyString());
Dispatchers dispatchers = new Dispatchers(mockDispatchers);
- for(Dispatchers.DispatcherType type : Dispatchers.DispatcherType.values()) {
+ for (Dispatchers.DispatcherType type : Dispatchers.DispatcherType.values()) {
assertEquals(Dispatchers.DEFAULT_DISPATCHER_PATH,
dispatchers.getDispatcherPath(type));
}
}
@Test
- public void testGetDefaultDispatcher(){
+ public void testGetDefaultDispatcher() {
akka.dispatch.Dispatchers mockDispatchers = mock(akka.dispatch.Dispatchers.class);
MessageDispatcher mockGlobalDispatcher = mock(MessageDispatcher.class);
doReturn(false).when(mockDispatchers).hasDispatcher(anyString());
doReturn(mockGlobalDispatcher).when(mockDispatchers).defaultGlobalDispatcher();
Dispatchers dispatchers = new Dispatchers(mockDispatchers);
- for(Dispatchers.DispatcherType type : Dispatchers.DispatcherType.values()) {
+ for (Dispatchers.DispatcherType type : Dispatchers.DispatcherType.values()) {
assertEquals(mockGlobalDispatcher,
dispatchers.getDispatcher(type));
}
}
@Test
- public void testGetDispatcherPath(){
+ public void testGetDispatcherPath() {
akka.dispatch.Dispatchers mockDispatchers = mock(akka.dispatch.Dispatchers.class);
doReturn(true).when(mockDispatchers).hasDispatcher(anyString());
Dispatchers dispatchers = new Dispatchers(mockDispatchers);
}
@Test
- public void testGetDispatcher(){
+ public void testGetDispatcher() {
akka.dispatch.Dispatchers mockDispatchers = mock(akka.dispatch.Dispatchers.class);
MessageDispatcher mockDispatcher = mock(MessageDispatcher.class);
doReturn(true).when(mockDispatchers).hasDispatcher(anyString());
dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Notification));
}
-}
\ No newline at end of file
+}
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
-public class ForwardingActor extends UntypedActor{
+public class ForwardingActor extends UntypedActor {
private final ActorRef target;
private ForwardingActor(ActorRef target) {
}
@Override
- public void onReceive(Object o) throws Exception {
- target.forward(o, context());
+ public void onReceive(Object obj) throws Exception {
+ target.forward(obj, context());
}
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore.utils;
-
-import static org.junit.Assert.assertNotNull;
-import akka.actor.ActorRef;
-import akka.actor.ActorSelection;
-import akka.actor.ActorSystem;
-
-public class MockActorContext extends ActorContext {
-
- private volatile Object executeShardOperationResponse;
- private volatile Object executeRemoteOperationResponse;
- private volatile Object executeLocalOperationResponse;
- private volatile Object executeLocalShardOperationResponse;
- private volatile Exception executeRemoteOperationFailure;
- private volatile Object inputMessage;
-
- public MockActorContext(ActorSystem actorSystem) {
- super(actorSystem, null, new MockClusterWrapper(), new MockConfiguration());
- }
-
- public MockActorContext(ActorSystem actorSystem, ActorRef shardManager) {
- super(actorSystem, shardManager, new MockClusterWrapper(), new MockConfiguration());
- }
-
- @Override public Object executeOperation(ActorSelection actor,
- Object message) {
- return executeRemoteOperationResponse;
- }
-
- public void setExecuteShardOperationResponse(Object response){
- executeShardOperationResponse = response;
- }
-
- public void setExecuteRemoteOperationResponse(Object response){
- executeRemoteOperationResponse = response;
- }
-
- public void setExecuteRemoteOperationFailure(Exception executeRemoteOperationFailure) {
- this.executeRemoteOperationFailure = executeRemoteOperationFailure;
- }
-
- public void setExecuteLocalOperationResponse(
- Object executeLocalOperationResponse) {
- this.executeLocalOperationResponse = executeLocalOperationResponse;
- }
-
- public void setExecuteLocalShardOperationResponse(
- Object executeLocalShardOperationResponse) {
- this.executeLocalShardOperationResponse = executeLocalShardOperationResponse;
- }
-
- @SuppressWarnings("unchecked")
- public <T> T getInputMessage(Class<T> expType) throws Exception {
- assertNotNull("Input message was null", inputMessage);
- return (T) expType.getMethod("fromSerializable", Object.class).invoke(null, inputMessage);
- }
-
- @Override
- public Object executeOperation(ActorRef actor,
- Object message) {
- return this.executeLocalOperationResponse;
- }
-
-}
import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
import scala.collection.JavaConversions;
-public class MockClusterWrapper implements ClusterWrapper{
+public class MockClusterWrapper implements ClusterWrapper {
private Address selfAddress = new Address("akka.tcp", "test", "127.0.0.1", 2550);
private final MemberName currentMemberName;
this.selfAddress = selfAddress;
}
- public static void sendMemberUp(ActorRef to, String memberName, String address){
+ public static void sendMemberUp(ActorRef to, String memberName, String address) {
to.tell(createMemberUp(memberName, address), null);
}
- public static void sendMemberRemoved(ActorRef to, String memberName, String address){
+ public static void sendMemberRemoved(ActorRef to, String memberName, String address) {
to.tell(createMemberRemoved(memberName, address), null);
}
public MockConfiguration(final Map<String, List<String>> shardMembers) {
super(configuration -> {
Map<String, ModuleConfig.Builder> retMap = new HashMap<>();
- for(Map.Entry<String, List<String>> e : shardMembers.entrySet()) {
+ for (Map.Entry<String, List<String>> e : shardMembers.entrySet()) {
String shardName = e.getKey();
retMap.put(shardName,
ModuleConfig.builder(shardName).shardConfig(
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.Collections;
reset(expChangeEventCount);
}
- public void reset(int expChangeEventCount) {
- changeLatch = new CountDownLatch(expChangeEventCount);
- this.expChangeEventCount = expChangeEventCount;
+ public void reset(int newExpChangeEventCount) {
+ changeLatch = new CountDownLatch(newExpChangeEventCount);
+ this.expChangeEventCount = newExpChangeEventCount;
changeList.clear();
}
public void waitForChangeEvents(YangInstanceIdentifier... expPaths) {
boolean done = Uninterruptibles.awaitUninterruptibly(changeLatch, 5, TimeUnit.SECONDS);
- if(!done) {
+ if (!done) {
fail(String.format("Missing change notifications. Expected: %d. Actual: %d",
- expChangeEventCount, (expChangeEventCount - changeLatch.getCount())));
+ expChangeEventCount, expChangeEventCount - changeLatch.getCount()));
}
- for(int i = 0; i < expPaths.length; i++) {
+ for (int i = 0; i < expPaths.length; i++) {
Map<YangInstanceIdentifier, NormalizedNode<?, ?>> createdData = changeList.get(i).getCreatedData();
- assertTrue(String.format("Change %d does not contain %s. Actual: %s", (i+1), expPaths[i], createdData),
+ assertTrue(String.format("Change %d does not contain %s. Actual: %s", i + 1, expPaths[i], createdData),
createdData.containsKey(expPaths[i]));
}
}
- public NormalizedNode<?, ?> getCreatedData(int i, YangInstanceIdentifier path) {
- return changeList.get(i).getCreatedData().get(path);
+ public NormalizedNode<?, ?> getCreatedData(int num, YangInstanceIdentifier path) {
+ return changeList.get(num).getCreatedData().get(path);
}
- public void verifyCreatedData(int i, YangInstanceIdentifier path) {
- Map<YangInstanceIdentifier, NormalizedNode<?, ?>> createdData = changeList.get(i).getCreatedData();
+ public void verifyCreatedData(int num, YangInstanceIdentifier path) {
+ Map<YangInstanceIdentifier, NormalizedNode<?, ?>> createdData = changeList.get(num).getCreatedData();
assertTrue(path + " not present in " + createdData.keySet(), createdData.get(path) != null);
}
assertEquals(assertMsg, expChangeEventCount, changeList.size());
}
- public void verifyNoCreatedData(int i, YangInstanceIdentifier path) {
- Map<YangInstanceIdentifier, NormalizedNode<?, ?>> createdData = changeList.get(i).getCreatedData();
+ public void verifyNoCreatedData(int num, YangInstanceIdentifier path) {
+ Map<YangInstanceIdentifier, NormalizedNode<?, ?>> createdData = changeList.get(num).getCreatedData();
assertTrue("Unexpected " + path + " present in createdData", createdData.get(path) == null);
}
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
+
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.Arrays;
reset(expChangeEventCount);
}
- public void reset(int expChangeEventCount) {
- changeLatch = new CountDownLatch(expChangeEventCount);
- this.expChangeEventCount = expChangeEventCount;
- synchronized(changeList) {
+ public void reset(int newExpChangeEventCount) {
+ changeLatch = new CountDownLatch(newExpChangeEventCount);
+ this.expChangeEventCount = newExpChangeEventCount;
+ synchronized (changeList) {
changeList.clear();
}
}
@Override
public void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
- synchronized(changeList) {
+ synchronized (changeList) {
changeList.add(changes);
}
changeLatch.countDown();
public void waitForChangeEvents() {
boolean done = Uninterruptibles.awaitUninterruptibly(changeLatch, 5, TimeUnit.SECONDS);
- if(!done) {
+ if (!done) {
fail(String.format("Missing change notifications. Expected: %d. Actual: %d",
- expChangeEventCount, (expChangeEventCount - changeLatch.getCount())));
+ expChangeEventCount, expChangeEventCount - changeLatch.getCount()));
}
}
public void verifyNotifiedData(YangInstanceIdentifier... paths) {
Set<YangInstanceIdentifier> pathSet = new HashSet<>(Arrays.asList(paths));
- synchronized(changeList) {
- for(Collection<DataTreeCandidate> list: changeList) {
- for(DataTreeCandidate c: list) {
+ synchronized (changeList) {
+ for (Collection<DataTreeCandidate> list : changeList) {
+ for (DataTreeCandidate c : list) {
pathSet.remove(c.getRootPath());
}
}
}
- if(!pathSet.isEmpty()) {
+ if (!pathSet.isEmpty()) {
fail(pathSet + " not present in " + changeList);
}
}
public void expectNoMoreChanges(String assertMsg) {
Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
- synchronized(changeList) {
+ synchronized (changeList) {
assertEquals(assertMsg, expChangeEventCount, changeList.size());
}
}
public void verifyNoNotifiedData(YangInstanceIdentifier... paths) {
Set<YangInstanceIdentifier> pathSet = new HashSet<>(Arrays.asList(paths));
- synchronized(changeList) {
- for(Collection<DataTreeCandidate> list: changeList) {
- for(DataTreeCandidate c: list) {
+ synchronized (changeList) {
+ for (Collection<DataTreeCandidate> list : changeList) {
+ for (DataTreeCandidate c : list) {
assertFalse("Unexpected " + c.getRootPath() + " present in DataTreeCandidate",
pathSet.contains(c.getRootPath()));
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.CheckedFuture;
public class NormalizedNodeAggregatorTest {
@Test
- public void testAggregate() throws InterruptedException, ExecutionException, ReadFailedException, DataValidationFailedException {
+ public void testAggregate() throws InterruptedException, ExecutionException, ReadFailedException,
+ DataValidationFailedException {
SchemaContext schemaContext = SchemaContextHelper.full();
NormalizedNode<?, ?> expectedNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
NormalizedNode<?, ?> expectedNode2 = ImmutableNodes.containerNode(CarsModel.CARS_QNAME);
assertTrue("Expect value to be a Collection", normalizedNode.getValue() instanceof Collection);
+ @SuppressWarnings("unchecked")
Collection<NormalizedNode<?,?>> collection = (Collection<NormalizedNode<?,?>>) normalizedNode.getValue();
- for(NormalizedNode<?,?> node : collection){
+ for (NormalizedNode<?,?> node : collection) {
assertTrue("Expected " + node + " to be a ContainerNode", node instanceof ContainerNode);
}
}
}
- public static NormalizedNode<?,?> findChildWithQName(Collection<NormalizedNode<?, ?>> collection, QName qName) {
- for(NormalizedNode<?,?> node : collection){
- if(node.getNodeType().equals(qName)){
+ public static NormalizedNode<?,?> findChildWithQName(Collection<NormalizedNode<?, ?>> collection, QName qname) {
+ for (NormalizedNode<?, ?> node : collection) {
+ if (node.getNodeType().equals(qname)) {
return node;
}
}
return null;
}
-
-}
\ No newline at end of file
+}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
+
import akka.actor.ActorSelection;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
assertEquals("getIfPresent", null, cache.getIfPresent("foo"));
- PrimaryShardInfo shardInfo = new PrimaryShardInfo(mock(ActorSelection.class), DataStoreVersions.CURRENT_VERSION);
+ PrimaryShardInfo shardInfo = new PrimaryShardInfo(mock(ActorSelection.class),
+ DataStoreVersions.CURRENT_VERSION);
cache.putSuccessful("foo", shardInfo);
Future<PrimaryShardInfo> future = cache.getIfPresent("foo");
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.innerNode;
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.outerNode;
import static org.opendaylight.controller.md.cluster.datastore.model.TestModel.outerNodeEntry;
+
import com.google.common.base.Optional;
import com.google.common.reflect.Reflection;
-import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
private PruningDataTreeModification pruningDataTreeModification;
@Before
- public void setUp(){
+ public void setUp() {
MockitoAnnotations.initMocks(this);
dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONFIGURATION);
dataTree.setSchemaContext(SCHEMA_CONTEXT);
realModification = dataTree.takeSnapshot().newModification();
- proxyModification = Reflection.newProxy(DataTreeModification.class, new InvocationHandler() {
- @Override
- public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
- try {
- method.invoke(mockModification, args);
- return method.invoke(realModification, args);
- } catch (InvocationTargetException e) {
- throw e.getCause();
- }
+ proxyModification = Reflection.newProxy(DataTreeModification.class, (proxy, method, args) -> {
+ try {
+ method.invoke(mockModification, args);
+ return method.invoke(realModification, args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
}
});
}
@Test
- public void testDelete(){
+ public void testDelete() {
pruningDataTreeModification.delete(CarsModel.BASE_PATH);
verify(mockModification, times(1)).delete(CarsModel.BASE_PATH);
}
@Test
- public void testDeleteOnException(){
+ public void testDeleteOnException() {
YangInstanceIdentifier path = CarsModel.BASE_PATH;
doThrow(SchemaValidationFailedException.class).when(mockModification).delete(path);
@Test
- public void testMerge(){
+ public void testMerge() {
NormalizedNode<?, ?> normalizedNode = CarsModel.create();
YangInstanceIdentifier path = CarsModel.BASE_PATH;
pruningDataTreeModification.merge(path, normalizedNode);
}
@Test
- public void testMergeWithInvalidNamespace() throws DataValidationFailedException{
+ public void testMergeWithInvalidNamespace() throws DataValidationFailedException {
NormalizedNode<?, ?> normalizedNode = PeopleModel.emptyContainer();
YangInstanceIdentifier path = PeopleModel.BASE_PATH;
}
@Test
- public void testMergeWithInvalidChildNodeNames() throws DataValidationFailedException{
+ public void testMergeWithInvalidChildNodeNames() throws DataValidationFailedException {
ContainerNode augContainer = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(AUG_CONTAINER)).withChild(
ImmutableNodes.containerNode(AUG_INNER_CONTAINER)).build();
DataContainerChild<?, ?> outerNode = outerNode(outerNodeEntry(1, innerNode("one", "two")));
- ContainerNode normalizedNode = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)).withChild(outerNode).withChild(augContainer).
- withChild(ImmutableNodes.leafNode(AUG_QNAME, "aug")).build();
+ ContainerNode normalizedNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)).withChild(outerNode)
+ .withChild(augContainer).withChild(ImmutableNodes.leafNode(AUG_QNAME, "aug")).build();
YangInstanceIdentifier path = TestModel.TEST_PATH;
}
@Test
- public void testMergeWithValidNamespaceAndInvalidNodeName() throws DataValidationFailedException{
+ public void testMergeWithValidNamespaceAndInvalidNodeName() throws DataValidationFailedException {
NormalizedNode<?, ?> normalizedNode = ImmutableNodes.containerNode(INVALID_TEST_QNAME);
YangInstanceIdentifier path = INVALID_TEST_PATH;
}
@Test
- public void testWrite(){
+ public void testWrite() {
NormalizedNode<?, ?> normalizedNode = CarsModel.create();
YangInstanceIdentifier path = CarsModel.BASE_PATH;
pruningDataTreeModification.write(path, normalizedNode);
}
@Test
- public void testWriteWithInvalidNamespace() throws DataValidationFailedException{
+ public void testWriteWithInvalidNamespace() throws DataValidationFailedException {
NormalizedNode<?, ?> normalizedNode = PeopleModel.emptyContainer();
YangInstanceIdentifier path = PeopleModel.BASE_PATH;
}
@Test
- public void testWriteWithInvalidChildNodeNames() throws DataValidationFailedException{
+ public void testWriteWithInvalidChildNodeNames() throws DataValidationFailedException {
ContainerNode augContainer = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(AUG_CONTAINER)).withChild(
ImmutableNodes.containerNode(AUG_INNER_CONTAINER)).build();
DataContainerChild<?, ?> outerNode = outerNode(outerNodeEntry(1, innerNode("one", "two")));
- ContainerNode normalizedNode = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)).withChild(outerNode).withChild(augContainer).
- withChild(ImmutableNodes.leafNode(AUG_QNAME, "aug")).
- withChild(ImmutableNodes.leafNode(NAME_QNAME, "name")).build();
+ ContainerNode normalizedNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)).withChild(outerNode)
+ .withChild(augContainer).withChild(ImmutableNodes.leafNode(AUG_QNAME, "aug"))
+ .withChild(ImmutableNodes.leafNode(NAME_QNAME, "name")).build();
YangInstanceIdentifier path = TestModel.TEST_PATH;
dataTree.commit(getCandidate());
- ContainerNode prunedNode = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)).withChild(outerNode).
- withChild(ImmutableNodes.leafNode(NAME_QNAME, "name")).build();
+ ContainerNode prunedNode = ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME)).withChild(outerNode)
+ .withChild(ImmutableNodes.leafNode(NAME_QNAME, "name")).build();
Optional<NormalizedNode<?, ?>> actual = dataTree.takeSnapshot().readNode(path);
assertEquals("After pruning present", true, actual.isPresent());
}
@Test
- public void testReady(){
+ public void testReady() {
pruningDataTreeModification.ready();
verify(mockModification).ready();
}
@Test
- public void testApplyToCursor(){
+ public void testApplyToCursor() {
DataTreeModificationCursor dataTreeModificationCursor = mock(DataTreeModificationCursor.class);
pruningDataTreeModification.applyToCursor(dataTreeModificationCursor);
}
@Test
- public void testReadNode(){
+ public void testReadNode() {
pruningDataTreeModification.readNode(CarsModel.BASE_PATH);
verify(mockModification).readNode(CarsModel.BASE_PATH);
}
@Test
- public void testNewModification(){
+ public void testNewModification() {
realModification.ready();
DataTreeModification dataTreeModification = pruningDataTreeModification.newModification();
- assertTrue("new modification not of type PruningDataTreeModification", dataTreeModification instanceof PruningDataTreeModification);
+ assertTrue("new modification not of type PruningDataTreeModification",
+ dataTreeModification instanceof PruningDataTreeModification);
}
private DataTreeCandidateTip getCandidate() throws DataValidationFailedException {
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore.utils;
-
-import akka.actor.ActorRef;
-import akka.actor.ActorSystem;
-import akka.actor.Props;
-import java.util.List;
-import org.junit.Assert;
-import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
-import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
-
-public class TestUtils {
-
- public static void assertFirstSentMessage(final ActorSystem actorSystem, final ActorRef actorRef, final Class<?> clazz){
- ActorContext testContext = new ActorContext(actorSystem, actorSystem.actorOf(
- Props.create(DoNothingActor.class)), new MockClusterWrapper(), new MockConfiguration());
- Object messages = testContext
- .executeOperation(actorRef, MessageCollectorActor.GET_ALL_MESSAGES);
-
- Assert.assertNotNull(messages);
-
- Assert.assertTrue(messages instanceof List);
-
- List<?> listMessages = (List<?>) messages;
-
- Assert.assertEquals(1, listMessages.size());
-
- Assert.assertTrue(listMessages.get(0).getClass().equals(clazz));
- }
-}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import java.util.concurrent.TimeUnit;
private Snapshot commitSnapshot;
@Before
- public void setUp(){
+ public void setUp() {
MockitoAnnotations.initMocks(this);
doReturn(datastoreContext).when(actorContext).getDatastoreContext();
doReturn(30).when(datastoreContext).getShardTransactionCommitTimeoutInSeconds();
}
@Test
- public void testAcquireRateLimitChanged(){
- for(int i=1;i<11;i++){
+ public void testAcquireRateLimitChanged() {
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(i) * 1D).when(commitSnapshot).getValue(i * 0.1);
@Test
- public void testAcquirePercentileValueZero(){
+ public void testAcquirePercentileValueZero() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(i) * 1D).when(commitSnapshot).getValue(i * 0.1);
}
@Test
- public void testAcquireOnePercentileValueVeryHigh(){
+ public void testAcquireOnePercentileValueVeryHigh() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(i) * 1D).when(commitSnapshot).getValue(i * 0.1);
}
@Test
- public void testAcquireWithAllPercentileValueVeryHigh(){
+ public void testAcquireWithAllPercentileValueVeryHigh() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(10000) * 1D).when(commitSnapshot).getValue(i * 0.1);
}
@Test
- public void testAcquireWithRealPercentileValues(){
+ public void testAcquireWithRealPercentileValues() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(8) * 1D).when(commitSnapshot).getValue(i * 0.1);
assertEquals(51, rateLimiter.getPollOnCount());
}
-
-
@Test
- public void testAcquireGetRateLimitFromOtherDataStores(){
- for(int i=1;i<11;i++){
+ public void testAcquireGetRateLimitFromOtherDataStores() {
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(0.0D).when(commitSnapshot).getValue(i * 0.1);
doReturn(operationalCommitTimerContext).when(operationalCommitTimer).time();
doReturn(operationalCommitSnapshot).when(operationalCommitTimer).getSnapshot();
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(i) * 1D).when(operationalCommitSnapshot).getValue(i * 0.1);
}
@Test
- public void testRateLimiting(){
+ public void testRateLimiting() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
doReturn(TimeUnit.SECONDS.toNanos(1) * 1D).when(commitSnapshot).getValue(i * 0.1);
}
}
@Test
- public void testRateLimitNotCalculatedUntilPollCountReached(){
+ public void testRateLimitNotCalculatedUntilPollCountReached() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(8) * 1D).when(commitSnapshot).getValue(i * 0.1);
assertEquals(51, rateLimiter.getPollOnCount());
- for(int i=0;i<49;i++){
+ for (int i = 0; i < 49; i++) {
rateLimiter.acquire();
}
}
@Test
- public void testAcquireNegativeAcquireAndPollOnCount(){
+ public void testAcquireNegativeAcquireAndPollOnCount() {
- for(int i=1;i<11;i++){
+ for (int i = 1; i < 11; i++) {
// Keep on increasing the amount of time it takes to complete transaction for each tenth of a
// percentile. Essentially this would be 1ms for the 10th percentile, 2ms for 20th percentile and so on.
doReturn(TimeUnit.MILLISECONDS.toNanos(8) * 1D).when(commitSnapshot).getValue(i * 0.1);
doReturn(TimeUnit.MILLISECONDS.toNanos(200) * 1D).when(commitSnapshot).getValue(1.0);
TransactionRateLimiter rateLimiter = new TransactionRateLimiter(actorContext);
- rateLimiter.setAcquireCount(Long.MAX_VALUE-1);
+ rateLimiter.setAcquireCount(Long.MAX_VALUE - 1);
rateLimiter.setPollOnCount(Long.MAX_VALUE);
rateLimiter.acquire();
assertEquals(-9223372036854775759L, rateLimiter.getPollOnCount());
- for(int i=0;i<50;i++){
+ for (int i = 0; i < 50; i++) {
rateLimiter.acquire();
}
}
- public Matcher<Double> approximately(final double val){
+ public Matcher<Double> approximately(final double val) {
return new BaseMatcher<Double>() {
@Override
- public boolean matches(Object o) {
- Double aDouble = (Double) o;
- return aDouble >= val && aDouble <= val+1;
+ public boolean matches(Object obj) {
+ Double value = (Double) obj;
+ return value >= val && value <= val + 1;
}
@Override
public void describeTo(Description description) {
- description.appendText("> " + val +" < " + (val+1));
+ description.appendText("> " + val + " < " + (val + 1));
}
};
}
-}
\ No newline at end of file
+}
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
public class CarsModel {
- public static final QName BASE_QNAME = QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:cars", "2014-03-13",
- "cars");
+ public static final QName BASE_QNAME = QName.create(
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:cars", "2014-03-13", "cars");
public static final QName CARS_QNAME = QName.create(BASE_QNAME, "cars");
public static final QName CAR_QNAME = QName.create(CARS_QNAME, "car");
public static final YangInstanceIdentifier BASE_PATH = YangInstanceIdentifier.of(BASE_QNAME);
public static final YangInstanceIdentifier CAR_LIST_PATH = BASE_PATH.node(CAR_QNAME);
- public static NormalizedNode<?, ?> create(){
+ public static NormalizedNode<?, ?> create() {
// Create a list builder
CollectionNodeBuilder<MapEntryNode, MapNode> cars =
}
- public static NormalizedNode<?, ?> createEmptyCarsList(){
+ public static NormalizedNode<?, ?> createEmptyCarsList() {
return newCarsNode(newCarsMapNode());
}
}
public static MapNode newCarsMapNode(MapEntryNode... carEntries) {
- CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableMapNodeBuilder.create().
- withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CAR_QNAME));
- for(MapEntryNode e: carEntries) {
+ CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableMapNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CAR_QNAME));
+ for (MapEntryNode e : carEntries) {
builder.withChild(e);
}
return builder.build();
}
- public static NormalizedNode<?, ?> emptyContainer(){
+ public static NormalizedNode<?, ?> emptyContainer() {
return ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(BASE_QNAME))
.build();
public class CompositeModel {
- public static final QName TEST_QNAME = QName.create(
- "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test",
- "2014-03-13", "test");
-
- public static final QName AUG_QNAME = QName.create(
- "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug",
- "2014-03-13", "name");
-
- public static final QName AUG_CONTAINER = QName.create(AUG_QNAME, "aug-container");
- public static final QName AUG_INNER_CONTAINER = QName.create(AUG_QNAME, "aug-inner-container");
- public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc");
- public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME,
- "outer-list");
- public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME,
- "inner-list");
- public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME,
- "outer-choice");
- public static final QName ID_QNAME = QName.create(TEST_QNAME, "id");
- public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name");
- public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value");
- private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
- private static final String DATASTORE_AUG_YANG =
- "/odl-datastore-augmentation.yang";
- private static final String DATASTORE_TEST_NOTIFICATION_YANG =
- "/odl-datastore-test-notification.yang";
-
-
- public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier
- .of(TEST_QNAME);
- public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier
- .builder(TEST_PATH).node(DESC_QNAME).build();
- public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier
- .builder(TEST_PATH).node(OUTER_LIST_QNAME).build();
- public static final QName TWO_QNAME = QName.create(TEST_QNAME, "two");
- public static final QName THREE_QNAME = QName.create(TEST_QNAME, "three");
-
- private static final Integer ONE_ID = 1;
- private static final Integer TWO_ID = 2;
- private static final String TWO_ONE_NAME = "one";
- private static final String TWO_TWO_NAME = "two";
- private static final String DESC = "Hello there";
-
- // Family specific constants
- public static final QName FAMILY_QNAME =
- QName
- .create(
- "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test",
- "2014-04-17", "family");
- public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME,
- "children");
- public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME,
- "grand-children");
- public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME,
- "child-number");
- public static final QName CHILD_NAME_QNAME = QName.create(FAMILY_QNAME,
- "child-name");
- public static final QName GRAND_CHILD_NUMBER_QNAME = QName.create(
- FAMILY_QNAME, "grand-child-number");
- public static final QName GRAND_CHILD_NAME_QNAME = QName.create(FAMILY_QNAME,
- "grand-child-name");
-
- public static final YangInstanceIdentifier FAMILY_PATH = YangInstanceIdentifier
- .of(FAMILY_QNAME);
- public static final YangInstanceIdentifier FAMILY_DESC_PATH = YangInstanceIdentifier
- .builder(FAMILY_PATH).node(DESC_QNAME).build();
- public static final YangInstanceIdentifier CHILDREN_PATH = YangInstanceIdentifier
- .builder(FAMILY_PATH).node(CHILDREN_QNAME).build();
-
- private static final Integer FIRST_CHILD_ID = 1;
- private static final Integer SECOND_CHILD_ID = 2;
-
- private static final String FIRST_CHILD_NAME = "first child";
- private static final String SECOND_CHILD_NAME = "second child";
-
- private static final Integer FIRST_GRAND_CHILD_ID = 1;
- private static final Integer SECOND_GRAND_CHILD_ID = 2;
-
- private static final String FIRST_GRAND_CHILD_NAME = "first grand child";
- private static final String SECOND_GRAND_CHILD_NAME = "second grand child";
-
- // first child
- private static final YangInstanceIdentifier CHILDREN_1_PATH = YangInstanceIdentifier
- .builder(CHILDREN_PATH)
- .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID) //
- .build();
- private static final YangInstanceIdentifier CHILDREN_1_NAME_PATH =
- YangInstanceIdentifier.builder(CHILDREN_PATH)
- .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, FIRST_CHILD_NAME) //
- .build();
-
- private static final YangInstanceIdentifier CHILDREN_2_PATH = YangInstanceIdentifier
- .builder(CHILDREN_PATH)
- .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID) //
- .build();
- private static final YangInstanceIdentifier CHILDREN_2_NAME_PATH =
- YangInstanceIdentifier.builder(CHILDREN_PATH)
- .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, SECOND_CHILD_NAME) //
- .build();
-
-
- private static final YangInstanceIdentifier GRAND_CHILD_1_PATH =
- YangInstanceIdentifier.builder(CHILDREN_1_PATH)
- .node(GRAND_CHILDREN_QNAME)
- //
- .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
- FIRST_GRAND_CHILD_ID) //
- .build();
-
- private static final YangInstanceIdentifier GRAND_CHILD_1_NAME_PATH =
- YangInstanceIdentifier.builder(CHILDREN_1_PATH)
- .node(GRAND_CHILDREN_QNAME)
- //
- .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
- FIRST_GRAND_CHILD_NAME) //
- .build();
-
- private static final YangInstanceIdentifier GRAND_CHILD_2_PATH =
- YangInstanceIdentifier.builder(CHILDREN_2_PATH)
- .node(GRAND_CHILDREN_QNAME)
- //
- .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
- SECOND_GRAND_CHILD_ID) //
- .build();
-
- private static final YangInstanceIdentifier GRAND_CHILD_2_NAME_PATH =
- YangInstanceIdentifier.builder(CHILDREN_2_PATH)
- .node(GRAND_CHILDREN_QNAME)
- //
- .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
- SECOND_GRAND_CHILD_NAME) //
- .build();
-
- private static final YangInstanceIdentifier DESC_PATH_ID = YangInstanceIdentifier
- .builder(DESC_PATH).build();
- private static final YangInstanceIdentifier OUTER_LIST_1_PATH =
- YangInstanceIdentifier.builder(OUTER_LIST_PATH)
- .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
- .build();
-
- private static final YangInstanceIdentifier OUTER_LIST_2_PATH =
- YangInstanceIdentifier.builder(OUTER_LIST_PATH)
- .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
- .build();
-
- private static final YangInstanceIdentifier TWO_TWO_PATH = YangInstanceIdentifier
- .builder(OUTER_LIST_2_PATH).node(INNER_LIST_QNAME) //
- .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
- .build();
-
- private static final YangInstanceIdentifier TWO_TWO_VALUE_PATH =
- YangInstanceIdentifier.builder(TWO_TWO_PATH).node(VALUE_QNAME) //
- .build();
-
- private static final MapEntryNode BAR_NODE = mapEntryBuilder(
- OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
- .withChild(mapNodeBuilder(INNER_LIST_QNAME) //
- .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
- .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
- .build()) //
- .build();
-
- public static final InputStream getDatastoreTestInputStream() {
- return getInputStream(DATASTORE_TEST_YANG);
- }
-
- public static final InputStream getDatastoreAugInputStream() {
- return getInputStream(DATASTORE_AUG_YANG);
- }
-
- public static final InputStream getDatastoreTestNotificationInputStream() {
- return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG);
- }
-
- private static InputStream getInputStream(final String resourceName) {
- return CompositeModel.class.getResourceAsStream(resourceName);
- }
-
- public static SchemaContext createTestContext() {
- List<InputStream> inputStreams = new ArrayList<>();
- inputStreams.add(getDatastoreTestInputStream());
- inputStreams.add(getDatastoreAugInputStream());
- inputStreams.add(getDatastoreTestNotificationInputStream());
-
- final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- final SchemaContext schemaContext;
-
- try {
- schemaContext = reactor.buildEffective(inputStreams);
- } catch (ReactorException e) {
- throw new RuntimeException("Unable to build schema context from " + inputStreams, e);
- }
- return schemaContext;
- }
-
- /**
- * Returns a test document
- *
- * <pre>
- * test
- * outer-list
- * id 1
- * outer-list
- * id 2
- * inner-list
- * name "one"
- * inner-list
- * name "two"
- *
- * </pre>
- *
- * @return
- */
- public static NormalizedNode<?, ?> createDocumentOne(
- SchemaContext schemaContext) {
- return ImmutableContainerNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(schemaContext.getQName()))
- .withChild(createTestContainer()).build();
-
- }
-
- public static ContainerNode createTestContainer() {
-
-
- final LeafSetEntryNode<Object> nike =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME,
- "shoe"), "nike")).withValue("nike").build();
- final LeafSetEntryNode<Object> puma =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME,
- "shoe"), "puma")).withValue("puma").build();
- final LeafSetNode<Object> shoes =
- ImmutableLeafSetNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(QName.create(TEST_QNAME,
- "shoe"))).withChild(nike).withChild(puma).build();
-
-
- final LeafSetEntryNode<Object> five =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- (new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME,
- "number"), 5))).withValue(5).build();
- final LeafSetEntryNode<Object> fifteen =
- ImmutableLeafSetEntryNodeBuilder
- .create()
- .withNodeIdentifier(
- (new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME,
- "number"), 15))).withValue(15).build();
- final LeafSetNode<Object> numbers =
- ImmutableLeafSetNodeBuilder
- .create()
- .withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(QName.create(TEST_QNAME,
- "number"))).withChild(five).withChild(fifteen).build();
-
-
- Set<QName> childAugmentations = new HashSet<>();
- childAugmentations.add(AUG_QNAME);
- final YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
- new YangInstanceIdentifier.AugmentationIdentifier(childAugmentations);
- final AugmentationNode augmentationNode =
- Builders.augmentationBuilder()
- .withNodeIdentifier(augmentationIdentifier)
- .withChild(ImmutableNodes.leafNode(AUG_QNAME, "First Test"))
+ public static final QName TEST_QNAME = QName
+ .create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", "2014-03-13", "test");
+
+ public static final QName AUG_QNAME = QName
+ .create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug", "2014-03-13", "name");
+
+ public static final QName AUG_CONTAINER = QName.create(AUG_QNAME, "aug-container");
+ public static final QName AUG_INNER_CONTAINER = QName.create(AUG_QNAME, "aug-inner-container");
+ public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc");
+ public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME, "outer-list");
+ public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME, "inner-list");
+ public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME, "outer-choice");
+ public static final QName ID_QNAME = QName.create(TEST_QNAME, "id");
+ public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name");
+ public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value");
+ private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
+ private static final String DATASTORE_AUG_YANG = "/odl-datastore-augmentation.yang";
+ private static final String DATASTORE_TEST_NOTIFICATION_YANG = "/odl-datastore-test-notification.yang";
+
+ public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_QNAME);
+ public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier.builder(TEST_PATH).node(DESC_QNAME)
+ .build();
+ public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier.builder(TEST_PATH)
+ .node(OUTER_LIST_QNAME).build();
+ public static final QName TWO_QNAME = QName.create(TEST_QNAME, "two");
+ public static final QName THREE_QNAME = QName.create(TEST_QNAME, "three");
+
+ private static final Integer ONE_ID = 1;
+ private static final Integer TWO_ID = 2;
+ private static final String TWO_ONE_NAME = "one";
+ private static final String TWO_TWO_NAME = "two";
+ private static final String DESC = "Hello there";
+
+ // Family specific constants
+ public static final QName FAMILY_QNAME = QName.create(
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test", "2014-04-17",
+ "family");
+ public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME, "children");
+ public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME, "grand-children");
+ public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME, "child-number");
+ public static final QName CHILD_NAME_QNAME = QName.create(FAMILY_QNAME, "child-name");
+ public static final QName GRAND_CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME, "grand-child-number");
+ public static final QName GRAND_CHILD_NAME_QNAME = QName.create(FAMILY_QNAME, "grand-child-name");
+
+ public static final YangInstanceIdentifier FAMILY_PATH = YangInstanceIdentifier.of(FAMILY_QNAME);
+ public static final YangInstanceIdentifier FAMILY_DESC_PATH = YangInstanceIdentifier.builder(FAMILY_PATH)
+ .node(DESC_QNAME).build();
+ public static final YangInstanceIdentifier CHILDREN_PATH = YangInstanceIdentifier.builder(FAMILY_PATH)
+ .node(CHILDREN_QNAME).build();
+
+ private static final Integer FIRST_CHILD_ID = 1;
+ private static final Integer SECOND_CHILD_ID = 2;
+
+ private static final String FIRST_CHILD_NAME = "first child";
+ private static final String SECOND_CHILD_NAME = "second child";
+
+ private static final Integer FIRST_GRAND_CHILD_ID = 1;
+ private static final Integer SECOND_GRAND_CHILD_ID = 2;
+
+ private static final String FIRST_GRAND_CHILD_NAME = "first grand child";
+ private static final String SECOND_GRAND_CHILD_NAME = "second grand child";
+
+ private static final MapEntryNode BAR_NODE = mapEntryBuilder(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
+ .withChild(mapNodeBuilder(INNER_LIST_QNAME) //
+ .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
+ .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
+ .build()) //
.build();
- return ImmutableContainerNodeBuilder
- .create()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME))
- .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC))
- .withChild(augmentationNode)
- .withChild(shoes)
- .withChild(numbers)
- .withChild(
- mapNodeBuilder(OUTER_LIST_QNAME)
- .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
- .withChild(BAR_NODE).build()).build();
-
- }
-
-
- public static ContainerNode createFamily() {
- final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> familyContainerBuilder =
- ImmutableContainerNodeBuilder.create().withNodeIdentifier(
- new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME));
-
- final CollectionNodeBuilder<MapEntryNode, MapNode> childrenBuilder =
- mapNodeBuilder(CHILDREN_QNAME);
-
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstChildBuilder =
- mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondChildBuilder =
- mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID);
-
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstGrandChildBuilder =
- mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
- FIRST_GRAND_CHILD_ID);
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondGrandChildBuilder =
- mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
- SECOND_GRAND_CHILD_ID);
-
- firstGrandChildBuilder
- .withChild(
- ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME,
- FIRST_GRAND_CHILD_ID)).withChild(
- ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME,
- FIRST_GRAND_CHILD_NAME));
-
- secondGrandChildBuilder.withChild(
- ImmutableNodes
- .leafNode(GRAND_CHILD_NUMBER_QNAME, SECOND_GRAND_CHILD_ID))
- .withChild(
- ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME,
- SECOND_GRAND_CHILD_NAME));
-
- firstChildBuilder
- .withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID))
- .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, FIRST_CHILD_NAME))
- .withChild(
- mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(
- firstGrandChildBuilder.build()).build());
-
-
- secondChildBuilder
- .withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, SECOND_CHILD_ID))
- .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, SECOND_CHILD_NAME))
- .withChild(
- mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(
- firstGrandChildBuilder.build()).build());
-
- childrenBuilder.withChild(firstChildBuilder.build());
- childrenBuilder.withChild(secondChildBuilder.build());
-
- return familyContainerBuilder.withChild(childrenBuilder.build()).build();
- }
+
+ public static final InputStream getDatastoreTestInputStream() {
+ return getInputStream(DATASTORE_TEST_YANG);
+ }
+
+ public static final InputStream getDatastoreAugInputStream() {
+ return getInputStream(DATASTORE_AUG_YANG);
+ }
+
+ public static final InputStream getDatastoreTestNotificationInputStream() {
+ return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG);
+ }
+
+ private static InputStream getInputStream(final String resourceName) {
+ return CompositeModel.class.getResourceAsStream(resourceName);
+ }
+
+ public static SchemaContext createTestContext() {
+ List<InputStream> inputStreams = new ArrayList<>();
+ inputStreams.add(getDatastoreTestInputStream());
+ inputStreams.add(getDatastoreAugInputStream());
+ inputStreams.add(getDatastoreTestNotificationInputStream());
+
+ final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
+ final SchemaContext schemaContext;
+
+ try {
+ schemaContext = reactor.buildEffective(inputStreams);
+ } catch (ReactorException e) {
+ throw new RuntimeException("Unable to build schema context from " + inputStreams, e);
+ }
+ return schemaContext;
+ }
+
+ /**
+ * Returns a test document.
+ *
+ * <pre>
+ * test
+ * outer-list
+ * id 1
+ * outer-list
+ * id 2
+ * inner-list
+ * name "one"
+ * inner-list
+ * name "two"
+ *
+ * </pre>
+ */
+ public static NormalizedNode<?, ?> createDocumentOne(SchemaContext schemaContext) {
+ return ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(schemaContext.getQName()))
+ .withChild(createTestContainer()).build();
+
+ }
+
+ public static ContainerNode createTestContainer() {
+
+ final LeafSetEntryNode<Object> nike = ImmutableLeafSetEntryNodeBuilder.create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME, "shoe"), "nike"))
+ .withValue("nike").build();
+ final LeafSetEntryNode<Object> puma = ImmutableLeafSetEntryNodeBuilder.create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME, "shoe"), "puma"))
+ .withValue("puma").build();
+ final LeafSetNode<Object> shoes = ImmutableLeafSetNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(TEST_QNAME, "shoe")))
+ .withChild(nike).withChild(puma).build();
+
+ final LeafSetEntryNode<Object> five = ImmutableLeafSetEntryNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME, "number"), 5))
+ .withValue(5).build();
+ final LeafSetEntryNode<Object> fifteen = ImmutableLeafSetEntryNodeBuilder.create()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeWithValue<>(QName.create(TEST_QNAME, "number"), 15))
+ .withValue(15).build();
+ final LeafSetNode<Object> numbers = ImmutableLeafSetNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(TEST_QNAME, "number")))
+ .withChild(five).withChild(fifteen).build();
+
+ Set<QName> childAugmentations = new HashSet<>();
+ childAugmentations.add(AUG_QNAME);
+ final YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
+ new YangInstanceIdentifier.AugmentationIdentifier(childAugmentations);
+ final AugmentationNode augmentationNode = Builders.augmentationBuilder()
+ .withNodeIdentifier(augmentationIdentifier).withChild(ImmutableNodes.leafNode(AUG_QNAME, "First Test"))
+ .build();
+ return ImmutableContainerNodeBuilder.create()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME))
+ .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC)).withChild(augmentationNode).withChild(shoes)
+ .withChild(numbers).withChild(mapNodeBuilder(OUTER_LIST_QNAME)
+ .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID)).withChild(BAR_NODE).build())
+ .build();
+
+ }
+
+ public static ContainerNode createFamily() {
+ final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode>
+ familyContainerBuilder = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME));
+
+ final CollectionNodeBuilder<MapEntryNode, MapNode> childrenBuilder = mapNodeBuilder(CHILDREN_QNAME);
+
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ firstChildBuilder = mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ secondChildBuilder = mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID);
+
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ firstGrandChildBuilder = mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+ FIRST_GRAND_CHILD_ID);
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ secondGrandChildBuilder = mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+ SECOND_GRAND_CHILD_ID);
+
+ firstGrandChildBuilder.withChild(ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME, FIRST_GRAND_CHILD_ID))
+ .withChild(ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME, FIRST_GRAND_CHILD_NAME));
+
+ secondGrandChildBuilder.withChild(ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME, SECOND_GRAND_CHILD_ID))
+ .withChild(ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME, SECOND_GRAND_CHILD_NAME));
+
+ firstChildBuilder.withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID))
+ .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, FIRST_CHILD_NAME))
+ .withChild(mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(firstGrandChildBuilder.build()).build());
+
+ secondChildBuilder.withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, SECOND_CHILD_ID))
+ .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, SECOND_CHILD_NAME))
+ .withChild(mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(firstGrandChildBuilder.build()).build());
+
+ childrenBuilder.withChild(firstChildBuilder.build());
+ childrenBuilder.withChild(secondChildBuilder.build());
+
+ return familyContainerBuilder.withChild(childrenBuilder.build()).build();
+ }
}
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
public class PeopleModel {
- public static final QName BASE_QNAME = QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:people", "2014-03-13",
- "people");
+ public static final QName BASE_QNAME = QName.create(
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:people", "2014-03-13", "people");
public static final QName PEOPLE_QNAME = QName.create(BASE_QNAME, "people");
public static final QName PERSON_QNAME = QName.create(PEOPLE_QNAME, "person");
public static final YangInstanceIdentifier BASE_PATH = YangInstanceIdentifier.of(BASE_QNAME);
public static final YangInstanceIdentifier PERSON_LIST_PATH = BASE_PATH.node(PERSON_QNAME);
- public static NormalizedNode<?, ?> create(){
+ public static NormalizedNode<?, ?> create() {
// Create a list builder
CollectionNodeBuilder<MapEntryNode, MapNode> cars =
}
- public static NormalizedNode<?, ?> emptyContainer(){
+ public static NormalizedNode<?, ?> emptyContainer() {
return ImmutableContainerNodeBuilder.create()
.withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(BASE_QNAME))
}
public static YangInstanceIdentifier newPersonPath(String name) {
- return YangInstanceIdentifier.builder(PERSON_LIST_PATH).nodeWithKey(PERSON_QNAME, PERSON_NAME_QNAME, name).build();
+ return YangInstanceIdentifier.builder(PERSON_LIST_PATH)
+ .nodeWithKey(PERSON_QNAME, PERSON_NAME_QNAME, name).build();
}
}
public class SampleModelsTest {
@Test
- public void testPeopleModel(){
+ public void testPeopleModel() {
final NormalizedNode<?, ?> expected = PeopleModel.create();
@Test
- public void testCarsModel(){
+ public void testCarsModel() {
final NormalizedNode<?, ?> expected = CarsModel.create();
return SchemaContextHelper.class.getResourceAsStream(yangFileName);
}
- public static SchemaContext full(){
+ public static SchemaContext full() {
return select(ODL_DATASTORE_TEST_YANG, PEOPLE_YANG, CARS_YANG);
}
- public static SchemaContext select(String... schemaFiles){
+ public static SchemaContext select(String... schemaFiles) {
final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
final SchemaContext schemaContext;
List<InputStream> streams = new ArrayList<>();
- for(String schemaFile : schemaFiles){
+ for (String schemaFile : schemaFiles) {
streams.add(getInputStream(schemaFile));
}
public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_QNAME);
public static final YangInstanceIdentifier TEST2_PATH = YangInstanceIdentifier.of(TEST2_QNAME);
public static final YangInstanceIdentifier JUNK_PATH = YangInstanceIdentifier.of(JUNK_QNAME);
- public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier.builder(TEST_PATH).
- node(OUTER_LIST_QNAME).build();
- public static final YangInstanceIdentifier INNER_LIST_PATH = YangInstanceIdentifier.builder(TEST_PATH).
- node(OUTER_LIST_QNAME).node(INNER_LIST_QNAME).build();
+ public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier.builder(TEST_PATH)
+ .node(OUTER_LIST_QNAME).build();
+ public static final YangInstanceIdentifier INNER_LIST_PATH = YangInstanceIdentifier.builder(TEST_PATH)
+ .node(OUTER_LIST_QNAME).node(INNER_LIST_QNAME).build();
public static final YangInstanceIdentifier OUTER_CONTAINER_PATH = TEST_PATH.node(OUTER_CONTAINER_QNAME);
public static final QName TWO_QNAME = QName.create(TEST_QNAME,"two");
public static final QName THREE_QNAME = QName.create(TEST_QNAME,"three");
public static SchemaContext createTestContext() {
final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
final SchemaContext schemaContext;
- final Set<ByteSource> sources = Collections.singleton(Resources.asByteSource(TestModel.class.getResource
- (DATASTORE_TEST_YANG)));
+ final Set<ByteSource> sources = Collections
+ .singleton(Resources.asByteSource(TestModel.class.getResource(DATASTORE_TEST_YANG)));
try {
schemaContext = reactor.buildEffective(sources);
public static DataContainerChild<?, ?> outerNode(int... ids) {
CollectionNodeBuilder<MapEntryNode, MapNode> outer = ImmutableNodes.mapNodeBuilder(OUTER_LIST_QNAME);
- for(int id: ids) {
+ for (int id: ids) {
outer.addChild(ImmutableNodes.mapEntry(OUTER_LIST_QNAME, ID_QNAME, id));
}
public static DataContainerChild<?, ?> outerNode(MapEntryNode... entries) {
CollectionNodeBuilder<MapEntryNode, MapNode> outer = ImmutableNodes.mapNodeBuilder(OUTER_LIST_QNAME);
- for(MapEntryNode e: entries) {
+ for (MapEntryNode e: entries) {
outer.addChild(e);
}
public static DataContainerChild<?, ?> innerNode(String... names) {
CollectionNodeBuilder<MapEntryNode, MapNode> outer = ImmutableNodes.mapNodeBuilder(INNER_LIST_QNAME);
- for(String name: names) {
+ for (String name: names) {
outer.addChild(ImmutableNodes.mapEntry(INNER_LIST_QNAME, NAME_QNAME, name));
}