setFailure(failureMessage, null);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected void setFailure(final String failureMessage, final Throwable failureCause) {
this.failureMessage = failureMessage;
this.failureCause = failureCause;
this.message = message;
}
- public void setTrace(final String stackTrace) {
+ public void setStackTrace(final String stackTrace) {
this.stackTrace = stackTrace;
}
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
-public class ConfigRegistryConstants {
+public final class ConfigRegistryConstants {
private ConfigRegistryConstants() {
}
return service;
} catch (final InterruptedException e) {
throw new ServiceNotFoundException(
- String.format("Wait for OSGi service %s was interrrupted", serviceInterface));
+ String.format("Wait for OSGi service %s was interrrupted", serviceInterface), e);
}
}
protected abstract AutoCloseable createInstance();
@Override
- public final boolean canReuse(final Module oldModule) {
+ public final boolean canReuse(final Module prevModule) {
// Just cast into a specific instance
// TODO unify this method with canReuseInstance (required Module interface to be
// generic which requires quite a lot of changes)
- return canReuseInstance && getClass().isInstance(oldModule) ? canReuseInstance((M) oldModule) : false;
+ return canReuseInstance && getClass().isInstance(prevModule) ? canReuseInstance((M) prevModule) : false;
}
/**
* Users are welcome to override this method to provide custom logic for
* advanced reusability detection.
*
- * @param oldModule
+ * @param prevModule
* old instance of a Module
* @return true if the old instance is reusable false if a new one should be
* spawned
*/
- protected abstract boolean canReuseInstance(M oldModule);
+ protected abstract boolean canReuseInstance(M prevModule);
/**
* By default the oldInstance is returned since this method is by default called
* Users are welcome to override this method to provide custom logic for
* advanced reusability.
*
- * @param oldInstance
+ * @param prevInstance
* old instance of a class wrapped by the module
* @return reused instance
*/
- protected AutoCloseable reuseInstance(final AutoCloseable oldInstance) {
+ protected AutoCloseable reuseInstance(final AutoCloseable prevInstance) {
// implement if instance reuse should be supported. Override canReuseInstance to
// change the criteria.
- return oldInstance;
+ return prevInstance;
}
/**
@Test(expected = NullPointerException.class)
public void testConstructor2() throws Exception {
- IdentityAttributeRef attr = new IdentityAttributeRef(null);
+ new IdentityAttributeRef(null);
}
@Test
public void testGetTrace() throws Exception {
ValidationException.ExceptionMessageWithStackTrace exp =
new ValidationException.ExceptionMessageWithStackTrace();
- exp.setTrace("trace");
+ exp.setStackTrace("trace");
Assert.assertEquals(exp.getTrace(), "trace");
}
}
private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(
- final ConfigRegistryClient configRegistryClient,
+ final ConfigRegistryClient client,
final Map<String, Map<String, ModuleMXBeanEntry>> mbeanentries) {
Map<String, Map<String, ModuleRuntime>> retVal = new HashMap<>();
Map<RuntimeBeanEntry, InstanceConfig> cache = new HashMap<>();
RuntimeBeanEntry root = null;
for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
- cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap(),
+ cache.put(rbe, new InstanceConfig(client, rbe.getYangPropertiesToTypesMap(),
mbe.getNullableDummyContainerName()));
if (rbe.isRoot()) {
root = rbe;
public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ this(message, null, errorType, errorTag, errorSeverity, Collections.emptyMap());
+ }
+
+ public ConfigHandlingException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ this(message, cause, errorType, errorTag, errorSeverity, Collections.emptyMap());
}
public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message, errorType, errorTag, errorSeverity, errorInfo);
+ this(message, null, errorType, errorTag, errorSeverity, errorInfo);
+ }
+
+ public ConfigHandlingException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
}
}
private AttributeIfc lastAttribute;
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
public T switchAttribute(final AttributeIfc attributeIfc) {
this.lastAttribute = attributeIfc;
abstract AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException;
+ @SuppressWarnings("checkstyle:hiddenField")
protected Object postprocessNullableDefault(final String nullableDefault) {
return nullableDefault;
}
private String key;
private Map<String, Map<Date, IdentityMapping>> identityMap;
+ @SuppressWarnings("checkstyle:hiddenField")
public Map<String, AttributeReadingStrategy> prepareReading(final Map<String, AttributeIfc> yangToAttrConfig,
final Map<String, Map<Date, IdentityMapping>> identityMap) {
Map<String, AttributeReadingStrategy> strategies = Maps.newHashMap();
return strategies;
}
- private AttributeReadingStrategy prepareReadingStrategy(final String key, final AttributeIfc attributeIfc) {
- this.key = key;
+ private AttributeReadingStrategy prepareReadingStrategy(final String attrKey, final AttributeIfc attributeIfc) {
+ this.key = attrKey;
return switchAttribute(attributeIfc);
}
private EnumResolver enumResolver;
+ @SuppressWarnings("checkstyle:hiddenField")
public Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> prepareMapping(
final Map<String, AttributeIfc> configDefinition, final EnumResolver enumResolver) {
this.enumResolver = Preconditions.checkNotNull(enumResolver);
try {
return (Class<?>) innerTypeClass.getField("TYPE").get(null);
} catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) {
- throw new IllegalStateException("Unable to determine primitive type to " + innerTypeClass);
+ throw new IllegalStateException("Unable to determine primitive type to " + innerTypeClass, e);
}
}
this.serviceTracker = serviceTracker;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public Map<String, AttributeResolvingStrategy<?, ? extends OpenType<?>>> prepareResolving(
final Map<String, AttributeIfc> configDefinition, final EnumResolver enumResolver) {
this.enumResolver = enumResolver;
try {
return parseObject(type, value);
} catch (final DocumentedException e) {
- throw new DocumentedException("Unable to resolve attribute " + attrName + " from " + value,
+ throw new DocumentedException("Unable to resolve attribute " + attrName + " from " + value, e,
DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
return method.invoke(null, value);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
LOG.trace("Error parsing object ", e);
- throw new DocumentedException("Error parsing object.", DocumentedException.ErrorType.APPLICATION,
+ throw new DocumentedException("Error parsing object.", e, DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorSeverity.ERROR);
}
}
return Util.readDate(value);
} catch (final ParseException e) {
LOG.trace("Unable parse value {} due to ", value, e);
- throw new DocumentedException("Unable to parse value " + value + " as date.",
+ throw new DocumentedException("Unable to parse value " + value + " as date.", e,
DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
private Document document;
private String key;
+ @SuppressWarnings("checkstyle:hiddenField")
public Map<String, AttributeWritingStrategy> prepareWriting(final Map<String, AttributeIfc> yangToAttrConfig,
final Document document) {
return preparedWriting;
}
+ @SuppressWarnings("checkstyle:hiddenField")
public AttributeWritingStrategy prepareWritingStrategy(final String key, final AttributeIfc expectedAttr,
final Document document) {
Preconditions.checkNotNull(expectedAttr, "Mbean attributes mismatch, unable to find expected attribute for %s",
parentElement.appendChild(innerNode);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected Element createElement(final Document document, final String key, final String value,
final Optional<String> namespace) {
Element typeElement = XmlUtil.createElement(document, key, namespace);
} catch (final DocumentedException e) {
throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : "
+ nameElement.getTextContent() + " - Expected child node with name "
- + nullableDummyContainerName + "." + e.getMessage());
+ + nullableDummyContainerName + "." + e.getMessage(), e);
}
} // else 2 elements, no need to descend
}
} catch (final DocumentedException e) {
throw new DocumentedException(
"Error reading module " + typeElement.getTextContent() + " : " + nameElement.getTextContent()
- + " - " + e.getMessage(),
+ + " - " + e.getMessage(), e,
e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
// TODO: add check for conflicts between global and local edit strategy
private ServiceRegistration<ConfigSubsystemFacadeFactory> osgiRegistrayion;
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void start(final BundleContext context) throws Exception {
LOG.debug("ConfigPersister starting");
this.context = context;
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void stop(final BundleContext context) throws Exception {
if (this.configRegistryLookup != null) {
this.configRegistryLookup.interrupt();
private final YangStoreService yangStoreService;
- private ConfigRegistryLookupThread(final YangStoreService yangStoreService) {
+ ConfigRegistryLookupThread(final YangStoreService yangStoreService) {
super("config-registry-lookup");
this.yangStoreService = yangStoreService;
}
}
}
- final Map<String, Map<String, ModuleMXBeanEntry>> moduleMXBeanEntryMap = Maps.newHashMap();
+ final Map<String, Map<String, ModuleMXBeanEntry>> moduleMXBeanEntries = Maps.newHashMap();
final Map<QName, Map<String /* identity local name */,
ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries = new HashMap<>();
final Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs =
Collections.unmodifiableMap(ModuleMXBeanEntry.create(module, qNamesToSIEs, schemaContext,
typeProviderWrapper, packageName));
- moduleMXBeanEntryMap.put(module.getNamespace().toString(), namesToMBEs);
+ moduleMXBeanEntries.put(module.getNamespace().toString(), namesToMBEs);
qNamesToIdentitiesToModuleMXBeanEntries.put(qName, namesToMBEs);
}
- this.moduleMXBeanEntryMap = Collections.unmodifiableMap(moduleMXBeanEntryMap);
+ this.moduleMXBeanEntryMap = Collections.unmodifiableMap(moduleMXBeanEntries);
this.namesToIdentitiesToModuleMXBeanEntries =
Collections.unmodifiableMap(qNamesToIdentitiesToModuleMXBeanEntries);
}
private static final Logger LOG = LoggerFactory.getLogger(DeleteEditConfigStrategy.class);
@Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
+ void handleMissingInstance(final Map<String, AttributeConfigElement> configuration,
+ final ConfigTransactionClient ta, final String module, final String instance,
+ final ServiceRegistryWrapper services)
+ throws ConfigHandlingException {
throw new ConfigHandlingException(
String.format("Unable to delete %s : %s , ServiceInstance not found", module, instance),
DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on,
- ServiceRegistryWrapper services) throws ConfigHandlingException {
+ void executeStrategy(final Map<String, AttributeConfigElement> configuration, final ConfigTransactionClient ta,
+ final ObjectName on, final ServiceRegistryWrapper services) throws ConfigHandlingException {
try {
ta.destroyModule(on);
LOG.debug("ServiceInstance {} deleted successfully", on);
} catch (InstanceNotFoundException e) {
throw new ConfigHandlingException(
- String.format("Unable to delete %s because of exception %s" + on, e.getMessage()),
+ String.format("Unable to delete %s because of exception %s" + on, e.getMessage()), e,
DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
+ "Error with attribute %s : %s ",
on,
configAttributeEntry.getKey(),
- configAttributeEntry.getValue()),
+ configAttributeEntry.getValue()), e,
DocumentedException.ErrorType.APPLICATION,
DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
LOG.trace("New instance for {} {} created under name {}", module, instance, on);
} catch (InstanceAlreadyExistsException e1) {
throw new ConfigHandlingException(String.format("Unable to create instance for %s : %s.", module, instance),
- DocumentedException.ErrorType.APPLICATION,
- DocumentedException.ErrorTag.OPERATION_FAILED,
+ e1, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
ta.reCreateModule(objectName);
} catch (InstanceNotFoundException e) {
throw new ConfigHandlingException(String.format("Unable to recreate instance for %s", objectName),
- DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
+ e, DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.OPERATION_FAILED,
DocumentedException.ErrorSeverity.ERROR);
}
}
/**
* Commit and notification send must be atomic.
*/
- public synchronized CommitStatus commitTransaction(final ConfigRegistryClient configRegistryClient)
+ public synchronized CommitStatus commitTransaction(final ConfigRegistryClient client)
throws ValidationException, ConflictingVersionException {
if (!getTransaction().isPresent()) {
// making empty commit without prior opened transaction, just return commit
final Optional<ObjectName> maybeTaON = getTransaction();
ObjectName taON = maybeTaON.get();
try {
- CommitStatus status = configRegistryClient.commitConfig(taON);
+ CommitStatus status = client.commitConfig(taON);
// clean up
allOpenedTransactions.remove(candidateTx);
candidateTx = null;
return "DeadlockMonitor{" + transactionIdentifier + '}';
}
- private class DeadlockMonitorRunnable extends Thread {
+ private final class DeadlockMonitorRunnable extends Thread {
- private DeadlockMonitorRunnable() {
+ DeadlockMonitorRunnable() {
super(DeadlockMonitor.this.toString());
}
}
}
- private static class ModuleIdentifierWithNanos {
+ private static final class ModuleIdentifierWithNanos {
private static ModuleIdentifierWithNanos empty = new ModuleIdentifierWithNanos();
@Nullable
private final ModuleIdentifier moduleIdentifier;
private final long nanoTime;
- private ModuleIdentifierWithNanos() {
+ ModuleIdentifierWithNanos() {
this((ModuleIdentifier) null);
}
- private ModuleIdentifierWithNanos(final ModuleIdentifier moduleIdentifier) {
+ ModuleIdentifierWithNanos(final ModuleIdentifier moduleIdentifier) {
this.moduleIdentifier = moduleIdentifier;
nanoTime = System.nanoTime();
}
- private ModuleIdentifierWithNanos(final ModuleIdentifierWithNanos copy) {
+ ModuleIdentifierWithNanos(final ModuleIdentifierWithNanos copy) {
moduleIdentifier = copy.moduleIdentifier;
nanoTime = copy.nanoTime;
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ServiceReferenceRegistryImpl
+public final class ServiceReferenceRegistryImpl
implements CloseableServiceReferenceReadableRegistry, SearchableServiceReferenceWritableRegistry {
private static final Logger LOG = LoggerFactory.getLogger(ServiceReferenceRegistryImpl.class);
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public Object getAttribute(final ObjectName name, final String attribute)
throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
ObjectName newName = translateServiceRefIfPossible(name);
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public <T> T newMXBeanProxy(final ObjectName name, final Class<T> interfaceClass) {
ObjectName newName = translateServiceRefIfPossible(name);
// add transaction name
}
@Override
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
throws Throwable {
boolean isGetInstance = "getInstance".equals(method.getName());
* platform mbean server. Wait until this wrapper gets unregistered, in that
* case unregister the module and remove listener.
*/
- private NotificationListener registerActualModule(final ObjectName objectNameInternal,
+ private NotificationListener registerActualModule(final ObjectName internalObjectName,
final MBeanServer configMBeanServer) {
try {
- internalServer.registerMBean(module, objectNameInternal);
+ internalServer.registerMBean(module, internalObjectName);
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException
| IllegalStateException e) {
- throw new IllegalStateException("Error occured during mbean registration with name " + objectNameInternal,
+ throw new IllegalStateException("Error occured during mbean registration with name " + internalObjectName,
e);
}
- NotificationListener listener = new ModuleNotificationListener(objectNameInternal, internalServer,
+ NotificationListener listener = new ModuleNotificationListener(internalObjectName, internalServer,
configMBeanServer);
try {
configMBeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, listener, null, null);
// inspect all exported interfaces ending with MXBean, extract getters &
// setters into attribute holder
- private Map<String, AttributeHolder> buildMBeanInfo(final boolean writable, final ModuleIdentifier moduleIdentifier,
+ private Map<String, AttributeHolder> buildMBeanInfo(final boolean writable, final ModuleIdentifier modId,
final Set<Class<?>> jmxInterfaces, final ObjectName internalObjectName) {
// internal variables for describing MBean elements
try {
setter = module.getClass().getMethod(method.getName(), method.getParameterTypes());
} catch (final NoSuchMethodException e) {
- throw new RuntimeException("No such method on " + moduleIdentifier, e);
+ throw new RuntimeException("No such method on " + modId, e);
}
RequireInterface ifc = AttributeHolder.findRequireInterfaceAnnotation(setter, jmxInterfaces);
String description = null;
beanServer.unregisterMBean(ConfigJMXNotification.OBJECT_NAME);
} catch (InstanceNotFoundException | MBeanRegistrationException e) {
throw new IllegalStateException(
- "Notifier: " + ConfigJMXNotification.OBJECT_NAME + " not found in JMX when closing");
+ "Notifier: " + ConfigJMXNotification.OBJECT_NAME + " not found in JMX when closing", e);
}
}
private final RefreshingSCPModuleInfoRegistry moduleInfoRegistry;
- private BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> bundleTracker;
+ private BundleTracker<Collection<ObjectRegistration<YangModuleInfo>>> tracker;
private boolean starting;
public ModuleInfoBundleTracker(final RefreshingSCPModuleInfoRegistry moduleInfoRegistry) {
LOG.debug("ModuleInfoBundleTracker open starting with bundleTracker {}", bundleTracker);
if (bundleTracker != null) {
- this.bundleTracker = bundleTracker;
+ this.tracker = bundleTracker;
starting = true;
bundleTracker.open();
@Override
public void close() {
- if (bundleTracker != null) {
- bundleTracker.close();
- bundleTracker = null;
+ if (tracker != null) {
+ tracker.close();
+ tracker = null;
}
}
private class ObjectRegistrationWrapper implements ObjectRegistration<YangModuleInfo> {
private final ObjectRegistration<YangModuleInfo> inner;
- private ObjectRegistrationWrapper(final ObjectRegistration<YangModuleInfo> inner) {
+ ObjectRegistrationWrapper(final ObjectRegistration<YangModuleInfo> inner) {
this.inner = inner;
}
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.LookupRegistry;
-public class LookupBeansUtil {
+public final class LookupBeansUtil {
private LookupBeansUtil() {
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class OsgiRegistrationUtil {
+public final class OsgiRegistrationUtil {
private static final Logger LOG = LoggerFactory.getLogger(OsgiRegistrationUtil.class);
private OsgiRegistrationUtil() {
* jmx proxy which will be wrapped and returned
*/
protected <T> T rethrowCause(final T innerObject) {
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "unchecked", "checkstyle:avoidHidingCauseException" })
final T proxy = (T) Proxy.newProxyInstance(innerObject.getClass().getClassLoader(),
innerObject.getClass().getInterfaces(), (proxy1, method, args) -> {
try {
static class NotExtendingTestingFactory {
}
- static class NoAccessConstructorTestingFactory extends TestingFactory {
+ static final class NoAccessConstructorTestingFactory extends TestingFactory {
private NoAccessConstructorTestingFactory() {
}
}
);
}
+ public DocumentedException(final String message, final Exception cause) {
+ this(message, cause,
+ DocumentedException.ErrorType.APPLICATION,
+ DocumentedException.ErrorTag.INVALID_VALUE,
+ DocumentedException.ErrorSeverity.ERROR
+ );
+ }
+
public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
final ErrorSeverity errorSeverity) {
this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
return createReadRequest(target, sequence, replyTo, snapshotOnly);
}
+ @SuppressWarnings("checkstyle:hiddenField")
abstract T createReadRequest(TransactionIdentifier target, long sequence, ActorRef replyTo, boolean snapshotOnly);
}
message = (T) in.readObject();
}
+ @SuppressWarnings("checkstyle:hiddenField")
abstract Envelope<T> createEnvelope(T wrappedNessage, long sessionId, long txSequence);
final Object readResolve() {
return createEnvelope(message, sessionId, txSequence, executionTimeNanos);
}
+ @SuppressWarnings("checkstyle:hiddenField")
abstract ResponseEnvelope<T> createEnvelope(T message, long sessionId, long txSequence, long executionTimeNanos);
}
protected abstract E createEnvelope();
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract void doAdditionalAssertions(E envelope, E resolvedObject);
}
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
ClientActorBehavior<T> lockedReconnect(final ClientActorBehavior<T> current, final RequestException cause) {
this.cause = Preconditions.checkNotNull(cause);
LOG.warn("Skipping reconnect of already-reconnecting connection {}", this);
/**
* Util class to access package private members in cds-access-client for test purposes.
*/
-public class AccessClientUtil {
+public final class AccessClientUtil {
+ private AccessClientUtil() {
+ throw new UnsupportedOperationException();
+ }
public static ClientActorContext createClientActorContext(final ActorSystem system, final ActorRef actor,
final ClientIdentifier id, final String persistenceId) {
return Props.create(MockedActor.class, () -> new MockedActor(frontendId, initialBehavior));
}
- private MockedActor(final FrontendIdentifier frontendId, final ClientActorBehavior<?> initialBehavior) {
+ MockedActor(final FrontendIdentifier frontendId, final ClientActorBehavior<?> initialBehavior) {
super(frontendId);
this.initialBehavior = initialBehavior;
}
/**
* Matcher checks, whether matched {@link ConnectionEntry} tracks provided {@link Request}.
*/
-class ConnectionEntryMatcher extends BaseMatcher<ConnectionEntry> {
+final class ConnectionEntryMatcher extends BaseMatcher<ConnectionEntry> {
private final Request<?, ?> request;
return child.startsWith(parent.substring(parentOffset), childOffset);
}
+ @SuppressWarnings("checkstyle:hiddenField")
public boolean subtreesOverlap(YangInstanceIdentifier iid, LogicalDatastoreType store,
AsyncDataBroker.DataChangeScope scope) {
if (this.store != null && !this.store.equals(store)) {
}
}
+ @SuppressWarnings("checkstyle:hiddenField")
public boolean eventIsOfInterest(YangInstanceIdentifier iid, LogicalDatastoreType store) {
if (this.store != null && !this.store.equals(store)) {
return false;
* @param matchIndex the initial match index.
* @param context the RaftActorContext.
*/
- public FollowerLogInformationImpl(PeerInfo peerInfo, long matchIndex, RaftActorContext context) {
+ public FollowerLogInformationImpl(final PeerInfo peerInfo, final long matchIndex, final RaftActorContext context) {
this.nextIndex = context.getCommitIndex();
this.matchIndex = matchIndex;
this.context = context;
}
@Override
- public boolean setNextIndex(long nextIndex) {
+ @SuppressWarnings("checkstyle:hiddenField")
+ public boolean setNextIndex(final long nextIndex) {
if (this.nextIndex != nextIndex) {
this.nextIndex = nextIndex;
return true;
}
@Override
- public boolean setMatchIndex(long matchIndex) {
+ @SuppressWarnings("checkstyle:hiddenField")
+ public boolean setMatchIndex(final long matchIndex) {
// If the new match index is the index of the entry currently being sliced, then we know slicing is complete
// and the follower received the entry and responded so clear the slicedLogEntryIndex
if (isLogEntrySlicingInProgress() && slicedLogEntryIndex == matchIndex) {
}
@Override
- public void setPayloadVersion(short payloadVersion) {
+ public void setPayloadVersion(final short payloadVersion) {
this.payloadVersion = payloadVersion;
}
}
@Override
- public void setRaftVersion(short raftVersion) {
+ public void setRaftVersion(final short raftVersion) {
this.raftVersion = raftVersion;
}
}
@Override
- public void setLeaderInstallSnapshotState(@Nonnull LeaderInstallSnapshotState state) {
+ public void setLeaderInstallSnapshotState(@Nonnull final LeaderInstallSnapshotState state) {
if (this.installSnapshotState == null) {
this.installSnapshotState = Preconditions.checkNotNull(state);
}
}
@Override
- public void setSlicedLogEntryIndex(long index) {
+ public void setSlicedLogEntryIndex(final long index) {
slicedLogEntryIndex = index;
}
private final Params params;
- private GetSnapshotReplyActor(Params params) {
+ GetSnapshotReplyActor(final Params params) {
this.params = params;
getContext().setReceiveTimeout(params.receiveTimeout);
}
@Override
- public void onReceive(Object message) {
+ public void onReceive(final Object message) {
if (message instanceof CaptureSnapshotReply) {
Snapshot snapshot = Snapshot.create(
((CaptureSnapshotReply)message).getSnapshotState(),
}
}
- public static Props props(CaptureSnapshot captureSnapshot, ElectionTerm electionTerm, ActorRef replyToActor,
- Duration receiveTimeout, String id, ServerConfigurationPayload updatedPeerInfo) {
+ public static Props props(final CaptureSnapshot captureSnapshot, final ElectionTerm electionTerm,
+ final ActorRef replyToActor, final Duration receiveTimeout, final String id,
+ final ServerConfigurationPayload updatedPeerInfo) {
return Props.create(GetSnapshotReplyActor.class, new Params(captureSnapshot, electionTerm, replyToActor,
receiveTimeout, id, updatedPeerInfo));
}
final String id;
final ServerConfigurationPayload peerInformation;
- Params(CaptureSnapshot captureSnapshot, ElectionTerm electionTerm, ActorRef replyToActor,
- Duration receiveTimeout, String id, ServerConfigurationPayload peerInfo) {
+ Params(final CaptureSnapshot captureSnapshot, final ElectionTerm electionTerm, final ActorRef replyToActor,
+ final Duration receiveTimeout, final String id, final ServerConfigurationPayload peerInfo) {
this.captureSnapshot = Preconditions.checkNotNull(captureSnapshot);
this.electionTerm = Preconditions.checkNotNull(electionTerm);
this.replyToActor = Preconditions.checkNotNull(replyToActor);
*
* @author Thomas Pantelis
*/
-public class ImmutableElectionTerm implements ElectionTerm {
+public final class ImmutableElectionTerm implements ElectionTerm {
private final long currentTerm;
private final String votedFor;
- private ImmutableElectionTerm(long currentTerm, String votedFor) {
+ private ImmutableElectionTerm(final long currentTerm, final String votedFor) {
this.currentTerm = currentTerm;
this.votedFor = votedFor;
}
}
@Override
- public void update(long newTerm, String newVotedFor) {
+ public void update(final long newTerm, final String newVotedFor) {
throw new UnsupportedOperationException();
}
@Override
- public void updateAndPersist(long newTerm, String newVotedFor) {
+ public void updateAndPersist(final long newTerm, final String newVotedFor) {
throw new UnsupportedOperationException();
}
return "ImmutableElectionTerm [currentTerm=" + currentTerm + ", votedFor=" + votedFor + "]";
}
- public static ElectionTerm copyOf(ElectionTerm from) {
+ public static ElectionTerm copyOf(final ElectionTerm from) {
return new ImmutableElectionTerm(from.getCurrentTerm(), from.getVotedFor());
}
}
*
* @param <T> the Procedure type
*/
-public class NoopProcedure<T> implements Procedure<T> {
+public final class NoopProcedure<T> implements Procedure<T> {
private static final NoopProcedure<Object> INSTANCE = new NoopProcedure<>();
}
@Override
- public void apply(Object notUsed) {
+ public void apply(final Object notUsed) {
// nothing to do
}
}
private boolean shuttingDown;
- protected RaftActor(String id, Map<String, String> peerAddresses,
- Optional<ConfigParams> configParams, short payloadVersion) {
+ protected RaftActor(final String id, final Map<String, String> peerAddresses,
+ final Optional<ConfigParams> configParams, final short payloadVersion) {
persistentProvider = new PersistentDataProvider(this);
delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
}
@Override
- protected void handleRecover(Object message) {
+ protected void handleRecover(final Object message) {
if (raftRecovery == null) {
raftRecovery = newRaftActorRecoverySupport();
}
@VisibleForTesting
@SuppressWarnings("checkstyle:IllegalCatch")
- protected void changeCurrentBehavior(RaftActorBehavior newBehavior) {
+ protected void changeCurrentBehavior(final RaftActorBehavior newBehavior) {
final RaftActorBehavior currentBehavior = getCurrentBehavior();
if (currentBehavior != null) {
try {
}
private void initiateLeadershipTransfer(final RaftActorLeadershipTransferCohort.OnComplete onComplete,
- @Nullable final String followerId, long newLeaderTimeoutInMillis) {
+ @Nullable final String followerId, final long newLeaderTimeoutInMillis) {
LOG.debug("{}: Initiating leader transfer", persistenceId());
RaftActorLeadershipTransferCohort leadershipTransferInProgress = context.getRaftActorLeadershipTransferCohort();
leadershipTransferInProgress.setNewLeaderTimeoutInMillis(newLeaderTimeoutInMillis);
leadershipTransferInProgress.addOnComplete(new RaftActorLeadershipTransferCohort.OnComplete() {
@Override
- public void onSuccess(ActorRef raftActorRef) {
+ public void onSuccess(final ActorRef raftActorRef) {
context.setRaftActorLeadershipTransferCohort(null);
}
@Override
- public void onFailure(ActorRef raftActorRef) {
+ public void onFailure(final ActorRef raftActorRef) {
context.setRaftActorLeadershipTransferCohort(null);
}
});
if (context.hasFollowers()) {
initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
@Override
- public void onSuccess(ActorRef raftActorRef) {
+ public void onSuccess(final ActorRef raftActorRef) {
LOG.debug("{}: leader transfer succeeded - sending PoisonPill", persistenceId());
raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
}
@Override
- public void onFailure(ActorRef raftActorRef) {
+ public void onFailure(final ActorRef raftActorRef) {
LOG.debug("{}: leader transfer failed - sending PoisonPill", persistenceId());
raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
}
}
}
- private void switchBehavior(SwitchBehavior message) {
+ private void switchBehavior(final SwitchBehavior message) {
if (!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
RaftState newState = message.getNewState();
if (newState == RaftState.Leader || newState == RaftState.Follower) {
return OnDemandRaftState.builder();
}
- private void handleBehaviorChange(BehaviorState oldBehaviorState, RaftActorBehavior currentBehavior) {
+ private void handleBehaviorChange(final BehaviorState oldBehaviorState, final RaftActorBehavior currentBehavior) {
RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
if (oldBehavior != currentBehavior) {
}
}
- private void handleApplyState(ApplyState applyState) {
+ private void handleApplyState(final ApplyState applyState) {
long startTime = System.nanoTime();
Payload payload = applyState.getReplicatedLogEntry().getData();
self().tell(applyState, self());
}
- protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
+ protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
+ final short leaderPayloadVersion) {
return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
}
}
@VisibleForTesting
- void setCurrentBehavior(RaftActorBehavior behavior) {
+ void setCurrentBehavior(final RaftActorBehavior behavior) {
context.setCurrentBehavior(behavior);
}
return context;
}
- protected void updateConfigParams(ConfigParams configParams) {
+ protected void updateConfigParams(final ConfigParams configParams) {
// obtain the RaftPolicy for oldConfigParams and the updated one.
String oldRaftPolicy = context.getConfigParams().getCustomRaftPolicyImplementationClass();
return delegatingPersistenceProvider.getDelegate();
}
- public void setPersistence(DataPersistenceProvider provider) {
+ public void setPersistence(final DataPersistenceProvider provider) {
delegatingPersistenceProvider.setDelegate(provider);
}
- protected void setPersistence(boolean persistent) {
+ protected void setPersistence(final boolean persistent) {
DataPersistenceProvider currentPersistence = persistence();
if (persistent && (currentPersistence == null || !currentPersistence.isRecoveryApplicable())) {
setPersistence(new PersistentDataProvider(this));
}
} else if (!persistent && (currentPersistence == null || currentPersistence.isRecoveryApplicable())) {
setPersistence(new NonPersistentDataProvider(this) {
- /**
+ /*
* The way snapshotting works is,
* <ol>
* <li> RaftActor calls createSnapshot on the Shard
* </ol>
*/
@Override
- public void saveSnapshot(Object object) {
+ public void saveSnapshot(final Object object) {
// Make saving Snapshot successful
// Committing the snapshot here would end up calling commit in the creating state which would
// be a state violation. That's why now we send a message to commit the snapshot.
* Note that if the peerId does not match the list of peers passed to
* this actor during construction an IllegalStateException will be thrown.
*/
- protected void setPeerAddress(String peerId, String peerAddress) {
+ protected void setPeerAddress(final String peerId, final String peerAddress) {
context.setPeerAddress(peerId, peerAddress);
}
*
* @param operation the operation to run
*/
- protected void pauseLeader(Runnable operation) {
+ protected void pauseLeader(final Runnable operation) {
operation.run();
}
}
- protected void onLeaderChanged(String oldLeader, String newLeader) {
+ protected void onLeaderChanged(final String oldLeader, final String newLeader) {
}
private String getLeaderAddress() {
if (isLeader()) {
initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
@Override
- public void onSuccess(ActorRef raftActorRef) {
+ public void onSuccess(final ActorRef raftActorRef) {
LOG.debug("{}: leader transfer succeeded after change to non-voting", persistenceId());
ensureFollowerState();
}
@Override
- public void onFailure(ActorRef raftActorRef) {
+ public void onFailure(final ActorRef raftActorRef) {
LOG.debug("{}: leader transfer failed after change to non-voting", persistenceId());
ensureFollowerState();
}
private RaftActorLeadershipTransferCohort leadershipTransferCohort;
- public RaftActorContextImpl(ActorRef actor, ActorContext context, String id,
- @Nonnull ElectionTerm termInformation, long commitIndex, long lastApplied,
- @Nonnull Map<String, String> peerAddresses,
- @Nonnull ConfigParams configParams, @Nonnull DataPersistenceProvider persistenceProvider,
- @Nonnull Consumer<ApplyState> applyStateConsumer, @Nonnull Logger logger) {
+ public RaftActorContextImpl(final ActorRef actor, final ActorContext context, final String id,
+ @Nonnull final ElectionTerm termInformation, final long commitIndex, final long lastApplied,
+ @Nonnull final Map<String, String> peerAddresses,
+ @Nonnull final ConfigParams configParams, @Nonnull final DataPersistenceProvider persistenceProvider,
+ @Nonnull final Consumer<ApplyState> applyStateConsumer, @Nonnull final Logger logger) {
this.actor = actor;
this.context = context;
this.id = id;
}
@VisibleForTesting
- public void setPayloadVersion(short payloadVersion) {
+ public void setPayloadVersion(final short payloadVersion) {
this.payloadVersion = payloadVersion;
}
return payloadVersion;
}
- public void setConfigParams(ConfigParams configParams) {
+ public void setConfigParams(final ConfigParams configParams) {
this.configParams = configParams;
}
@Override
- public ActorRef actorOf(Props props) {
+ public ActorRef actorOf(final Props props) {
return context.actorOf(props);
}
@Override
- public ActorSelection actorSelection(String path) {
+ public ActorSelection actorSelection(final String path) {
return context.actorSelection(path);
}
return commitIndex;
}
- @Override public void setCommitIndex(long commitIndex) {
+ @Override public void setCommitIndex(final long commitIndex) {
this.commitIndex = commitIndex;
}
}
@Override
- public void setLastApplied(long lastApplied) {
+ public void setLastApplied(final long lastApplied) {
final Throwable stackTrace = log.isTraceEnabled() ? new Throwable() : null;
log.debug("{}: Moving last applied index from {} to {}", id, this.lastApplied, lastApplied, stackTrace);
this.lastApplied = lastApplied;
}
@Override
- public void setReplicatedLog(ReplicatedLog replicatedLog) {
+ public void setReplicatedLog(final ReplicatedLog replicatedLog) {
this.replicatedLog = replicatedLog;
}
}
@Override
- public PeerInfo getPeerInfo(String peerId) {
+ public PeerInfo getPeerInfo(final String peerId) {
return peerInfoMap.get(peerId);
}
@Override
- public String getPeerAddress(String peerId) {
+ public String getPeerAddress(final String peerId) {
String peerAddress;
PeerInfo peerInfo = peerInfoMap.get(peerId);
if (peerInfo != null) {
}
@Override
- public void updatePeerIds(ServerConfigurationPayload serverConfig) {
+ public void updatePeerIds(final ServerConfigurationPayload serverConfig) {
votingMember = true;
boolean foundSelf = false;
Set<String> currentPeers = new HashSet<>(this.getPeerIds());
}
@Override
- public void addToPeers(String peerId, String address, VotingState votingState) {
+ public void addToPeers(final String peerId, final String address, final VotingState votingState) {
peerInfoMap.put(peerId, new PeerInfo(peerId, address, votingState));
numVotingPeers = -1;
}
@Override
- public void removePeer(String name) {
+ public void removePeer(final String name) {
if (getId().equals(name)) {
votingMember = false;
} else {
}
}
- @Override public ActorSelection getPeerActorSelection(String peerId) {
+ @Override public ActorSelection getPeerActorSelection(final String peerId) {
String peerAddress = getPeerAddress(peerId);
if (peerAddress != null) {
return actorSelection(peerAddress);
}
@Override
- public void setPeerAddress(String peerId, String peerAddress) {
+ public void setPeerAddress(final String peerId, final String peerAddress) {
PeerInfo peerInfo = peerInfoMap.get(peerId);
if (peerInfo != null) {
log.info("Peer address for peer {} set to {}", peerId, peerAddress);
}
@Override
- public void setTotalMemoryRetriever(LongSupplier retriever) {
+ public void setTotalMemoryRetriever(final LongSupplier retriever) {
totalMemoryRetriever = retriever == null ? JVM_MEMORY_RETRIEVER : retriever;
}
}
@Override
- public ServerConfigurationPayload getPeerServerInfo(boolean includeSelf) {
+ public ServerConfigurationPayload getPeerServerInfo(final boolean includeSelf) {
if (!isDynamicServerConfigurationInUse()) {
return null;
}
}
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void setRaftActorLeadershipTransferCohort(
- @Nullable RaftActorLeadershipTransferCohort leadershipTransferCohort) {
+ @Nullable final RaftActorLeadershipTransferCohort leadershipTransferCohort) {
this.leadershipTransferCohort = leadershipTransferCohort;
}
}
private OperationState currentOperationState = IDLE;
- RaftActorServerConfigurationSupport(RaftActor raftActor) {
+ RaftActorServerConfigurationSupport(final RaftActor raftActor) {
this.raftActor = raftActor;
this.raftContext = raftActor.getRaftActorContext();
}
- boolean handleMessage(Object message, ActorRef sender) {
+ boolean handleMessage(final Object message, final ActorRef sender) {
if (message instanceof AddServer) {
onAddServer((AddServer) message, sender);
return true;
}
}
- void onNewLeader(String leaderId) {
+ void onNewLeader(final String leaderId) {
currentOperationState.onNewLeader(leaderId);
}
- private void onChangeServersVotingStatus(ChangeServersVotingStatus message, ActorRef sender) {
+ private void onChangeServersVotingStatus(final ChangeServersVotingStatus message, final ActorRef sender) {
LOG.debug("{}: onChangeServersVotingStatus: {}, state: {}", raftContext.getId(), message,
currentOperationState);
}
}
- private void onRemoveServer(RemoveServer removeServer, ActorRef sender) {
+ private void onRemoveServer(final RemoveServer removeServer, final ActorRef sender) {
LOG.debug("{}: onRemoveServer: {}, state: {}", raftContext.getId(), removeServer, currentOperationState);
boolean isSelf = removeServer.getServerId().equals(raftContext.getId());
if (isSelf && !raftContext.hasFollowers()) {
}
}
- private boolean onApplyState(ApplyState applyState) {
+ private boolean onApplyState(final ApplyState applyState) {
Payload data = applyState.getReplicatedLogEntry().getData();
if (data instanceof ServerConfigurationPayload) {
currentOperationState.onApplyState(applyState);
}
/**
- * The algorithm for AddServer is as follows:
+ * Add a server. The algorithm for AddServer is as follows:
* <ul>
* <li>Add the new server as a peer.</li>
* <li>Add the new follower to the leader.</li>
* <li>Respond to caller with TIMEOUT.</li>
* </ul>
*/
- private void onAddServer(AddServer addServer, ActorRef sender) {
+ private void onAddServer(final AddServer addServer, final ActorRef sender) {
LOG.debug("{}: onAddServer: {}, state: {}", raftContext.getId(), addServer, currentOperationState);
onNewOperation(new AddServerContext(addServer, sender));
}
- private void onNewOperation(ServerOperationContext<?> operationContext) {
+ private void onNewOperation(final ServerOperationContext<?> operationContext) {
if (raftActor.isLeader()) {
currentOperationState.onNewOperation(operationContext);
} else {
* Abstract base class for a server operation FSM state. Handles common behavior for all states.
*/
private abstract class OperationState {
- void onNewOperation(ServerOperationContext<?> operationContext) {
+ void onNewOperation(final ServerOperationContext<?> operationContext) {
// We're currently processing another operation so queue it to be processed later.
LOG.debug("{}: Server operation already in progress - queueing {}", raftContext.getId(),
pendingOperationsQueue.add(operationContext);
}
- void onServerOperationTimeout(ServerOperationTimeout timeout) {
+ void onServerOperationTimeout(final ServerOperationTimeout timeout) {
LOG.debug("onServerOperationTimeout should not be called in state {}", this);
}
- void onUnInitializedFollowerSnapshotReply(UnInitializedFollowerSnapshotReply reply) {
+ void onUnInitializedFollowerSnapshotReply(final UnInitializedFollowerSnapshotReply reply) {
LOG.debug("onUnInitializedFollowerSnapshotReply was called in state {}", this);
}
- void onApplyState(ApplyState applyState) {
+ void onApplyState(final ApplyState applyState) {
LOG.debug("onApplyState was called in state {}", this);
}
}
- void onNewLeader(String newLeader) {
+ void onNewLeader(final String newLeader) {
}
- protected void persistNewServerConfiguration(ServerOperationContext<?> operationContext) {
+ protected void persistNewServerConfiguration(final ServerOperationContext<?> operationContext) {
raftContext.setDynamicServerConfigurationInUse();
ServerConfigurationPayload payload = raftContext.getPeerServerInfo(
sendReply(operationContext, ServerChangeStatus.OK);
}
- protected void operationComplete(ServerOperationContext<?> operationContext,
- @Nullable ServerChangeStatus replyStatus) {
+ protected void operationComplete(final ServerOperationContext<?> operationContext,
+ @Nullable final ServerChangeStatus replyStatus) {
if (replyStatus != null) {
sendReply(operationContext, replyStatus);
}
}
}
- protected void sendReply(ServerOperationContext<?> operationContext, ServerChangeStatus status) {
+ protected void sendReply(final ServerOperationContext<?> operationContext, final ServerChangeStatus status) {
LOG.debug("{}: Returning {} for operation {}", raftContext.getId(), status,
operationContext.getOperation());
raftActor.self());
}
- Cancellable newTimer(Object message) {
+ Cancellable newTimer(final Object message) {
return newTimer(raftContext.getConfigParams().getElectionTimeOutInterval().$times(2), message);
}
- Cancellable newTimer(FiniteDuration timeout, Object message) {
+ Cancellable newTimer(final FiniteDuration timeout, final Object message) {
return raftContext.getActorSystem().scheduler().scheduleOnce(
timeout, raftContext.getActor(), message,
raftContext.getActorSystem().dispatcher(), raftContext.getActor());
*/
private final class Idle extends OperationState {
@Override
- public void onNewOperation(ServerOperationContext<?> operationContext) {
+ public void onNewOperation(final ServerOperationContext<?> operationContext) {
operationContext.newInitialOperationState(RaftActorServerConfigurationSupport.this).initiate();
}
@Override
- public void onApplyState(ApplyState applyState) {
+ public void onApplyState(final ApplyState applyState) {
// Noop - we override b/c ApplyState is called normally for followers in the idle state.
}
}
private final Cancellable timer;
private boolean timedOut = false;
- Persisting(ServerOperationContext<?> operationContext, Cancellable timer) {
+ Persisting(final ServerOperationContext<?> operationContext, final Cancellable timer) {
this.operationContext = operationContext;
this.timer = timer;
}
@Override
- public void onApplyState(ApplyState applyState) {
+ public void onApplyState(final ApplyState applyState) {
// Sanity check - we could get an ApplyState from a previous operation that timed out so make
// sure it's meant for us.
if (operationContext.getContextId().equals(applyState.getIdentifier())) {
}
@Override
- public void onServerOperationTimeout(ServerOperationTimeout timeout) {
+ public void onServerOperationTimeout(final ServerOperationTimeout timeout) {
LOG.warn("{}: Timeout occured while replicating the new server configuration for {}", raftContext.getId(),
timeout.getLoggingContext());
}
@Override
- public void onNewOperation(ServerOperationContext<?> newOperationContext) {
+ public void onNewOperation(final ServerOperationContext<?> newOperationContext) {
if (timedOut) {
sendReply(newOperationContext, ServerChangeStatus.PRIOR_REQUEST_CONSENSUS_TIMEOUT);
} else {
private abstract class AddServerState extends OperationState {
private final AddServerContext addServerContext;
- AddServerState(AddServerContext addServerContext) {
+ AddServerState(final AddServerContext addServerContext) {
this.addServerContext = addServerContext;
}
return newTimer(new ServerOperationTimeout(addServerContext.getOperation().getNewServerId()));
}
- void handleInstallSnapshotTimeout(ServerOperationTimeout timeout) {
+ void handleInstallSnapshotTimeout(final ServerOperationTimeout timeout) {
String serverId = timeout.getLoggingContext();
LOG.debug("{}: handleInstallSnapshotTimeout for new server {}", raftContext.getId(), serverId);
* snapshot capture, if necessary.
*/
private final class InitialAddServerState extends AddServerState implements InitialOperationState {
- InitialAddServerState(AddServerContext addServerContext) {
+ InitialAddServerState(final AddServerContext addServerContext) {
super(addServerContext);
}
private final class InstallingSnapshot extends AddServerState {
private final Cancellable installSnapshotTimer;
- InstallingSnapshot(AddServerContext addServerContext, Cancellable installSnapshotTimer) {
+ InstallingSnapshot(final AddServerContext addServerContext, final Cancellable installSnapshotTimer) {
super(addServerContext);
this.installSnapshotTimer = Preconditions.checkNotNull(installSnapshotTimer);
}
@Override
- public void onServerOperationTimeout(ServerOperationTimeout timeout) {
+ public void onServerOperationTimeout(final ServerOperationTimeout timeout) {
handleInstallSnapshotTimeout(timeout);
LOG.warn("{}: Timeout occured for new server {} while installing snapshot", raftContext.getId(),
}
@Override
- public void onUnInitializedFollowerSnapshotReply(UnInitializedFollowerSnapshotReply reply) {
+ public void onUnInitializedFollowerSnapshotReply(final UnInitializedFollowerSnapshotReply reply) {
LOG.debug("{}: onUnInitializedFollowerSnapshotReply: {}", raftContext.getId(), reply);
String followerId = reply.getFollowerId();
private final class WaitingForPriorSnapshotComplete extends AddServerState {
private final Cancellable snapshotTimer;
- WaitingForPriorSnapshotComplete(AddServerContext addServerContext, Cancellable snapshotTimer) {
+ WaitingForPriorSnapshotComplete(final AddServerContext addServerContext, final Cancellable snapshotTimer) {
super(addServerContext);
this.snapshotTimer = Preconditions.checkNotNull(snapshotTimer);
}
}
@Override
- public void onServerOperationTimeout(ServerOperationTimeout timeout) {
+ public void onServerOperationTimeout(final ServerOperationTimeout timeout) {
handleInstallSnapshotTimeout(timeout);
LOG.warn("{}: Timeout occured for new server {} while waiting for prior snapshot to complete",
private final ActorRef clientRequestor;
private final Identifier contextId;
- ServerOperationContext(T operation, ActorRef clientRequestor) {
+ ServerOperationContext(final T operation, final ActorRef clientRequestor) {
this.operation = operation;
this.clientRequestor = clientRequestor;
contextId = new ServerOperationContextIdentifier();
return clientRequestor;
}
- void operationComplete(RaftActor raftActor, boolean succeeded) {
+ void operationComplete(final RaftActor raftActor, final boolean succeeded) {
}
- boolean includeSelfInNewConfiguration(RaftActor raftActor) {
+ boolean includeSelfInNewConfiguration(final RaftActor raftActor) {
return true;
}
* Stores context information for an AddServer operation.
*/
private static class AddServerContext extends ServerOperationContext<AddServer> {
- AddServerContext(AddServer addServer, ActorRef clientRequestor) {
+ AddServerContext(final AddServer addServer, final ActorRef clientRequestor) {
super(addServer, clientRequestor);
}
@Override
- Object newReply(ServerChangeStatus status, String leaderId) {
+ Object newReply(final ServerChangeStatus status, final String leaderId) {
return new AddServerReply(status, leaderId);
}
@Override
- InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
+ InitialOperationState newInitialOperationState(final RaftActorServerConfigurationSupport support) {
return support.new InitialAddServerState(this);
}
private abstract class RemoveServerState extends OperationState {
private final RemoveServerContext removeServerContext;
- protected RemoveServerState(RemoveServerContext removeServerContext) {
+ protected RemoveServerState(final RemoveServerContext removeServerContext) {
this.removeServerContext = Preconditions.checkNotNull(removeServerContext);
}
private final class InitialRemoveServerState extends RemoveServerState implements InitialOperationState {
- protected InitialRemoveServerState(RemoveServerContext removeServerContext) {
+ protected InitialRemoveServerState(final RemoveServerContext removeServerContext) {
super(removeServerContext);
}
private static class RemoveServerContext extends ServerOperationContext<RemoveServer> {
private final String peerAddress;
- RemoveServerContext(RemoveServer operation, String peerAddress, ActorRef clientRequestor) {
+ RemoveServerContext(final RemoveServer operation, final String peerAddress, final ActorRef clientRequestor) {
super(operation, clientRequestor);
this.peerAddress = peerAddress;
}
@Override
- Object newReply(ServerChangeStatus status, String leaderId) {
+ Object newReply(final ServerChangeStatus status, final String leaderId) {
return new RemoveServerReply(status, leaderId);
}
@Override
- InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
+ InitialOperationState newInitialOperationState(final RaftActorServerConfigurationSupport support) {
return support.new InitialRemoveServerState(this);
}
@Override
- void operationComplete(RaftActor raftActor, boolean succeeded) {
+ void operationComplete(final RaftActor raftActor, final boolean succeeded) {
if (peerAddress != null) {
raftActor.context().actorSelection(peerAddress).tell(
new ServerRemoved(getOperation().getServerId()), raftActor.getSelf());
}
@Override
- boolean includeSelfInNewConfiguration(RaftActor raftActor) {
+ boolean includeSelfInNewConfiguration(final RaftActor raftActor) {
return !getOperation().getServerId().equals(raftActor.getId());
}
private static class ChangeServersVotingStatusContext extends ServerOperationContext<ChangeServersVotingStatus> {
private final boolean tryToElectLeader;
- ChangeServersVotingStatusContext(ChangeServersVotingStatus convertMessage, ActorRef clientRequestor,
- boolean tryToElectLeader) {
+ ChangeServersVotingStatusContext(final ChangeServersVotingStatus convertMessage, final ActorRef clientRequestor,
+ final boolean tryToElectLeader) {
super(convertMessage, clientRequestor);
this.tryToElectLeader = tryToElectLeader;
}
@Override
- InitialOperationState newInitialOperationState(RaftActorServerConfigurationSupport support) {
+ InitialOperationState newInitialOperationState(final RaftActorServerConfigurationSupport support) {
return support.new ChangeServersVotingStatusState(this, tryToElectLeader);
}
@Override
- Object newReply(ServerChangeStatus status, String leaderId) {
+ Object newReply(final ServerChangeStatus status, final String leaderId) {
return new ServerChangeReply(status, leaderId);
}
@Override
- void operationComplete(final RaftActor raftActor, boolean succeeded) {
+ void operationComplete(final RaftActor raftActor, final boolean succeeded) {
// If this leader changed to non-voting we need to step down as leader so we'll try to transfer
// leadership.
boolean localServerChangedToNonVoting = Boolean.FALSE.equals(getOperation()
private final ChangeServersVotingStatusContext changeVotingStatusContext;
private final boolean tryToElectLeader;
- ChangeServersVotingStatusState(ChangeServersVotingStatusContext changeVotingStatusContext,
- boolean tryToElectLeader) {
+ ChangeServersVotingStatusState(final ChangeServersVotingStatusContext changeVotingStatusContext,
+ final boolean tryToElectLeader) {
this.changeVotingStatusContext = changeVotingStatusContext;
this.tryToElectLeader = tryToElectLeader;
}
private final ChangeServersVotingStatusContext operationContext;
private final Cancellable timer;
- WaitingForLeaderElected(ChangeServersVotingStatusContext operationContext,
- ServerConfigurationPayload previousServerConfig) {
+ WaitingForLeaderElected(final ChangeServersVotingStatusContext operationContext,
+ final ServerConfigurationPayload previousServerConfig) {
this.operationContext = operationContext;
this.previousServerConfig = previousServerConfig;
}
@Override
- void onNewLeader(String newLeader) {
+ void onNewLeader(final String newLeader) {
if (newLeader == null) {
return;
}
}
@Override
- void onServerOperationTimeout(ServerOperationTimeout timeout) {
+ void onServerOperationTimeout(final ServerOperationTimeout timeout) {
LOG.warn("{}: Leader election timed out - cannot apply operation {}",
raftContext.getId(), timeout.getLoggingContext());
static class ServerOperationTimeout {
private final String loggingContext;
- ServerOperationTimeout(String loggingContext) {
+ ServerOperationTimeout(final String loggingContext) {
this.loggingContext = Preconditions.checkNotNull(loggingContext, "loggingContext should not be null");
}
/**
* Implementation of ReplicatedLog used by the RaftActor.
*/
-class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
+final class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
private static final int DATA_SIZE_DIVIDER = 5;
private final RaftActorContext context;
}
@Override
- public boolean shouldCaptureSnapshot(long logIndex) {
+ public boolean shouldCaptureSnapshot(final long logIndex) {
final ConfigParams config = context.getConfigParams();
final long journalSize = logIndex + 1;
final long dataThreshold = context.getTotalMemory() * config.getSnapshotDataThresholdPercentage() / 100;
@Override
public boolean appendAndPersist(@Nonnull final ReplicatedLogEntry replicatedLogEntry,
- @Nullable final Procedure<ReplicatedLogEntry> callback, boolean doAsync) {
+ @Nullable final Procedure<ReplicatedLogEntry> callback, final boolean doAsync) {
context.getLogger().debug("{}: Append log entry and persist {} ", context.getId(), replicatedLogEntry);
* @param context the RaftActorContext
* @param logger the Logger
*/
- public SnapshotManager(RaftActorContext context, Logger logger) {
+ public SnapshotManager(final RaftActorContext context, final Logger logger) {
this.context = context;
this.log = logger;
}
}
@Override
- public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
+ public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+ final String targetFollower) {
return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
}
@Override
- public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
+ public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
return currentState.capture(lastLogEntry, replicatedToAllIndex);
}
@Override
- public void apply(ApplySnapshot snapshot) {
+ public void apply(final ApplySnapshot snapshot) {
currentState.apply(snapshot);
}
}
@Override
- public void commit(final long sequenceNumber, long timeStamp) {
+ public void commit(final long sequenceNumber, final long timeStamp) {
currentState.commit(sequenceNumber, timeStamp);
}
return currentState.trimLog(desiredTrimIndex);
}
- void setCreateSnapshotConsumer(Consumer<Optional<OutputStream>> createSnapshotProcedure) {
+ @SuppressWarnings("checkstyle:hiddenField")
+ void setCreateSnapshotConsumer(final Consumer<Optional<OutputStream>> createSnapshotProcedure) {
this.createSnapshotProcedure = createSnapshotProcedure;
}
}
@Nonnull
- public Snapshot.State convertSnapshot(ByteSource snapshotBytes) throws IOException {
+ public Snapshot.State convertSnapshot(final ByteSource snapshotBytes) throws IOException {
return snapshotCohort.deserializeSnapshot(snapshotBytes);
}
* @param replicatedToAllIndex the index of the last entry replicated to all followers.
* @return a new CaptureSnapshot instance.
*/
- public CaptureSnapshot newCaptureSnapshot(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
+ public CaptureSnapshot newCaptureSnapshot(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
TermInformationReader lastAppliedTermInfoReader =
lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
lastLogEntry, hasFollowers());
}
@Override
- public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
+ public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
log.debug("capture should not be called in state {}", this);
return false;
}
@Override
- public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
- String targetFollower) {
+ public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+ final String targetFollower) {
log.debug("captureToInstall should not be called in state {}", this);
return false;
}
@Override
- public void apply(ApplySnapshot snapshot) {
+ public void apply(final ApplySnapshot snapshot) {
log.debug("apply should not be called in state {}", this);
}
}
@Override
- public void commit(final long sequenceNumber, long timeStamp) {
+ public void commit(final long sequenceNumber, final long timeStamp) {
log.debug("commit should not be called in state {}", this);
}
}
@SuppressWarnings("checkstyle:IllegalCatch")
- private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
+ private boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+ final String targetFollower) {
captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex);
OutputStream installSnapshotStream = null;
}
@Override
- public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
+ public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
return capture(lastLogEntry, replicatedToAllIndex, null);
}
@Override
- public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
- String targetFollower) {
+ public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+ final String targetFollower) {
return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
}
@Override
- public void apply(ApplySnapshot toApply) {
+ public void apply(final ApplySnapshot toApply) {
SnapshotManager.this.applySnapshot = toApply;
lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
- public void commit(final long sequenceNumber, long timeStamp) {
+ public void commit(final long sequenceNumber, final long timeStamp) {
log.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
if (applySnapshot != null) {
private long index;
private long term;
- LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex, ReplicatedLogEntry lastLogEntry,
- boolean hasFollowers) {
+ LastAppliedTermInformationReader init(final ReplicatedLog log, final long originalIndex,
+ final ReplicatedLogEntry lastLogEntry, final boolean hasFollowers) {
ReplicatedLogEntry entry = log.get(originalIndex);
this.index = -1L;
this.term = -1L;
private long index;
private long term;
- ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex) {
+ ReplicatedToAllTermInformationReader init(final ReplicatedLog log, final long originalIndex) {
ReplicatedLogEntry entry = log.get(originalIndex);
this.index = -1L;
this.term = -1L;
*
* @author Thomas Pantelis
*/
-public class SnapshotComplete implements ControlMessage {
+public final class SnapshotComplete implements ControlMessage {
public static final SnapshotComplete INSTANCE = new SnapshotComplete();
private SnapshotComplete() {
import scala.concurrent.duration.FiniteDuration;
/**
- * The behavior of a RaftActor when it is in the Leader state
+ * The behavior of a RaftActor when it is in the Leader state.
*
* <p>
* Leaders:
}
@VisibleForTesting
- void setSnapshot(@Nullable final SnapshotHolder snapshotHolder) {
+ void setSnapshotHolder(@Nullable final SnapshotHolder snapshotHolder) {
this.snapshotHolder = Optional.fromNullable(snapshotHolder);
}
scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
} else if (message instanceof SendInstallSnapshot) {
SendInstallSnapshot sendInstallSnapshot = (SendInstallSnapshot) message;
- setSnapshot(new SnapshotHolder(sendInstallSnapshot.getSnapshot(), sendInstallSnapshot.getSnapshotBytes()));
+ setSnapshotHolder(new SnapshotHolder(sendInstallSnapshot.getSnapshot(),
+ sendInstallSnapshot.getSnapshotBytes()));
sendInstallSnapshot();
} else if (message instanceof Replicate) {
replicate((Replicate) message);
if (!anyFollowersInstallingSnapshot()) {
// once there are no pending followers receiving snapshots
// we can remove snapshot from the memory
- setSnapshot(null);
+ setSnapshotHolder(null);
}
wasLastChunk = true;
}
}
- private List<ReplicatedLogEntry> getEntriesToSend(FollowerLogInformation followerLogInfo,
- ActorSelection followerActor) {
+ private List<ReplicatedLogEntry> getEntriesToSend(final FollowerLogInformation followerLogInfo,
+ final ActorSelection followerActor) {
// Try to get all the entries in the journal but not exceeding the max data size for a single AppendEntries
// message.
int maxEntries = (int) context.getReplicatedLog().size();
return Collections.emptyList();
}
- private void sendAppendEntriesToFollower(ActorSelection followerActor, List<ReplicatedLogEntry> entries,
- FollowerLogInformation followerLogInformation) {
+ private void sendAppendEntriesToFollower(final ActorSelection followerActor, final List<ReplicatedLogEntry> entries,
+ final FollowerLogInformation followerLogInformation) {
// In certain cases outlined below we don't want to send the actual commit index to prevent the follower from
// possibly committing and applying conflicting entries (those with same index, different term) from a prior
// term that weren't replicated to a majority, which would be a violation of raft.
*
* @author Thomas Pantelis
*/
-public class GetOnDemandRaftState implements ControlMessage {
+public final class GetOnDemandRaftState implements ControlMessage {
public static final GetOnDemandRaftState INSTANCE = new GetOnDemandRaftState();
private GetOnDemandRaftState() {
*
* @author Thomas Pantelis
*/
-public class EmptyState implements Snapshot.State {
+public final class EmptyState implements Snapshot.State {
private static final long serialVersionUID = 1L;
public static final EmptyState INSTANCE = new EmptyState();
*
* @author Thomas Pantelis
*/
+// Not final for mocking
public class Snapshot implements Serializable {
/**
private final String electionVotedFor;
private final ServerConfigurationPayload serverConfig;
- private Snapshot(State state, List<ReplicatedLogEntry> unAppliedEntries, long lastIndex, long lastTerm,
- long lastAppliedIndex, long lastAppliedTerm, long electionTerm, String electionVotedFor,
- ServerConfigurationPayload serverConfig) {
+ Snapshot(final State state, final List<ReplicatedLogEntry> unAppliedEntries, final long lastIndex,
+ final long lastTerm, final long lastAppliedIndex, final long lastAppliedTerm, final long electionTerm,
+ final String electionVotedFor, final ServerConfigurationPayload serverConfig) {
this.state = state;
this.unAppliedEntries = unAppliedEntries;
this.lastIndex = lastIndex;
this.serverConfig = serverConfig;
}
- public static Snapshot create(State state, List<ReplicatedLogEntry> entries, long lastIndex, long lastTerm,
- long lastAppliedIndex, long lastAppliedTerm, long electionTerm, String electionVotedFor,
- ServerConfigurationPayload serverConfig) {
+ public static Snapshot create(final State state, final List<ReplicatedLogEntry> entries, final long lastIndex,
+ final long lastTerm, final long lastAppliedIndex, final long lastAppliedTerm, final long electionTerm,
+ final String electionVotedFor, final ServerConfigurationPayload serverConfig) {
return new Snapshot(state, entries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm,
electionTerm, electionVotedFor, serverConfig);
}
private static final class MockIdentifier extends AbstractStringIdentifier<MockIdentifier> {
private static final long serialVersionUID = 1L;
- protected MockIdentifier(String string) {
+ protected MockIdentifier(final String string) {
super(string);
}
}
private final String peerId;
private final String peerAddress;
- public SetPeerAddress(String peerId, String peerAddress) {
+ public SetPeerAddress(final String peerId, final String peerAddress) {
this.peerId = peerId;
this.peerAddress = peerAddress;
}
private final ActorRef collectorActor;
private final Map<Class<?>, Predicate<?>> dropMessages = new ConcurrentHashMap<>();
- private TestRaftActor(Builder builder) {
+ TestRaftActor(final Builder builder) {
super(builder);
this.collectorActor = builder.collectorActor;
}
- public void startDropMessages(Class<?> msgClass) {
+ public void startDropMessages(final Class<?> msgClass) {
dropMessages.put(msgClass, msg -> true);
}
- <T> void startDropMessages(Class<T> msgClass, Predicate<T> filter) {
+ <T> void startDropMessages(final Class<T> msgClass, final Predicate<T> filter) {
dropMessages.put(msgClass, filter);
}
- public void stopDropMessages(Class<?> msgClass) {
+ public void stopDropMessages(final Class<?> msgClass) {
dropMessages.remove(msgClass);
}
@SuppressWarnings({ "rawtypes", "unchecked", "checkstyle:IllegalCatch" })
@Override
- public void handleCommand(Object message) {
+ public void handleCommand(final Object message) {
if (message instanceof MockPayload) {
MockPayload payload = (MockPayload) message;
super.persistData(collectorActor, new MockIdentifier(payload.toString()), payload, false);
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
- public void createSnapshot(ActorRef actorRef, Optional<OutputStream> installSnapshotStream) {
+ public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) {
MockSnapshotState snapshotState = new MockSnapshotState(new ArrayList<>(getState()));
if (installSnapshotStream.isPresent()) {
SerializationUtils.serialize(snapshotState, installSnapshotStream.get());
public static class Builder extends AbstractBuilder<Builder, TestRaftActor> {
private ActorRef collectorActor;
- public Builder collectorActor(ActorRef newCollectorActor) {
- this.collectorActor = newCollectorActor;
- return this;
+ Builder() {
+ super(TestRaftActor.class);
}
- private Builder() {
- super(TestRaftActor.class);
+ public Builder collectorActor(final ActorRef newCollectorActor) {
+ this.collectorActor = newCollectorActor;
+ return this;
}
}
}
return configParams;
}
- protected void waitUntilLeader(ActorRef actorRef) {
+ protected void waitUntilLeader(final ActorRef actorRef) {
RaftActorTestKit.waitUntilLeader(actorRef);
}
- protected TestActorRef<TestRaftActor> newTestRaftActor(String id, Map<String, String> newPeerAddresses,
- ConfigParams configParams) {
+ protected TestActorRef<TestRaftActor> newTestRaftActor(final String id, final Map<String, String> newPeerAddresses,
+ final ConfigParams configParams) {
return newTestRaftActor(id, TestRaftActor.newBuilder().peerAddresses(newPeerAddresses != null
? newPeerAddresses : Collections.<String, String>emptyMap()).config(configParams));
}
- protected TestActorRef<TestRaftActor> newTestRaftActor(String id, TestRaftActor.Builder builder) {
+ protected TestActorRef<TestRaftActor> newTestRaftActor(final String id, final TestRaftActor.Builder builder) {
builder.collectorActor(factory.createActor(
MessageCollectorActor.props(), factory.generateActorId(id + "-collector"))).id(id);
throw lastEx;
}
- protected void killActor(TestActorRef<TestRaftActor> actor) {
+ protected void killActor(final TestActorRef<TestRaftActor> actor) {
JavaTestKit testkit = new JavaTestKit(getSystem());
testkit.watch(actor);
testkit.unwatch(actor);
}
- protected void verifyApplyJournalEntries(ActorRef actor, final long expIndex) {
+ protected void verifyApplyJournalEntries(final ActorRef actor, final long expIndex) {
MessageCollectorActor.expectFirstMatching(actor, ApplyJournalEntries.class,
msg -> msg.getToIndex() == expIndex);
}
- protected void verifySnapshot(String prefix, Snapshot snapshot, long lastAppliedTerm,
- long lastAppliedIndex, long lastTerm, long lastIndex)
+ protected void verifySnapshot(final String prefix, final Snapshot snapshot, final long lastAppliedTerm,
+ final long lastAppliedIndex, final long lastTerm, final long lastIndex)
throws Exception {
assertEquals(prefix + " Snapshot getLastAppliedTerm", lastAppliedTerm, snapshot.getLastAppliedTerm());
assertEquals(prefix + " Snapshot getLastAppliedIndex", lastAppliedIndex, snapshot.getLastAppliedIndex());
}
}
- protected void verifyPersistedJournal(String persistenceId, List<? extends ReplicatedLogEntry> expJournal) {
+ protected void verifyPersistedJournal(final String persistenceId,
+ final List<? extends ReplicatedLogEntry> expJournal) {
List<ReplicatedLogEntry> journal = InMemoryJournal.get(persistenceId, ReplicatedLogEntry.class);
assertEquals("Journal ReplicatedLogEntry count", expJournal.size(), journal.size());
for (int i = 0; i < expJournal.size(); i++) {
}
}
- protected MockPayload sendPayloadData(ActorRef actor, String data) {
+ protected MockPayload sendPayloadData(final ActorRef actor, final String data) {
return sendPayloadData(actor, data, 0);
}
- protected MockPayload sendPayloadData(ActorRef actor, String data, int size) {
+ protected MockPayload sendPayloadData(final ActorRef actor, final String data, final int size) {
MockPayload payload;
if (size > 0) {
payload = new MockPayload(data, size);
return payload;
}
- protected void verifyApplyState(ApplyState applyState, ActorRef expClientActor,
- String expId, long expTerm, long expIndex, Payload payload) {
+ protected void verifyApplyState(final ApplyState applyState, final ActorRef expClientActor,
+ final String expId, final long expTerm, final long expIndex, final Payload payload) {
assertEquals("ApplyState getClientActor", expClientActor, applyState.getClientActor());
final Identifier id = expId == null ? null : new MockIdentifier(expId);
verifyReplicatedLogEntry(replicatedLogEntry, expTerm, expIndex, payload);
}
- protected void verifyReplicatedLogEntry(ReplicatedLogEntry replicatedLogEntry, long expTerm, long expIndex,
- Payload payload) {
+ protected void verifyReplicatedLogEntry(final ReplicatedLogEntry replicatedLogEntry, final long expTerm,
+ final long expIndex, final Payload payload) {
assertEquals("ReplicatedLogEntry getTerm", expTerm, replicatedLogEntry.getTerm());
assertEquals("ReplicatedLogEntry getIndex", expIndex, replicatedLogEntry.getIndex());
assertEquals("ReplicatedLogEntry getData", payload, replicatedLogEntry.getData());
}
- protected String testActorPath(String id) {
+ protected String testActorPath(final String id) {
return factory.createTestActorPath(id);
}
- protected void verifyLeadersTrimmedLog(long lastIndex) {
+ protected void verifyLeadersTrimmedLog(final long lastIndex) {
verifyTrimmedLog("Leader", leaderActor, lastIndex, lastIndex - 1);
}
- protected void verifyLeadersTrimmedLog(long lastIndex, long replicatedToAllIndex) {
+ protected void verifyLeadersTrimmedLog(final long lastIndex, final long replicatedToAllIndex) {
verifyTrimmedLog("Leader", leaderActor, lastIndex, replicatedToAllIndex);
}
- protected void verifyFollowersTrimmedLog(int num, TestActorRef<TestRaftActor> actorRef, long lastIndex) {
+ protected void verifyFollowersTrimmedLog(final int num, final TestActorRef<TestRaftActor> actorRef,
+ final long lastIndex) {
verifyTrimmedLog("Follower " + num, actorRef, lastIndex, lastIndex - 1);
}
- protected void verifyTrimmedLog(String name, TestActorRef<TestRaftActor> actorRef, long lastIndex,
- long replicatedToAllIndex) {
+ protected void verifyTrimmedLog(final String name, final TestActorRef<TestRaftActor> actorRef, final long lastIndex,
+ final long replicatedToAllIndex) {
TestRaftActor actor = actorRef.underlyingActor();
RaftActorContext context = actor.getRaftActorContext();
long snapshotIndex = lastIndex - 1;
}
@SuppressWarnings("checkstyle:IllegalCatch")
- static void verifyRaftState(ActorRef raftActor, Consumer<OnDemandRaftState> verifier) {
+ static void verifyRaftState(final ActorRef raftActor, final Consumer<OnDemandRaftState> verifier) {
Timeout timeout = new Timeout(500, TimeUnit.MILLISECONDS);
AssertionError lastError = null;
Stopwatch sw = Stopwatch.createStarted();
}
public static class Builder extends AbstractBuilder<Builder, MockRaftActor> {
- private Builder() {
+ Builder() {
super(MockRaftActor.class);
}
}
}
}
- static class SendImmediateHeartBeat implements ControlMessage {
- public static final SendImmediateHeartBeat INSTANCE = new SendImmediateHeartBeat();
+ static final class SendImmediateHeartBeat implements ControlMessage {
+ static final SendImmediateHeartBeat INSTANCE = new SendImmediateHeartBeat();
private SendImmediateHeartBeat() {
}
}
- static class GetBehaviorState implements ControlMessage {
- public static final GetBehaviorState INSTANCE = new GetBehaviorState();
+ static final class GetBehaviorState implements ControlMessage {
+ static final GetBehaviorState INSTANCE = new GetBehaviorState();
private GetBehaviorState() {
}
leader.markFollowerActive(FOLLOWER_ID);
ByteString bs = toByteString(leadersSnapshot);
- leader.setSnapshot(new SnapshotHolder(Snapshot.create(ByteState.of(bs.toByteArray()),
+ leader.setSnapshotHolder(new SnapshotHolder(Snapshot.create(ByteState.of(bs.toByteArray()),
Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
-1, null, null), ByteSource.wrap(bs.toByteArray())));
LeaderInstallSnapshotState fts = new LeaderInstallSnapshotState(
MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
// set the snapshot as absent and check if capture-snapshot is invoked.
- leader.setSnapshot(null);
+ leader.setSnapshotHolder(null);
// new entry
SimpleReplicatedLogEntry entry = new SimpleReplicatedLogEntry(newEntryIndex, currentTerm,
MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
// set the snapshot as absent and check if capture-snapshot is invoked.
- leader.setSnapshot(null);
+ leader.setSnapshotHolder(null);
for (int i = 0; i < 4; i++) {
actorContext.getReplicatedLog().append(new SimpleReplicatedLogEntry(i, 1,
actorContext.getTermInformation().update(currentTerm, leaderActor.path().toString());
ByteString bs = toByteString(leadersSnapshot);
- leader.setSnapshot(new SnapshotHolder(Snapshot.create(ByteState.of(bs.toByteArray()),
+ leader.setSnapshotHolder(new SnapshotHolder(Snapshot.create(ByteState.of(bs.toByteArray()),
Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
-1, null, null), ByteSource.wrap(bs.toByteArray())));
LeaderInstallSnapshotState fts = new LeaderInstallSnapshotState(
*
* @author Thomas Pantelis
*/
-public class ByteState implements Snapshot.State {
+public final class ByteState implements Snapshot.State {
private static final long serialVersionUID = 1L;
private final byte[] bytes;
- private ByteState(@Nonnull byte[] bytes) {
+ private ByteState(@Nonnull final byte[] bytes) {
this.bytes = Preconditions.checkNotNull(bytes);
}
- public static ByteState of(@Nonnull byte[] bytes) {
+ public static ByteState of(@Nonnull final byte[] bytes) {
return new ByteState(bytes);
}
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
private static final Map<String, CountDownLatch> SNAPSHOT_DELETED_LATCHES = new ConcurrentHashMap<>();
private static Map<String, List<StoredSnapshot>> snapshots = new ConcurrentHashMap<>();
- public static void addSnapshot(String persistentId, Object snapshot) {
+ public static void addSnapshot(final String persistentId, final Object snapshot) {
List<StoredSnapshot> snapshotList = snapshots.computeIfAbsent(persistentId, k -> new ArrayList<>());
synchronized (snapshotList) {
}
@SuppressWarnings("unchecked")
- public static <T> List<T> getSnapshots(String persistentId, Class<T> type) {
+ public static <T> List<T> getSnapshots(final String persistentId, final Class<T> type) {
List<StoredSnapshot> stored = snapshots.get(persistentId);
if (stored == null) {
return Collections.emptyList();
snapshots.clear();
}
- public static void addSnapshotSavedLatch(String persistenceId) {
+ public static void addSnapshotSavedLatch(final String persistenceId) {
SNAPSHOT_SAVED_LATCHES.put(persistenceId, new CountDownLatch(1));
}
- public static void addSnapshotDeletedLatch(String persistenceId) {
+ public static void addSnapshotDeletedLatch(final String persistenceId) {
SNAPSHOT_DELETED_LATCHES.put(persistenceId, new CountDownLatch(1));
}
- public static <T> T waitForSavedSnapshot(String persistenceId, Class<T> type) {
+ public static <T> T waitForSavedSnapshot(final String persistenceId, final Class<T> type) {
if (!Uninterruptibles.awaitUninterruptibly(SNAPSHOT_SAVED_LATCHES.get(persistenceId), 5, TimeUnit.SECONDS)) {
throw new AssertionError("Snapshot was not saved");
}
return getSnapshots(persistenceId, type).get(0);
}
- public static void waitForDeletedSnapshot(String persistenceId) {
+ public static void waitForDeletedSnapshot(final String persistenceId) {
if (!Uninterruptibles.awaitUninterruptibly(SNAPSHOT_DELETED_LATCHES.get(persistenceId), 5, TimeUnit.SECONDS)) {
throw new AssertionError("Snapshot was not deleted");
}
}
@Override
- public Future<Optional<SelectedSnapshot>> doLoadAsync(String persistenceId,
- SnapshotSelectionCriteria snapshotSelectionCriteria) {
+ public Future<Optional<SelectedSnapshot>> doLoadAsync(final String persistenceId,
+ final SnapshotSelectionCriteria snapshotSelectionCriteria) {
List<StoredSnapshot> snapshotList = snapshots.get(persistenceId);
if (snapshotList == null) {
return Futures.successful(Optional.<SelectedSnapshot>empty());
return Futures.successful(Optional.<SelectedSnapshot>empty());
}
- private static boolean matches(StoredSnapshot snapshot, SnapshotSelectionCriteria criteria) {
+ private static boolean matches(final StoredSnapshot snapshot, final SnapshotSelectionCriteria criteria) {
return snapshot.metadata.sequenceNr() <= criteria.maxSequenceNr()
&& snapshot.metadata.timestamp() <= criteria.maxTimestamp();
}
@Override
- public Future<Void> doSaveAsync(SnapshotMetadata snapshotMetadata, Object obj) {
+ public Future<Void> doSaveAsync(final SnapshotMetadata snapshotMetadata, final Object obj) {
List<StoredSnapshot> snapshotList = snapshots.get(snapshotMetadata.persistenceId());
LOG.trace("doSaveAsync: persistentId {}: sequenceNr: {}: timestamp {}: {}", snapshotMetadata.persistenceId(),
}
@Override
- public Future<Void> doDeleteAsync(SnapshotMetadata metadata) {
+ public Future<Void> doDeleteAsync(final SnapshotMetadata metadata) {
List<StoredSnapshot> snapshotList = snapshots.get(metadata.persistenceId());
if (snapshotList != null) {
}
@Override
- public Future<Void> doDeleteAsync(String persistenceId, SnapshotSelectionCriteria criteria) {
+ public Future<Void> doDeleteAsync(final String persistenceId, final SnapshotSelectionCriteria criteria) {
LOG.trace("doDelete: persistentId {}: maxSequenceNr: {}: maxTimestamp {}", persistenceId,
criteria.maxSequenceNr(), criteria.maxTimestamp());
return Futures.successful(null);
}
- private static class StoredSnapshot {
+ private static final class StoredSnapshot {
private final SnapshotMetadata metadata;
private final Object data;
- private StoredSnapshot(SnapshotMetadata metadata, Object data) {
+ StoredSnapshot(final SnapshotMetadata metadata, final Object data) {
this.metadata = metadata;
this.data = data;
}
private final String path;
- DispatcherType(String path) {
+ DispatcherType(final String path) {
this.path = path;
}
- private String path(akka.dispatch.Dispatchers dispatchers) {
- if (dispatchers.hasDispatcher(path)) {
+ String path(final akka.dispatch.Dispatchers knownDispatchers) {
+ if (knownDispatchers.hasDispatcher(path)) {
return path;
}
return DEFAULT_DISPATCHER_PATH;
}
- private ExecutionContext dispatcher(akka.dispatch.Dispatchers dispatchers) {
- if (dispatchers.hasDispatcher(path)) {
- return dispatchers.lookup(path);
+ ExecutionContext dispatcher(final akka.dispatch.Dispatchers knownDispatchers) {
+ if (knownDispatchers.hasDispatcher(path)) {
+ return knownDispatchers.lookup(path);
}
- return dispatchers.defaultGlobalDispatcher();
+ return knownDispatchers.defaultGlobalDispatcher();
}
}
- public Dispatchers(akka.dispatch.Dispatchers dispatchers) {
+ public Dispatchers(final akka.dispatch.Dispatchers dispatchers) {
Preconditions.checkNotNull(dispatchers, "dispatchers should not be null");
this.dispatchers = dispatchers;
}
- public ExecutionContext getDispatcher(DispatcherType dispatcherType) {
+ public ExecutionContext getDispatcher(final DispatcherType dispatcherType) {
return dispatcherType.dispatcher(this.dispatchers);
}
- public String getDispatcherPath(DispatcherType dispatcherType) {
+ public String getDispatcherPath(final DispatcherType dispatcherType) {
return dispatcherType.path(this.dispatchers);
}
}
* @author Thomas Pantelis
* @see MessageSlicer
*/
-public class MessageAssembler implements AutoCloseable {
+public final class MessageAssembler implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(MessageAssembler.class);
private final Cache<Identifier, AssembledMessageState> stateCache;
private final BiConsumer<Object, ActorRef> assembledMessageCallback;
private final String logContext;
- private MessageAssembler(final Builder builder) {
+ MessageAssembler(final Builder builder) {
this.fileBackedStreamFactory = Preconditions.checkNotNull(builder.fileBackedStreamFactory,
"FiledBackedStreamFactory cannot be null");
this.assembledMessageCallback = Preconditions.checkNotNull(builder.assembledMessageCallback,
*
* @author Thomas Pantelis
*/
-public class MessageSliceReply implements Serializable {
+public final class MessageSliceReply implements Serializable {
private static final long serialVersionUID = 1L;
private final Identifier identifier;
public Proxy() {
}
- Proxy(MessageSliceReply messageSliceReply) {
+ Proxy(final MessageSliceReply messageSliceReply) {
this.messageSliceReply = messageSliceReply;
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
out.writeObject(messageSliceReply.identifier);
out.writeInt(messageSliceReply.sliceIndex);
out.writeObject(messageSliceReply.failure);
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
final Identifier identifier = (Identifier) in.readObject();
final int sliceIndex = in.readInt();
final MessageSliceException failure = (MessageSliceException) in.readObject();
private final String logContext;
private final long id;
- private MessageSlicer(final Builder builder) {
+ MessageSlicer(final Builder builder) {
this.fileBackedStreamFactory = builder.fileBackedStreamFactory;
this.messageSliceSize = builder.messageSliceSize;
this.maxSlicingTries = builder.maxSlicingTries;
*
* @author Thomas Pantelis
*/
-public class SliceOptions {
+public final class SliceOptions {
private final Builder builder;
- private SliceOptions(Builder builder) {
+ private SliceOptions(final Builder builder) {
this.builder = builder;
}
private final JmxReporter jmxReporter;
private final MetricRegistry metricRegistry = new MetricRegistry();
- private MetricsReporter(final String domainName) {
+ MetricsReporter(final String domainName) {
this.domainName = domainName;
jmxReporter = JmxReporter.forRegistry(metricRegistry).inDomain(domainName).build();
jmxReporter.start();
ReentrantLock lock;
- private PingPongActor(final ReentrantLock lock) {
+ PingPongActor(final ReentrantLock lock) {
this.lock = lock;
}
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-public class TestModel {
+public final class TestModel {
public static final QName TEST_QNAME = QName.create(
"urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test",
private static final String DATASTORE_AUG_YANG = "/odl-datastore-augmentation.yang";
private static final String DATASTORE_TEST_NOTIFICATION_YANG = "/odl-datastore-test-notification.yang";
-
public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_QNAME);
public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier
.builder(TEST_PATH).node(DESC_QNAME).build();
.build()) //
.build();
- public static final InputStream getDatastoreTestInputStream() {
+ private TestModel() {
+ throw new UnsupportedOperationException();
+ }
+
+ public static InputStream getDatastoreTestInputStream() {
return getInputStream(DATASTORE_TEST_YANG);
}
- public static final InputStream getDatastoreAugInputStream() {
+ public static InputStream getDatastoreAugInputStream() {
return getInputStream(DATASTORE_AUG_YANG);
}
- public static final InputStream getDatastoreTestNotificationInputStream() {
+ public static InputStream getDatastoreTestNotificationInputStream() {
return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG);
}
JavaTestKit.shutdownActorSystem(ACTOR_SYSTEM, Boolean.TRUE);
}
- void setupMockFiledBackedStream(final FileBackedOutputStream mockFiledBackedStream) throws IOException {
- doNothing().when(mockFiledBackedStream).write(any(byte[].class), anyInt(), anyInt());
- doNothing().when(mockFiledBackedStream).write(any(byte[].class));
- doNothing().when(mockFiledBackedStream).write(anyInt());
- doNothing().when(mockFiledBackedStream).close();
- doNothing().when(mockFiledBackedStream).cleanup();
- doNothing().when(mockFiledBackedStream).flush();
- doReturn(mockByteSource).when(mockFiledBackedStream).asByteSource();
+ void setupMockFiledBackedStream(final FileBackedOutputStream mockOutputStream) throws IOException {
+ doNothing().when(mockOutputStream).write(any(byte[].class), anyInt(), anyInt());
+ doNothing().when(mockOutputStream).write(any(byte[].class));
+ doNothing().when(mockOutputStream).write(anyInt());
+ doNothing().when(mockOutputStream).close();
+ doNothing().when(mockOutputStream).cleanup();
+ doNothing().when(mockOutputStream).flush();
+ doReturn(mockByteSource).when(mockOutputStream).asByteSource();
}
}
return Verify.verifyNotNull(initialBehavior(context, actorContext));
}
+ @SuppressWarnings("checkstyle:hiddenField")
abstract AbstractDataStoreClientBehavior initialBehavior(ClientActorContext context, ActorContext actorContext);
@SuppressWarnings("checkstyle:IllegalCatch")
return result;
}
- private synchronized void onStageResolved(final ShardBackendInfo result, final Throwable failure) {
+ private synchronized void onStageResolved(final ShardBackendInfo info, final Throwable failure) {
if (failure == null) {
- this.result = Preconditions.checkNotNull(result);
+ this.result = Preconditions.checkNotNull(info);
} else {
LOG.warn("Failed to resolve shard", failure);
}
return parent().onTransactionReady(this, cohort);
}
- void closeCursor(@Nonnull final DOMDataTreeCursor cursor) {
- if (cursor.equals(this.cursor)) {
+ void closeCursor(@Nonnull final DOMDataTreeCursor cursorToClose) {
+ if (cursorToClose.equals(this.cursor)) {
this.cursor = null;
}
}
}
@GuardedBy("lock")
+ @SuppressWarnings("checkstyle:hiddenField")
abstract AbstractProxyTransaction doCreateTransactionProxy(AbstractClientConnection<ShardBackendInfo> connection,
TransactionIdentifier txId, boolean snapshotOnly, boolean isDone);
+ @SuppressWarnings("checkstyle:hiddenField")
abstract ProxyHistory createSuccessor(AbstractClientConnection<ShardBackendInfo> connection);
@SuppressFBWarnings(value = "UL_UNRELEASED_LOCK", justification = "Lock is released asynchronously via the cohort")
import scala.concurrent.Future;
/**
- * ListenerRegistrationProxy acts as a proxy for a ListenerRegistration that was done on a remote shard
+ * ListenerRegistrationProxy acts as a proxy for a ListenerRegistration that was done on a remote shard.
+ *
* <p>
* Registering a DataChangeListener on the Data Store creates a new instance of the ListenerRegistrationProxy
* The ListenerRegistrationProxy talks to a remote ListenerRegistration actor.
- * </p>
*/
@SuppressWarnings("rawtypes")
public class DataChangeListenerRegistrationProxy implements ListenerRegistration {
private boolean closed = false;
public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
- DataChangeListenerRegistrationProxy(String shardName, ActorContext actorContext, L listener) {
+ DataChangeListenerRegistrationProxy(final String shardName, final ActorContext actorContext,
+ final L listener) {
this.shardName = Preconditions.checkNotNull(shardName);
this.actorContext = Preconditions.checkNotNull(actorContext);
this.listener = Preconditions.checkNotNull(listener);
return listener;
}
- private void setListenerRegistrationActor(ActorSelection listenerRegistrationActor) {
+ private void setListenerRegistrationActor(final ActorSelection listenerRegistrationActor) {
if (listenerRegistrationActor == null) {
return;
}
Future<ActorRef> findFuture = actorContext.findLocalShardAsync(shardName);
findFuture.onComplete(new OnComplete<ActorRef>() {
@Override
- public void onComplete(Throwable failure, ActorRef shard) {
+ public void onComplete(final Throwable failure, final ActorRef shard) {
if (failure instanceof LocalShardNotFoundException) {
LOG.debug("No local shard found for {} - DataChangeListener {} at path {} "
+ "cannot be registered", shardName, listener, path);
}, actorContext.getClientDispatcher());
}
- private void doRegistration(ActorRef shard, final YangInstanceIdentifier path,
- DataChangeScope scope) {
+ private void doRegistration(final ActorRef shard, final YangInstanceIdentifier path,
+ final DataChangeScope scope) {
Future<Object> future = actorContext.executeOperationAsync(shard,
new RegisterChangeListener(path, dataChangeListenerActor, scope,
future.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(Throwable failure, Object result) {
+ public void onComplete(final Throwable failure, final Object result) {
if (failure != null) {
LOG.error("Failed to register DataChangeListener {} at path {}",
listener, path.toString(), failure);
*
* @author Thomas Pantelis
*/
+// Noo-final for mocking
public class DatastoreContext implements ClientActorConfig {
public static final String METRICS_DOMAIN = "org.opendaylight.controller.cluster.datastore";
return GLOBAL_DATASTORE_NAMES;
}
- private DatastoreContext() {
+ DatastoreContext() {
setShardJournalRecoveryLogBatchSize(DEFAULT_JOURNAL_RECOVERY_BATCH_SIZE);
setSnapshotBatchCount(DEFAULT_SNAPSHOT_BATCH_COUNT);
setHeartbeatInterval(DEFAULT_HEARTBEAT_INTERVAL_IN_MILLIS);
private int maxShardDataStoreExecutorQueueSize =
InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_STORE_EXECUTOR_QUEUE_SIZE;
- private Builder(final DatastoreContext datastoreContext) {
+ Builder(final DatastoreContext datastoreContext) {
this.datastoreContext = datastoreContext;
if (datastoreContext.getDataStoreProperties() != null) {
return this;
}
- public Builder maxShardDataChangeExecutorPoolSize(final int maxShardDataChangeExecutorPoolSize) {
- this.maxShardDataChangeExecutorPoolSize = maxShardDataChangeExecutorPoolSize;
+ public Builder maxShardDataChangeExecutorPoolSize(final int newMaxShardDataChangeExecutorPoolSize) {
+ this.maxShardDataChangeExecutorPoolSize = newMaxShardDataChangeExecutorPoolSize;
return this;
}
- public Builder maxShardDataChangeExecutorQueueSize(final int maxShardDataChangeExecutorQueueSize) {
- this.maxShardDataChangeExecutorQueueSize = maxShardDataChangeExecutorQueueSize;
+ public Builder maxShardDataChangeExecutorQueueSize(final int newMaxShardDataChangeExecutorQueueSize) {
+ this.maxShardDataChangeExecutorQueueSize = newMaxShardDataChangeExecutorQueueSize;
return this;
}
- public Builder maxShardDataChangeListenerQueueSize(final int maxShardDataChangeListenerQueueSize) {
- this.maxShardDataChangeListenerQueueSize = maxShardDataChangeListenerQueueSize;
+ public Builder maxShardDataChangeListenerQueueSize(final int newMaxShardDataChangeListenerQueueSize) {
+ this.maxShardDataChangeListenerQueueSize = newMaxShardDataChangeListenerQueueSize;
return this;
}
- public Builder maxShardDataStoreExecutorQueueSize(final int maxShardDataStoreExecutorQueueSize) {
- this.maxShardDataStoreExecutorQueueSize = maxShardDataStoreExecutorQueueSize;
+ public Builder maxShardDataStoreExecutorQueueSize(final int newMaxShardDataStoreExecutorQueueSize) {
+ this.maxShardDataStoreExecutorQueueSize = newMaxShardDataStoreExecutorQueueSize;
return this;
}
*
* @author Thomas Pantelis
*/
-public class DatastoreSnapshotRestore {
+public final class DatastoreSnapshotRestore {
private static final Logger LOG = LoggerFactory.getLogger(DatastoreSnapshotRestore.class);
private static AtomicReference<DatastoreSnapshotRestore> instance = new AtomicReference<>();
private final String restoreDirectoryPath;
private final Map<String, DatastoreSnapshot> datastoreSnapshots = new ConcurrentHashMap<>();
- public static DatastoreSnapshotRestore instance(String restoreDirectoryPath) {
+ public static DatastoreSnapshotRestore instance(final String restoreDirectoryPath) {
instance.compareAndSet(null, new DatastoreSnapshotRestore(restoreDirectoryPath));
return instance.get();
}
- private DatastoreSnapshotRestore(String restoreDirectoryPath) {
+ private DatastoreSnapshotRestore(final String restoreDirectoryPath) {
this.restoreDirectoryPath = Preconditions.checkNotNull(restoreDirectoryPath);
}
}
}
- private static DatastoreSnapshotList deserialize(InputStream inputStream)
+ private static DatastoreSnapshotList deserialize(final InputStream inputStream)
throws IOException, ClassNotFoundException {
try (ObjectInputStream ois = new ObjectInputStream(inputStream)) {
return (DatastoreSnapshotList) ois.readObject();
}
}
- public DatastoreSnapshot getAndRemove(String datastoreType) {
+ public DatastoreSnapshot getAndRemove(final String datastoreType) {
initialize();
return datastoreSnapshots.remove(datastoreType);
}
}
@VisibleForTesting
- void setLogger(final Logger log) {
- this.log = log;
+ void setLogger(final Logger logger) {
+ this.log = logger;
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class DistributedDataStoreFactory {
+public final class DistributedDataStoreFactory {
private static final Logger LOG = LoggerFactory.getLogger(DistributedDataStoreFactory.class);
private static final String DEFAULT_MODULE_SHARDS_PATH = "./configuration/initial/module-shards.conf";
/**
* Sets the target primary shard and initiates a CreateTransaction try.
*/
- void setPrimaryShard(PrimaryShardInfo primaryShardInfo) {
- this.primaryShardInfo = primaryShardInfo;
+ void setPrimaryShard(final PrimaryShardInfo newPrimaryShardInfo) {
+ this.primaryShardInfo = newPrimaryShardInfo;
if (getTransactionType() == TransactionType.WRITE_ONLY
&& getActorContext().getDatastoreContext().isWriteOnlyTransactionOptimizationsEnabled()) {
- ActorSelection primaryShard = primaryShardInfo.getPrimaryShardActor();
+ ActorSelection primaryShard = newPrimaryShardInfo.getPrimaryShardActor();
LOG.debug("Tx {} Primary shard {} found - creating WRITE_ONLY transaction context",
getIdentifier(), primaryShard);
// For write-only Tx's we prepare the transaction modifications directly on the shard actor
// to avoid the overhead of creating a separate transaction actor.
transactionContextWrapper.executePriorTransactionOperations(createValidTransactionContext(
- primaryShard, String.valueOf(primaryShard.path()), primaryShardInfo.getPrimaryShardVersion()));
+ primaryShard, String.valueOf(primaryShard.path()), newPrimaryShardInfo.getPrimaryShardVersion()));
} else {
tryCreateTransaction();
}
createTxFuture.onComplete(new OnComplete<Object>() {
@Override
- public void onComplete(Throwable failure, Object response) {
+ public void onComplete(final Throwable failure, final Object response) {
onCreateTransactionComplete(failure, response);
}
}, getActorContext().getClientDispatcher());
}
}
- private void onCreateTransactionComplete(Throwable failure, Object response) {
+ private void onCreateTransactionComplete(final Throwable failure, final Object response) {
// An AskTimeoutException will occur if the local shard forwards to an unavailable remote leader or
// the cached remote leader actor is no longer available.
boolean retryCreateTransaction = primaryShardInfo != null
createTransactionContext(failure, response);
}
- private void createTransactionContext(Throwable failure, Object response) {
+ private void createTransactionContext(final Throwable failure, final Object response) {
// Create the TransactionContext from the response or failure. Store the new
// TransactionContext locally until we've completed invoking the
// TransactionOperations. This avoids thread timing issues which could cause
transactionContextWrapper.executePriorTransactionOperations(localTransactionContext);
}
- private TransactionContext createValidTransactionContext(CreateTransactionReply reply) {
+ private TransactionContext createValidTransactionContext(final CreateTransactionReply reply) {
LOG.debug("Tx {} Received {}", getIdentifier(), reply);
return createValidTransactionContext(getActorContext().actorSelection(reply.getTransactionPath()),
reply.getTransactionPath(), primaryShardInfo.getPrimaryShardVersion());
}
- private TransactionContext createValidTransactionContext(ActorSelection transactionActor, String transactionPath,
- short remoteTransactionVersion) {
+ private TransactionContext createValidTransactionContext(final ActorSelection transactionActor,
+ final String transactionPath, final short remoteTransactionVersion) {
final TransactionContext ret = new RemoteTransactionContext(transactionContextWrapper.getIdentifier(),
transactionActor, getActorContext(), remoteTransactionVersion, transactionContextWrapper.getLimiter());
return self();
}
- public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
+ public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
checkSealed();
- this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
+ this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
return self();
}
}
public static class Builder extends AbstractBuilder<Builder, Shard> {
- private Builder() {
+ Builder() {
super(Shard.class);
}
}
*
* @author Thomas Pantelis
*/
-public class ShardDataChangePublisherActor
+public final class ShardDataChangePublisherActor
extends ShardDataTreeNotificationPublisherActor<ShardDataChangeListenerPublisher> {
private ShardDataChangePublisherActor(final String name, final String logContext) {
}
@Override
- protected void handleReceive(Object message) {
+ protected void handleReceive(final Object message) {
if (message instanceof RegisterListener) {
RegisterListener reg = (RegisterListener)message;
if (reg.initialState.isPresent()) {
*
* @author Thomas Pantelis
*/
-public class ShardDataTreeChangePublisherActor
+public final class ShardDataTreeChangePublisherActor
extends ShardDataTreeNotificationPublisherActor<ShardDataTreeChangeListenerPublisher> {
private ShardDataTreeChangePublisherActor(final String name, final String logContext) {
}
@Override
- protected void handleReceive(Object message) {
+ protected void handleReceive(final Object message) {
if (message instanceof RegisterListener) {
RegisterListener reg = (RegisterListener)message;
LOG.debug("{}: Received {}", logContext(), reg);
*
* @author Thomas Pantelis
*/
-class ShardSnapshotCohort implements RaftActorSnapshotCohort {
+final class ShardSnapshotCohort implements RaftActorSnapshotCohort {
private static final FrontendType SNAPSHOT_APPLY = FrontendType.forName("snapshot-apply");
private final ActorRef snapshotActor;
*
* @author Thomas Pantelis
*/
-public class ModuleConfig {
+public final class ModuleConfig {
private final String name;
private final String namespace;
private final ShardStrategy shardStrategy;
private final Map<String, ShardConfig> shardConfigs;
- private ModuleConfig(String name, String namespace, ShardStrategy shardStrategy,
- Map<String, ShardConfig> shardConfigs) {
+ ModuleConfig(final String name, final String namespace, final ShardStrategy shardStrategy,
+ final Map<String, ShardConfig> shardConfigs) {
this.name = name;
this.namespace = namespace;
this.shardStrategy = shardStrategy;
}
@Nullable
- public ShardConfig getShardConfig(String forName) {
+ public ShardConfig getShardConfig(final String forName) {
return shardConfigs.get(forName);
}
return shardConfigs.keySet();
}
- public static Builder builder(String name) {
+ public static Builder builder(final String name) {
return new Builder(name);
}
- public static Builder builder(ModuleConfig moduleConfig) {
+ public static Builder builder(final ModuleConfig moduleConfig) {
return new Builder(moduleConfig);
}
- public static class Builder {
+ public static final class Builder {
private String name;
private String nameSpace;
private ShardStrategy shardStrategy;
private final Map<String, ShardConfig> shardConfigs = new HashMap<>();
- private Builder(String name) {
+ Builder(final String name) {
this.name = name;
}
- private Builder(ModuleConfig moduleConfig) {
+ private Builder(final ModuleConfig moduleConfig) {
this.name = moduleConfig.getName();
this.nameSpace = moduleConfig.getNamespace();
this.shardStrategy = moduleConfig.getShardStrategy();
}
}
- public Builder name(String newName) {
+ public Builder name(final String newName) {
this.name = newName;
return this;
}
- public Builder nameSpace(String newNameSpace) {
+ public Builder nameSpace(final String newNameSpace) {
this.nameSpace = newNameSpace;
return this;
}
- public Builder shardStrategy(ShardStrategy newShardStrategy) {
+ public Builder shardStrategy(final ShardStrategy newShardStrategy) {
this.shardStrategy = newShardStrategy;
return this;
}
- public Builder shardConfig(String shardName, Collection<MemberName> replicas) {
+ public Builder shardConfig(final String shardName, final Collection<MemberName> replicas) {
shardConfigs.put(shardName, new ShardConfig(shardName, replicas));
return this;
}
private volatile ActorRef localEntityOwnershipShard;
private volatile DataTree localEntityOwnershipShardDataTree;
- private DistributedEntityOwnershipService(final ActorContext context) {
+ DistributedEntityOwnershipService(final ActorContext context) {
this.context = Preconditions.checkNotNull(context);
}
*
* @author Thomas Pantelis
*/
-class EntityOwnershipListenerActor extends AbstractUntypedActor {
+final class EntityOwnershipListenerActor extends AbstractUntypedActor {
private final DOMEntityOwnershipListener listener;
- private EntityOwnershipListenerActor(DOMEntityOwnershipListener listener) {
+ private EntityOwnershipListenerActor(final DOMEntityOwnershipListener listener) {
this.listener = listener;
}
@Override
- protected void handleReceive(Object message) {
+ protected void handleReceive(final Object message) {
if (message instanceof DOMEntityOwnershipChange) {
onEntityOwnershipChanged((DOMEntityOwnershipChange)message);
} else {
}
@SuppressWarnings("checkstyle:IllegalCatch")
- private void onEntityOwnershipChanged(DOMEntityOwnershipChange change) {
+ private void onEntityOwnershipChanged(final DOMEntityOwnershipChange change) {
LOG.debug("Notifying EntityOwnershipListener {}: {}", listener, change);
try {
}
}
- static Props props(DOMEntityOwnershipListener listener) {
+ static Props props(final DOMEntityOwnershipListener listener) {
return Props.create(new EntityOwnershipListenerCreator(listener));
}
+ "create remote instances of this actor and thus don't need it to be Serializable.")
private final DOMEntityOwnershipListener listener;
- EntityOwnershipListenerCreator(DOMEntityOwnershipListener listener) {
+ EntityOwnershipListenerCreator(final DOMEntityOwnershipListener listener) {
this.listener = Preconditions.checkNotNull(listener);
}
private volatile boolean inJeopardy = false;
- EntityOwnershipListenerSupport(ActorContext actorContext, String logId) {
+ EntityOwnershipListenerSupport(final ActorContext actorContext, final String logId) {
this.actorContext = actorContext;
this.logId = logId;
}
+ @Override
String getLogId() {
return logId;
}
* @param inJeopardy new value of the in-jeopardy flag
* @return Previous value of the flag.
*/
+ @SuppressWarnings("checkstyle:hiddenField")
boolean setInJeopardy(final boolean inJeopardy) {
final boolean wasInJeopardy = this.inJeopardy;
this.inJeopardy = inJeopardy;
return wasInJeopardy;
}
- void addEntityOwnershipListener(String entityType, DOMEntityOwnershipListener listener) {
+ void addEntityOwnershipListener(final String entityType, final DOMEntityOwnershipListener listener) {
LOG.debug("{}: Adding EntityOwnershipListener {} for entity type {}", logId, listener, entityType);
listenerLock.writeLock().lock();
}
}
- void removeEntityOwnershipListener(String entityType, DOMEntityOwnershipListener listener) {
+ void removeEntityOwnershipListener(final String entityType, final DOMEntityOwnershipListener listener) {
LOG.debug("{}: Removing EntityOwnershipListener {} for entity type {}", logId, listener, entityType);
listenerLock.writeLock().lock();
}
@Override
- void notifyEntityOwnershipListeners(DOMEntity entity, boolean wasOwner, boolean isOwner, boolean hasOwner) {
+ void notifyEntityOwnershipListeners(final DOMEntity entity, final boolean wasOwner, final boolean isOwner,
+ final boolean hasOwner) {
listenerLock.readLock().lock();
try {
Collection<DOMEntityOwnershipListener> listeners = entityTypeListenerMap.get(entity.getType());
}
}
- void notifyEntityOwnershipListener(DOMEntity entity, boolean wasOwner, boolean isOwner, boolean hasOwner,
- DOMEntityOwnershipListener listener) {
+ void notifyEntityOwnershipListener(final DOMEntity entity, final boolean wasOwner, final boolean isOwner,
+ final boolean hasOwner, final DOMEntityOwnershipListener listener) {
listenerLock.readLock().lock();
try {
notifyListeners(entity, wasOwner, isOwner, hasOwner, ImmutableList.of(listenerActorMap.get(listener)));
}
@GuardedBy("listenerLock")
- private void notifyListeners(DOMEntity entity, boolean wasOwner, boolean isOwner, boolean hasOwner,
- Collection<ListenerActorRefEntry> listenerEntries) {
+ private void notifyListeners(final DOMEntity entity, final boolean wasOwner, final boolean isOwner,
+ final boolean hasOwner, final Collection<ListenerActorRefEntry> listenerEntries) {
DOMEntityOwnershipChange changed = new DOMEntityOwnershipChange(entity,
EntityOwnershipChangeState.from(wasOwner, isOwner, hasOwner), inJeopardy);
for (ListenerActorRefEntry entry: listenerEntries) {
return entityTypeToStrategyInfo.get(entityType) != null;
}
- public EntityOwnerSelectionStrategy createStrategy(String entityType, Map<String, Long> initialStatistics) {
+ public EntityOwnerSelectionStrategy createStrategy(final String entityType,
+ final Map<String, Long> initialStatistics) {
final EntityOwnerSelectionStrategy strategy;
final EntityOwnerSelectionStrategy existingStrategy = entityTypeToOwnerSelectionStrategy.get(entityType);
if (existingStrategy != null) {
this.delay = delay;
}
- public EntityOwnerSelectionStrategy createStrategy(Map<String, Long> initialStatistics) {
+ public EntityOwnerSelectionStrategy createStrategy(final Map<String, Long> initialStatistics) {
try {
return strategyClass.getDeclaredConstructor(long.class, Map.class)
.newInstance(delay, initialStatistics);
return new Builder(new EntityOwnerSelectionStrategyConfig());
}
- public static class Builder {
+ public static final class Builder {
private final EntityOwnerSelectionStrategyConfig config;
- private Builder(final EntityOwnerSelectionStrategyConfig config) {
+ Builder(final EntityOwnerSelectionStrategyConfig config) {
this.config = config;
}
private final String type;
private final String fullName;
- private ShardIdentifier(String shardName, MemberName memberName, String type) {
+ ShardIdentifier(final String shardName, final MemberName memberName, final String type) {
this.shardName = Preconditions.checkNotNull(shardName, "shardName should not be null");
this.memberName = Preconditions.checkNotNull(memberName, "memberName should not be null");
this.type = Preconditions.checkNotNull(type, "type should not be null");
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
return new ShardIdentifier(shardName, memberName, type);
}
- public Builder shardName(String newShardName) {
+ public Builder shardName(final String newShardName) {
this.shardName = newShardName;
return this;
}
- public Builder memberName(MemberName newMemberName) {
+ public Builder memberName(final MemberName newMemberName) {
this.memberName = newMemberName;
return this;
}
- public Builder type(String newType) {
+ public Builder type(final String newType) {
this.type = newType;
return this;
}
- public Builder fromShardIdString(String shardId) {
+ public Builder fromShardIdString(final String shardId) {
Matcher matcher = PATTERN.matcher(shardId);
if (matcher.matches()) {
import akka.util.Timeout;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
-import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
-import com.google.common.util.concurrent.ExecutionError;
-import com.google.common.util.concurrent.UncheckedExecutionException;
-import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
private final String shardName;
private volatile String stateRetrievalTime;
- OnDemandShardStateCache(String shardName, ActorRef shardActor) {
+ OnDemandShardStateCache(final String shardName, final ActorRef shardActor) {
this.shardName = Preconditions.checkNotNull(shardName);
this.shardActor = shardActor;
}
return OnDemandShardState.newBuilder().build();
}
- try {
- return ONDEMAND_SHARD_STATE_CACHE.get(shardName, this::retrieveState);
- } catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
- if (e.getCause() != null) {
- Throwables.propagateIfPossible(e.getCause(), Exception.class);
- throw new RuntimeException("unexpected", e.getCause());
- }
-
- throw e;
- }
+ return ONDEMAND_SHARD_STATE_CACHE.get(shardName, this::retrieveState);
}
String getStatRetrievaelTime() {
*
* @author Basheeruddin syedbahm@cisco.com
*/
-public class ShardMBeanFactory {
+public final class ShardMBeanFactory {
private ShardMBeanFactory() {
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
-public class DataChangedReply {
+public final class DataChangedReply {
public static final DataChangedReply INSTANCE = new DataChangedReply();
private DataChangedReply() {
*
* @author Thomas Pantelis
*/
-public class GetShardDataTree {
+public final class GetShardDataTree {
public static final GetShardDataTree INSTANCE = new GetShardDataTree();
private GetShardDataTree() {
*
* @author Thomas Pantelis
*/
-public class SuccessReply implements Serializable {
+public final class SuccessReply implements Serializable {
private static final long serialVersionUID = 1L;
public static final SuccessReply INSTANCE = new SuccessReply();
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.modification;
import java.util.List;
/**
- * CompositeModification contains a list of modifications that need to be applied to the DOMStore
+ * CompositeModification contains a list of modifications that need to be applied to the DOMStore.
+ *
* <p>
* A CompositeModification gets stored in the transaction log for a Shard. During recovery when the transaction log
* is being replayed a DOMStoreWriteTransaction could be created and a CompositeModification could be applied to it.
- * </p>
*/
public interface CompositeModification extends Modification {
/**
protected abstract T readIdentifier(@Nonnull DataInput in) throws IOException;
@Nonnull
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract Identifiable<T> createObject(@Nonnull T identifier, @Nonnull byte[] serialized);
}
}
@Nonnull
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract AbstractProxy<T> externalizableProxy(@Nonnull byte[] serialized);
}
return distributedDataStore;
}
- public T distributedDataStore(final AbstractDataStore distributedDataStore) {
+ public T distributedDataStore(final AbstractDataStore newDistributedDataStore) {
checkSealed();
- this.distributedDataStore = distributedDataStore;
+ this.distributedDataStore = newDistributedDataStore;
return self();
}
private DatastoreContext datastoreContext;
private Shard.AbstractBuilder<?, ?> builder;
- private boolean isActiveMember = true;
+ private boolean activeMember = true;
ShardInformation(final String shardName, final ShardIdentifier shardId,
final Map<String, String> initialPeerAddresses, final DatastoreContext datastoreContext,
return shardId;
}
- void setLocalDataTree(final Optional<DataTree> localShardDataTree) {
- this.localShardDataTree = localShardDataTree;
+ void setLocalDataTree(final Optional<DataTree> dataTree) {
+ this.localShardDataTree = dataTree;
}
Optional<DataTree> getLocalShardDataTree() {
return datastoreContext;
}
- void setDatastoreContext(final DatastoreContext datastoreContext, final ActorRef sender) {
- this.datastoreContext = datastoreContext;
+ void setDatastoreContext(final DatastoreContext newDatastoreContext, final ActorRef sender) {
+ this.datastoreContext = newDatastoreContext;
if (actor != null) {
LOG.debug("Sending new DatastoreContext to {}", shardId);
actor.tell(this.datastoreContext, sender);
return false;
}
- boolean setLeaderId(final String leaderId) {
- final boolean changed = !Objects.equals(this.leaderId, leaderId);
- this.leaderId = leaderId;
- if (leaderId != null) {
+ boolean setLeaderId(final String newLeaderId) {
+ final boolean changed = !Objects.equals(this.leaderId, newLeaderId);
+ this.leaderId = newLeaderId;
+ if (newLeaderId != null) {
this.leaderAvailable = true;
}
notifyOnShardInitializedCallbacks();
}
boolean isActiveMember() {
- return isActiveMember;
+ return activeMember;
}
void setActiveMember(final boolean isActiveMember) {
- this.isActiveMember = isActiveMember;
+ this.activeMember = isActiveMember;
}
SchemaContext getSchemaContext() {
*
* @author Thomas Pantelis
*/
-class ShardManagerGetSnapshotReplyActor extends UntypedActor {
+final class ShardManagerGetSnapshotReplyActor extends UntypedActor {
private static final Logger LOG = LoggerFactory.getLogger(ShardManagerGetSnapshotReplyActor.class);
private final Set<String> remainingShardNames;
private final Params params;
private final List<ShardSnapshot> shardSnapshots = new ArrayList<>();
- private ShardManagerGetSnapshotReplyActor(Params params) {
+ private ShardManagerGetSnapshotReplyActor(final Params params) {
this.params = params;
remainingShardNames = new HashSet<>(params.shardNames);
}
@Override
- public void onReceive(Object message) {
+ public void onReceive(final Object message) {
if (message instanceof GetSnapshotReply) {
onGetSnapshotReply((GetSnapshotReply)message);
} else if (message instanceof Failure) {
}
}
- private void onGetSnapshotReply(GetSnapshotReply getSnapshotReply) {
+ private void onGetSnapshotReply(final GetSnapshotReply getSnapshotReply) {
LOG.debug("{}: Received {}", params.id, getSnapshotReply);
ShardIdentifier shardId = ShardIdentifier.fromShardIdString(getSnapshotReply.getId());
}
}
- public static Props props(Collection<String> shardNames, String datastoreType,
- ShardManagerSnapshot shardManagerSnapshot, ActorRef replyToActor, String id, Duration receiveTimeout) {
+ public static Props props(final Collection<String> shardNames, final String datastoreType,
+ final ShardManagerSnapshot shardManagerSnapshot, final ActorRef replyToActor, final String id,
+ final Duration receiveTimeout) {
return Props.create(ShardManagerGetSnapshotReplyActor.class, new Params(shardNames, datastoreType,
shardManagerSnapshot, replyToActor, id, receiveTimeout));
}
final String id;
final Duration receiveTimeout;
- Params(Collection<String> shardNames, String datastoreType, ShardManagerSnapshot shardManagerSnapshot,
- ActorRef replyToActor, String id, Duration receiveTimeout) {
+ Params(final Collection<String> shardNames, final String datastoreType,
+ final ShardManagerSnapshot shardManagerSnapshot, final ActorRef replyToActor, final String id,
+ final Duration receiveTimeout) {
this.shardNames = shardNames;
this.datastoreType = datastoreType;
this.shardManagerSnapshot = shardManagerSnapshot;
/**
* Utils for encoding prefix shard name.
*/
-public class ClusterUtils {
+public final class ClusterUtils {
private static final Logger LOG = LoggerFactory.getLogger(ClusterUtils.class);
// id for the shard used to store prefix configuration
import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-public class NormalizedNodeAggregator {
+public final class NormalizedNodeAggregator {
private final YangInstanceIdentifier rootIdentifier;
private final List<Optional<NormalizedNode<?, ?>>> nodes;
private final DataTree dataTree;
return listenerPathArgs;
}
- private static class ProxyRegistration implements ListenerRegistration<DOMDataTreeChangeListener> {
+ private static final class ProxyRegistration implements ListenerRegistration<DOMDataTreeChangeListener> {
private final ListenerRegistration<org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener> proxy;
private final DOMDataTreeChangeListener listener;
@Nullable
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public DataTreeCandidateNode getModifiedChild(final PathArgument identifier) {
return null;
}
@Nonnull
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public DOMDataTreeProducer createProducer(@Nonnull final Collection<DOMDataTreeIdentifier> subtrees) {
// TODO we probably don't need to distribute this on the remote nodes since once we have this producer
// open we surely have the rights to all the subtrees.
abstract class LookupTask implements Runnable {
private final int maxRetries;
private final ActorRef replyTo;
- private int retries = 0;
+ private int retried = 0;
LookupTask(final ActorRef replyTo, final int maxRetries) {
this.replyTo = replyTo;
abstract void reschedule(int retries);
void tryReschedule(@Nullable final Throwable throwable) {
- if (retries <= maxRetries) {
- retries++;
- reschedule(retries);
+ if (retried <= maxRetries) {
+ retried++;
+ reschedule(retried);
} else {
fail(throwable);
}
* {@link LeaderLocationListener#onLeaderLocationChanged(LeaderLocation)}
* events.
*/
-public class RoleChangeListenerActor extends AbstractUntypedActor {
+public final class RoleChangeListenerActor extends AbstractUntypedActor {
private final LeaderLocationListener leaderLocationListener;
private final ActorRef roleChangeNotifier;
return this;
}
- public ShardedDataTreeActorCreator setClusterWrapper(final ClusterWrapper cluster) {
- this.cluster = cluster;
+ public ShardedDataTreeActorCreator setClusterWrapper(final ClusterWrapper clusterWrapper) {
+ this.cluster = clusterWrapper;
return this;
}
return this;
}
- public ShardedDataTreeActorCreator setLookupTaskMaxRetries(final int maxRetries) {
- this.maxRetries = maxRetries;
+ public ShardedDataTreeActorCreator setLookupTaskMaxRetries(final int newMaxRetries) {
+ this.maxRetries = newMaxRetries;
return this;
}
* Message sent to the local ShardManager, once the shard configuration shard is ready and the ShardManager should
* start its listener.
*/
-public class InitConfigListener {
+public final class InitConfigListener {
public static final InitConfigListener INSTANCE = new InitConfigListener();
import com.typesafe.config.ConfigFactory;
import org.opendaylight.controller.cluster.common.actor.AkkaConfigurationReader;
-public class AkkaConfigFactory {
+public final class AkkaConfigFactory {
private static final String CONFIGURATION_NAME = "odl-cluster-data";
+ private AkkaConfigFactory() {
+
+ }
+
public static Config createAkkaConfig(final AkkaConfigurationReader reader) {
return ConfigFactory.load(reader.read()).getConfig(CONFIGURATION_NAME);
}
import java.security.PrivilegedAction;
import org.osgi.framework.BundleContext;
-public class BundleClassLoaderFactory {
+public final class BundleClassLoaderFactory {
+
+ private BundleClassLoaderFactory() {
+
+ }
public static ClassLoader createClassLoader(final BundleContext bundleContext) {
return AccessController
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class QuarantinedMonitorActorPropsFactory {
+public final class QuarantinedMonitorActorPropsFactory {
private static final Logger LOG = LoggerFactory.getLogger(QuarantinedMonitorActorPropsFactory.class);
+ private QuarantinedMonitorActorPropsFactory() {
+
+ }
+
public static Props createProps(final BundleContext bundleContext) {
return QuarantinedMonitorActor.props(() -> {
// restart the entire karaf container
LogicalDatastoreType.OPERATIONAL, operationalDomStore, LogicalDatastoreType.CONFIGURATION,
configDomStore), futureExecutor) {
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public CheckedFuture<Void, TransactionCommitFailedException> submit(DOMDataWriteTransaction transaction,
Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
commitCohorts.addAll(cohorts);
handle = createHandle(parent);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract T createHandle(AbstractClientHistory parent);
/**
*
* @param handle handle
*/
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract void doHandleOperation(T handle);
@After
behavior = createBehavior(clientContext, context);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract AbstractDataStoreClientBehavior createBehavior(ClientActorContext clientContext,
ActorContext context);
return mock;
}
-}
\ No newline at end of file
+}
tester = new TransactionTester<>(transaction, connection, backendProbe);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected abstract T createTransaction(ProxyHistory parent, TransactionIdentifier id, DataTreeSnapshot snapshot);
@After
Assert.assertThat(modifications, hasItem(both(isA(TransactionDelete.class)).and(hasPath(PATH_3))));
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected <R extends TransactionRequest<R>> void testRequestResponse(final Consumer<VotingFuture<Void>> consumer,
final Class<R> expectedRequest,
final BiFunction<TransactionIdentifier, Long, TransactionSuccess<?>> replySupplier) throws Exception {
return new TestProbe(system);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected TransactionTester<LocalReadWriteProxyTransaction> createLocalProxy() {
final TestProbe backendProbe = new TestProbe(system, "backend2");
final TestProbe clientContextProbe = new TestProbe(system, "clientContext2");
return new TransactionTester<>(tx, connection, backendProbe);
}
+ @SuppressWarnings("checkstyle:hiddenField")
protected TransactionTester<RemoteProxyTransaction> createRemoteProxyTransactionTester() {
final TestProbe clientContextProbe = new TestProbe(system, "remoteClientContext");
final TestProbe backendProbe = new TestProbe(system, "remoteBackend");
@Override
@Test
public void testOnTransactionComplete() throws Exception {
- final ClientTransaction transaction = object().createTransaction();
+ final ClientTransaction tx = object().createTransaction();
// make transaction ready
- object().onTransactionReady(transaction, cohort);
+ object().onTransactionReady(tx, cohort);
// state should be set to IDLE
Assert.assertEquals(AbstractClientHistory.State.IDLE, object.state());
// complete transaction
- object().onTransactionComplete(transaction.getIdentifier());
+ object().onTransactionComplete(tx.getIdentifier());
// state is still IDLE
Assert.assertEquals(AbstractClientHistory.State.IDLE, object.state());
}
@Override
@Test(expected = IllegalStateException.class)
public void testOnTransactionReadyDuplicate() throws Exception {
- final ClientTransaction transaction = object().createTransaction();
- object().onTransactionReady(transaction, cohort);
- object().onTransactionReady(transaction, cohort);
+ final ClientTransaction tx = object().createTransaction();
+ object().onTransactionReady(tx, cohort);
+ object().onTransactionReady(tx, cohort);
}
@Test
public void testOnTransactionReadyAndCompleteIdleFail() throws Exception {
object().onTransactionReady(transaction, cohort);
}
-}
\ No newline at end of file
+}
private DataTreeSnapshot snapshot;
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
protected LocalReadOnlyProxyTransaction createTransaction(final ProxyHistory parent,
final TransactionIdentifier id,
final DataTreeSnapshot snapshot) {
assertOperationThrowsException(() -> transaction.replayModifyTransactionRequest(request, createCallbackMock(),
Ticker.systemTicker().read()), VerifyException.class);
}
-}
\ No newline at end of file
+}
import org.opendaylight.controller.cluster.access.concepts.MemberName;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-class TestUtils {
+final class TestUtils {
+ @FunctionalInterface
+ public interface RunnableWithException {
+ void run() throws Exception;
+ }
static final MemberName MEMBER_NAME = MemberName.forName("member-1");
static final FrontendType FRONTEND_TYPE = FrontendType.forName("type-1");
static final LocalHistoryIdentifier HISTORY_ID = new LocalHistoryIdentifier(CLIENT_ID, 0L);
static final TransactionIdentifier TRANSACTION_ID = new TransactionIdentifier(HISTORY_ID, 0L);
- @FunctionalInterface
- public interface RunnableWithException {
- void run() throws Exception;
- }
-
private static final long TIMEOUT = 3;
+ private TestUtils() {
+
+ }
+
/**
* Asserts, that future result when it completes is equal to given object.
* Future must complete in {@link TestUtils#TIMEOUT} seconds.
private static class MockFailure extends RequestFailure<TransactionIdentifier, TransactionFailure> {
private static final long serialVersionUID = 1L;
- private MockFailure(@Nonnull final TransactionIdentifier target, final long sequence,
+ MockFailure(@Nonnull final TransactionIdentifier target, final long sequence,
@Nonnull final RequestException cause) {
super(target, sequence, cause);
}
shardName);
}
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
protected void propagateReadFailedExceptionCause(final CheckedFuture<?, ReadFailedException> future)
throws Exception {
try {
private DatastoreContextFactory contextFactory;
@Override
+ @SuppressWarnings("checkstyle:hiddenField")
public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
public final class MockIdentifiers {
+ private MockIdentifiers() {
+
+ }
+
public static ClientIdentifier clientIdentifier(final Class<?> clazz, final String memberName) {
return ClientIdentifier.create(FrontendIdentifier.create(MemberName.forName(memberName),
FrontendType.forName(clazz.getSimpleName())), 0);
verifyCohortActors();
}
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
private void propagateExecutionExceptionCause(final ListenableFuture<?> future) throws Exception {
-
try {
future.get(5, TimeUnit.SECONDS);
fail("Expected ExecutionException");
private final AtomicInteger abortCount = new AtomicInteger();
private volatile AssertionError assertionError;
- private CohortActor(final Builder builder) {
+ CohortActor(final Builder builder) {
this.builder = builder;
}
private CountDownLatch memberReachableReceived = new CountDownLatch(1);
private volatile MessageInterceptor messageInterceptor;
- private TestShardManager(final Builder builder) {
+ TestShardManager(final Builder builder) {
super(builder);
shardActor = builder.shardActor;
shardActors = builder.shardActors;
private static class TestMessage {
}
- private static class MockShardManager extends UntypedActor {
+ private static final class MockShardManager extends UntypedActor {
private final boolean found;
private final ActorRef actorRef;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
-public class ForwardingActor extends UntypedActor {
+public final class ForwardingActor extends UntypedActor {
private final ActorRef target;
- private ForwardingActor(ActorRef target) {
+ private ForwardingActor(final ActorRef target) {
this.target = target;
}
@Override
- public void onReceive(Object obj) throws Exception {
+ public void onReceive(final Object obj) throws Exception {
target.forward(obj, context());
}
private PruningDataTreeModification pruningDataTreeModification;
@Before
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
public void setUp() {
MockitoAnnotations.initMocks(this);
final DOMDataTreeProducer producer = shardedDOMDataTree.createProducer(Collections.singletonList(ROOT));
final DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(false);
- final DOMDataTreeWriteCursor cursor = tx.createCursor(ROOT);
+ final DOMDataTreeWriteCursor txCursor = tx.createCursor(ROOT);
- assertNotNull(cursor);
- cursor.write(TestModel.TEST_PATH.getLastPathArgument(), createCrossShardContainer());
+ assertNotNull(txCursor);
+ txCursor.write(TestModel.TEST_PATH.getLastPathArgument(), createCrossShardContainer());
//check the lower shard got the correct modification
verify(outerListCursor, times(2)).write(pathArgumentCaptor.capture(), nodeCaptor.capture());
final MapNode actualInnerListNode = (MapNode) nodeCaptor.getAllValues().get(1);
assertEquals(createInnerMapNode(1), actualInnerListNode);
- cursor.close();
+ txCursor.close();
tx.submit().checkedGet();
verify(commitCohort, times(2)).canCommit();
verify(commitCohort, times(2)).preCommit();
verify(commitCohort, times(2)).commit();
-
}
private static MapNode createInnerMapNode(final int id) {
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.md.cluster.datastore.model;
import java.math.BigInteger;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
-public class CarsModel {
+public final class CarsModel {
public static final QName BASE_QNAME = QName.create(
"urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:cars", "2014-03-13", "cars");
public static final YangInstanceIdentifier BASE_PATH = YangInstanceIdentifier.of(BASE_QNAME);
public static final YangInstanceIdentifier CAR_LIST_PATH = BASE_PATH.node(CAR_QNAME);
+ private CarsModel() {
+
+ }
+
public static NormalizedNode<?, ?> create() {
// Create a list builder
return newCarsNode(newCarsMapNode());
}
- public static ContainerNode newCarsNode(MapNode carsList) {
+ public static ContainerNode newCarsNode(final MapNode carsList) {
return ImmutableContainerNodeBuilder.create().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(
BASE_QNAME)).withChild(carsList).build();
}
- public static MapNode newCarsMapNode(MapEntryNode... carEntries) {
+ public static MapNode newCarsMapNode(final MapEntryNode... carEntries) {
CollectionNodeBuilder<MapEntryNode, MapNode> builder = ImmutableMapNodeBuilder.create()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CAR_QNAME));
for (MapEntryNode e : carEntries) {
return ImmutableNodes.mapNodeBuilder(CAR_QNAME).build();
}
- public static MapEntryNode newCarEntry(String name, BigInteger price) {
+ public static MapEntryNode newCarEntry(final String name, final BigInteger price) {
return ImmutableNodes.mapEntryBuilder(CAR_QNAME, CAR_NAME_QNAME, name)
.withChild(ImmutableNodes.leafNode(CAR_NAME_QNAME, name))
.withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, price)).build();
}
- public static YangInstanceIdentifier newCarPath(String name) {
+ public static YangInstanceIdentifier newCarPath(final String name) {
return YangInstanceIdentifier.builder(CAR_LIST_PATH).nodeWithKey(CAR_QNAME, CAR_NAME_QNAME, name).build();
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.md.cluster.datastore.model;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-public class CompositeModel {
+public final class CompositeModel {
public static final QName TEST_QNAME = QName
.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", "2014-03-13", "test");
private static final String FIRST_GRAND_CHILD_NAME = "first grand child";
private static final String SECOND_GRAND_CHILD_NAME = "second grand child";
- private static final MapEntryNode BAR_NODE = mapEntryBuilder(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
- .withChild(mapNodeBuilder(INNER_LIST_QNAME) //
- .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
- .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
- .build()) //
+ private static final MapEntryNode BAR_NODE = mapEntryBuilder(OUTER_LIST_QNAME, ID_QNAME, TWO_ID)
+ .withChild(mapNodeBuilder(INNER_LIST_QNAME)
+ .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME))
+ .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME))
+ .build())
.build();
- public static final InputStream getDatastoreTestInputStream() {
+ private CompositeModel() {
+
+ }
+
+ public static InputStream getDatastoreTestInputStream() {
return getInputStream(DATASTORE_TEST_YANG);
}
- public static final InputStream getDatastoreAugInputStream() {
+ public static InputStream getDatastoreAugInputStream() {
return getInputStream(DATASTORE_AUG_YANG);
}
- public static final InputStream getDatastoreTestNotificationInputStream() {
+ public static InputStream getDatastoreTestNotificationInputStream() {
return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG);
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.md.cluster.datastore.model;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
-public class PeopleModel {
+public final class PeopleModel {
public static final QName BASE_QNAME = QName.create(
"urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test:people", "2014-03-13", "people");
public static final YangInstanceIdentifier BASE_PATH = YangInstanceIdentifier.of(BASE_QNAME);
public static final YangInstanceIdentifier PERSON_LIST_PATH = BASE_PATH.node(PERSON_QNAME);
+ private PeopleModel() {
+
+ }
+
public static NormalizedNode<?, ?> create() {
// Create a list builder
return ImmutableNodes.mapNodeBuilder(PERSON_QNAME).build();
}
- public static MapEntryNode newPersonEntry(String name) {
+ public static MapEntryNode newPersonEntry(final String name) {
return ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, name)
.withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, name)).build();
}
- public static YangInstanceIdentifier newPersonPath(String name) {
+ public static YangInstanceIdentifier newPersonPath(final String name) {
return YangInstanceIdentifier.builder(PERSON_LIST_PATH)
.nodeWithKey(PERSON_QNAME, PERSON_NAME_QNAME, name).build();
}
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-public class SchemaContextHelper {
+public final class SchemaContextHelper {
public static final String ODL_DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
public static final String PEOPLE_YANG = "/people.yang";
public static final String CARS_YANG = "/cars.yang";
+ private SchemaContextHelper() {
+
+ }
+
public static InputStream getInputStream(final String yangFileName) {
return SchemaContextHelper.class.getResourceAsStream(yangFileName);
}
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
-public class TestModel {
+public final class TestModel {
public static final QName TEST_QNAME =
QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", "2014-03-13", "test");
public static final QName JUNK_QNAME =
QName.create("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:junk", "2014-03-13", "junk");
-
public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME, "outer-list");
public static final QName OUTER_CONTAINER_QNAME = QName.create(TEST_QNAME, "outer-container");
public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME, "inner-list");
public static final QName TWO_QNAME = QName.create(TEST_QNAME,"two");
public static final QName THREE_QNAME = QName.create(TEST_QNAME,"three");
+ private TestModel() {
+
+ }
+
public static SchemaContext createTestContext() {
final List<InputStream> sources;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
abstract class AbstractDOMRpcRoutingTableEntry {
- private final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls;
+ private final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> implementations;
private final SchemaPath schemaPath;
AbstractDOMRpcRoutingTableEntry(final SchemaPath schemaPath,
- final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> impls) {
+ final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> implementations) {
this.schemaPath = Preconditions.checkNotNull(schemaPath);
- this.impls = Preconditions.checkNotNull(impls);
+ this.implementations = Preconditions.checkNotNull(implementations);
}
final SchemaPath getSchemaPath() {
}
final List<DOMRpcImplementation> getImplementations(final YangInstanceIdentifier context) {
- return impls.get(context);
+ return implementations.get(context);
}
final Map<YangInstanceIdentifier, List<DOMRpcImplementation>> getImplementations() {
- return impls;
+ return implementations;
}
final boolean containsContext(final YangInstanceIdentifier contextReference) {
- return impls.containsKey(contextReference);
+ return implementations.containsKey(contextReference);
}
final Set<YangInstanceIdentifier> registeredIdentifiers(final DOMRpcAvailabilityListener listener) {
- return Maps.filterValues(impls, list -> list.stream().anyMatch(listener::acceptsImplementation)).keySet();
+ return Maps.filterValues(implementations, list -> list.stream().anyMatch(listener::acceptsImplementation))
+ .keySet();
}
/**
final AbstractDOMRpcRoutingTableEntry add(final DOMRpcImplementation implementation,
final List<YangInstanceIdentifier> newRpcs) {
final Builder<YangInstanceIdentifier, List<DOMRpcImplementation>> vb = ImmutableMap.builder();
- for (final Entry<YangInstanceIdentifier, List<DOMRpcImplementation>> ve : impls.entrySet()) {
+ for (final Entry<YangInstanceIdentifier, List<DOMRpcImplementation>> ve : implementations.entrySet()) {
if (newRpcs.remove(ve.getKey())) {
final List<DOMRpcImplementation> i = new ArrayList<>(ve.getValue().size() + 1);
i.addAll(ve.getValue());
final AbstractDOMRpcRoutingTableEntry remove(final DOMRpcImplementation implementation,
final List<YangInstanceIdentifier> removed) {
final Builder<YangInstanceIdentifier, List<DOMRpcImplementation>> vb = ImmutableMap.builder();
- for (final Entry<YangInstanceIdentifier, List<DOMRpcImplementation>> ve : impls.entrySet()) {
+ for (final Entry<YangInstanceIdentifier, List<DOMRpcImplementation>> ve : implementations.entrySet()) {
if (removed.remove(ve.getKey())) {
final List<DOMRpcImplementation> i = new ArrayList<>(ve.getValue());
i.remove(implementation);
// Hidden on purpose, initialized in initialize()
}
+ @SuppressWarnings("checkstyle:hiddenField")
ListenableFuture<Void> initialize(final DOMNotification notification,
final Collection<ListenerRegistration<? extends DOMNotificationListener>>
subscribers) {
return ret;
}
- DOMRpcRoutingTable add(final DOMRpcImplementation implementation, final Set<DOMRpcIdentifier> rpcs) {
- if (rpcs.isEmpty()) {
+ DOMRpcRoutingTable add(final DOMRpcImplementation implementation, final Set<DOMRpcIdentifier> rpcsToAdd) {
+ if (rpcsToAdd.isEmpty()) {
return this;
}
// First decompose the identifiers to a multimap
- final ListMultimap<SchemaPath, YangInstanceIdentifier> toAdd = decomposeIdentifiers(rpcs);
+ final ListMultimap<SchemaPath, YangInstanceIdentifier> toAdd = decomposeIdentifiers(rpcsToAdd);
// Now iterate over existing entries, modifying them as appropriate...
final Builder<SchemaPath, AbstractDOMRpcRoutingTableEntry> mb = ImmutableMap.builder();
return new DOMRpcRoutingTable(mb.build(), schemaContext);
}
- DOMRpcRoutingTable remove(final DOMRpcImplementation implementation, final Set<DOMRpcIdentifier> rpcs) {
- if (rpcs.isEmpty()) {
+ DOMRpcRoutingTable remove(final DOMRpcImplementation implementation, final Set<DOMRpcIdentifier> rpcIds) {
+ if (rpcIds.isEmpty()) {
return this;
}
// First decompose the identifiers to a multimap
- final ListMultimap<SchemaPath, YangInstanceIdentifier> toRemove = decomposeIdentifiers(rpcs);
+ final ListMultimap<SchemaPath, YangInstanceIdentifier> toRemove = decomposeIdentifiers(rpcIds);
// Now iterate over existing entries, modifying them as appropriate...
final Builder<SchemaPath, AbstractDOMRpcRoutingTableEntry> b = ImmutableMap.builder();
public class LegacyEntityOwnershipServiceAdapter implements EntityOwnershipService, AutoCloseable {
private final DOMEntityOwnershipService domService;
- public LegacyEntityOwnershipServiceAdapter(@Nonnull DOMEntityOwnershipService domService) {
+ public LegacyEntityOwnershipServiceAdapter(@Nonnull final DOMEntityOwnershipService domService) {
this.domService = Preconditions.checkNotNull(domService);
}
@Override
+ @SuppressWarnings("checkstyle:avoidHidingCauseException")
public EntityOwnershipCandidateRegistration registerCandidate(
- Entity entity) throws CandidateAlreadyRegisteredException {
+ final Entity entity) throws CandidateAlreadyRegisteredException {
try {
return new EntityOwnershipCandidateRegistrationAdapter(domService.registerCandidate(toDOMEntity(entity)),
entity);
}
@Override
- public EntityOwnershipListenerRegistration registerListener(String entityType, EntityOwnershipListener listener) {
+ public EntityOwnershipListenerRegistration registerListener(final String entityType,
+ final EntityOwnershipListener listener) {
return new EntityOwnershipListenerRegistrationAdapter(entityType, listener, domService
.registerListener(entityType, new DOMEntityOwnershipListenerAdapter(listener)));
}
@Override
- public Optional<EntityOwnershipState> getOwnershipState(Entity forEntity) {
+ public Optional<EntityOwnershipState> getOwnershipState(final Entity forEntity) {
return toEntityOwnershipState(domService.getOwnershipState(toDOMEntity(forEntity)));
}
@Override
- public boolean isCandidateRegistered(Entity entity) {
+ public boolean isCandidateRegistered(final Entity entity) {
return domService.isCandidateRegistered(toDOMEntity(entity));
}
public void close() {
}
- private DOMEntity toDOMEntity(Entity from) {
+ private static DOMEntity toDOMEntity(final Entity from) {
return new DOMEntity(from.getType(), from.getId());
}
- private Optional<EntityOwnershipState> toEntityOwnershipState(
- Optional<org.opendaylight.mdsal.eos.common.api.EntityOwnershipState> from) {
+ private static Optional<EntityOwnershipState> toEntityOwnershipState(
+ final Optional<org.opendaylight.mdsal.eos.common.api.EntityOwnershipState> from) {
if (!from.isPresent()) {
return Optional.absent();
}
implements EntityOwnershipCandidateRegistration {
private final DOMEntityOwnershipCandidateRegistration domRegistration;
- EntityOwnershipCandidateRegistrationAdapter(DOMEntityOwnershipCandidateRegistration domRegistration,
- Entity entity) {
+ EntityOwnershipCandidateRegistrationAdapter(final DOMEntityOwnershipCandidateRegistration domRegistration,
+ final Entity entity) {
super(entity);
this.domRegistration = Preconditions.checkNotNull(domRegistration);
}
private final String entityType;
private final DOMEntityOwnershipListenerRegistration domRegistration;
- EntityOwnershipListenerRegistrationAdapter(String entityType, EntityOwnershipListener listener,
- DOMEntityOwnershipListenerRegistration domRegistration) {
+ EntityOwnershipListenerRegistrationAdapter(final String entityType, final EntityOwnershipListener listener,
+ final DOMEntityOwnershipListenerRegistration domRegistration) {
super(listener);
this.entityType = Preconditions.checkNotNull(entityType);
this.domRegistration = Preconditions.checkNotNull(domRegistration);
private static class DOMEntityOwnershipListenerAdapter implements DOMEntityOwnershipListener {
private final EntityOwnershipListener delegateListener;
- DOMEntityOwnershipListenerAdapter(EntityOwnershipListener delegateListener) {
+ DOMEntityOwnershipListenerAdapter(final EntityOwnershipListener delegateListener) {
this.delegateListener = Preconditions.checkNotNull(delegateListener);
}
@Override
- public void ownershipChanged(DOMEntityOwnershipChange ownershipChange) {
+ public void ownershipChanged(final DOMEntityOwnershipChange ownershipChange) {
Entity entity = new Entity(ownershipChange.getEntity().getType(),
ownershipChange.getEntity().getIdentifier());
delegateListener.ownershipChanged(new EntityOwnershipChange(entity, ownershipChange.getState().wasOwner(),
throw caughtEx.get();
}
- NormalizedNode<?, ?> actualNode = dcListener.change.getCreatedData().get(TestModel.TEST_PATH);
+ NormalizedNode<?, ?> actualNode = dcListener.capturedChange.getCreatedData().get(TestModel.TEST_PATH);
assertEquals("Created node", testNode, actualNode);
}
static class TestDOMDataChangeListener implements DOMDataChangeListener {
- volatile AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change;
+ volatile AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> capturedChange;
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public void onDataChanged(final AsyncDataChangeEvent<YangInstanceIdentifier, NormalizedNode<?, ?>> change) {
- this.change = change;
+ this.capturedChange = change;
latch.countDown();
}
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
-class RemoteDOMRpcFuture extends AbstractFuture<DOMRpcResult> implements CheckedFuture<DOMRpcResult, DOMRpcException> {
+final class RemoteDOMRpcFuture extends AbstractFuture<DOMRpcResult>
+ implements CheckedFuture<DOMRpcResult, DOMRpcException> {
private static final Logger LOG = LoggerFactory.getLogger(RemoteDOMRpcFuture.class);
import org.opendaylight.controller.md.sal.dom.api.DOMRpcProviderService;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-public class RemoteRpcProviderFactory {
+public final class RemoteRpcProviderFactory {
+ private RemoteRpcProviderFactory() {
+
+ }
+
public static RemoteRpcProvider createInstance(final DOMRpcProviderService rpcProviderService,
final DOMRpcService rpcService, final ActorSystem actorSystem, final RemoteRpcProviderConfig config) {
private ActorRef rpcRegistry;
private ActorRef rpcRegistrar;
- private RpcManager(final DOMRpcProviderService rpcProvisionRegistry,
- final DOMRpcService rpcServices,
- final RemoteRpcProviderConfig config) {
+ RpcManager(final DOMRpcProviderService rpcProvisionRegistry, final DOMRpcService rpcServices,
+ final RemoteRpcProviderConfig config) {
this.rpcProvisionRegistry = Preconditions.checkNotNull(rpcProvisionRegistry);
this.rpcServices = Preconditions.checkNotNull(rpcServices);
this.config = Preconditions.checkNotNull(config);
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-public class ExecuteRpc implements Serializable {
+public final class ExecuteRpc implements Serializable {
private static final long serialVersionUID = 1128904894827335676L;
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "This field is not Serializable but this class "
return new BucketImpl<>(version, data);
}
- boolean setData(final T data) {
- this.data = Preconditions.checkNotNull(data);
+ boolean setData(final T newData) {
+ this.data = Preconditions.checkNotNull(newData);
if (!bumpVersion) {
return false;
}