From b5cb353e3553a39f576c284119af75ffa5ea66a9 Mon Sep 17 00:00:00 2001 From: Robert Varga Date: Tue, 27 Jun 2017 23:43:40 +0200 Subject: [PATCH] Cleanup warnings - pom.xml groupId duplicate - Futures.addCallback() - Throwables.propagate*() - pontentially-static methods - remove 'throws Exception' where it is not really needed Change-Id: Ib47e6255e0f510ab7dd0dcd08f71f2dd124df7b7 Signed-off-by: Robert Varga --- .../raft/behaviors/AbstractLeader.java | 61 ++++++------ .../behaviors/LeaderInstallSnapshotState.java | 11 +-- .../cluster/raft/MockRaftActor.java | 61 ++++++------ .../cluster/raft/MockRaftActorContext.java | 49 ++++----- .../AbstractLeaderElectionScenarioTest.java | 43 ++++---- .../AbstractRaftActorBehaviorTest.java | 29 +++--- .../cluster/raft/behaviors/CandidateTest.java | 9 +- .../DelayedMessagesElectionScenarioTest.java | 11 +-- .../cluster/raft/behaviors/FollowerTest.java | 91 ++++++++--------- .../raft/behaviors/IsolatedLeaderTest.java | 6 +- .../cluster/raft/behaviors/LeaderTest.java | 16 +-- ...andidateOnStartupElectionScenarioTest.java | 9 +- ...artitionedLeadersElectionScenarioTest.java | 8 +- .../raft/behaviors/SnapshotTrackerTest.java | 2 +- .../cluster/raft/persisted/SnapshotTest.java | 4 +- .../raft/utils/MessageCollectorActor.java | 44 +++++---- .../md-sal/sal-clustering-commons/pom.xml | 1 - .../common/actor/MeteredBoundedMailbox.java | 11 ++- .../common/actor/MeteringBehavior.java | 2 +- .../cluster/messaging/MessageAssembler.java | 14 +-- .../cluster/messaging/MessageSlicer.java | 14 +-- .../RemoteYangTextSourceProviderImpl.java | 19 ++-- .../MessageSlicingIntegrationTest.java | 15 +-- .../persistence/LocalSnapshotStoreTest.java | 11 ++- .../databroker/DOMBrokerTransactionChain.java | 5 +- .../dds/AbstractDataStoreClientActor.java | 5 +- .../dds/AbstractDataStoreClientBehavior.java | 3 +- .../actors/dds/AbstractProxyTransaction.java | 3 +- .../cluster/datastore/AbstractDataStore.java | 3 +- .../datastore/CompositeDataTreeCohort.java | 4 +- .../ThreePhaseCommitCohortProxy.java | 43 ++++---- .../persisted/AbortTransactionPayload.java | 3 +- .../persisted/CloseLocalHistoryPayload.java | 3 +- .../persisted/CreateLocalHistoryPayload.java | 3 +- .../persisted/PurgeLocalHistoryPayload.java | 3 +- .../persisted/PurgeTransactionPayload.java | 3 +- .../shardmanager/ShardManagerInfo.java | 15 +-- .../utils/DataTreeModificationOutput.java | 17 ++-- .../DistributedShardedDOMDataTree.java | 19 ++-- .../ConcurrentDOMDataBrokerTest.java | 3 +- .../cluster/datastore/AbstractShardTest.java | 4 +- .../AbstractTransactionProxyTest.java | 99 ++++++++++--------- .../DataTreeChangeListenerSupportTest.java | 27 ++--- .../DistributedDataStoreIntegrationTest.java | 8 +- .../cluster/datastore/ShardTest.java | 11 ++- .../datastore/ShardTransactionTest.java | 9 +- .../ThreePhaseCommitCohortProxyTest.java | 40 ++++---- .../datastore/TransactionProxyTest.java | 7 +- .../datastore/model/SchemaContextHelper.java | 3 +- 49 files changed, 454 insertions(+), 430 deletions(-) diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java index 9fc7b3393c..73112818f2 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeader.java @@ -14,7 +14,6 @@ import akka.actor.Cancellable; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import com.google.common.io.ByteSource; import java.io.IOException; import java.io.ObjectOutputStream; @@ -102,8 +101,8 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { private Optional snapshotHolder = Optional.absent(); private int minReplicationCount; - protected AbstractLeader(RaftActorContext context, RaftState state, - @Nullable AbstractLeader initializeFromLeader) { + protected AbstractLeader(final RaftActorContext context, final RaftState state, + @Nullable final AbstractLeader initializeFromLeader) { super(context, state); appendEntriesMessageSlicer = MessageSlicer.builder().logContext(logName()) @@ -136,7 +135,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval()); } - protected AbstractLeader(RaftActorContext context, RaftState state) { + protected AbstractLeader(final RaftActorContext context, final RaftState state) { this(context, state, null); } @@ -149,7 +148,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { return followerToLog.keySet(); } - public void addFollower(String followerId) { + public void addFollower(final String followerId) { FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl( context.getPeerInfo(followerId), -1, context); followerToLog.put(followerId, followerLogInformation); @@ -159,7 +158,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } } - public void removeFollower(String followerId) { + public void removeFollower(final String followerId) { followerToLog.remove(followerId); } @@ -186,7 +185,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } @VisibleForTesting - void setSnapshot(@Nullable SnapshotHolder snapshotHolder) { + void setSnapshot(@Nullable final SnapshotHolder snapshotHolder) { this.snapshotHolder = Optional.fromNullable(snapshotHolder); } @@ -196,8 +195,8 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } @Override - protected RaftActorBehavior handleAppendEntries(ActorRef sender, - AppendEntries appendEntries) { + protected RaftActorBehavior handleAppendEntries(final ActorRef sender, + final AppendEntries appendEntries) { log.debug("{}: handleAppendEntries: {}", logName(), appendEntries); @@ -205,7 +204,8 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } @Override - protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) { + protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender, + final AppendEntriesReply appendEntriesReply) { log.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply); // Update the FollowerLogInformation @@ -403,8 +403,8 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } } - private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation, - AppendEntriesReply appendEntriesReply) { + private boolean updateFollowerLogInformation(final FollowerLogInformation followerLogInformation, + final AppendEntriesReply appendEntriesReply) { boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex()); updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated; @@ -431,7 +431,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } @Override - protected ClientRequestTracker removeClientRequestTracker(long logIndex) { + protected ClientRequestTracker removeClientRequestTracker(final long logIndex) { final Iterator it = trackers.iterator(); while (it.hasNext()) { final ClientRequestTracker t = it.next(); @@ -445,15 +445,15 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } @Override - protected RaftActorBehavior handleRequestVoteReply(ActorRef sender, - RequestVoteReply requestVoteReply) { + protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender, + final RequestVoteReply requestVoteReply) { return this; } protected void beforeSendHeartbeat(){} @Override - public RaftActorBehavior handleMessage(ActorRef sender, Object message) { + public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) { Preconditions.checkNotNull(sender, "sender should not be null"); if (appendEntriesMessageSlicer.handleMessage(message)) { @@ -509,7 +509,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { return this; } - private void handleInstallSnapshotReply(InstallSnapshotReply reply) { + private void handleInstallSnapshotReply(final InstallSnapshotReply reply) { log.debug("{}: handleInstallSnapshotReply: {}", logName(), reply); String followerId = reply.getFollowerId(); @@ -603,7 +603,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { return false; } - private void replicate(Replicate replicate) { + private void replicate(final Replicate replicate) { long logIndex = replicate.getReplicatedLogEntry().getIndex(); log.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}, isSendImmediate: {}", logName(), @@ -630,7 +630,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } } - protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) { + protected void sendAppendEntries(final long timeSinceLastActivityInterval, final boolean isHeartbeat) { // Send an AppendEntries to all followers for (Entry e : followerToLog.entrySet()) { final String followerId = e.getKey(); @@ -647,8 +647,8 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { * This method checks if any update needs to be sent to the given follower. This includes append log entries, * sending next snapshot chunk, and initiating a snapshot. */ - private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation, - boolean sendHeartbeat, boolean isHeartbeat) { + private void sendUpdatesToFollower(final String followerId, final FollowerLogInformation followerLogInformation, + final boolean sendHeartbeat, final boolean isHeartbeat) { ActorSelection followerActor = context.getPeerActorSelection(followerId); if (followerActor != null) { @@ -843,7 +843,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { * @param followerId the id of the follower. * @return true if capture was initiated, false otherwise. */ - public boolean initiateCaptureSnapshot(String followerId) { + public boolean initiateCaptureSnapshot(final String followerId) { FollowerLogInformation followerLogInfo = followerToLog.get(followerId); if (snapshotHolder.isPresent()) { // If a snapshot is present in the memory, most likely another install is in progress no need to capture @@ -865,7 +865,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { return captureInitiated; } - private boolean canInstallSnapshot(long nextIndex) { + private boolean canInstallSnapshot(final long nextIndex) { // If the follower's nextIndex is -1 then we might as well send it a snapshot // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present // in the snapshot @@ -897,7 +897,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { * Sends a snapshot chunk to a given follower * InstallSnapshot should qualify as a heartbeat too. */ - private void sendSnapshotChunk(ActorSelection followerActor, FollowerLogInformation followerLogInfo) { + private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo) { if (snapshotHolder.isPresent()) { LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState(); if (installSnapshotState == null) { @@ -938,11 +938,12 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { actor() ); - log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(), - installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks()); } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } + + log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(), + installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks()); } } @@ -961,7 +962,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } } - private void scheduleHeartBeat(FiniteDuration interval) { + private void scheduleHeartBeat(final FiniteDuration interval) { if (followerToLog.isEmpty()) { // Optimization - do not bother scheduling a heartbeat as there are // no followers @@ -1028,7 +1029,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { } @VisibleForTesting - public FollowerLogInformation getFollower(String followerId) { + public FollowerLogInformation getFollower(final String followerId) { return followerToLog.get(followerId); } @@ -1042,7 +1043,7 @@ public abstract class AbstractLeader extends AbstractRaftActorBehavior { private final long lastIncludedIndex; private final ByteSource snapshotBytes; - SnapshotHolder(Snapshot snapshot, ByteSource snapshotBytes) { + SnapshotHolder(final Snapshot snapshot, final ByteSource snapshotBytes) { this.lastIncludedTerm = snapshot.getLastAppliedTerm(); this.lastIncludedIndex = snapshot.getLastAppliedIndex(); this.snapshotBytes = snapshotBytes; diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderInstallSnapshotState.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderInstallSnapshotState.java index 3b4c7d8133..946c56bec0 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderInstallSnapshotState.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderInstallSnapshotState.java @@ -7,7 +7,6 @@ */ package org.opendaylight.controller.cluster.raft.behaviors; -import com.google.common.base.Throwables; import com.google.common.io.ByteSource; import java.io.IOException; import java.io.InputStream; @@ -45,12 +44,12 @@ public final class LeaderInstallSnapshotState implements AutoCloseable { private long snapshotSize; private InputStream snapshotInputStream; - LeaderInstallSnapshotState(int snapshotChunkSize, String logName) { + LeaderInstallSnapshotState(final int snapshotChunkSize, final String logName) { this.snapshotChunkSize = snapshotChunkSize; this.logName = logName; } - void setSnapshotBytes(ByteSource snapshotBytes) throws IOException { + void setSnapshotBytes(final ByteSource snapshotBytes) throws IOException { if (this.snapshotBytes != null) { return; } @@ -98,11 +97,11 @@ public final class LeaderInstallSnapshotState implements AutoCloseable { || replyReceivedForOffset == offset); } - boolean isLastChunk(int index) { + boolean isLastChunk(final int index) { return totalChunks == index; } - void markSendStatus(boolean success) { + void markSendStatus(final boolean success) { if (success) { // if the chunk sent was successful replyReceivedForOffset = offset; @@ -153,7 +152,7 @@ public final class LeaderInstallSnapshotState implements AutoCloseable { try { snapshotInputStream = snapshotBytes.openStream(); } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActor.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActor.java index 7f3b12c54b..108156d951 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActor.java @@ -15,7 +15,6 @@ import akka.actor.ActorRef; import akka.actor.Props; import com.google.common.base.Function; import com.google.common.base.Optional; -import com.google.common.base.Throwables; import com.google.common.io.ByteSource; import com.google.common.util.concurrent.Uninterruptibles; import java.io.IOException; @@ -50,7 +49,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, final CountDownLatch snapshotCommitted = new CountDownLatch(1); private final Function pauseLeaderFunction; - protected MockRaftActor(AbstractBuilder builder) { + protected MockRaftActor(final AbstractBuilder builder) { super(builder.id, builder.peerAddresses != null ? builder.peerAddresses : Collections.emptyMap(), Optional.fromNullable(builder.config), PAYLOAD_VERSION); state = new ArrayList<>(); @@ -72,7 +71,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, pauseLeaderFunction = builder.pauseLeaderFunction; } - public void setRaftActorRecoverySupport(RaftActorRecoverySupport support) { + public void setRaftActorRecoverySupport(final RaftActorRecoverySupport support) { raftActorRecoverySupport = support; } @@ -100,7 +99,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, try { assertEquals("Recovery complete", true, recoveryComplete.await(5, TimeUnit.SECONDS)); } catch (InterruptedException e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -108,7 +107,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, try { assertEquals("Behavior initialized", true, initializeBehaviorComplete.await(5, TimeUnit.SECONDS)); } catch (InterruptedException e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -127,7 +126,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } @Override - protected void applyState(ActorRef clientActor, Identifier identifier, Object data) { + protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) { actorDelegate.applyState(clientActor, identifier, data); LOG.info("{}: applyState called: {}", persistenceId(), data); @@ -146,11 +145,11 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } @Override - public void startLogRecoveryBatch(int maxBatchSize) { + public void startLogRecoveryBatch(final int maxBatchSize) { } @Override - public void appendRecoveredLogEntry(Payload data) { + public void appendRecoveredLogEntry(final Payload data) { state.add(data); } @@ -171,12 +170,12 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } @Override - public void applyRecoverySnapshot(Snapshot.State newState) { + public void applyRecoverySnapshot(final Snapshot.State newState) { recoveryCohortDelegate.applyRecoverySnapshot(newState); applySnapshotState(newState); } - private void applySnapshotState(Snapshot.State newState) { + private void applySnapshotState(final Snapshot.State newState) { if (newState instanceof MockSnapshotState) { state.clear(); state.addAll(((MockSnapshotState)newState).getState()); @@ -184,20 +183,20 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } @Override - public void createSnapshot(ActorRef actorRef, java.util.Optional installSnapshotStream) { + public void createSnapshot(final ActorRef actorRef, final java.util.Optional installSnapshotStream) { LOG.info("{}: createSnapshot called", persistenceId()); snapshotCohortDelegate.createSnapshot(actorRef, installSnapshotStream); } @Override - public void applySnapshot(Snapshot.State newState) { + public void applySnapshot(final Snapshot.State newState) { LOG.info("{}: applySnapshot called", persistenceId()); applySnapshotState(newState); snapshotCohortDelegate.applySnapshot(newState); } @Override - public Snapshot.State deserializeSnapshot(ByteSource snapshotBytes) { + public Snapshot.State deserializeSnapshot(final ByteSource snapshotBytes) { try { return (Snapshot.State) SerializationUtils.deserialize(snapshotBytes.read()); } catch (IOException e) { @@ -219,7 +218,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, return this.getId(); } - protected void newBehavior(RaftActorBehavior newBehavior) { + protected void newBehavior(final RaftActorBehavior newBehavior) { self().tell(newBehavior, ActorRef.noSender()); } @@ -237,7 +236,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } @Override - protected void pauseLeader(Runnable operation) { + protected void pauseLeader(final Runnable operation) { if (pauseLeaderFunction != null) { pauseLeaderFunction.apply(operation); } else { @@ -245,7 +244,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } } - public static List fromState(Snapshot.State from) { + public static List fromState(final Snapshot.State from) { if (from instanceof MockSnapshotState) { return ((MockSnapshotState)from).getState(); } @@ -262,12 +261,12 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, return restoreFromSnapshot; } - public static Props props(final String id, final Map peerAddresses, ConfigParams config) { + public static Props props(final String id, final Map peerAddresses, final ConfigParams config) { return builder().id(id).peerAddresses(peerAddresses).config(config).props(); } public static Props props(final String id, final Map peerAddresses, - ConfigParams config, DataPersistenceProvider dataPersistenceProvider) { + final ConfigParams config, final DataPersistenceProvider dataPersistenceProvider) { return builder().id(id).peerAddresses(peerAddresses).config(config) .dataPersistenceProvider(dataPersistenceProvider).props(); } @@ -289,7 +288,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, private Function pauseLeaderFunction; private RaftActorSnapshotCohort snapshotCohort; - protected AbstractBuilder(Class actorClass) { + protected AbstractBuilder(final Class actorClass) { this.actorClass = actorClass; } @@ -298,52 +297,52 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, return (T) this; } - public T id(String newId) { + public T id(final String newId) { this.id = newId; return self(); } - public T peerAddresses(Map newPeerAddresses) { + public T peerAddresses(final Map newPeerAddresses) { this.peerAddresses = newPeerAddresses; return self(); } - public T config(ConfigParams newConfig) { + public T config(final ConfigParams newConfig) { this.config = newConfig; return self(); } - public T dataPersistenceProvider(DataPersistenceProvider newDataPersistenceProvider) { + public T dataPersistenceProvider(final DataPersistenceProvider newDataPersistenceProvider) { this.dataPersistenceProvider = newDataPersistenceProvider; return self(); } - public T roleChangeNotifier(ActorRef newRoleChangeNotifier) { + public T roleChangeNotifier(final ActorRef newRoleChangeNotifier) { this.roleChangeNotifier = newRoleChangeNotifier; return self(); } - public T snapshotMessageSupport(RaftActorSnapshotMessageSupport newSnapshotMessageSupport) { + public T snapshotMessageSupport(final RaftActorSnapshotMessageSupport newSnapshotMessageSupport) { this.snapshotMessageSupport = newSnapshotMessageSupport; return self(); } - public T restoreFromSnapshot(Snapshot newRestoreFromSnapshot) { + public T restoreFromSnapshot(final Snapshot newRestoreFromSnapshot) { this.restoreFromSnapshot = newRestoreFromSnapshot; return self(); } - public T persistent(Optional newPersistent) { + public T persistent(final Optional newPersistent) { this.persistent = newPersistent; return self(); } - public T pauseLeaderFunction(Function newPauseLeaderFunction) { + public T pauseLeaderFunction(final Function newPauseLeaderFunction) { this.pauseLeaderFunction = newPauseLeaderFunction; return self(); } - public T snapshotCohort(RaftActorSnapshotCohort newSnapshotCohort) { + public T snapshotCohort(final RaftActorSnapshotCohort newSnapshotCohort) { this.snapshotCohort = newSnapshotCohort; return self(); } @@ -364,7 +363,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, private final List state; - public MockSnapshotState(List state) { + public MockSnapshotState(final List state) { this.state = state; } @@ -381,7 +380,7 @@ public class MockRaftActor extends RaftActor implements RaftActorRecoveryCohort, } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java index 05b1d34a0f..f4f2b9f6a8 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java @@ -13,7 +13,6 @@ import akka.actor.ActorSelection; import akka.actor.ActorSystem; import akka.actor.Props; import akka.japi.Procedure; -import com.google.common.base.Throwables; import com.google.common.io.ByteSource; import java.io.IOException; import java.io.OutputStream; @@ -55,14 +54,14 @@ public class MockRaftActorContext extends RaftActorContextImpl { } @Override - public void update(long newTerm, String newVotedFor) { + public void update(final long newTerm, final String newVotedFor) { this.currentTerm = newTerm; this.votedFor = newVotedFor; // TODO : Write to some persistent state } - @Override public void updateAndPersist(long newTerm, String newVotedFor) { + @Override public void updateAndPersist(final long newTerm, final String newVotedFor) { update(newTerm, newVotedFor); } }; @@ -74,7 +73,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { setReplicatedLog(new MockReplicatedLogBuilder().build()); } - public MockRaftActorContext(String id, ActorSystem system, ActorRef actor) { + public MockRaftActorContext(final String id, final ActorSystem system, final ActorRef actor) { super(actor, null, id, newElectionTerm(), -1, -1, new HashMap<>(), new DefaultConfigParamsImpl(), new NonPersistentDataProvider(), applyState -> actor.tell(applyState, actor), LOG); @@ -95,11 +94,11 @@ public class MockRaftActorContext extends RaftActorContextImpl { setLastApplied(replicatedLog.lastIndex()); } - @Override public ActorRef actorOf(Props props) { + @Override public ActorRef actorOf(final Props props) { return system.actorOf(props); } - @Override public ActorSelection actorSelection(String path) { + @Override public ActorSelection actorSelection(final String path) { return system.actorSelection(path); } @@ -107,7 +106,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { return this.system; } - @Override public ActorSelection getPeerActorSelection(String peerId) { + @Override public ActorSelection getPeerActorSelection(final String peerId) { String peerAddress = getPeerAddress(peerId); if (peerAddress != null) { return actorSelection(peerAddress); @@ -115,7 +114,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { return null; } - public void setPeerAddresses(Map peerAddresses) { + public void setPeerAddresses(final Map peerAddresses) { for (String id: getPeerIds()) { removePeer(id); } @@ -132,23 +131,23 @@ public class MockRaftActorContext extends RaftActorContextImpl { snapshotManager.setSnapshotCohort(new RaftActorSnapshotCohort() { @Override - public State deserializeSnapshot(ByteSource snapshotBytes) throws IOException { + public State deserializeSnapshot(final ByteSource snapshotBytes) throws IOException { return ByteState.of(snapshotBytes.read()); } @Override - public void createSnapshot(ActorRef actorRef, java.util.Optional installSnapshotStream) { + public void createSnapshot(final ActorRef actorRef, final Optional installSnapshotStream) { } @Override - public void applySnapshot(State snapshotState) { + public void applySnapshot(final State snapshotState) { } }); return snapshotManager; } - public void setCreateSnapshotProcedure(Consumer> createSnapshotProcedure) { + public void setCreateSnapshotProcedure(final Consumer> createSnapshotProcedure) { this.createSnapshotProcedure = createSnapshotProcedure; } @@ -157,7 +156,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { return raftPolicy != null ? raftPolicy : super.getRaftPolicy(); } - public void setRaftPolicy(RaftPolicy raftPolicy) { + public void setRaftPolicy(final RaftPolicy raftPolicy) { this.raftPolicy = raftPolicy; } @@ -168,30 +167,32 @@ public class MockRaftActorContext extends RaftActorContextImpl { } @Override - public void captureSnapshotIfReady(ReplicatedLogEntry replicatedLogEntry) { + public void captureSnapshotIfReady(final ReplicatedLogEntry replicatedLogEntry) { } @Override - public boolean shouldCaptureSnapshot(long logIndex) { + public boolean shouldCaptureSnapshot(final long logIndex) { return false; } @Override - public boolean removeFromAndPersist(long index) { + public boolean removeFromAndPersist(final long index) { return removeFrom(index) >= 0; } @Override @SuppressWarnings("checkstyle:IllegalCatch") - public boolean appendAndPersist(ReplicatedLogEntry replicatedLogEntry, Procedure callback, - boolean doAsync) { + public boolean appendAndPersist(final ReplicatedLogEntry replicatedLogEntry, + final Procedure callback, final boolean doAsync) { append(replicatedLogEntry); if (callback != null) { try { callback.apply(replicatedLogEntry); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -207,12 +208,12 @@ public class MockRaftActorContext extends RaftActorContextImpl { public MockPayload() { } - public MockPayload(String data) { + public MockPayload(final String data) { this.value = data; size = value.length(); } - public MockPayload(String data, int size) { + public MockPayload(final String data, final int size) { this(data); this.size = size; } @@ -236,7 +237,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { } @Override - public boolean equals(Object obj) { + public boolean equals(final Object obj) { if (this == obj) { return true; } @@ -261,7 +262,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { public static class MockReplicatedLogBuilder { private final ReplicatedLog mockLog = new SimpleReplicatedLog(); - public MockReplicatedLogBuilder createEntries(int start, int end, int term) { + public MockReplicatedLogBuilder createEntries(final int start, final int end, final int term) { for (int i = start; i < end; i++) { this.mockLog.append(new SimpleReplicatedLogEntry(i, term, new MockRaftActorContext.MockPayload(Integer.toString(i)))); @@ -269,7 +270,7 @@ public class MockRaftActorContext extends RaftActorContextImpl { return this; } - public MockReplicatedLogBuilder addEntry(int index, int term, MockPayload payload) { + public MockReplicatedLogBuilder addEntry(final int index, final int term, final MockPayload payload) { this.mockLog.append(new SimpleReplicatedLogEntry(index, term, payload)); return this; } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderElectionScenarioTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderElectionScenarioTest.java index 8c7c9cb7c4..1d4fde1a44 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderElectionScenarioTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractLeaderElectionScenarioTest.java @@ -22,12 +22,12 @@ import akka.pattern.Patterns; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import akka.util.Timeout; -import com.google.common.base.Throwables; import com.google.common.util.concurrent.Uninterruptibles; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.Before; import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl; @@ -127,22 +127,22 @@ public class AbstractLeaderElectionScenarioTest { Uninterruptibles.awaitUninterruptibly(behaviorStateChangeLatch, 5, TimeUnit.SECONDS)); } - void expectMessageClass(Class expClass, int expCount) { + void expectMessageClass(final Class expClass, final int expCount) { messagesReceivedLatches.put(expClass, new CountDownLatch(expCount)); } - void waitForExpectedMessages(Class expClass) { + void waitForExpectedMessages(final Class expClass) { CountDownLatch latch = messagesReceivedLatches.get(expClass); assertNotNull("No messages received for " + expClass, latch); assertTrue("Missing messages of type " + expClass, Uninterruptibles.awaitUninterruptibly(latch, 5, TimeUnit.SECONDS)); } - void dropMessagesToBehavior(Class msgClass) { + void dropMessagesToBehavior(final Class msgClass) { dropMessagesToBehavior(msgClass, 1); } - void dropMessagesToBehavior(Class msgClass, int expCount) { + void dropMessagesToBehavior(final Class msgClass, final int expCount) { expectMessageClass(msgClass, expCount); dropMessagesToBehavior.put(msgClass, Boolean.TRUE); } @@ -159,19 +159,19 @@ public class AbstractLeaderElectionScenarioTest { super.clear(); } - void forwardCapturedMessageToBehavior(Class msgClass, ActorRef sender) throws Exception { + void forwardCapturedMessageToBehavior(final Class msgClass, final ActorRef sender) { Object message = getFirstMatching(getSelf(), msgClass); assertNotNull("Message of type " + msgClass + " not received", message); getSelf().tell(message, sender); } - void forwardCapturedMessagesToBehavior(Class msgClass, ActorRef sender) throws Exception { + void forwardCapturedMessagesToBehavior(final Class msgClass, final ActorRef sender) { for (Object m: getAllMatching(getSelf(), msgClass)) { getSelf().tell(m, sender); } } - T getCapturedMessage(Class msgClass) throws Exception { + T getCapturedMessage(final Class msgClass) { T message = getFirstMatching(getSelf(), msgClass); assertNotNull("Message of type " + msgClass + " not received", message); return message; @@ -196,7 +196,7 @@ public class AbstractLeaderElectionScenarioTest { RaftActorBehavior behavior; MockRaftActorContext context; - SetBehavior(RaftActorBehavior behavior, MockRaftActorContext context) { + SetBehavior(final RaftActorBehavior behavior, final MockRaftActorContext context) { this.behavior = behavior; this.context = context; } @@ -239,8 +239,8 @@ public class AbstractLeaderElectionScenarioTest { return configParams; } - MockRaftActorContext newRaftActorContext(String id, ActorRef actor, - Map peerAddresses) { + MockRaftActorContext newRaftActorContext(final String id, final ActorRef actor, + final Map peerAddresses) { MockRaftActorContext context = new MockRaftActorContext(id, system, actor); context.setPeerAddresses(peerAddresses); context.getTermInformation().updateAndPersist(1, ""); @@ -248,18 +248,21 @@ public class AbstractLeaderElectionScenarioTest { } @SuppressWarnings("checkstyle:IllegalCatch") - void verifyBehaviorState(String name, MemberActor actor, RaftState expState) { + void verifyBehaviorState(final String name, final MemberActor actor, final RaftState expState) { + RaftState actualState; try { - RaftState actualState = (RaftState) Await.result(Patterns.ask(actor.self(), GetBehaviorState.INSTANCE, - Timeout.apply(5, TimeUnit.SECONDS)), Duration.apply(5, TimeUnit.SECONDS)); - assertEquals(name + " behavior state", expState, actualState); + actualState = (RaftState) Await.result(Patterns.ask(actor.self(), GetBehaviorState.INSTANCE, + Timeout.apply(5, TimeUnit.SECONDS)), Duration.apply(5, TimeUnit.SECONDS)); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - Throwables.propagate(e); + throw new RuntimeException(e); } + assertEquals(name + " behavior state", expState, actualState); } - void initializeLeaderBehavior(MemberActor actor, MockRaftActorContext context, int numActiveFollowers) - throws Exception { + void initializeLeaderBehavior(final MemberActor actor, final MockRaftActorContext context, + final int numActiveFollowers) { // Leader sends immediate heartbeats - we don't care about it so ignore it. // Sometimes the initial AppendEntries messages go to dead letters, probably b/c the follower actors // haven't been fully created/initialized by akka. So we try up to 3 times to create the Leader as @@ -294,14 +297,14 @@ public class AbstractLeaderElectionScenarioTest { } - TestActorRef newMemberActor(String name) throws Exception { + TestActorRef newMemberActor(final String name) throws TimeoutException, InterruptedException { TestActorRef actor = factory.createTestActor(MemberActor.props() .withDispatcher(Dispatchers.DefaultDispatcherId()), name); MessageCollectorActor.waitUntilReady(actor); return actor; } - void sendHeartbeat(TestActorRef leaderActor) { + void sendHeartbeat(final TestActorRef leaderActor) { Uninterruptibles.sleepUninterruptibly(HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS); leaderActor.tell(SendImmediateHeartBeat.INSTANCE, ActorRef.noSender()); } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehaviorTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehaviorTest.java index 03950dbd4b..94563da318 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehaviorTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehaviorTest.java @@ -55,7 +55,7 @@ public abstract class AbstractRaftActorBehaviorTest RaftActorBehavior behavior; @After - public void tearDown() throws Exception { + public void tearDown() { if (behavior != null) { behavior.close(); } @@ -71,7 +71,7 @@ public abstract class AbstractRaftActorBehaviorTest * term the RaftActor gets into the Follower state. */ @Test - public void testHandleRaftRPCWithNewerTerm() throws Exception { + public void testHandleRaftRPCWithNewerTerm() { MockRaftActorContext actorContext = createActorContext(); assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, behaviorActor, @@ -94,7 +94,7 @@ public abstract class AbstractRaftActorBehaviorTest * change it's state and it responds back with a failure. */ @Test - public void testHandleAppendEntriesSenderTermLessThanReceiverTerm() throws Exception { + public void testHandleAppendEntriesSenderTermLessThanReceiverTerm() { MockRaftActorContext context = createActorContext(); short payloadVersion = 5; context.setPayloadVersion(payloadVersion); @@ -124,7 +124,7 @@ public abstract class AbstractRaftActorBehaviorTest @Test - public void testHandleAppendEntriesAddSameEntryToLog() throws Exception { + public void testHandleAppendEntriesAddSameEntryToLog() { MockRaftActorContext context = createActorContext(); context.getTermInformation().update(2, "test"); @@ -156,8 +156,7 @@ public abstract class AbstractRaftActorBehaviorTest handleAppendEntriesAddSameEntryToLogReply(behaviorActor); } - protected void handleAppendEntriesAddSameEntryToLogReply(TestActorRef replyActor) - throws Exception { + protected void handleAppendEntriesAddSameEntryToLogReply(final TestActorRef replyActor) { AppendEntriesReply reply = MessageCollectorActor.getFirstMatching(replyActor, AppendEntriesReply.class); Assert.assertNull("Expected no AppendEntriesReply", reply); } @@ -279,8 +278,8 @@ public abstract class AbstractRaftActorBehaviorTest } - protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(MockRaftActorContext actorContext, - ActorRef actorRef, RaftRPC rpc) throws Exception { + protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext, + final ActorRef actorRef, final RaftRPC rpc) { Payload payload = new MockRaftActorContext.MockPayload(""); setLastLogEntry(actorContext, 1, 0, payload); @@ -297,12 +296,12 @@ public abstract class AbstractRaftActorBehaviorTest } protected MockRaftActorContext.SimpleReplicatedLog setLastLogEntry( - MockRaftActorContext actorContext, long term, long index, Payload data) { + final MockRaftActorContext actorContext, final long term, final long index, final Payload data) { return setLastLogEntry(actorContext, new SimpleReplicatedLogEntry(index, term, data)); } - protected MockRaftActorContext.SimpleReplicatedLog setLastLogEntry(MockRaftActorContext actorContext, - ReplicatedLogEntry logEntry) { + protected MockRaftActorContext.SimpleReplicatedLog setLastLogEntry(final MockRaftActorContext actorContext, + final ReplicatedLogEntry logEntry) { MockRaftActorContext.SimpleReplicatedLog log = new MockRaftActorContext.SimpleReplicatedLog(); log.append(logEntry); actorContext.setReplicatedLog(log); @@ -312,7 +311,7 @@ public abstract class AbstractRaftActorBehaviorTest protected abstract T createBehavior(RaftActorContext actorContext); - protected final T createBehavior(MockRaftActorContext actorContext) { + protected final T createBehavior(final MockRaftActorContext actorContext) { T ret = createBehavior((RaftActorContext)actorContext); actorContext.setCurrentBehavior(ret); return ret; @@ -326,7 +325,7 @@ public abstract class AbstractRaftActorBehaviorTest return new MockRaftActorContext(); } - protected MockRaftActorContext createActorContext(ActorRef actor) { + protected MockRaftActorContext createActorContext(final ActorRef actor) { return new MockRaftActorContext("test", getSystem(), actor); } @@ -346,7 +345,7 @@ public abstract class AbstractRaftActorBehaviorTest return new RequestVoteReply(100, false); } - protected ByteString toByteString(Map state) { + protected ByteString toByteString(final Map state) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(state); @@ -356,7 +355,7 @@ public abstract class AbstractRaftActorBehaviorTest } } - protected void logStart(String name) { + protected void logStart(final String name) { LoggerFactory.getLogger(getClass()).info("Starting " + name); } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java index 4124a94d5f..87fae0fe24 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/CandidateTest.java @@ -61,7 +61,7 @@ public class CandidateTest extends AbstractRaftActorBehaviorTest { @Override @After - public void tearDown() throws Exception { + public void tearDown() { if (candidate != null) { candidate.close(); } @@ -307,7 +307,7 @@ public class CandidateTest extends AbstractRaftActorBehaviorTest { @Test @Override - public void testHandleAppendEntriesAddSameEntryToLog() throws Exception { + public void testHandleAppendEntriesAddSameEntryToLog() { MockRaftActorContext context = createActorContext(); context.getTermInformation().update(2, "test"); @@ -347,7 +347,8 @@ public class CandidateTest extends AbstractRaftActorBehaviorTest { return new Candidate(actorContext); } - @Override protected MockRaftActorContext createActorContext() { + @Override + protected MockRaftActorContext createActorContext() { return new MockRaftActorContext("candidate", getSystem(), candidateActor); } @@ -366,7 +367,7 @@ public class CandidateTest extends AbstractRaftActorBehaviorTest { @Override protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext, - final ActorRef actorRef, final RaftRPC rpc) throws Exception { + final ActorRef actorRef, final RaftRPC rpc) { super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc); if (rpc instanceof RequestVote) { assertEquals("New votedFor", ((RequestVote)rpc).getCandidateId(), diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/DelayedMessagesElectionScenarioTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/DelayedMessagesElectionScenarioTest.java index 825a55b921..d481e6f149 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/DelayedMessagesElectionScenarioTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/DelayedMessagesElectionScenarioTest.java @@ -27,7 +27,7 @@ import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply; public class DelayedMessagesElectionScenarioTest extends AbstractLeaderElectionScenarioTest { @Test - public void runTest() throws Exception { + public void runTest() { testLog.info("DelayedMessagesElectionScenarioTest starting"); setupInitialMemberBehaviors(); @@ -43,7 +43,7 @@ public class DelayedMessagesElectionScenarioTest extends AbstractLeaderElectionS testLog.info("DelayedMessagesElectionScenarioTest ending"); } - private void forwardDelayedRequestVoteReplyFromOriginalFollowerMember3ToMember2() throws Exception { + private void forwardDelayedRequestVoteReplyFromOriginalFollowerMember3ToMember2() { testLog.info("forwardDelayedRequestVoteReplyFromOriginalFollowerMember3ToMember2 starting"); // Now forward the original delayed RequestVoteReply from member 3 to member 2 that granted @@ -65,7 +65,7 @@ public class DelayedMessagesElectionScenarioTest extends AbstractLeaderElectionS testLog.info("forwardDelayedRequestVoteReplyFromOriginalFollowerMember3ToMember2 ending"); } - private void sendElectionTimeoutToFollowerMember3() throws Exception { + private void sendElectionTimeoutToFollowerMember3() { testLog.info("sendElectionTimeoutToFollowerMember3 starting"); // Send ElectionTimeout to member 3 to simulate missing heartbeat from a Leader. member 3 @@ -104,7 +104,7 @@ public class DelayedMessagesElectionScenarioTest extends AbstractLeaderElectionS testLog.info("sendElectionTimeoutToFollowerMember3 ending"); } - private void forwardDelayedRequestVotesToLeaderMember1AndFollowerMember3() throws Exception { + private void forwardDelayedRequestVotesToLeaderMember1AndFollowerMember3() { testLog.info("forwardDelayedRequestVotesToLeaderMember1AndFollowerMember3 starting"); // At this point member 1 and 3 actors have captured the RequestVote messages. First @@ -170,7 +170,7 @@ public class DelayedMessagesElectionScenarioTest extends AbstractLeaderElectionS testLog.info("sendInitialElectionTimeoutToFollowerMember2 ending"); } - private void setupInitialMemberBehaviors() throws Exception { + private void setupInitialMemberBehaviors() { testLog.info("setupInitialMemberBehaviors starting"); // Create member 2's behavior initially as Follower @@ -215,6 +215,5 @@ public class DelayedMessagesElectionScenarioTest extends AbstractLeaderElectionS member3Actor.clear(); testLog.info("setupInitialMemberBehaviors ending"); - } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java index 37a8b6b906..3e6c7590c0 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/FollowerTest.java @@ -26,7 +26,6 @@ import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; -import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.io.ByteSource; @@ -91,7 +90,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { @Override @After - public void tearDown() throws Exception { + public void tearDown() { if (follower != null) { follower.close(); } @@ -100,7 +99,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Override - protected Follower createBehavior(RaftActorContext actorContext) { + protected Follower createBehavior(final RaftActorContext actorContext) { return spy(new Follower(actorContext)); } @@ -110,7 +109,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Override - protected MockRaftActorContext createActorContext(ActorRef actorRef) { + protected MockRaftActorContext createActorContext(final ActorRef actorRef) { MockRaftActorContext context = new MockRaftActorContext("follower", getSystem(), actorRef); context.setPayloadVersion(payloadVersion); return context; @@ -209,7 +208,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { @Test - public void testHandleFirstAppendEntries() throws Exception { + public void testHandleFirstAppendEntries() { logStart("testHandleFirstAppendEntries"); MockRaftActorContext context = createActorContext(); @@ -237,7 +236,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testHandleFirstAppendEntriesWithPrevIndexMinusOne() throws Exception { + public void testHandleFirstAppendEntriesWithPrevIndexMinusOne() { logStart("testHandleFirstAppendEntries"); MockRaftActorContext context = createActorContext(); @@ -260,8 +259,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testHandleFirstAppendEntriesWithPrevIndexMinusOneAndReplicatedToAllIndexPresentInLog() - throws Exception { + public void testHandleFirstAppendEntriesWithPrevIndexMinusOneAndReplicatedToAllIndexPresentInLog() { logStart("testHandleFirstAppendEntries"); MockRaftActorContext context = createActorContext(); @@ -287,8 +285,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testHandleFirstAppendEntriesWithPrevIndexMinusOneAndReplicatedToAllIndexPresentInSnapshot() - throws Exception { + public void testHandleFirstAppendEntriesWithPrevIndexMinusOneAndReplicatedToAllIndexPresentInSnapshot() { logStart("testHandleFirstAppendEntries"); MockRaftActorContext context = createActorContext(); @@ -313,8 +310,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testFirstAppendEntriesWithNoPrevIndexAndReplicatedToAllPresentInSnapshotButCalculatedPrevEntryMissing() - throws Exception { + public void testFirstAppendEntriesWithNoPrevIndexAndReplToAllPresentInSnapshotButCalculatedPrevEntryMissing() { logStart( "testFirstAppendEntriesWithNoPrevIndexAndReplicatedToAllPresentInSnapshotButCalculatedPrevEntryMissing"); @@ -340,7 +336,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testHandleSyncUpAppendEntries() throws Exception { + public void testHandleSyncUpAppendEntries() { logStart("testHandleSyncUpAppendEntries"); MockRaftActorContext context = createActorContext(); @@ -364,11 +360,9 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { context.setLastApplied(101); context.setCommitIndex(101); - setLastLogEntry(context, 1, 101, - new MockRaftActorContext.MockPayload("")); + setLastLogEntry(context, 1, 101, new MockRaftActorContext.MockPayload("")); - entries = Arrays.asList( - newReplicatedLogEntry(2, 101, "foo")); + entries = Arrays.asList(newReplicatedLogEntry(2, 101, "foo")); // The new commitIndex is 101 appendEntries = new AppendEntries(2, "leader-1", 101, 1, entries, 102, 101, (short)0); @@ -387,11 +381,10 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { syncStatus = MessageCollectorActor.getFirstMatching(followerActor, FollowerInitialSyncUpStatus.class); assertNull(syncStatus); - } @Test - public void testHandleAppendEntriesLeaderChangedBeforeSyncUpComplete() throws Exception { + public void testHandleAppendEntriesLeaderChangedBeforeSyncUpComplete() { logStart("testHandleAppendEntriesLeaderChangedBeforeSyncUpComplete"); MockRaftActorContext context = createActorContext(); @@ -428,12 +421,10 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { // We get a new message saying initial status is not done assertFalse(syncStatus.isInitialSyncDone()); - } - @Test - public void testHandleAppendEntriesLeaderChangedAfterSyncUpComplete() throws Exception { + public void testHandleAppendEntriesLeaderChangedAfterSyncUpComplete() { logStart("testHandleAppendEntriesLeaderChangedAfterSyncUpComplete"); MockRaftActorContext context = createActorContext(); @@ -489,10 +480,8 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { // We get a new message saying initial status is not done assertFalse(syncStatus.isInitialSyncDone()); - } - /** * This test verifies that when an AppendEntries RPC is received by a RaftActor * with a commitIndex that is greater than what has been applied to the @@ -500,7 +489,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { * sets it current applied state to the commitIndex of the sender. */ @Test - public void testHandleAppendEntriesWithNewerCommitIndex() throws Exception { + public void testHandleAppendEntriesWithNewerCommitIndex() { logStart("testHandleAppendEntriesWithNewerCommitIndex"); MockRaftActorContext context = createActorContext(); @@ -806,7 +795,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { * the follower its applied correctly. */ @Test - public void testHandleInstallSnapshot() throws Exception { + public void testHandleInstallSnapshot() { logStart("testHandleInstallSnapshot"); MockRaftActorContext context = createActorContext(); @@ -864,13 +853,12 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { assertNull("Expected null SnapshotTracker", follower.getSnapshotTracker()); } - /** * Verify that when an AppendEntries is sent to a follower during a snapshot install * the Follower short-circuits the processing of the AppendEntries message. */ @Test - public void testReceivingAppendEntriesDuringInstallSnapshot() throws Exception { + public void testReceivingAppendEntriesDuringInstallSnapshot() { logStart("testReceivingAppendEntriesDuringInstallSnapshot"); MockRaftActorContext context = createActorContext(); @@ -913,7 +901,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testReceivingAppendEntriesDuringInstallSnapshotFromDifferentLeader() throws Exception { + public void testReceivingAppendEntriesDuringInstallSnapshotFromDifferentLeader() { logStart("testReceivingAppendEntriesDuringInstallSnapshotFromDifferentLeader"); MockRaftActorContext context = createActorContext(); @@ -956,7 +944,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testInitialSyncUpWithHandleInstallSnapshotFollowedByAppendEntries() throws Exception { + public void testInitialSyncUpWithHandleInstallSnapshotFollowedByAppendEntries() { logStart("testInitialSyncUpWithHandleInstallSnapshot"); MockRaftActorContext context = createActorContext(); @@ -1009,7 +997,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testHandleOutOfSequenceInstallSnapshot() throws Exception { + public void testHandleOutOfSequenceInstallSnapshot() { logStart("testHandleOutOfSequenceInstallSnapshot"); MockRaftActorContext context = createActorContext(); @@ -1111,7 +1099,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testCaptureSnapshotOnLastEntryInAppendEntries() throws Exception { + public void testCaptureSnapshotOnLastEntryInAppendEntries() { String id = "testCaptureSnapshotOnLastEntryInAppendEntries"; logStart(id); @@ -1166,7 +1154,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testCaptureSnapshotOnMiddleEntryInAppendEntries() throws Exception { + public void testCaptureSnapshotOnMiddleEntryInAppendEntries() { String id = "testCaptureSnapshotOnMiddleEntryInAppendEntries"; logStart(id); @@ -1241,7 +1229,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Test - public void testCaptureSnapshotOnAppendEntriesWithUnapplied() throws Exception { + public void testCaptureSnapshotOnAppendEntriesWithUnapplied() { String id = "testCaptureSnapshotOnAppendEntriesWithUnapplied"; logStart(id); @@ -1299,31 +1287,35 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @SuppressWarnings("checkstyle:IllegalCatch") - private RaftActorSnapshotCohort newRaftActorSnapshotCohort(final AtomicReference followerRaftActor) { + private static RaftActorSnapshotCohort newRaftActorSnapshotCohort( + final AtomicReference followerRaftActor) { RaftActorSnapshotCohort snapshotCohort = new RaftActorSnapshotCohort() { @Override - public void createSnapshot(ActorRef actorRef, java.util.Optional installSnapshotStream) { + public void createSnapshot(final ActorRef actorRef, + final java.util.Optional installSnapshotStream) { try { actorRef.tell(new CaptureSnapshotReply(new MockSnapshotState(followerRaftActor.get().getState()), installSnapshotStream), actorRef); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } @Override - public void applySnapshot(State snapshotState) { + public void applySnapshot(final State snapshotState) { } @Override - public State deserializeSnapshot(ByteSource snapshotBytes) { + public State deserializeSnapshot(final ByteSource snapshotBytes) { throw new UnsupportedOperationException(); } }; return snapshotCohort; } - public byte[] getNextChunk(ByteString bs, int offset, int chunkSize) { + public byte[] getNextChunk(final ByteString bs, final int offset, final int chunkSize) { int snapshotLength = bs.size(); int start = offset; int size = chunkSize; @@ -1340,14 +1332,14 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { return nextChunk; } - private void expectAndVerifyAppendEntriesReply(int expTerm, boolean expSuccess, - String expFollowerId, long expLogLastTerm, long expLogLastIndex) { + private void expectAndVerifyAppendEntriesReply(final int expTerm, final boolean expSuccess, + final String expFollowerId, final long expLogLastTerm, final long expLogLastIndex) { expectAndVerifyAppendEntriesReply(expTerm, expSuccess, expFollowerId, expLogLastTerm, expLogLastIndex, false); } - private void expectAndVerifyAppendEntriesReply(int expTerm, boolean expSuccess, - String expFollowerId, long expLogLastTerm, long expLogLastIndex, - boolean expForceInstallSnapshot) { + private void expectAndVerifyAppendEntriesReply(final int expTerm, final boolean expSuccess, + final String expFollowerId, final long expLogLastTerm, final long expLogLastIndex, + final boolean expForceInstallSnapshot) { AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(leaderActor, AppendEntriesReply.class); @@ -1362,7 +1354,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } - private static ReplicatedLogEntry newReplicatedLogEntry(long term, long index, String data) { + private static ReplicatedLogEntry newReplicatedLogEntry(final long term, final long index, final String data) { return new SimpleReplicatedLogEntry(index, term, new MockRaftActorContext.MockPayload(data)); } @@ -1377,8 +1369,8 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Override - protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(MockRaftActorContext actorContext, - ActorRef actorRef, RaftRPC rpc) throws Exception { + protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext, + final ActorRef actorRef, final RaftRPC rpc) { super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc); String expVotedFor = rpc instanceof RequestVote ? ((RequestVote)rpc).getCandidateId() : null; @@ -1386,8 +1378,7 @@ public class FollowerTest extends AbstractRaftActorBehaviorTest { } @Override - protected void handleAppendEntriesAddSameEntryToLogReply(final TestActorRef replyActor) - throws Exception { + protected void handleAppendEntriesAddSameEntryToLogReply(final TestActorRef replyActor) { AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(replyActor, AppendEntriesReply.class); assertEquals("isSuccess", true, reply.isSuccess()); } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java index 417e1661ee..dae7c6c0d2 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/IsolatedLeaderTest.java @@ -35,7 +35,7 @@ public class IsolatedLeaderTest extends AbstractLeaderTest { @Override @After - public void tearDown() throws Exception { + public void tearDown() { if (isolatedLeader != null) { isolatedLeader.close(); } @@ -44,7 +44,7 @@ public class IsolatedLeaderTest extends AbstractLeaderTest { } @Override - protected IsolatedLeader createBehavior(RaftActorContext actorContext) { + protected IsolatedLeader createBehavior(final RaftActorContext actorContext) { return new IsolatedLeader(actorContext); } @@ -54,7 +54,7 @@ public class IsolatedLeaderTest extends AbstractLeaderTest { } @Override - protected MockRaftActorContext createActorContext(ActorRef actor) { + protected MockRaftActorContext createActorContext(final ActorRef actor) { DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl(); configParams.setElectionTimeoutFactor(100000); MockRaftActorContext context = new MockRaftActorContext("isolated-leader", getSystem(), actor); diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java index 930c1968ac..ae58652b20 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/LeaderTest.java @@ -95,7 +95,7 @@ public class LeaderTest extends AbstractLeaderTest { @Override @After - public void tearDown() throws Exception { + public void tearDown() { if (leader != null) { leader.close(); } @@ -159,7 +159,7 @@ public class LeaderTest extends AbstractLeaderTest { } - private RaftActorBehavior sendReplicate(MockRaftActorContext actorContext, long index) { + private RaftActorBehavior sendReplicate(final MockRaftActorContext actorContext, final long index) { return sendReplicate(actorContext, 1, index); } @@ -1240,11 +1240,11 @@ public class LeaderTest extends AbstractLeaderTest { } @Override - protected MockRaftActorContext createActorContext(ActorRef actorRef) { + protected MockRaftActorContext createActorContext(final ActorRef actorRef) { return createActorContext(LEADER_ID, actorRef); } - private MockRaftActorContext createActorContext(String id, ActorRef actorRef) { + private MockRaftActorContext createActorContext(final String id, final ActorRef actorRef) { DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl(); configParams.setHeartBeatInterval(new FiniteDuration(50, TimeUnit.MILLISECONDS)); configParams.setElectionTimeoutFactor(100000); @@ -1895,7 +1895,7 @@ public class LeaderTest extends AbstractLeaderTest { assertTrue("Expected Leader", newBehavior instanceof Leader); } - private RaftActorBehavior setupIsolatedLeaderCheckTestWithTwoFollowers(RaftPolicy raftPolicy) { + private RaftActorBehavior setupIsolatedLeaderCheckTestWithTwoFollowers(final RaftPolicy raftPolicy) { ActorRef followerActor1 = getSystem().actorOf(MessageCollectorActor.props(), "follower-1"); ActorRef followerActor2 = getSystem().actorOf(MessageCollectorActor.props(), "follower-2"); @@ -2377,8 +2377,8 @@ public class LeaderTest extends AbstractLeaderTest { } @Override - protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(MockRaftActorContext actorContext, - ActorRef actorRef, RaftRPC rpc) throws Exception { + protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(final MockRaftActorContext actorContext, + final ActorRef actorRef, final RaftRPC rpc) { super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc); assertEquals("New votedFor", null, actorContext.getTermInformation().getVotedFor()); } @@ -2388,7 +2388,7 @@ public class LeaderTest extends AbstractLeaderTest { private final long electionTimeOutIntervalMillis; private final int snapshotChunkSize; - MockConfigParamsImpl(long electionTimeOutIntervalMillis, int snapshotChunkSize) { + MockConfigParamsImpl(final long electionTimeOutIntervalMillis, final int snapshotChunkSize) { super(); this.electionTimeOutIntervalMillis = electionTimeOutIntervalMillis; this.snapshotChunkSize = snapshotChunkSize; diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedCandidateOnStartupElectionScenarioTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedCandidateOnStartupElectionScenarioTest.java index 3f5ca17d7a..7b8529a0b1 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedCandidateOnStartupElectionScenarioTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedCandidateOnStartupElectionScenarioTest.java @@ -33,7 +33,7 @@ public class PartitionedCandidateOnStartupElectionScenarioTest extends AbstractL private long candidateElectionTerm; @Test - public void runTest() throws Exception { + public void runTest() { testLog.info("PartitionedCandidateOnStartupElectionScenarioTest starting"); setupInitialMember1AndMember2Behaviors(); @@ -47,7 +47,7 @@ public class PartitionedCandidateOnStartupElectionScenarioTest extends AbstractL testLog.info("PartitionedCandidateOnStartupElectionScenarioTest ending"); } - private void sendElectionTimeoutToFollowerMember1() throws Exception { + private void sendElectionTimeoutToFollowerMember1() { testLog.info("sendElectionTimeoutToFollowerMember1 starting"); // At this point we have no leader. Candidate member 3 would continue to start new elections @@ -96,7 +96,7 @@ public class PartitionedCandidateOnStartupElectionScenarioTest extends AbstractL testLog.info("sendElectionTimeoutToFollowerMember1 ending"); } - private void resolvePartitionAndSendElectionTimeoutsToCandidateMember3() throws Exception { + private void resolvePartitionAndSendElectionTimeoutsToCandidateMember3() { testLog.info("resolvePartitionAndSendElectionTimeoutsToCandidateMember3 starting"); // Now send a couple more ElectionTimeouts to Candidate member 3 with the partition resolved. @@ -208,7 +208,7 @@ public class PartitionedCandidateOnStartupElectionScenarioTest extends AbstractL testLog.info("setupPartitionedCandidateMember3AndSendElectionTimeouts ending"); } - private void setupInitialMember1AndMember2Behaviors() throws Exception { + private void setupInitialMember1AndMember2Behaviors() { testLog.info("setupInitialMember1AndMember2Behaviors starting"); // Initialize the ReplicatedLog and election term info for member 1 and 2. The current term @@ -257,6 +257,5 @@ public class PartitionedCandidateOnStartupElectionScenarioTest extends AbstractL member3Actor.clear(); testLog.info("setupInitialMember1AndMember2Behaviors ending"); - } } diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedLeadersElectionScenarioTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedLeadersElectionScenarioTest.java index cf02a1f23e..38740355be 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedLeadersElectionScenarioTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/PartitionedLeadersElectionScenarioTest.java @@ -105,7 +105,7 @@ public class PartitionedLeadersElectionScenarioTest extends AbstractLeaderElecti testLog.info("resolvePartitionedLeadersWithLeaderMember2SendingHeartbeatFirst ending"); } - private void resolvePartitionedLeadersWithLeaderMember3SendingHeartbeatFirst() throws Exception { + private void resolvePartitionedLeadersWithLeaderMember3SendingHeartbeatFirst() { testLog.info("resolvePartitionedLeadersWithLeaderMember3SendingHeartbeatFirst starting"); // Re-establish connectivity between member 2 and 3, ie stop dropping messages between @@ -141,7 +141,7 @@ public class PartitionedLeadersElectionScenarioTest extends AbstractLeaderElecti testLog.info("resolvePartitionedLeadersWithLeaderMember3SendingHeartbeatFirst ending"); } - private void sendElectionTimeoutToNowCandidateMember2() throws Exception { + private void sendElectionTimeoutToNowCandidateMember2() { testLog.info("sendElectionTimeoutToNowCandidateMember2 starting"); // member 2, now a candidate, is partitioned from the Leader (now member 3) and hasn't received any @@ -189,7 +189,7 @@ public class PartitionedLeadersElectionScenarioTest extends AbstractLeaderElecti testLog.info("sendElectionTimeoutToNowCandidateMember2 ending"); } - private void sendInitialElectionTimeoutToFollowerMember3() throws Exception { + private void sendInitialElectionTimeoutToFollowerMember3() { testLog.info("sendInitialElectionTimeoutToFollowerMember3 starting"); // Send ElectionTimeout to member 3 to simulate no heartbeat from a Leader (originally member 1). @@ -238,7 +238,7 @@ public class PartitionedLeadersElectionScenarioTest extends AbstractLeaderElecti testLog.info("sendInitialElectionTimeoutToFollowerMember3 ending"); } - private void sendInitialElectionTimeoutToFollowerMember2() { + private void sendInitialElectionTimeoutToFollowerMember2() throws Exception { testLog.info("sendInitialElectionTimeoutToFollowerMember2 starting"); // Send ElectionTimeout to member 2 to simulate no heartbeat from the Leader (member 1). diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/SnapshotTrackerTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/SnapshotTrackerTest.java index 658e2ca53f..2ef2c26d8f 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/SnapshotTrackerTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/behaviors/SnapshotTrackerTest.java @@ -119,7 +119,7 @@ public class SnapshotTrackerTest { } } - private byte[] getNextChunk(ByteString bs, int offset, int size) { + private static byte[] getNextChunk(final ByteString bs, final int offset, int size) { int snapshotLength = bs.size(); int start = offset; if (size > snapshotLength) { diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/persisted/SnapshotTest.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/persisted/SnapshotTest.java index 19f0ec132b..9f1f924252 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/persisted/SnapshotTest.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/persisted/SnapshotTest.java @@ -25,13 +25,13 @@ import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry; public class SnapshotTest { @Test - public void testSerialization() throws Exception { + public void testSerialization() { testSerialization(new byte[]{1, 2, 3, 4, 5, 6, 7}, Arrays.asList( new SimpleReplicatedLogEntry(6, 2, new MockPayload("payload")))); testSerialization(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, Collections.emptyList()); } - private void testSerialization(byte[] state, List unapplied) throws Exception { + private static void testSerialization(final byte[] state, final List unapplied) { long lastIndex = 6; long lastTerm = 2; long lastAppliedIndex = 5; diff --git a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java index 68d6b619cd..32077a2719 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java +++ b/opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/utils/MessageCollectorActor.java @@ -17,7 +17,6 @@ import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; import com.google.common.util.concurrent.Uninterruptibles; import java.util.ArrayList; import java.util.Collections; @@ -37,7 +36,7 @@ public class MessageCollectorActor extends UntypedActor { private final List messages = new ArrayList<>(); - @Override public void onReceive(Object message) throws Exception { + @Override public void onReceive(final Object message) throws Exception { if (ARE_YOU_READY.equals(message)) { getSender().tell("yes", getSelf()); } else if (GET_ALL_MESSAGES.equals(message)) { @@ -53,16 +52,22 @@ public class MessageCollectorActor extends UntypedActor { messages.clear(); } - @SuppressWarnings("unchecked") - private static List getAllMessages(ActorRef actor) throws Exception { + @SuppressWarnings({"unchecked", "checkstyle:illegalCatch"}) + private static List getAllMessages(final ActorRef actor) { FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS); Timeout operationTimeout = new Timeout(operationDuration); Future future = Patterns.ask(actor, GET_ALL_MESSAGES, operationTimeout); - return (List) Await.result(future, operationDuration); + try { + return (List) Await.result(future, operationDuration); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } } - public static void clearMessages(ActorRef actor) { + public static void clearMessages(final ActorRef actor) { actor.tell(CLEAR_MESSAGES, ActorRef.noSender()); } @@ -73,7 +78,7 @@ public class MessageCollectorActor extends UntypedActor { * @param clazz the class to match * @return the first matching message */ - public static T getFirstMatching(ActorRef actor, Class clazz) throws Exception { + public static T getFirstMatching(final ActorRef actor, final Class clazz) { List allMessages = getAllMessages(actor); for (Object message : allMessages) { @@ -86,13 +91,13 @@ public class MessageCollectorActor extends UntypedActor { } @SuppressWarnings("checkstyle:IllegalCatch") - public static List expectMatching(ActorRef actor, Class clazz, int count) { + public static List expectMatching(final ActorRef actor, final Class clazz, final int count) { return expectMatching(actor, clazz, count, msg -> true); } @SuppressWarnings("checkstyle:IllegalCatch") - public static List expectMatching(ActorRef actor, Class clazz, int count, - Predicate matcher) { + public static List expectMatching(final ActorRef actor, final Class clazz, final int count, + final Predicate matcher) { int timeout = 5000; Exception lastEx = null; List messages = Collections.emptyList(); @@ -116,12 +121,12 @@ public class MessageCollectorActor extends UntypedActor { clazz, messages.size(), messages), lastEx); } - public static T expectFirstMatching(ActorRef actor, Class clazz) { + public static T expectFirstMatching(final ActorRef actor, final Class clazz) { return expectFirstMatching(actor, clazz, 5000); } @SuppressWarnings("checkstyle:IllegalCatch") - public static T expectFirstMatching(ActorRef actor, Class clazz, long timeout) { + public static T expectFirstMatching(final ActorRef actor, final Class clazz, final long timeout) { Exception lastEx = null; int count = (int) (timeout / 50); for (int i = 0; i < count; i++) { @@ -143,7 +148,7 @@ public class MessageCollectorActor extends UntypedActor { } @SuppressWarnings("checkstyle:IllegalCatch") - public static T expectFirstMatching(ActorRef actor, Class clazz, Predicate matcher) { + public static T expectFirstMatching(final ActorRef actor, final Class clazz, final Predicate matcher) { int timeout = 5000; Exception lastEx = null; T lastMessage = null; @@ -170,12 +175,12 @@ public class MessageCollectorActor extends UntypedActor { clazz, lastMessage), lastEx); } - public static void assertNoneMatching(ActorRef actor, Class clazz) { + public static void assertNoneMatching(final ActorRef actor, final Class clazz) { assertNoneMatching(actor, clazz, 5000); } @SuppressWarnings("checkstyle:IllegalCatch") - public static void assertNoneMatching(ActorRef actor, Class clazz, long timeout) { + public static void assertNoneMatching(final ActorRef actor, final Class clazz, final long timeout) { Exception lastEx = null; int count = (int) (timeout / 50); for (int i = 0; i < count; i++) { @@ -195,17 +200,18 @@ public class MessageCollectorActor extends UntypedActor { } if (lastEx != null) { - Throwables.propagate(lastEx); + Throwables.throwIfUnchecked(lastEx); + throw new RuntimeException(lastEx); } return; } - public static List getAllMatching(ActorRef actor, Class clazz) throws Exception { + public static List getAllMatching(final ActorRef actor, final Class clazz) { List allMessages = getAllMessages(actor); - List output = Lists.newArrayList(); + List output = new ArrayList<>(); for (Object message : allMessages) { if (message.getClass().equals(clazz)) { @@ -216,7 +222,7 @@ public class MessageCollectorActor extends UntypedActor { return output; } - public static void waitUntilReady(ActorRef actor) throws Exception { + public static void waitUntilReady(final ActorRef actor) throws TimeoutException, InterruptedException { long timeout = 500; FiniteDuration duration = Duration.create(timeout, TimeUnit.MILLISECONDS); for (int i = 0; i < 10; i++) { diff --git a/opendaylight/md-sal/sal-clustering-commons/pom.xml b/opendaylight/md-sal/sal-clustering-commons/pom.xml index a4c8ac00fc..b949b6d894 100644 --- a/opendaylight/md-sal/sal-clustering-commons/pom.xml +++ b/opendaylight/md-sal/sal-clustering-commons/pom.xml @@ -8,7 +8,6 @@ ../../config/config-parent - org.opendaylight.controller sal-clustering-commons 1.6.0-SNAPSHOT bundle diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java index 258672114a..c3f61c66fe 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java @@ -30,7 +30,7 @@ public class MeteredBoundedMailbox implements MailboxType, private final Integer capacity; private final FiniteDuration pushTimeOut; - public MeteredBoundedMailbox(ActorSystem.Settings settings, Config config) { + public MeteredBoundedMailbox(final ActorSystem.Settings settings, final Config config) { CommonConfig commonConfig = new CommonConfig(settings.config()); this.capacity = commonConfig.getMailBoxCapacity(); @@ -39,13 +39,13 @@ public class MeteredBoundedMailbox implements MailboxType, @Override - public MeteredMessageQueue create(final scala.Option owner, scala.Option system) { + public MeteredMessageQueue create(final scala.Option owner, final scala.Option system) { final MeteredMessageQueue queue = new MeteredMessageQueue(this.capacity, this.pushTimeOut); monitorQueueSize(owner, queue); return queue; } - private void monitorQueueSize(scala.Option owner, final MeteredMessageQueue monitoredQueue) { + private static void monitorQueueSize(final scala.Option owner, final MeteredMessageQueue monitoredQueue) { registerMetric(owner, QUEUE_SIZE, getQueueSizeGuage(monitoredQueue)); } @@ -53,7 +53,8 @@ public class MeteredBoundedMailbox implements MailboxType, return monitoredQueue::size; } - static void registerMetric(scala.Option owner, String metricName, T metric) { + static void registerMetric(final scala.Option owner, final String metricName, + final T metric) { if (owner.isEmpty()) { // there's no actor to monitor return; @@ -80,7 +81,7 @@ public class MeteredBoundedMailbox implements MailboxType, public static class MeteredMessageQueue extends BoundedDequeBasedMailbox.MessageQueue { private static final long serialVersionUID = 1L; - public MeteredMessageQueue(int capacity, FiniteDuration pushTimeOut) { + public MeteredMessageQueue(final int capacity, final FiniteDuration pushTimeOut) { super(capacity, pushTimeOut); } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java index 523417ec76..8a8eed1daa 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java @@ -104,7 +104,7 @@ public class MeteringBehavior implements Procedure { meteredActor.onReceive(message); } catch (Throwable e) { Throwables.propagateIfPossible(e, Exception.class); - throw Throwables.propagate(e); + throw new RuntimeException(e); } finally { //stop timers contextByMsgType.stop(); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageAssembler.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageAssembler.java index 328ff0c44a..45e3a8e828 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageAssembler.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageAssembler.java @@ -40,7 +40,7 @@ public class MessageAssembler implements AutoCloseable { private final BiConsumer assembledMessageCallback; private final String logContext; - private MessageAssembler(Builder builder) { + private MessageAssembler(final Builder builder) { this.fileBackedStreamFactory = Preconditions.checkNotNull(builder.fileBackedStreamFactory, "FiledBackedStreamFactory cannot be null"); this.assembledMessageCallback = Preconditions.checkNotNull(builder.assembledMessageCallback, @@ -69,7 +69,7 @@ public class MessageAssembler implements AutoCloseable { * @param message the message to check * @return true if handled, false otherwise */ - public static boolean isHandledMessage(Object message) { + public static boolean isHandledMessage(final Object message) { return message instanceof MessageSlice || message instanceof AbortSlicing; } @@ -144,7 +144,7 @@ public class MessageAssembler implements AutoCloseable { messageSlice.getSliceIndex()), true); } - private void processMessageSliceForState(final MessageSlice messageSlice, AssembledMessageState state, + private void processMessageSliceForState(final MessageSlice messageSlice, final AssembledMessageState state, final ActorRef sendTo) { final Identifier identifier = messageSlice.getIdentifier(); final ActorRef replyTo = messageSlice.getReplyTo(); @@ -177,7 +177,7 @@ public class MessageAssembler implements AutoCloseable { } } - private Object reAssembleMessage(final AssembledMessageState state) throws MessageSliceException { + private static Object reAssembleMessage(final AssembledMessageState state) throws MessageSliceException { try { final ByteSource assembledBytes = state.getAssembledBytes(); try (ObjectInputStream in = new ObjectInputStream(assembledBytes.openStream())) { @@ -190,7 +190,7 @@ public class MessageAssembler implements AutoCloseable { } } - private void onAbortSlicing(AbortSlicing message) { + private void onAbortSlicing(final AbortSlicing message) { removeState(message.getIdentifier()); } @@ -199,7 +199,7 @@ public class MessageAssembler implements AutoCloseable { stateCache.invalidate(identifier); } - private void stateRemoved(RemovalNotification notification) { + private void stateRemoved(final RemovalNotification notification) { if (notification.wasEvicted()) { LOG.warn("{}: AssembledMessageState for {} was expired from the cache", logContext, notification.getKey()); } else { @@ -211,7 +211,7 @@ public class MessageAssembler implements AutoCloseable { } @VisibleForTesting - boolean hasState(Identifier forIdentifier) { + boolean hasState(final Identifier forIdentifier) { boolean exists = stateCache.getIfPresent(forIdentifier) != null; stateCache.cleanUp(); return exists; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageSlicer.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageSlicer.java index 1454e72cc0..ec7dcca06a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageSlicer.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/messaging/MessageSlicer.java @@ -44,7 +44,7 @@ public class MessageSlicer implements AutoCloseable { private final String logContext; private final long id; - private MessageSlicer(Builder builder) { + private MessageSlicer(final Builder builder) { this.fileBackedStreamFactory = builder.fileBackedStreamFactory; this.messageSliceSize = builder.messageSliceSize; this.maxSlicingTries = builder.maxSlicingTries; @@ -83,7 +83,7 @@ public class MessageSlicer implements AutoCloseable { * @param message the message to check * @return true if handled, false otherwise */ - public static boolean isHandledMessage(Object message) { + public static boolean isHandledMessage(final Object message) { return message instanceof MessageSliceReply; } @@ -93,7 +93,7 @@ public class MessageSlicer implements AutoCloseable { * * @param options the SliceOptions */ - public void slice(SliceOptions options) { + public void slice(final SliceOptions options) { final Identifier identifier = options.getIdentifier(); final Serializable message = options.getMessage(); final FileBackedOutputStream fileBackedStream; @@ -154,7 +154,7 @@ public class MessageSlicer implements AutoCloseable { } } - private void sendTo(SliceOptions options, Object message, ActorRef sender) { + private static void sendTo(final SliceOptions options, final Object message, final ActorRef sender) { if (options.getSendToRef() != null) { options.getSendToRef().tell(message, sender); } else { @@ -196,7 +196,7 @@ public class MessageSlicer implements AutoCloseable { stateCache.invalidateAll(); } - private MessageSlice getNextSliceMessage(SlicedMessageState state) throws IOException { + private static MessageSlice getNextSliceMessage(final SlicedMessageState state) throws IOException { final byte[] firstSliceBytes = state.getNextSlice(); return new MessageSlice(state.getIdentifier(), firstSliceBytes, state.getCurrentSliceIndex(), state.getTotalSlices(), state.getLastSliceHashCode(), state.getReplyTarget()); @@ -278,7 +278,7 @@ public class MessageSlicer implements AutoCloseable { stateCache.invalidate(identifier); } - private void stateRemoved(RemovalNotification> notification) { + private void stateRemoved(final RemovalNotification> notification) { final SlicedMessageState state = notification.getValue(); state.close(); if (notification.wasEvicted()) { @@ -298,7 +298,7 @@ public class MessageSlicer implements AutoCloseable { } @VisibleForTesting - boolean hasState(Identifier forIdentifier) { + boolean hasState(final Identifier forIdentifier) { boolean exists = stateCache.getIfPresent(forIdentifier) != null; stateCache.cleanUp(); return exists; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java index fc492872bd..eeab236ed9 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java @@ -9,9 +9,11 @@ package org.opendaylight.controller.cluster.schema.provider.impl; import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.CheckedFuture; +import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.Set; import javax.annotation.Nonnull; @@ -34,8 +36,9 @@ public class RemoteYangTextSourceProviderImpl implements RemoteYangTextSourcePro private final SchemaRepository repository; private final Set providedSources; - public RemoteYangTextSourceProviderImpl(SchemaRepository repository, Set providedSources) { - this.repository = repository; + public RemoteYangTextSourceProviderImpl(final SchemaRepository repository, + final Set providedSources) { + this.repository = Preconditions.checkNotNull(repository); this.providedSources = providedSources; } @@ -45,16 +48,16 @@ public class RemoteYangTextSourceProviderImpl implements RemoteYangTextSourcePro } @Override - public Future getYangTextSchemaSource(SourceIdentifier identifier) { + public Future getYangTextSchemaSource(final SourceIdentifier identifier) { LOG.trace("Sending yang schema source for {}", identifier); final Promise promise = akka.dispatch.Futures.promise(); - CheckedFuture future = + ListenableFuture future = repository.getSchemaSource(identifier, YangTextSchemaSource.class); Futures.addCallback(future, new FutureCallback() { @Override - public void onSuccess(@Nonnull YangTextSchemaSource result) { + public void onSuccess(@Nonnull final YangTextSchemaSource result) { try { promise.success(new YangTextSchemaSourceSerializationProxy(result)); } catch (IOException e) { @@ -64,11 +67,11 @@ public class RemoteYangTextSourceProviderImpl implements RemoteYangTextSourcePro } @Override - public void onFailure(Throwable failure) { + public void onFailure(final Throwable failure) { LOG.warn("Unable to retrieve schema source from provider", failure); promise.failure(failure); } - }); + }, MoreExecutors.directExecutor()); return promise.future(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/messaging/MessageSlicingIntegrationTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/messaging/MessageSlicingIntegrationTest.java index 23d04b5ed2..a1a1e24c69 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/messaging/MessageSlicingIntegrationTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/messaging/MessageSlicingIntegrationTest.java @@ -256,7 +256,8 @@ public class MessageSlicingIntegrationTest { } @SuppressWarnings("unchecked") - private void testSlicing(String logContext, int messageSliceSize, int expTotalSlices, byte[] messageData) { + private void testSlicing(final String logContext, final int messageSliceSize, final int expTotalSlices, + final byte[] messageData) { reset(mockAssembledMessageCallback); final BytesMessage message = new BytesMessage(messageData); @@ -308,21 +309,23 @@ public class MessageSlicingIntegrationTest { assertEquals("Sender ActorRef", sender, senderActorRefCaptor.getValue()); } - static void assertSuccessfulMessageSliceReply(MessageSliceReply reply, Identifier identifier, int sliceIndex) { + static void assertSuccessfulMessageSliceReply(final MessageSliceReply reply, final Identifier identifier, + final int sliceIndex) { assertEquals("Identifier", identifier, ((MessageSliceIdentifier)reply.getIdentifier()) .getClientIdentifier()); assertEquals("SliceIndex", sliceIndex, reply.getSliceIndex()); } - static void assertFailedMessageSliceReply(MessageSliceReply reply, Identifier identifier, boolean isRetriable) { + static void assertFailedMessageSliceReply(final MessageSliceReply reply, final Identifier identifier, + final boolean isRetriable) { assertEquals("Identifier", identifier, ((MessageSliceIdentifier)reply.getIdentifier()) .getClientIdentifier()); assertEquals("Failure present", Boolean.TRUE, reply.getFailure().isPresent()); assertEquals("isRetriable", isRetriable, reply.getFailure().get().isRetriable()); } - static void assertMessageSlice(MessageSlice sliceMessage, Identifier identifier, int sliceIndex, int totalSlices, - int lastSliceHashCode, ActorRef replyTo) { + static void assertMessageSlice(final MessageSlice sliceMessage, final Identifier identifier, final int sliceIndex, + final int totalSlices, final int lastSliceHashCode, final ActorRef replyTo) { assertEquals("Identifier", identifier, ((MessageSliceIdentifier)sliceMessage.getIdentifier()) .getClientIdentifier()); assertEquals("SliceIndex", sliceIndex, sliceMessage.getSliceIndex()); @@ -334,7 +337,7 @@ public class MessageSlicingIntegrationTest { } } - private MessageSlicer newMessageSlicer(String logContext, final int messageSliceSize) { + private static MessageSlicer newMessageSlicer(final String logContext, final int messageSliceSize) { return MessageSlicer.builder().messageSliceSize(messageSliceSize).logContext(logContext) .fileBackedStreamFactory(FILE_BACKED_STREAM_FACTORY).build(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/persistence/LocalSnapshotStoreTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/persistence/LocalSnapshotStoreTest.java index b69b6345cc..417a9db7ea 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/persistence/LocalSnapshotStoreTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/persistence/LocalSnapshotStoreTest.java @@ -28,7 +28,6 @@ import akka.persistence.SnapshotSelectionCriteria; import akka.persistence.serialization.Snapshot; import akka.persistence.serialization.SnapshotSerializer; import akka.testkit.JavaTestKit; -import com.google.common.base.Throwables; import com.typesafe.config.ConfigFactory; import java.io.File; import java.io.FileOutputStream; @@ -152,15 +151,16 @@ public class LocalSnapshotStoreTest { assertEquals("SelectedSnapshot snapshot", "one", possibleSnapshot.get().snapshot()); } + @SuppressWarnings("checkstyle:illegalThrows") @Test(expected = IOException.class) - public void testDoLoadAsyncWithFailure() throws IOException { + public void testDoLoadAsyncWithFailure() throws Throwable { createSnapshotFile(PERSISTENCE_ID, null, 1, 2000); JavaTestKit probe = new JavaTestKit(system); snapshotStore.tell(new SnapshotProtocol.LoadSnapshot(PERSISTENCE_ID, SnapshotSelectionCriteria.latest(), Long.MAX_VALUE), probe.getRef()); LoadSnapshotFailed failed = probe.expectMsgClass(LoadSnapshotFailed.class); - Throwables.propagateIfInstanceOf(failed.cause(), IOException.class); + throw failed.cause(); } @Test @@ -185,7 +185,8 @@ public class LocalSnapshotStoreTest { assertEquals("SelectedSnapshot snapshot", "one", possibleSnapshot.get().snapshot()); } - private void createSnapshotFile(String persistenceId, String payload, int seqNr, int timestamp) throws IOException { + private static void createSnapshotFile(final String persistenceId, final String payload, final int seqNr, + final int timestamp) throws IOException { String name = toSnapshotName(persistenceId, seqNr, timestamp); try (FileOutputStream fos = new FileOutputStream(new File(SNAPSHOT_DIR, name))) { if (payload != null) { @@ -194,7 +195,7 @@ public class LocalSnapshotStoreTest { } } - private static String toSnapshotName(String persistenceId, int seqNr, int timestamp) + private static String toSnapshotName(final String persistenceId, final int seqNr, final int timestamp) throws UnsupportedEncodingException { final String encodedPersistenceId = URLEncoder.encode(persistenceId, StandardCharsets.UTF_8.name()); return "snapshot-" + encodedPersistenceId + "-" + seqNr + "-" + timestamp; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/databroker/DOMBrokerTransactionChain.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/databroker/DOMBrokerTransactionChain.java index 4bc22e4643..a25b07b3a9 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/databroker/DOMBrokerTransactionChain.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/databroker/DOMBrokerTransactionChain.java @@ -12,6 +12,7 @@ import com.google.common.base.Preconditions; import com.google.common.util.concurrent.CheckedFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.MoreExecutors; import java.util.Collection; import java.util.Map; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; @@ -62,7 +63,7 @@ final class DOMBrokerTransactionChain extends AbstractDOMTransactionFactory chains, - AbstractDOMBroker broker, final TransactionChainListener listener) { + final AbstractDOMBroker broker, final TransactionChainListener listener) { super(chains); this.chainId = chainId; this.broker = Preconditions.checkNotNull(broker); @@ -97,7 +98,7 @@ final class DOMBrokerTransactionChain extends AbstractDOMTransactionFactory cohorts, - TransactionIdentifier transactionId) { + public ThreePhaseCommitCohortProxy(final ActorContext actorContext, final List cohorts, + final TransactionIdentifier transactionId) { this.actorContext = actorContext; this.cohorts = cohorts; this.transactionId = Preconditions.checkNotNull(transactionId); @@ -91,7 +92,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< for (final CohortInfo info: cohorts) { info.getActorFuture().onComplete(new OnComplete() { @Override - public void onComplete(Throwable failure, ActorSelection actor) { + public void onComplete(final Throwable failure, final ActorSelection actor) { synchronized (lock) { boolean done = completed.decrementAndGet() == 0; if (failure != null) { @@ -128,15 +129,15 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< Futures.addCallback(resolveCohorts(), new FutureCallback() { @Override - public void onSuccess(Void notUsed) { + public void onSuccess(final Void notUsed) { finishCanCommit(returnFuture); } @Override - public void onFailure(Throwable failure) { + public void onFailure(final Throwable failure) { returnFuture.setException(failure); } - }); + }, MoreExecutors.directExecutor()); return returnFuture; } @@ -158,7 +159,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< final OnComplete onComplete = new OnComplete() { @Override - public void onComplete(Throwable failure, Object response) { + public void onComplete(final Throwable failure, final Object response) { if (failure != null) { LOG.debug("Tx {}: a canCommit cohort Future failed", transactionId, failure); @@ -200,7 +201,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< sendCanCommitTransaction(iterator.next(), onComplete); } - private void sendCanCommitTransaction(CohortInfo toCohortInfo, OnComplete onComplete) { + private void sendCanCommitTransaction(final CohortInfo toCohortInfo, final OnComplete onComplete) { CanCommitTransaction message = new CanCommitTransaction(transactionId, toCohortInfo.getActorVersion()); LOG.debug("Tx {}: sending {} to {}", transactionId, message, toCohortInfo.getResolvedActor()); @@ -210,7 +211,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< future.onComplete(onComplete, actorContext.getClientDispatcher()); } - private Future> invokeCohorts(MessageSupplier messageSupplier) { + private Future> invokeCohorts(final MessageSupplier messageSupplier) { List> futureList = Lists.newArrayListWithCapacity(cohorts.size()); for (CohortInfo cohort : cohorts) { Object message = messageSupplier.newMessage(transactionId, cohort.getActorVersion()); @@ -253,7 +254,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< } @SuppressWarnings("checkstyle:IllegalCatch") - private static boolean successfulFuture(ListenableFuture future) { + private static boolean successfulFuture(final ListenableFuture future) { if (!future.isDone()) { return false; } @@ -283,13 +284,13 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< } else { Futures.addCallback(future, new FutureCallback() { @Override - public void onSuccess(Void notUsed) { + public void onSuccess(final Void notUsed) { finishVoidOperation(operationName, messageSupplier, expectedResponseClass, propagateException, returnFuture, callback); } @Override - public void onFailure(Throwable failure) { + public void onFailure(final Throwable failure) { LOG.debug("Tx {}: a {} cohort path Future failed: {}", transactionId, operationName, failure); if (propagateException) { @@ -298,13 +299,13 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< returnFuture.set(null); } } - }); + }, MoreExecutors.directExecutor()); } return returnFuture; } - private void finishVoidOperation(final String operationName, MessageSupplier messageSupplier, + private void finishVoidOperation(final String operationName, final MessageSupplier messageSupplier, final Class expectedResponseClass, final boolean propagateException, final SettableFuture returnFuture, final OperationCallback callback) { LOG.debug("Tx {} finish {}", transactionId, operationName); @@ -315,7 +316,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< combinedFuture.onComplete(new OnComplete>() { @Override - public void onComplete(Throwable failure, Iterable responses) throws Throwable { + public void onComplete(final Throwable failure, final Iterable responses) throws Throwable { Throwable exceptionToPropagate = failure; if (exceptionToPropagate == null) { for (Object response: responses) { @@ -367,7 +368,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< private volatile ActorSelection resolvedActor; private final Supplier actorVersionSupplier; - CohortInfo(Future actorFuture, Supplier actorVersionSupplier) { + CohortInfo(final Future actorFuture, final Supplier actorVersionSupplier) { this.actorFuture = actorFuture; this.actorVersionSupplier = actorVersionSupplier; } @@ -380,7 +381,7 @@ public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort< return resolvedActor; } - void setResolvedActor(ActorSelection resolvedActor) { + void setResolvedActor(final ActorSelection resolvedActor) { this.resolvedActor = resolvedActor; } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/persisted/AbortTransactionPayload.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/persisted/AbortTransactionPayload.java index 751f5b21ba..ad9bc4a7e8 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/persisted/AbortTransactionPayload.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/persisted/AbortTransactionPayload.java @@ -7,7 +7,6 @@ */ package org.opendaylight.controller.cluster.datastore.persisted; -import com.google.common.base.Throwables; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import java.io.DataInput; @@ -62,7 +61,7 @@ public final class AbortTransactionPayload extends AbstractIdentifiablePayload) Await.result( Patterns.ask(shardManager, GetLocalShardIds.INSTANCE, ASK_TIMEOUT_MILLIS), Duration.Inf()); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -58,7 +59,7 @@ final class ShardManagerInfo extends AbstractMXBean implements ShardManagerInfoM return syncStatus; } - void setSyncStatus(boolean syncStatus) { + void setSyncStatus(final boolean syncStatus) { this.syncStatus = syncStatus; } @@ -79,8 +80,10 @@ final class ShardManagerInfo extends AbstractMXBean implements ShardManagerInfoM try { Await.result(Patterns.ask(shardManager, new SwitchShardBehavior(shardId, state, term), ASK_TIMEOUT_MILLIS), Duration.Inf()); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } break; case Candidate: @@ -91,13 +94,13 @@ final class ShardManagerInfo extends AbstractMXBean implements ShardManagerInfoM } @Override - public void switchAllLocalShardsState(String newState, long term) { + public void switchAllLocalShardsState(final String newState, final long term) { LOG.info("switchAllLocalShardsState called newState = {}, term = {}", newState, term); requestSwitchShardState(null, newState, term); } @Override - public void switchShardState(String shardId, String newState, long term) { + public void switchShardState(final String shardId, final String newState, final long term) { final ShardIdentifier identifier = ShardIdentifier.fromShardIdString(shardId); LOG.info("switchShardState called shardName = {}, newState = {}, term = {}", shardId, newState, term); requestSwitchShardState(identifier, newState, term); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/DataTreeModificationOutput.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/DataTreeModificationOutput.java index dde7e60a92..9dc308e209 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/DataTreeModificationOutput.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/DataTreeModificationOutput.java @@ -7,7 +7,6 @@ */ package org.opendaylight.controller.cluster.datastore.utils; -import com.google.common.base.Throwables; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -33,7 +32,7 @@ public final class DataTreeModificationOutput { } @SuppressWarnings("checkstyle:IllegalCatch") - public static void toFile(File file, DataTreeModification modification) { + public static void toFile(final File file, final DataTreeModification modification) { try (FileOutputStream outStream = new FileOutputStream(file)) { modification.applyToCursor(new DataTreeModificationOutputCursor(new DataOutputStream(outStream))); } catch (IOException | RuntimeException e) { @@ -44,32 +43,32 @@ public final class DataTreeModificationOutput { private static class DataTreeModificationOutputCursor extends AbstractDataTreeModificationCursor { private final DataOutputStream output; - DataTreeModificationOutputCursor(DataOutputStream output) { + DataTreeModificationOutputCursor(final DataOutputStream output) { this.output = output; } @Override - public void delete(PathArgument child) { + public void delete(final PathArgument child) { try { output.write("\nDELETE -> ".getBytes(StandardCharsets.UTF_8)); output.write(current().node(child).toString().getBytes(StandardCharsets.UTF_8)); output.writeByte('\n'); } catch (IOException e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } @Override - public void merge(PathArgument child, NormalizedNode data) { + public void merge(final PathArgument child, final NormalizedNode data) { outputPathAndNode("MERGE", child, data); } @Override - public void write(PathArgument child, NormalizedNode data) { + public void write(final PathArgument child, final NormalizedNode data) { outputPathAndNode("WRITE", child, data); } - private void outputPathAndNode(String name, PathArgument child, NormalizedNode data) { + private void outputPathAndNode(final String name, final PathArgument child, final NormalizedNode data) { try { output.writeByte('\n'); output.write(name.getBytes(StandardCharsets.UTF_8)); @@ -79,7 +78,7 @@ public final class DataTreeModificationOutput { NormalizedNodeXMLOutput.toStream(output, data); output.writeByte('\n'); } catch (IOException | XMLStreamException e) { - Throwables.propagate(e); + throw new RuntimeException(e); } } } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/sharding/DistributedShardedDOMDataTree.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/sharding/DistributedShardedDOMDataTree.java index 277c09f730..cdb249f3cd 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/sharding/DistributedShardedDOMDataTree.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/sharding/DistributedShardedDOMDataTree.java @@ -25,6 +25,7 @@ import com.google.common.collect.ForwardingObject; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.Uninterruptibles; import java.util.AbstractMap.SimpleEntry; @@ -308,13 +309,15 @@ public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDat distributedConfigDatastore.getActorContext().getClusterWrapper().getCurrentMemberName(), subtrees); return new ProxyProducer(producer, subtrees, shardedDataTreeActor, distributedConfigDatastore.getActorContext(), shards); - } else if (response instanceof Exception) { - closeProducer(producer); - throw Throwables.propagate((Exception) response); - } else { - closeProducer(producer); - throw new RuntimeException("Unexpected response to create producer received." + response); } + + closeProducer(producer); + + if (response instanceof Throwable) { + Throwables.throwIfUnchecked((Throwable) response); + throw new RuntimeException((Throwable) response); + } + throw new RuntimeException("Unexpected response to create producer received." + response); } @Override @@ -366,7 +369,7 @@ public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDat shardRegistrationPromise.failure( new DOMDataTreeShardCreationFailedException("Unable to create a cds shard.", throwable)); } - }); + }, MoreExecutors.directExecutor()); return FutureConverters.toJava(shardRegistrationPromise.future()); } @@ -458,7 +461,7 @@ public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDat public void onFailure(final Throwable throwable) { LOG.error("Removal of shard {} from configuration failed.", prefix, throwable); } - }); + }, MoreExecutors.directExecutor()); } DOMDataTreePrefixTableEntry> lookupShardFrontend( diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/databroker/ConcurrentDOMDataBrokerTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/databroker/ConcurrentDOMDataBrokerTest.java index 8335fcdc3c..9cbf3b5a31 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/databroker/ConcurrentDOMDataBrokerTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/databroker/ConcurrentDOMDataBrokerTest.java @@ -158,7 +158,8 @@ public class ConcurrentDOMDataBrokerTest { assertEquals("Submit complete", true, doneLatch.await(5, TimeUnit.SECONDS)); if (caughtEx.get() != null) { - Throwables.propagate(caughtEx.get()); + Throwables.throwIfUnchecked(caughtEx.get()); + throw new RuntimeException(caughtEx.get()); } assertEquals("Task count", doAsync ? 1 : 0, futureExecutor.getTaskCount()); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractShardTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractShardTest.java index f5a7551176..e99710e2fc 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractShardTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractShardTest.java @@ -306,7 +306,7 @@ public abstract class AbstractShardTest extends AbstractActorTest { } public static void writeToStore(final ShardDataTree store, final YangInstanceIdentifier id, - final NormalizedNode node) throws Exception { + final NormalizedNode node) throws DataValidationFailedException { BatchedModifications batched = newBatchedModifications(nextTransactionId(), id, node, true, true, 1); DataTreeModification modification = store.getDataTree().takeSnapshot().newModification(); batched.apply(modification); @@ -325,7 +325,7 @@ public abstract class AbstractShardTest extends AbstractActorTest { } public void mergeToStore(final ShardDataTree store, final YangInstanceIdentifier id, - final NormalizedNode node) throws Exception { + final NormalizedNode node) throws DataValidationFailedException { final BatchedModifications batched = new BatchedModifications(nextTransactionId(), CURRENT_VERSION); batched.addModification(new MergeModification(id, node)); batched.setReady(true); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractTransactionProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractTransactionProxyTest.java index a80a0515fb..322e15b3ca 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractTransactionProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractTransactionProxyTest.java @@ -100,34 +100,34 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { Map strategyMap = ImmutableMap.builder().put( "junk", new ShardStrategy() { @Override - public String findShard(YangInstanceIdentifier path) { + public String findShard(final YangInstanceIdentifier path) { return "junk"; } @Override - public YangInstanceIdentifier getPrefixForPath(YangInstanceIdentifier path) { + public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) { return YangInstanceIdentifier.EMPTY; } }).put( "cars", new ShardStrategy() { @Override - public String findShard(YangInstanceIdentifier path) { + public String findShard(final YangInstanceIdentifier path) { return "cars"; } @Override - public YangInstanceIdentifier getPrefixForPath(YangInstanceIdentifier path) { + public YangInstanceIdentifier getPrefixForPath(final YangInstanceIdentifier path) { return YangInstanceIdentifier.EMPTY; } }).build(); @Override - public ShardStrategy getStrategyForModule(String moduleName) { + public ShardStrategy getStrategyForModule(final String moduleName) { return strategyMap.get(moduleName); } @Override - public String getModuleNameFromNameSpace(String nameSpace) { + public String getModuleNameFromNameSpace(final String nameSpace) { if (TestModel.JUNK_QNAME.getNamespace().toASCIIString().equals(nameSpace)) { return "junk"; } else if (CarsModel.BASE_QNAME.getNamespace().toASCIIString().equals(nameSpace)) { @@ -201,7 +201,7 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { final TransactionType type) { ArgumentMatcher matcher = new ArgumentMatcher() { @Override - public boolean matches(Object argument) { + public boolean matches(final Object argument) { if (CreateTransaction.class.equals(argument.getClass())) { CreateTransaction obj = CreateTransaction.fromSerializable(argument); return obj.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName() @@ -218,7 +218,7 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { protected DataExists eqDataExists() { ArgumentMatcher matcher = new ArgumentMatcher() { @Override - public boolean matches(Object argument) { + public boolean matches(final Object argument) { return argument instanceof DataExists && ((DataExists)argument).getPath().equals(TestModel.TEST_PATH); } }; @@ -233,7 +233,7 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { protected ReadData eqReadData(final YangInstanceIdentifier path) { ArgumentMatcher matcher = new ArgumentMatcher() { @Override - public boolean matches(Object argument) { + public boolean matches(final Object argument) { return argument instanceof ReadData && ((ReadData)argument).getPath().equals(path); } }; @@ -241,20 +241,20 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { return argThat(matcher); } - protected Future readyTxReply(String path) { + protected Future readyTxReply(final String path) { return Futures.successful((Object)new ReadyTransactionReply(path)); } - protected Future readDataReply(NormalizedNode data) { + protected Future readDataReply(final NormalizedNode data) { return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION)); } - protected Future dataExistsReply(boolean exists) { + protected Future dataExistsReply(final boolean exists) { return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION)); } - protected Future batchedModificationsReply(int count) { + protected Future batchedModificationsReply(final int count) { return Futures.successful(new BatchedModificationsReply(count)); } @@ -263,25 +263,25 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { return mock(Future.class); } - protected ActorSelection actorSelection(ActorRef actorRef) { + protected ActorSelection actorSelection(final ActorRef actorRef) { return getSystem().actorSelection(actorRef.path()); } - protected void expectBatchedModifications(ActorRef actorRef, int count) { + protected void expectBatchedModifications(final ActorRef actorRef, final int count) { doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync( eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class)); } - protected void expectBatchedModifications(int count) { + protected void expectBatchedModifications(final int count) { doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync( any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class)); } - protected void expectBatchedModificationsReady(ActorRef actorRef) { + protected void expectBatchedModificationsReady(final ActorRef actorRef) { expectBatchedModificationsReady(actorRef, false); } - protected void expectBatchedModificationsReady(ActorRef actorRef, boolean doCommitOnReady) { + protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) { doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) : readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class)); @@ -292,32 +292,33 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class)); } - protected void expectFailedBatchedModifications(ActorRef actorRef) { + protected void expectFailedBatchedModifications(final ActorRef actorRef) { doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync( eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class)); } - protected void expectReadyLocalTransaction(ActorRef actorRef, boolean doCommitOnReady) { + protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) { doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) : readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync( eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class)); } - protected CreateTransactionReply createTransactionReply(ActorRef actorRef, short transactionVersion) { + protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) { return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion); } - protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem) { + protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) { return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD); } - protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName) { + protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem, + final String shardName) { return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, DataStoreVersions.CURRENT_VERSION); } - protected ActorRef setupActorContextWithoutInitialCreateTransaction(ActorSystem actorSystem, String shardName, - short transactionVersion) { + protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem, + final String shardName, final short transactionVersion) { ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class)); log.info("Created mock shard actor {}", actorRef); @@ -330,18 +331,18 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { return actorRef; } - protected Future primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef) { + protected Future primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) { return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION); } - protected Future primaryShardInfoReply(ActorSystem actorSystem, ActorRef actorRef, - short transactionVersion) { + protected Future primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef, + final short transactionVersion) { return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()), transactionVersion)); } - protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, - TransactionType type, short transactionVersion, String shardName) { + protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem, + final TransactionType type, final short transactionVersion, final String shardName) { ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName, transactionVersion); @@ -349,8 +350,9 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { memberName, shardActorRef); } - protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, - TransactionType type, short transactionVersion, String prefix, ActorRef shardActorRef) { + protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem, + final TransactionType type, final short transactionVersion, final String prefix, + final ActorRef shardActorRef) { ActorRef txActorRef; if (type == TransactionType.WRITE_ONLY @@ -371,18 +373,21 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { return txActorRef; } - protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type) { + protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem, + final TransactionType type) { return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION, DefaultShardStrategy.DEFAULT_SHARD); } - protected ActorRef setupActorContextWithInitialCreateTransaction(ActorSystem actorSystem, TransactionType type, - String shardName) { + protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem, + final TransactionType type, + final String shardName) { return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION, shardName); } - protected void propagateReadFailedExceptionCause(CheckedFuture future) throws Exception { + protected void propagateReadFailedExceptionCause(final CheckedFuture future) + throws Exception { try { future.checkedGet(5, TimeUnit.SECONDS); fail("Expected ReadFailedException"); @@ -395,12 +400,12 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { cause = e.getCause(); } - Throwables.throwIfInstanceOf(cause, Exception.class); - Throwables.propagate(cause); + Throwables.propagateIfPossible(cause, Exception.class); + throw new RuntimeException(cause); } } - protected List captureBatchedModifications(ActorRef actorRef) { + protected List captureBatchedModifications(final ActorRef actorRef) { ArgumentCaptor batchedModificationsCaptor = ArgumentCaptor.forClass(BatchedModifications.class); verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync( @@ -411,7 +416,7 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { return batchedModifications; } - protected List filterCaptured(ArgumentCaptor captor, Class type) { + protected List filterCaptured(final ArgumentCaptor captor, final Class type) { List captured = new ArrayList<>(); for (T c: captor.getAllValues()) { if (type.isInstance(c)) { @@ -422,19 +427,21 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { return captured; } - protected void verifyOneBatchedModification(ActorRef actorRef, Modification expected, boolean expIsReady) { + protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected, + final boolean expIsReady) { List batchedModifications = captureBatchedModifications(actorRef); assertEquals("Captured BatchedModifications count", 1, batchedModifications.size()); verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected); } - protected void verifyBatchedModifications(Object message, boolean expIsReady, Modification... expected) { + protected void verifyBatchedModifications(final Object message, final boolean expIsReady, + final Modification... expected) { verifyBatchedModifications(message, expIsReady, false, expected); } - protected void verifyBatchedModifications(Object message, boolean expIsReady, boolean expIsDoCommitOnReady, - Modification... expected) { + protected void verifyBatchedModifications(final Object message, final boolean expIsReady, + final boolean expIsDoCommitOnReady, final Modification... expected) { assertEquals("Message type", BatchedModifications.class, message.getClass()); BatchedModifications batchedModifications = (BatchedModifications)message; assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size()); @@ -453,8 +460,8 @@ public abstract class AbstractTransactionProxyTest extends AbstractTest { } @SuppressWarnings("checkstyle:IllegalCatch") - protected void verifyCohortFutures(AbstractThreePhaseCommitCohort proxy, - Object... expReplies) throws Exception { + protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort proxy, + final Object... expReplies) { assertEquals("getReadyOperationFutures size", expReplies.length, proxy.getCohortFutures().size()); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataTreeChangeListenerSupportTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataTreeChangeListenerSupportTest.java index c8adf06dcf..3278ff625f 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataTreeChangeListenerSupportTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataTreeChangeListenerSupportTest.java @@ -26,7 +26,6 @@ import akka.pattern.Patterns; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import akka.util.Timeout; -import com.google.common.base.Throwables; import java.util.AbstractMap.SimpleEntry; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; @@ -40,6 +39,7 @@ import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNo import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import scala.concurrent.Await; import scala.concurrent.duration.Duration; @@ -68,14 +68,14 @@ public class DataTreeChangeListenerSupportTest extends AbstractShardTest { } @Test - public void testChangeListenerWithNoInitialData() throws Exception { + public void testChangeListenerWithNoInitialData() { MockDataTreeChangeListener listener = registerChangeListener(TEST_PATH, 0).getKey(); listener.expectNoMoreChanges("Unexpected initial change event"); } @Test - public void testInitialChangeListenerEventWithContainerPath() throws Exception { + public void testInitialChangeListenerEventWithContainerPath() throws DataValidationFailedException { writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME)); Entry entry = registerChangeListener(TEST_PATH, 1); @@ -100,7 +100,7 @@ public class DataTreeChangeListenerSupportTest extends AbstractShardTest { } @Test - public void testInitialChangeListenerEventWithListPath() throws Exception { + public void testInitialChangeListenerEventWithListPath() throws DataValidationFailedException { mergeToStore(shard.getDataStore(), TEST_PATH, testNodeWithOuter(1, 2)); MockDataTreeChangeListener listener = registerChangeListener(OUTER_LIST_PATH, 1).getKey(); @@ -110,7 +110,7 @@ public class DataTreeChangeListenerSupportTest extends AbstractShardTest { } @Test - public void testInitialChangeListenerEventWithWildcardedListPath() throws Exception { + public void testInitialChangeListenerEventWithWildcardedListPath() throws DataValidationFailedException { mergeToStore(shard.getDataStore(), TEST_PATH, testNodeWithOuter(1, 2)); MockDataTreeChangeListener listener = @@ -121,7 +121,7 @@ public class DataTreeChangeListenerSupportTest extends AbstractShardTest { } @Test - public void testInitialChangeListenerEventWithNestedWildcardedListsPath() throws Exception { + public void testInitialChangeListenerEventWithNestedWildcardedListsPath() throws DataValidationFailedException { mergeToStore(shard.getDataStore(), TEST_PATH, testNodeWithOuter(outerNode( outerNodeEntry(1, innerNode("one", "two")), outerNodeEntry(2, innerNode("three", "four"))))); @@ -160,16 +160,17 @@ public class DataTreeChangeListenerSupportTest extends AbstractShardTest { MockDataTreeChangeListener listener = new MockDataTreeChangeListener(expectedEvents); ActorRef dclActor = actorFactory.createActor(DataTreeChangeListenerActor.props(listener, TestModel.TEST_PATH)); + RegisterDataTreeNotificationListenerReply reply; try { - RegisterDataTreeNotificationListenerReply reply = (RegisterDataTreeNotificationListenerReply) - Await.result(Patterns.ask(shardActor, new RegisterDataTreeChangeListener(path, dclActor, false), - new Timeout(5, TimeUnit.SECONDS)), Duration.create(5, TimeUnit.SECONDS)); - return new SimpleEntry<>(listener, getSystem().actorSelection(reply.getListenerRegistrationPath())); - + reply = (RegisterDataTreeNotificationListenerReply) + Await.result(Patterns.ask(shardActor, new RegisterDataTreeChangeListener(path, dclActor, false), + new Timeout(5, TimeUnit.SECONDS)), Duration.create(5, TimeUnit.SECONDS)); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - Throwables.propagate(e); - return null; + throw new RuntimeException(e); } + return new SimpleEntry<>(listener, getSystem().actorSelection(reply.getListenerRegistrationPath())); } private void createShard() { diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java index bd9d683970..688f9c377e 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java @@ -554,7 +554,9 @@ public class DistributedDataStoreIntegrationTest { txCohort.get().canCommit().get(5, TimeUnit.SECONDS); fail("Expected NotInitializedException"); } catch (final Exception e) { - Throwables.propagate(Throwables.getRootCause(e)); + final Throwable root = Throwables.getRootCause(e); + Throwables.throwIfUnchecked(root); + throw new RuntimeException(root); } finally { blockRecoveryLatch.countDown(); } @@ -625,7 +627,9 @@ public class DistributedDataStoreIntegrationTest { txReadFuture.get().checkedGet(5, TimeUnit.SECONDS); fail("Expected NotInitializedException"); } catch (final ReadFailedException e) { - Throwables.propagate(Throwables.getRootCause(e)); + final Throwable root = Throwables.getRootCause(e); + Throwables.throwIfUnchecked(root); + throw new RuntimeException(root); } finally { blockRecoveryLatch.countDown(); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java index 3eb84bde13..32b9900b0b 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java @@ -666,9 +666,10 @@ public class ShardTest extends AbstractShardTest { final boolean done = commitLatch.await(timeoutSec, TimeUnit.SECONDS); - if (caughtEx.get() != null) { - Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class); - Throwables.propagate(caughtEx.get()); + final Throwable t = caughtEx.get(); + if (t != null) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); } assertEquals("Commits complete", true, done); @@ -810,8 +811,8 @@ public class ShardTest extends AbstractShardTest { final Failure failure = expectMsgClass(duration("5 seconds"), akka.actor.Status.Failure.class); if (failure != null) { - Throwables.throwIfInstanceOf(failure.cause(), Exception.class); - Throwables.propagate(failure.cause()); + Throwables.propagateIfPossible(failure.cause(), Exception.class); + throw new RuntimeException(failure.cause()); } } }; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java index 84bc87238a..0d65faa060 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java @@ -319,8 +319,8 @@ public class ShardTransactionTest extends AbstractActorTest { watcher.expectMsgClass(duration("5 seconds"), Terminated.class); if (failure != null) { - Throwables.propagateIfInstanceOf(failure.cause(), Exception.class); - Throwables.propagate(failure.cause()); + Throwables.propagateIfPossible(failure.cause(), Exception.class); + throw new RuntimeException(failure.cause()); } } }; @@ -348,8 +348,9 @@ public class ShardTransactionTest extends AbstractActorTest { watcher.expectMsgClass(duration("5 seconds"), Terminated.class); if (failure != null) { - Throwables.propagateIfInstanceOf(failure.cause(), Exception.class); - Throwables.propagate(failure.cause()); + Throwables.throwIfInstanceOf(failure.cause(), Exception.class); + Throwables.throwIfUnchecked(failure.cause()); + throw new RuntimeException(failure.cause()); } } }; diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java index 0e6cf530d1..dadd3a99f7 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java @@ -82,7 +82,7 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { new MockClusterWrapper(), new MockConfiguration(), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache()) { @Override - public Timer getOperationTimer(String operationName) { + public Timer getOperationTimer(final String operationName) { return commitTimer; } @@ -260,30 +260,30 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { verifyCohortActors(); } - private void propagateExecutionExceptionCause(ListenableFuture future) throws Exception { + private void propagateExecutionExceptionCause(final ListenableFuture future) throws Exception { try { future.get(5, TimeUnit.SECONDS); fail("Expected ExecutionException"); } catch (ExecutionException e) { verifyCohortActors(); - Throwables.propagateIfInstanceOf(e.getCause(), Exception.class); - Throwables.propagate(e.getCause()); + Throwables.propagateIfPossible(e.getCause(), Exception.class); + throw new RuntimeException(e.getCause()); } } - private CohortInfo newCohortInfo(CohortActor.Builder builder, final short version) { + private CohortInfo newCohortInfo(final CohortActor.Builder builder, final short version) { TestActorRef actor = actorFactory.createTestActor(builder.props() .withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId("cohort")); cohortActors.add(actor); return new CohortInfo(Futures.successful(getSystem().actorSelection(actor.path())), () -> version); } - private CohortInfo newCohortInfo(CohortActor.Builder builder) { + private CohortInfo newCohortInfo(final CohortActor.Builder builder) { return newCohortInfo(builder, CURRENT_VERSION); } - private static CohortInfo newCohortInfoWithFailedFuture(Exception failure) { + private static CohortInfo newCohortInfoWithFailedFuture(final Exception failure) { return new CohortInfo(Futures.failed(failure), () -> CURRENT_VERSION); } @@ -294,7 +294,7 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { } @SuppressWarnings("checkstyle:IllegalCatch") - private T verifySuccessfulFuture(ListenableFuture future) throws Exception { + private T verifySuccessfulFuture(final ListenableFuture future) throws Exception { try { return future.get(5, TimeUnit.SECONDS); } catch (Exception e) { @@ -303,7 +303,7 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { } } - private void verifyCanCommit(ListenableFuture future, boolean expected) throws Exception { + private void verifyCanCommit(final ListenableFuture future, final boolean expected) throws Exception { Boolean actual = verifySuccessfulFuture(future); assertEquals("canCommit", expected, actual); } @@ -315,12 +315,12 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { private final AtomicInteger abortCount = new AtomicInteger(); private volatile AssertionError assertionError; - private CohortActor(Builder builder) { + private CohortActor(final Builder builder) { this.builder = builder; } @Override - public void onReceive(Object message) { + public void onReceive(final Object message) { if (CanCommitTransaction.isSerializedType(message)) { canCommitCount.incrementAndGet(); onMessage("CanCommitTransaction", message, CanCommitTransaction.fromSerializable(message), @@ -338,8 +338,8 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { } } - private void onMessage(String name, Object rawMessage, AbstractThreePhaseCommitMessage actualMessage, - Class expType, Object reply) { + private void onMessage(final String name, final Object rawMessage, + final AbstractThreePhaseCommitMessage actualMessage, final Class expType, final Object reply) { try { assertNotNull("Unexpected " + name, expType); assertEquals(name + " type", expType, rawMessage.getClass()); @@ -382,37 +382,37 @@ public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest { private Object abortReply; private final TransactionIdentifier transactionId; - Builder(TransactionIdentifier transactionId) { + Builder(final TransactionIdentifier transactionId) { this.transactionId = Preconditions.checkNotNull(transactionId); } - Builder expectCanCommit(Class newExpCanCommitType, Object newCanCommitReply) { + Builder expectCanCommit(final Class newExpCanCommitType, final Object newCanCommitReply) { this.expCanCommitType = newExpCanCommitType; this.canCommitReply = newCanCommitReply; return this; } - Builder expectCanCommit(Object newCanCommitReply) { + Builder expectCanCommit(final Object newCanCommitReply) { return expectCanCommit(CanCommitTransaction.class, newCanCommitReply); } - Builder expectCommit(Class newExpCommitType, Object newCommitReply) { + Builder expectCommit(final Class newExpCommitType, final Object newCommitReply) { this.expCommitType = newExpCommitType; this.commitReply = newCommitReply; return this; } - Builder expectCommit(Object newCommitReply) { + Builder expectCommit(final Object newCommitReply) { return expectCommit(CommitTransaction.class, newCommitReply); } - Builder expectAbort(Class newExpAbortType, Object newAbortReply) { + Builder expectAbort(final Class newExpAbortType, final Object newAbortReply) { this.expAbortType = newExpAbortType; this.abortReply = newAbortReply; return this; } - Builder expectAbort(Object newAbortReply) { + Builder expectAbort(final Object newAbortReply) { return expectAbort(AbortTransaction.class, newAbortReply); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java index ca804fdeee..8ee4a2dd70 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java @@ -378,9 +378,10 @@ public class TransactionProxyTest extends AbstractTransactionProxyTest { Uninterruptibles.awaitUninterruptibly(readComplete, 5, TimeUnit.SECONDS); - if (caughtEx.get() != null) { - Throwables.propagateIfInstanceOf(caughtEx.get(), Exception.class); - Throwables.propagate(caughtEx.get()); + final Throwable t = caughtEx.get(); + if (t != null) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); } // This sends the batched modification. diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SchemaContextHelper.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SchemaContextHelper.java index 4e906a4d15..ceee437ac3 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SchemaContextHelper.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SchemaContextHelper.java @@ -8,7 +8,6 @@ package org.opendaylight.controller.md.cluster.datastore.model; -import com.google.common.base.Throwables; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -65,7 +64,7 @@ public class SchemaContextHelper { try { return YangParserTestUtils.parseYangSources(new File("src/main/yang/entity-owners.yang")); } catch (IOException | ReactorException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } } -- 2.36.6