From: Tom Pantelis Date: Wed, 12 Oct 2016 20:28:13 +0000 (-0400) Subject: Fix CS warnings in sal-clustering-commons and enable enforcement X-Git-Tag: release/carbon~431 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=4e696d9795fe7eef40369c05c340d137394126f3 Fix CS warnings in sal-clustering-commons and enable enforcement Fixed checkstyle warnings and enabled enforcement. Most of the warnings/changes were for: - white space before if/for/while/catch - white space before beginning brace - line too long - illegal catching of Exception (suppressed) - variable name too short - indentation - local vars/params hiding a field - putting overloaded methods close to one another - remove unused vars - convert functional interfaces to lambdas (eclipse save action) - empty catch block - added comment or Throwables.propagate as appropriate - missing period after first sentence in javadoc - missing first sentence in javadoc - adding final for locals declared too far from first usage Change-Id: I0a6690f97820e8fb670f209221d8e4e2f1cf5d8b Signed-off-by: Tom Pantelis --- diff --git a/opendaylight/md-sal/sal-clustering-commons/pom.xml b/opendaylight/md-sal/sal-clustering-commons/pom.xml index 4c5c620818..097fdeeaf0 100644 --- a/opendaylight/md-sal/sal-clustering-commons/pom.xml +++ b/opendaylight/md-sal/sal-clustering-commons/pom.xml @@ -220,6 +220,13 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/ActorSystemProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/ActorSystemProvider.java index 31ce16a1c0..dcb3b6b714 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/ActorSystemProvider.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/ActorSystemProvider.java @@ -17,8 +17,11 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration; * @author Thomas Pantelis */ public interface ActorSystemProvider { + /** - * @return the current ActorSystem. + * Returns the ActorSystem. + * + * @return the ActorSystem. */ @Nonnull ActorSystem getActorSystem(); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java index 730310e22e..d136d45bc7 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DataPersistenceProvider.java @@ -16,44 +16,49 @@ import akka.persistence.SnapshotSelectionCriteria; * API. */ public interface DataPersistenceProvider { + /** - * @return false if recovery is not applicable. In that case the provider is not persistent and may not have - * anything to be recovered + * Returns whether or not persistence recovery is applicable/enabled. + * + * @return true if recovery is applicable, otherwise false, in which case the provider is not persistent and may + * not have anything to be recovered */ boolean isRecoveryApplicable(); /** - * Persist a journal entry. + * Persists an entry to he applicable synchronously. * - * @param o - * @param procedure - * @param + * @param entry the journal entry to persist + * @param procedure the callback when persistence is complete + * @param the type of the journal entry */ - void persist(T o, Procedure procedure); + void persist(T entry, Procedure procedure); /** - * Save a snapshot + * Saves a snapshot. * - * @param o + * @param snapshot the snapshot object to save */ - void saveSnapshot(Object o); + void saveSnapshot(Object snapshot); /** - * Delete snapshots based on the criteria + * Deletes snapshots based on the given criteria. * - * @param criteria + * @param criteria the search criteria */ void deleteSnapshots(SnapshotSelectionCriteria criteria); /** - * Delete journal entries up to the sequence number + * Deletes journal entries up to the given sequence number. * - * @param sequenceNumber + * @param sequenceNumber the sequence number */ void deleteMessages(long sequenceNumber); /** * Returns the last sequence number contained in the journal. + * + * @return the last sequence number */ long getLastSequenceNumber(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DelegatingPersistentDataProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DelegatingPersistentDataProvider.java index e27fa26aeb..c513e38fc6 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DelegatingPersistentDataProvider.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/DelegatingPersistentDataProvider.java @@ -36,13 +36,13 @@ public class DelegatingPersistentDataProvider implements DataPersistenceProvider } @Override - public void persist(T o, Procedure procedure) { - delegate.persist(o, procedure); + public void persist(T entry, Procedure procedure) { + delegate.persist(entry, procedure); } @Override - public void saveSnapshot(Object o) { - delegate.saveSnapshot(o); + public void saveSnapshot(Object entry) { + delegate.saveSnapshot(entry); } @Override diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/NonPersistentDataProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/NonPersistentDataProvider.java index d1af58f18b..91ae8f118e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/NonPersistentDataProvider.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/NonPersistentDataProvider.java @@ -24,28 +24,32 @@ public class NonPersistentDataProvider implements DataPersistenceProvider { } @Override - public void persist(T o, Procedure procedure) { + @SuppressWarnings("checkstyle:IllegalCatch") + public void persist(T entry, Procedure procedure) { try { - procedure.apply(o); + procedure.apply(entry); } catch (Exception e) { LOG.error("An unexpected error occurred", e); } } @Override - public void saveSnapshot(Object o) { + public void saveSnapshot(Object snapshot) { + // no-op } @Override public void deleteSnapshots(SnapshotSelectionCriteria criteria) { + // no-op } @Override public void deleteMessages(long sequenceNumber) { + // no-op } @Override public long getLastSequenceNumber() { return -1; } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/PersistentDataProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/PersistentDataProvider.java index 4ccd5f4d29..b4f08c0394 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/PersistentDataProvider.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/PersistentDataProvider.java @@ -29,13 +29,13 @@ public class PersistentDataProvider implements DataPersistenceProvider { } @Override - public void persist(T o, Procedure procedure) { - persistentActor.persist(o, procedure); + public void persist(T entry, Procedure procedure) { + persistentActor.persist(entry, procedure); } @Override - public void saveSnapshot(Object o) { - persistentActor.saveSnapshot(o); + public void saveSnapshot(Object snapshot) { + persistentActor.saveSnapshot(snapshot); } @Override @@ -52,4 +52,4 @@ public class PersistentDataProvider implements DataPersistenceProvider { public long getLastSequenceNumber() { return persistentActor.lastSequenceNr(); } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractConfig.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractConfig.java index 1a331b7e99..976d48d270 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractConfig.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractConfig.java @@ -18,7 +18,7 @@ public abstract class AbstractConfig implements UnifiedConfig { private final Config config; - public AbstractConfig(Config config){ + public AbstractConfig(Config config) { this.config = config; } @@ -27,19 +27,20 @@ public abstract class AbstractConfig implements UnifiedConfig { return config; } - public static abstract class Builder> { + public abstract static class Builder> { protected Map configHolder; protected Config fallback; private final String actorSystemName; - public Builder(String actorSystemName){ + public Builder(String actorSystemName) { Preconditions.checkArgument(actorSystemName != null, "Actor system name must not be null"); this.actorSystemName = actorSystemName; configHolder = new HashMap<>(); } - public T withConfigReader(AkkaConfigurationReader reader){ + @SuppressWarnings("unchecked") + public T withConfigReader(AkkaConfigurationReader reader) { fallback = reader.read().getConfig(actorSystemName); return (T)this; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActor.java index ca303a5c12..3a4419610a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActor.java @@ -14,6 +14,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractUntypedActor extends UntypedActor { + // The member name should be lower case but it's referenced in many subclasses. Suppressing the CS warning for now. + @SuppressWarnings("checkstyle:MemberName") protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected AbstractUntypedActor() { @@ -30,8 +32,8 @@ public abstract class AbstractUntypedActor extends UntypedActor { * Receive and handle an incoming message. If the implementation does not handle this particular message, * it should call {@link #ignoreMessage(Object)} or {@link #unknownMessage(Object)}. * - * @param message Incoming message - * @throws Exception + * @param message the incoming message + * @throws Exception on message failure */ protected abstract void handleReceive(Object message) throws Exception; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java index 04d9a43c2d..2124b24faf 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedActorWithMetering.java @@ -16,17 +16,19 @@ public abstract class AbstractUntypedActorWithMetering extends AbstractUntypedAc private String actorNameOverride; public AbstractUntypedActorWithMetering() { - if (isMetricsCaptureEnabled()) + if (isMetricsCaptureEnabled()) { getContext().become(new MeteringBehavior(this)); + } } - public AbstractUntypedActorWithMetering(String actorNameOverride){ + public AbstractUntypedActorWithMetering(String actorNameOverride) { this.actorNameOverride = actorNameOverride; - if (isMetricsCaptureEnabled()) + if (isMetricsCaptureEnabled()) { getContext().become(new MeteringBehavior(this)); + } } - private boolean isMetricsCaptureEnabled(){ + private boolean isMetricsCaptureEnabled() { CommonConfig config = new CommonConfig(getContext().system().settings().config()); return config.isMetricCaptureEnabled(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java index e378fdc561..c50ec64e84 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActor.java @@ -14,6 +14,8 @@ import org.slf4j.LoggerFactory; public abstract class AbstractUntypedPersistentActor extends UntypedPersistentActor { + // The member name should be lower case but it's referenced in many subclasses. Suppressing the CS warning for now. + @SuppressWarnings("checkstyle:MemberName") protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected AbstractUntypedPersistentActor() { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActorWithMetering.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActorWithMetering.java index 365a5bd015..ed03d33491 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActorWithMetering.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/AbstractUntypedPersistentActorWithMetering.java @@ -13,11 +13,12 @@ package org.opendaylight.controller.cluster.common.actor; public abstract class AbstractUntypedPersistentActorWithMetering extends AbstractUntypedPersistentActor { public AbstractUntypedPersistentActorWithMetering() { - if (isMetricsCaptureEnabled()) + if (isMetricsCaptureEnabled()) { getContext().become(new MeteringBehavior(this)); + } } - private boolean isMetricsCaptureEnabled(){ + private boolean isMetricsCaptureEnabled() { CommonConfig config = new CommonConfig(getContext().system().settings().config()); return config.isMetricCaptureEnabled(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java index 746ef4ebb1..84ac92e0ed 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/CommonConfig.java @@ -7,15 +7,13 @@ */ package org.opendaylight.controller.cluster.common.actor; - import com.google.common.base.Preconditions; import com.typesafe.config.Config; -import scala.concurrent.duration.Duration; -import scala.concurrent.duration.FiniteDuration; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; +import scala.concurrent.duration.Duration; +import scala.concurrent.duration.FiniteDuration; public class CommonConfig extends AbstractConfig { @@ -43,8 +41,8 @@ public class CommonConfig extends AbstractConfig { return get().getString(TAG_ACTOR_SYSTEM_NAME); } - public boolean isMetricCaptureEnabled(){ - if (cachedMetricCaptureEnableFlag != null){ + public boolean isMetricCaptureEnabled() { + if (cachedMetricCaptureEnableFlag != null) { return cachedMetricCaptureEnableFlag; } @@ -89,7 +87,7 @@ public class CommonConfig extends AbstractConfig { return cachedMailBoxPushTimeout; } - public static class Builder> extends AbstractConfig.Builder{ + public static class Builder> extends AbstractConfig.Builder { public Builder(String actorSystemName) { super(actorSystemName); @@ -101,11 +99,13 @@ public class CommonConfig extends AbstractConfig { configHolder.put(TAG_MAILBOX, new HashMap()); } + @SuppressWarnings("unchecked") public T metricCaptureEnabled(boolean enabled) { configHolder.put(TAG_METRIC_CAPTURE_ENABLED, String.valueOf(enabled)); return (T)this; } + @SuppressWarnings("unchecked") public T mailboxCapacity(int capacity) { Preconditions.checkArgument(capacity > 0, "mailbox capacity must be >0"); @@ -114,7 +114,8 @@ public class CommonConfig extends AbstractConfig { return (T)this; } - public T mailboxPushTimeout(String timeout){ + @SuppressWarnings("unchecked") + public T mailboxPushTimeout(String timeout) { Duration pushTimeout = Duration.create(timeout); Preconditions.checkArgument(pushTimeout.isFinite(), "invalid value for mailbox push timeout"); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/ExplicitAsk.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/ExplicitAsk.java index c1f7c8b2e5..e241d880c9 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/ExplicitAsk.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/ExplicitAsk.java @@ -53,7 +53,8 @@ public final class ExplicitAsk { return ASK_SUPPORT.ask(actor, (Function1)function, timeout); } - public static Future ask(final ActorRef actor, final Function function, final Timeout timeout) { + public static Future ask(final ActorRef actor, final Function function, + final Timeout timeout) { return ask(actor, toScala(function), timeout); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/FileAkkaConfigurationReader.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/FileAkkaConfigurationReader.java index 1e3adf9d39..883dbd7210 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/FileAkkaConfigurationReader.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/FileAkkaConfigurationReader.java @@ -23,7 +23,7 @@ public class FileAkkaConfigurationReader implements AkkaConfigurationReader { Preconditions.checkState(customConfigFile.exists(), "%s is missing", customConfigFile); File factoryConfigFile = new File(FACTORY_AKKA_CONF_PATH); - if(factoryConfigFile.exists()) { + if (factoryConfigFile.exists()) { return ConfigFactory.parseFile(customConfigFile).withFallback(ConfigFactory.parseFile(factoryConfigFile)); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MessageTracker.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MessageTracker.java index a602136229..326430922c 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MessageTracker.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MessageTracker.java @@ -10,6 +10,7 @@ package org.opendaylight.controller.cluster.common.actor; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; + import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; @@ -56,7 +57,7 @@ import org.slf4j.LoggerFactory; @Beta @NotThreadSafe public final class MessageTracker { - public static abstract class Context implements AutoCloseable { + public abstract static class Context implements AutoCloseable { Context() { // Hidden to prevent outside instantiation } @@ -69,7 +70,9 @@ public final class MessageTracker { public interface Error { Object getLastExpectedMessage(); + Object getCurrentExpectedMessage(); + List getMessageProcessingTimesSinceLastExpectedMessage(); } @@ -85,12 +88,11 @@ public final class MessageTracker { @Override public String toString() { - return "MessageProcessingTime{" + - "messageClass=" + messageClass.getSimpleName() + - ", elapsedTimeInMillis=" + NANOSECONDS.toMillis(elapsedTimeInNanos) + - '}'; + return "MessageProcessingTime [messageClass=" + messageClass + ", elapsedTimeInMillis=" + + NANOSECONDS.toMillis(elapsedTimeInNanos) + "]"; } + public Class getMessageClass() { return messageClass; } @@ -139,9 +141,10 @@ public final class MessageTracker { } /** + * Constructs an instance. * - * @param expectedMessageClass The class of the message to track - * @param expectedArrivalIntervalInMillis The expected arrival interval between two instances of the expected + * @param expectedMessageClass the class of the message to track + * @param expectedArrivalIntervalInMillis the expected arrival interval between two instances of the expected * message */ public MessageTracker(final Class expectedMessageClass, final long expectedArrivalIntervalInMillis) { @@ -234,6 +237,7 @@ public final class MessageTracker { private abstract class AbstractTimedContext extends Context { abstract Object message(); + abstract Stopwatch stopTimer(); @Override @@ -246,10 +250,10 @@ public final class MessageTracker { private final Stopwatch stopwatch = Stopwatch.createUnstarted(ticker); private Object message; - void reset(final Object message) { - this.message = Preconditions.checkNotNull(message); + void reset(final Object newMessage) { + this.message = Preconditions.checkNotNull(newMessage); Preconditions.checkState(!stopwatch.isRunning(), - "Trying to reset a context that is not done (%s). currentMessage = %s", this, message); + "Trying to reset a context that is not done (%s). currentMessage = %s", this, newMessage); stopwatch.start(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java index 7f3e1354cf..60a5106db4 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailbox.java @@ -21,17 +21,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.concurrent.duration.FiniteDuration; -public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue { - - private final Logger LOG = LoggerFactory.getLogger(MeteredBoundedMailbox.class); +public class MeteredBoundedMailbox implements MailboxType, + ProducesMessageQueue { + private static final Logger LOG = LoggerFactory.getLogger(MeteredBoundedMailbox.class); + private static final String QUEUE_SIZE = "q-size"; private MeteredMessageQueue queue; private final Integer capacity; private final FiniteDuration pushTimeOut; private final MetricRegistry registry; - private final String QUEUE_SIZE = "q-size"; - public MeteredBoundedMailbox(ActorSystem.Settings settings, Config config) { CommonConfig commonConfig = new CommonConfig(settings.config()); @@ -57,8 +56,7 @@ public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue< String actorName = owner.get().path().toStringWithoutAddress(); String metricName = MetricRegistry.name(actorName, QUEUE_SIZE); - if (registry.getMetrics().containsKey(metricName)) - { + if (registry.getMetrics().containsKey(metricName)) { return; //already registered } @@ -75,16 +73,11 @@ public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue< } } - private static Gauge getQueueSizeGuage(final MeteredMessageQueue monitoredQueue ){ - return new Gauge() { - @Override - public Integer getValue() { - return monitoredQueue.size(); - } - }; + private static Gauge getQueueSizeGuage(final MeteredMessageQueue monitoredQueue ) { + return () -> monitoredQueue.size(); } - private void registerQueueSizeMetric(String metricName, Gauge metric){ + private void registerQueueSizeMetric(String metricName, Gauge metric) { try { registry.register(metricName,metric); } catch (IllegalArgumentException e) { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java index 36c35be30a..45fe193338 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/MeteringBehavior.java @@ -12,7 +12,6 @@ import akka.japi.Procedure; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; import org.opendaylight.controller.cluster.reporting.MetricsReporter; /** @@ -23,21 +22,22 @@ import org.opendaylight.controller.cluster.reporting.MetricsReporter; *
  • message processing rate of actor's receive block
  • *
  • message processing rate by message type
  • * - * * The information is reported to {@link org.opendaylight.controller.cluster.reporting.MetricsReporter} */ public class MeteringBehavior implements Procedure { public static final String DOMAIN = "org.opendaylight.controller.actor.metric"; + private static final String MSG_PROCESSING_RATE = "msg-rate"; + private final UntypedActor meteredActor; - private final MetricRegistry METRICREGISTRY = MetricsReporter.getInstance(DOMAIN).getMetricsRegistry(); - private final String MSG_PROCESSING_RATE = "msg-rate"; + private final MetricRegistry metricRegistry = MetricsReporter.getInstance(DOMAIN).getMetricsRegistry(); private String actorQualifiedName; private Timer msgProcessingTimer; /** + * Constructs an instance. * * @param actor whose behaviour needs to be metered */ @@ -59,11 +59,11 @@ public class MeteringBehavior implements Procedure { } private void init(final String actorName) { - actorQualifiedName = new StringBuilder(meteredActor.getSelf().path().parent().toStringWithoutAddress()). - append("/").append(actorName).toString(); + actorQualifiedName = new StringBuilder(meteredActor.getSelf().path().parent().toStringWithoutAddress()) + .append("/").append(actorName).toString(); final String msgProcessingTime = MetricRegistry.name(actorQualifiedName, MSG_PROCESSING_RATE); - msgProcessingTimer = METRICREGISTRY.timer(msgProcessingTime); + msgProcessingTimer = metricRegistry.timer(msgProcessingTime); } /** @@ -79,8 +79,8 @@ public class MeteringBehavior implements Procedure { * @see * http://dropwizard.github.io/metrics/manual/core/#timers * - * @param message - * @throws Exception + * @param message the message to process + * @throws Exception on message failure */ @Override public void apply(final Object message) throws Exception { @@ -89,18 +89,13 @@ public class MeteringBehavior implements Procedure { final String msgProcessingTimeByMsgType = MetricRegistry.name(actorQualifiedName, MSG_PROCESSING_RATE, messageType); - final Timer msgProcessingTimerByMsgType = METRICREGISTRY.timer(msgProcessingTimeByMsgType); + final Timer msgProcessingTimerByMsgType = metricRegistry.timer(msgProcessingTimeByMsgType); //start timers final Timer.Context context = msgProcessingTimer.time(); final Timer.Context contextByMsgType = msgProcessingTimerByMsgType.time(); - try { - meteredActor.onReceive(message); - } catch (Throwable t) { - Throwables.propagateIfPossible(t, Exception.class); - throw Throwables.propagate(t); - } + meteredActor.onReceive(message); //stop timers contextByMsgType.stop(); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java index f81b34aad8..004d289715 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/Monitor.java @@ -9,14 +9,13 @@ package org.opendaylight.controller.cluster.common.actor; import akka.actor.ActorRef; - import java.io.Serializable; public class Monitor implements Serializable { private static final long serialVersionUID = 1L; private final ActorRef actorRef; - public Monitor(ActorRef actorRef){ + public Monitor(ActorRef actorRef) { this.actorRef = actorRef; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/QuarantinedMonitorActor.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/QuarantinedMonitorActor.java index a9f58898d4..9cb592a4c7 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/QuarantinedMonitorActor.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/QuarantinedMonitorActor.java @@ -23,12 +23,12 @@ import org.slf4j.LoggerFactory; * quarantined by another. Once this node gets quarantined, restart the ActorSystem to allow this * node to rejoin the cluster. * - * @author Gary Wu + * @author Gary Wu gary.wu1@huawei.com * */ public class QuarantinedMonitorActor extends UntypedActor { - private final Logger LOG = LoggerFactory.getLogger(QuarantinedMonitorActor.class); + private static final Logger LOG = LoggerFactory.getLogger(QuarantinedMonitorActor.class); public static final String ADDRESS = "quarantined-monitor"; @@ -55,7 +55,7 @@ public class QuarantinedMonitorActor extends UntypedActor { // check to see if we got quarantined by another node - if(quarantined) { + if (quarantined) { return; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/UnifiedConfig.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/UnifiedConfig.java index 903987a027..198ddf7ca8 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/UnifiedConfig.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/common/actor/UnifiedConfig.java @@ -17,14 +17,14 @@ import com.typesafe.config.Config; *
  • Config subsystem
  • *
  • Akka configuration files
  • * - * * Configurations defined in config subsystem takes precedence. */ public interface UnifiedConfig { /** - * Returns an immutable instance of unified configuration - * @return + * Returns an immutable instance of unified configuration. + * + * @return a Config instance */ Config get(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java index 5602b48e1b..8ca0e76b01 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java @@ -16,7 +16,6 @@ import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessa import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; public class NormalizedNodeToNodeCodec { public interface Encoded { @@ -31,13 +30,10 @@ public class NormalizedNodeToNodeCodec { YangInstanceIdentifier getDecodedPath(); } - private final SchemaContext ctx; - - public NormalizedNodeToNodeCodec(final SchemaContext ctx){ - this.ctx = ctx; + public NormalizedNodeToNodeCodec() { } - public NormalizedNodeMessages.Container encode(NormalizedNode node){ + public NormalizedNodeMessages.Container encode(NormalizedNode node) { return encode(null, node).getEncodedNode(); } @@ -50,8 +46,8 @@ public class NormalizedNodeToNodeCodec { // Note: parent path is no longer used builder.setParentPath(""); - if(node != null) { - if(path == null) { + if (node != null) { + if (path == null) { builder.setNormalizedNode(NormalizedNodeSerializer.serialize(node)); } else { Serializer serializer = NormalizedNodeSerializer.newSerializer(node); @@ -64,13 +60,13 @@ public class NormalizedNodeToNodeCodec { } - public NormalizedNode decode(NormalizedNodeMessages.Node node){ + public NormalizedNode decode(NormalizedNodeMessages.Node node) { return decode(null, node).getDecodedNode(); } public Decoded decode(NormalizedNodeMessages.InstanceIdentifier path, NormalizedNodeMessages.Node node) { - if(node.getIntType() < 0 || node.getSerializedSize() == 0){ + if (node.getIntType() < 0 || node.getSerializedSize() == 0) { return new DecodedImpl(null, null); } @@ -84,7 +80,7 @@ public class NormalizedNodeToNodeCodec { private final NormalizedNode decodedNode; private final YangInstanceIdentifier decodedPath; - public DecodedImpl(NormalizedNode decodedNode, YangInstanceIdentifier decodedPath) { + DecodedImpl(NormalizedNode decodedNode, YangInstanceIdentifier decodedPath) { this.decodedNode = decodedNode; this.decodedPath = decodedPath; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java index 296b744177..a0a2d0408d 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java @@ -17,7 +17,8 @@ import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class AugmentationIdentifierGenerator { - private static final Pattern PATTERN = Pattern.compile("AugmentationIdentifier\\Q{\\EchildNames=\\Q[\\E(.*)\\Q]}\\E"); + private static final Pattern PATTERN = + Pattern.compile("AugmentationIdentifier\\Q{\\EchildNames=\\Q[\\E(.*)\\Q]}\\E"); private static final Splitter COMMA_SPLITTER = Splitter.on(',').trimResults(); private final String id; @@ -44,5 +45,4 @@ public class AugmentationIdentifierGenerator { return new YangInstanceIdentifier.AugmentationIdentifier(childNames); } - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java index 08fd997aae..acfb05fc38 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java @@ -8,43 +8,43 @@ package org.opendaylight.controller.cluster.datastore.node.utils; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; - import java.util.HashMap; import java.util.Map; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; public class NodeIdentifierFactory { - private static final Map cache = new HashMap<>(); - public static YangInstanceIdentifier.PathArgument getArgument(String id){ - YangInstanceIdentifier.PathArgument value = cache.get(id); - if(value == null){ - synchronized (cache){ - value = cache.get(id); - if(value == null) { + private static final Map CACHE = new HashMap<>(); + + public static YangInstanceIdentifier.PathArgument getArgument(String id) { + YangInstanceIdentifier.PathArgument value = CACHE.get(id); + if (value == null) { + synchronized (CACHE) { + value = CACHE.get(id); + if (value == null) { value = createPathArgument(id, null); - cache.put(id, value); + CACHE.put(id, value); } } } return value; } - public static YangInstanceIdentifier.PathArgument createPathArgument(String id, DataSchemaNode schemaNode){ + public static YangInstanceIdentifier.PathArgument createPathArgument(String id, DataSchemaNode schemaNode) { final NodeIdentifierWithPredicatesGenerator nodeIdentifierWithPredicatesGenerator = new NodeIdentifierWithPredicatesGenerator(id, schemaNode); - if(nodeIdentifierWithPredicatesGenerator.matches()){ + if (nodeIdentifierWithPredicatesGenerator.matches()) { return nodeIdentifierWithPredicatesGenerator.getPathArgument(); } final NodeIdentifierWithValueGenerator nodeWithValueGenerator = new NodeIdentifierWithValueGenerator(id, schemaNode); - if(nodeWithValueGenerator.matches()){ + if (nodeWithValueGenerator.matches()) { return nodeWithValueGenerator.getPathArgument(); } final AugmentationIdentifierGenerator augmentationIdentifierGenerator = new AugmentationIdentifierGenerator(id); - if(augmentationIdentifierGenerator.matches()){ + if (augmentationIdentifierGenerator.matches()) { return augmentationIdentifierGenerator.getPathArgument(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java index c8afd1df38..b10d834dd5 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java @@ -12,15 +12,13 @@ import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class NodeIdentifierGenerator { - private final String id; - private final QName qName; + private final QName qname; - public NodeIdentifierGenerator(String id){ - this.id = id; - this.qName = QNameFactory.create(id); + public NodeIdentifierGenerator(String id) { + this.qname = QNameFactory.create(id); } - public YangInstanceIdentifier.PathArgument getArgument(){ - return new YangInstanceIdentifier.NodeIdentifier(qName); + public YangInstanceIdentifier.PathArgument getArgument() { + return new YangInstanceIdentifier.NodeIdentifier(qname); } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java index 11386e75a4..fa9783be04 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java @@ -8,31 +8,34 @@ package org.opendaylight.controller.cluster.datastore.node.utils; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +public class NodeIdentifierWithPredicatesGenerator { + private static final Logger LOG = LoggerFactory.getLogger(NodeIdentifierWithPredicatesGenerator.class); + private static final Pattern PATTERN = Pattern.compile("(.*)\\Q[{\\E(.*)\\Q}]\\E"); -public class NodeIdentifierWithPredicatesGenerator{ private final String id; - private static final Pattern pattern = Pattern.compile("(.*)\\Q[{\\E(.*)\\Q}]\\E"); private final Matcher matcher; private final boolean doesMatch; private final ListSchemaNode listSchemaNode; - public NodeIdentifierWithPredicatesGenerator(String id, DataSchemaNode schemaNode){ + public NodeIdentifierWithPredicatesGenerator(String id, DataSchemaNode schemaNode) { this.id = id; - matcher = pattern.matcher(this.id); + matcher = PATTERN.matcher(this.id); doesMatch = matcher.matches(); - if(schemaNode instanceof ListSchemaNode){ + if (schemaNode instanceof ListSchemaNode) { this.listSchemaNode = (ListSchemaNode) schemaNode; } else { this.listSchemaNode = null; @@ -40,35 +43,36 @@ public class NodeIdentifierWithPredicatesGenerator{ } - public boolean matches(){ + public boolean matches() { return doesMatch; } - public YangInstanceIdentifier.NodeIdentifierWithPredicates getPathArgument(){ + public YangInstanceIdentifier.NodeIdentifierWithPredicates getPathArgument() { final String group = matcher.group(2); final String[] keyValues = group.split(","); Map nameValues = new HashMap<>(); - for(String keyValue : keyValues){ + for (String keyValue : keyValues) { int eqIndex = keyValue.lastIndexOf('='); try { final QName key = QNameFactory .create(keyValue.substring(0, eqIndex)); nameValues.put(key, getValue(key, keyValue.substring(eqIndex + 1))); - } catch(IllegalArgumentException e){ - System.out.println("Error processing identifier : " + id); + } catch (IllegalArgumentException e) { + LOG.error("Error processing identifier {}", id, e); throw e; } } - return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QNameFactory.create(matcher.group(1)), nameValues); + return new YangInstanceIdentifier.NodeIdentifierWithPredicates( + QNameFactory.create(matcher.group(1)), nameValues); } - private Object getValue(QName key, String value){ - if(listSchemaNode != null){ - for(DataSchemaNode node : listSchemaNode.getChildNodes()){ - if(node instanceof LeafSchemaNode && node.getQName().equals(key)){ + private Object getValue(QName key, String value) { + if (listSchemaNode != null) { + for (DataSchemaNode node : listSchemaNode.getChildNodes()) { + if (node instanceof LeafSchemaNode && node.getQName().equals(key)) { return TypeDefinitionAwareCodec.from(LeafSchemaNode.class.cast(node).getType()).deserialize(value); } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java index 9dce97f9aa..6ecf9050c3 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java @@ -8,49 +8,48 @@ package org.opendaylight.controller.cluster.datastore.node.utils; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +public class NodeIdentifierWithValueGenerator { + private static final Pattern PATTERN = Pattern.compile("(.*)\\Q[\\E(.*)\\Q]\\E"); -public class NodeIdentifierWithValueGenerator{ - private final String id; + private final String id; private final DataSchemaNode schemaNode; - private static final Pattern pattern = Pattern.compile("(.*)\\Q[\\E(.*)\\Q]\\E"); - private final Matcher matcher; - private final boolean doesMatch; - - public NodeIdentifierWithValueGenerator(String id, DataSchemaNode schemaNode){ - this.id = id; - this.schemaNode = schemaNode; - matcher = pattern.matcher(this.id); - doesMatch = matcher.matches(); - } + private final Matcher matcher; + private final boolean doesMatch; + + public NodeIdentifierWithValueGenerator(String id, DataSchemaNode schemaNode) { + this.id = id; + this.schemaNode = schemaNode; + matcher = PATTERN.matcher(this.id); + doesMatch = matcher.matches(); + } - public boolean matches(){ - return doesMatch; - } + public boolean matches() { + return doesMatch; + } - public YangInstanceIdentifier.PathArgument getPathArgument(){ - final String name = matcher.group(1); - final String value = matcher.group(2); + public YangInstanceIdentifier.PathArgument getPathArgument() { + final String name = matcher.group(1); + final String value = matcher.group(2); - return new YangInstanceIdentifier.NodeWithValue<>( - QNameFactory.create(name), getValue(value)); - } + return new YangInstanceIdentifier.NodeWithValue<>(QNameFactory.create(name), getValue(value)); + } - private Object getValue(String value){ - if(schemaNode != null){ - if(schemaNode instanceof LeafListSchemaNode){ - return TypeDefinitionAwareCodec - .from(LeafListSchemaNode.class.cast(schemaNode).getType()).deserialize(value); + private Object getValue(String value) { + if (schemaNode != null) { + if (schemaNode instanceof LeafListSchemaNode) { + return TypeDefinitionAwareCodec.from(LeafListSchemaNode.class.cast(schemaNode).getType()) + .deserialize(value); - } } - return value; } - + return value; } + +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java index 20529996f8..e1e7b9f684 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java @@ -16,21 +16,21 @@ public class NormalizedNodeGetter implements private final String path; NormalizedNode output; - public NormalizedNodeGetter(String path){ + public NormalizedNodeGetter(String path) { Preconditions.checkNotNull(path); this.path = path; } @Override public void visitNode(int level, String parentPath, NormalizedNode normalizedNode) { - String nodePath = parentPath + "/"+ PathUtils.toString(normalizedNode.getIdentifier()); + String nodePath = parentPath + "/" + PathUtils.toString(normalizedNode.getIdentifier()); - if(nodePath.toString().equals(path)){ + if (nodePath.toString().equals(path)) { output = normalizedNode; } } - public NormalizedNode getOutput(){ + public NormalizedNode getOutput() { return output; } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java index 0b7cb373d4..a4e0b70a02 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java @@ -17,73 +17,69 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; /** - * NormalizedNodeNavigator walks a {@link NormalizedNodeVisitor} through the NormalizedNode - * - * {@link NormalizedNode } is a tree like structure that provides a generic structure for a yang data model - * - * For examples of visitors - * @see NormalizedNodePrinter - * - * + * NormalizedNodeNavigator walks a {@link NormalizedNodeVisitor} through the NormalizedNode. */ public class NormalizedNodeNavigator { - private final org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeVisitor - visitor; - - public NormalizedNodeNavigator( - org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeVisitor visitor){ - Preconditions.checkNotNull(visitor, "visitor should not be null"); - this.visitor = visitor; - } - public void navigate(String parentPath, NormalizedNode normalizedNode){ - if(parentPath == null){ - parentPath = ""; - } - navigateNormalizedNode(0, parentPath, normalizedNode); - } - - private void navigateDataContainerNode(int level, final String parentPath, final DataContainerNode dataContainerNode){ - visitor.visitNode(level, parentPath ,dataContainerNode); + private final org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeVisitor visitor; - String newParentPath = parentPath + "/" + dataContainerNode.getIdentifier().toString(); + public NormalizedNodeNavigator( + org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeVisitor visitor) { + Preconditions.checkNotNull(visitor, "visitor should not be null"); + this.visitor = visitor; + } - final Iterable> value = dataContainerNode.getValue(); - for(NormalizedNode node : value){ - if(node instanceof MixinNode && node instanceof NormalizedNodeContainer){ - navigateNormalizedNodeContainerMixin(level, newParentPath, (NormalizedNodeContainer) node); - } else { - navigateNormalizedNode(level, newParentPath, node); - } + public void navigate(String parentPath, NormalizedNode normalizedNode) { + if (parentPath == null) { + parentPath = ""; + } + navigateNormalizedNode(0, parentPath, normalizedNode); } - } + private void navigateDataContainerNode(int level, final String parentPath, + final DataContainerNode dataContainerNode) { + visitor.visitNode(level, parentPath, dataContainerNode); - private void navigateNormalizedNodeContainerMixin(int level, final String parentPath, NormalizedNodeContainer node) { - visitor.visitNode(level, parentPath, node); + String newParentPath = parentPath + "/" + dataContainerNode.getIdentifier().toString(); - String newParentPath = parentPath + "/" + node.getIdentifier().toString(); + final Iterable> value = dataContainerNode + .getValue(); + for (NormalizedNode node : value) { + if (node instanceof MixinNode && node instanceof NormalizedNodeContainer) { + navigateNormalizedNodeContainerMixin(level, newParentPath, (NormalizedNodeContainer) node); + } else { + navigateNormalizedNode(level, newParentPath, node); + } + } - final Iterable> value = node.getValue(); - for(NormalizedNode normalizedNode : value){ - if(normalizedNode instanceof MixinNode && normalizedNode instanceof NormalizedNodeContainer){ - navigateNormalizedNodeContainerMixin(level + 1, newParentPath, (NormalizedNodeContainer) normalizedNode); - } else { - navigateNormalizedNode(level, newParentPath, normalizedNode); - } } - } + private void navigateNormalizedNodeContainerMixin(int level, final String parentPath, + NormalizedNodeContainer node) { + visitor.visitNode(level, parentPath, node); + + String newParentPath = parentPath + "/" + node.getIdentifier().toString(); + final Iterable> value = node.getValue(); + for (NormalizedNode normalizedNode : value) { + if (normalizedNode instanceof MixinNode && normalizedNode instanceof NormalizedNodeContainer) { + navigateNormalizedNodeContainerMixin(level + 1, newParentPath, + (NormalizedNodeContainer) normalizedNode); + } else { + navigateNormalizedNode(level, newParentPath, normalizedNode); + } + } + + } - private void navigateNormalizedNode(int level, String parentPath, NormalizedNode normalizedNode){ - if(normalizedNode instanceof DataContainerNode){ + private void navigateNormalizedNode(int level, String parentPath, NormalizedNode normalizedNode) { + if (normalizedNode instanceof DataContainerNode) { - final DataContainerNode dataContainerNode = (DataContainerNode) normalizedNode; + final DataContainerNode dataContainerNode = (DataContainerNode) normalizedNode; - navigateDataContainerNode(level + 1, parentPath, dataContainerNode); - } else { - visitor.visitNode(level+1, parentPath, normalizedNode); + navigateDataContainerNode(level + 1, parentPath, dataContainerNode); + } else { + visitor.visitNode(level + 1, parentPath, normalizedNode); + } } - } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java deleted file mode 100644 index 23f314e292..0000000000 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.cluster.datastore.node.utils; - -import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; -import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -public class NormalizedNodePrinter implements NormalizedNodeVisitor { - - private static String spaces(int n){ - StringBuilder builder = new StringBuilder(); - for(int i=0;i normalizedNode) { - System.out.println(spaces((level) * 4) + normalizedNode.getClass().toString() + ":" + normalizedNode.getIdentifier()); - if(normalizedNode instanceof LeafNode || normalizedNode instanceof LeafSetEntryNode){ - System.out.println(spaces((level) * 4) + " parentPath = " + parentPath); - System.out.println(spaces((level) * 4) + " key = " + normalizedNode.getClass().toString() + ":" + normalizedNode.getIdentifier()); - System.out.println(spaces((level) * 4) + " value = " + normalizedNode.getValue()); - } - } -} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java index 8324b64aaa..588fc648fd 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java @@ -24,12 +24,27 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgum public class PathUtils { private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings(); + /** + * Given a serialized string version of a YangInstanceIdentifier convert + * to a YangInstanceIdentifier. + * + * @param path the path + * @return a YangInstanceIdentifier + */ + public static YangInstanceIdentifier toYangInstanceIdentifier(String path) { + List pathArguments = new ArrayList<>(); + for (String segment : SLASH_SPLITTER.split(path)) { + pathArguments.add(NodeIdentifierFactory.getArgument(segment)); + } + return YangInstanceIdentifier.create(pathArguments); + } + /** * Given a YangInstanceIdentifier return a serialized version of the same - * as a String + * as a String. * - * @param path - * @return + * @param path the path + * @return the path as a String */ public static String toString(YangInstanceIdentifier path) { final Iterator it = path.getPathArguments().iterator(); @@ -51,45 +66,30 @@ public class PathUtils { /** * Given a YangInstanceIdentifier.PathArgument return a serialized version - * of the same as a String + * of the same as a String. * - * @param pathArgument - * @return + * @param pathArgument the path argument + * @return the path argument as a String */ - public static String toString(PathArgument pathArgument){ - if(pathArgument instanceof NodeIdentifier){ + public static String toString(PathArgument pathArgument) { + if (pathArgument instanceof NodeIdentifier) { return toString((NodeIdentifier) pathArgument); - } else if(pathArgument instanceof AugmentationIdentifier){ + } else if (pathArgument instanceof AugmentationIdentifier) { return toString((AugmentationIdentifier) pathArgument); - } else if(pathArgument instanceof NodeWithValue){ + } else if (pathArgument instanceof NodeWithValue) { return toString((NodeWithValue) pathArgument); - } else if(pathArgument instanceof NodeIdentifierWithPredicates){ + } else if (pathArgument instanceof NodeIdentifierWithPredicates) { return toString((NodeIdentifierWithPredicates) pathArgument); } return pathArgument.toString(); } - /** - * Given a serialized string version of a YangInstanceIdentifier convert - * to a YangInstanceIdentifier - * - * @param path - * @return - */ - public static YangInstanceIdentifier toYangInstanceIdentifier(String path){ - List pathArguments = new ArrayList<>(); - for (String segment : SLASH_SPLITTER.split(path)) { - pathArguments.add(NodeIdentifierFactory.getArgument(segment)); - } - return YangInstanceIdentifier.create(pathArguments); - } - - private static String toString(NodeIdentifier pathArgument){ + private static String toString(NodeIdentifier pathArgument) { return pathArgument.getNodeType().toString(); } - private static String toString(AugmentationIdentifier pathArgument){ + private static String toString(AugmentationIdentifier pathArgument) { Set childNames = pathArgument.getPossibleChildNames(); final StringBuilder sb = new StringBuilder("AugmentationIdentifier{"); sb.append("childNames=").append(childNames).append('}'); @@ -101,8 +101,7 @@ public class PathUtils { return pathArgument.getNodeType().toString() + "[" + pathArgument.getValue() + "]"; } - private static String toString(NodeIdentifierWithPredicates pathArgument){ + private static String toString(NodeIdentifierWithPredicates pathArgument) { return pathArgument.getNodeType().toString() + '[' + pathArgument.getKeyValues() + ']'; } - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java index 4d26f74106..7d5379dfe0 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java @@ -30,7 +30,7 @@ public class QNameFactory { ); - public static QName create(String name){ + public static QName create(String name) { return CACHE.getUnchecked(name); } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeDeSerializationContext.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeDeSerializationContext.java index 0ed1317997..f072a61406 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeDeSerializationContext.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeDeSerializationContext.java @@ -10,11 +10,13 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; /** * NormalizedNodeDeSerializationContext provides methods which help in decoding - * certain components of a NormalizedNode properly + * certain components of a NormalizedNode properly. */ public interface NormalizedNodeDeSerializationContext { String getNamespace(int namespace); + String getRevision(int revision); + String getLocalName(int localName); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializationContext.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializationContext.java index 1920702527..d62cc8dc89 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializationContext.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializationContext.java @@ -10,7 +10,7 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; /** * NormalizedNodeSerializationContext provides methods which help in encoding - * certain components of a NormalizedNode properly + * certain components of a NormalizedNode properly. */ public interface NormalizedNodeSerializationContext { } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java index e4ba73c3b1..84c2ae515a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializer.java @@ -22,6 +22,7 @@ import static org.opendaylight.controller.cluster.datastore.node.utils.serializa import static org.opendaylight.controller.cluster.datastore.node.utils.serialization.NormalizedNodeType.UNKEYED_LIST_ENTRY_NODE_TYPE; import static org.opendaylight.controller.cluster.datastore.node.utils.serialization.NormalizedNodeType.UNKEYED_LIST_NODE_TYPE; import static org.opendaylight.controller.cluster.datastore.node.utils.serialization.NormalizedNodeType.getSerializableNodeType; + import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import java.util.EnumMap; @@ -62,7 +63,7 @@ public class NormalizedNodeSerializer { /** * Serialize a NormalizedNode into a protocol buffer message - *

    + *

    * The significant things to be aware of the Serialization process are *

      *
    • Repeated strings like namespaces, revisions and localNames are @@ -74,16 +75,15 @@ public class NormalizedNodeSerializer { * figure out how to decode values *
    • *
    - * * One question which may arise is why not use something like gzip to * compress the protocol buffer message instead of rolling our own * encoding scheme. This has to be explored further as it is a more * general solution. * - * @param node - * @return + * @param node the node + * @return a NormalizedNodeMessages.Node */ - public static NormalizedNodeMessages.Node serialize(final NormalizedNode node){ + public static NormalizedNodeMessages.Node serialize(final NormalizedNode node) { Preconditions.checkNotNull(node, "node should not be null"); return new Serializer(node).serialize(); } @@ -94,22 +94,16 @@ public class NormalizedNodeSerializer { } /** - * DeSerialize a protocol buffer message back into a NormalizedNode + * DeSerialize a protocol buffer message back into a NormalizedNode. * - * @param node - * @return + * @param node the node + * @return a NormalizedNode */ public static NormalizedNode deSerialize(final NormalizedNodeMessages.Node node) { Preconditions.checkNotNull(node, "node should not be null"); return new DeSerializer(null, node).deSerialize(); } - public static DeSerializer newDeSerializer(final NormalizedNodeMessages.InstanceIdentifier path, - final NormalizedNodeMessages.Node node) { - Preconditions.checkNotNull(node, "node should not be null"); - return new DeSerializer(path, node); - } - /** * DeSerialize a PathArgument which is in the protocol buffer format into * a yang PathArgument. The protocol buffer path argument is specially @@ -118,18 +112,20 @@ public class NormalizedNodeSerializer { * is that during the NormalizedNode serialization process certain repeated * strings are encoded into a "codes" list and the actual strings are * replaced by an integer which is an index into that list. - * - * @param node - * @param pathArgument - * @return */ public static YangInstanceIdentifier.PathArgument deSerialize(final NormalizedNodeMessages.Node node, - final NormalizedNodeMessages.PathArgument pathArgument){ + final NormalizedNodeMessages.PathArgument pathArgument) { Preconditions.checkNotNull(node, "node should not be null"); Preconditions.checkNotNull(pathArgument, "pathArgument should not be null"); return new DeSerializer(null, node).deSerialize(pathArgument); } + public static DeSerializer newDeSerializer(final NormalizedNodeMessages.InstanceIdentifier path, + final NormalizedNodeMessages.Node node) { + Preconditions.checkNotNull(node, "node should not be null"); + return new DeSerializer(path, node); + } + public static class Serializer extends QNameSerializationContextImpl implements NormalizedNodeSerializationContext { @@ -155,15 +151,14 @@ public class NormalizedNodeSerializer { return builder.addAllCode(getCodes()).build(); } - private NormalizedNodeMessages.Node.Builder serialize( - final NormalizedNode node) { + private NormalizedNodeMessages.Node.Builder serialize(final NormalizedNode fromNode) { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); - builder.setPathArgument(PathArgumentSerializer.serialize(this, node.getIdentifier())); - Integer nodeType = getSerializableNodeType(node).ordinal(); + builder.setPathArgument(PathArgumentSerializer.serialize(this, fromNode.getIdentifier())); + Integer nodeType = getSerializableNodeType(fromNode).ordinal(); builder.setIntType(nodeType); - Object value = node.getValue(); + Object value = fromNode.getValue(); // We need to do a specific check of the type of the node here // because if we looked at the value type alone we will not be @@ -175,8 +170,8 @@ public class NormalizedNodeSerializer { // which is also a Collection. Without the following check being // done first the code would flow into the Collection if condition // and the Set would be added as child nodes - if(nodeType == NormalizedNodeType.LEAF_NODE_TYPE.ordinal() || - nodeType == NormalizedNodeType.LEAF_SET_ENTRY_NODE_TYPE.ordinal()){ + if (nodeType == NormalizedNodeType.LEAF_NODE_TYPE.ordinal() + || nodeType == NormalizedNodeType.LEAF_SET_ENTRY_NODE_TYPE.ordinal()) { ValueSerializer.serialize(builder, this, value); @@ -202,117 +197,74 @@ public class NormalizedNodeSerializer { } } + @SuppressWarnings("rawtypes") public static class DeSerializer extends QNameDeSerializationContextImpl implements NormalizedNodeDeSerializationContext { private static final Map DESERIALIZATION_FUNCTIONS; + static { final EnumMap m = new EnumMap<>(NormalizedNodeType.class); - m.put(CONTAINER_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - DataContainerNodeAttrBuilder builder = Builders.containerBuilder() - .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); + m.put(CONTAINER_NODE_TYPE, (deSerializer, node) -> { + DataContainerNodeAttrBuilder builder = Builders.containerBuilder() + .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); - return deSerializer.buildDataContainer(builder, node); - } + return deSerializer.buildDataContainer(builder, node); }); - m.put(LEAF_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - NormalizedNodeAttrBuilder> builder = Builders.leafBuilder() - .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); + m.put(LEAF_NODE_TYPE, (deSerializer, node) -> { + NormalizedNodeAttrBuilder> builder = Builders.leafBuilder() + .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); - return deSerializer.buildNormalizedNode(builder, node); - } - }); - m.put(MAP_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - return deSerializer.buildCollectionNode(Builders.mapBuilder(), node); - } - }); - m.put(MAP_ENTRY_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - DataContainerNodeAttrBuilder builder = - Builders.mapEntryBuilder().withNodeIdentifier(deSerializer.toNodeIdentifierWithPredicates( - node.getPathArgument())); - - return deSerializer.buildDataContainer(builder, node); - } - }); - m.put(AUGMENTATION_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - DataContainerNodeBuilder builder = - Builders.augmentationBuilder().withNodeIdentifier( - deSerializer.toAugmentationIdentifier(node.getPathArgument())); - - return deSerializer.buildDataContainer(builder, node); - } + return deSerializer.buildNormalizedNode(builder, node); }); - m.put(LEAF_SET_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - return deSerializer.buildListNode(Builders.leafSetBuilder(), node); - } - }); - m.put(LEAF_SET_ENTRY_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - NormalizedNodeAttrBuilder> builder = - Builders.leafSetEntryBuilder().withNodeIdentifier(deSerializer.toNodeWithValue( - node.getPathArgument())); - - return deSerializer.buildNormalizedNode(builder, node); - } - }); - m.put(CHOICE_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - DataContainerNodeBuilder builder = Builders.choiceBuilder() - .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); + m.put(MAP_NODE_TYPE, (deSerializer, node) -> deSerializer.buildCollectionNode(Builders.mapBuilder(), node)); + m.put(MAP_ENTRY_NODE_TYPE, (deSerializer, node) -> { + DataContainerNodeAttrBuilder builder = + Builders.mapEntryBuilder().withNodeIdentifier(deSerializer.toNodeIdentifierWithPredicates( + node.getPathArgument())); - return deSerializer.buildDataContainer(builder, node); - } + return deSerializer.buildDataContainer(builder, node); }); - m.put(ORDERED_LEAF_SET_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - return deSerializer.buildListNode(Builders.orderedLeafSetBuilder(), node); - } + m.put(AUGMENTATION_NODE_TYPE, (deSerializer, node) -> { + DataContainerNodeBuilder builder = + Builders.augmentationBuilder().withNodeIdentifier( + deSerializer.toAugmentationIdentifier(node.getPathArgument())); + + return deSerializer.buildDataContainer(builder, node); }); - m.put(ORDERED_MAP_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - return deSerializer.buildCollectionNode(Builders.orderedMapBuilder(), node); - } + m.put(LEAF_SET_NODE_TYPE, (deSerializer, node) + -> deSerializer.buildListNode(Builders.leafSetBuilder(), node)); + m.put(LEAF_SET_ENTRY_NODE_TYPE, (deSerializer, node) -> { + NormalizedNodeAttrBuilder> builder = + Builders.leafSetEntryBuilder().withNodeIdentifier(deSerializer.toNodeWithValue( + node.getPathArgument())); + + return deSerializer.buildNormalizedNode(builder, node); }); - m.put(UNKEYED_LIST_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - return deSerializer.buildCollectionNode(Builders.unkeyedListBuilder(), node); - } + m.put(CHOICE_NODE_TYPE, (deSerializer, node) -> { + DataContainerNodeBuilder builder = Builders.choiceBuilder() + .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); + + return deSerializer.buildDataContainer(builder, node); }); - m.put(UNKEYED_LIST_ENTRY_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - DataContainerNodeAttrBuilder builder = - Builders.unkeyedListEntryBuilder().withNodeIdentifier(deSerializer.toNodeIdentifier( - node.getPathArgument())); - - return deSerializer.buildDataContainer(builder, node); - } + m.put(ORDERED_LEAF_SET_NODE_TYPE, (deSerializer, node) + -> deSerializer.buildListNode(Builders.orderedLeafSetBuilder(), node)); + m.put(ORDERED_MAP_NODE_TYPE, (deSerializer, node) + -> deSerializer.buildCollectionNode(Builders.orderedMapBuilder(), node)); + m.put(UNKEYED_LIST_NODE_TYPE, (deSerializer, node) + -> deSerializer.buildCollectionNode(Builders.unkeyedListBuilder(), node)); + m.put(UNKEYED_LIST_ENTRY_NODE_TYPE, (deSerializer, node) -> { + DataContainerNodeAttrBuilder builder = + Builders.unkeyedListEntryBuilder().withNodeIdentifier(deSerializer.toNodeIdentifier( + node.getPathArgument())); + + return deSerializer.buildDataContainer(builder, node); }); - m.put(ANY_XML_NODE_TYPE, new DeSerializationFunction() { - @Override - public NormalizedNode apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) { - NormalizedNodeAttrBuilder builder = Builders.anyXmlBuilder() - .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); + m.put(ANY_XML_NODE_TYPE, (deSerializer, node) -> { + NormalizedNodeAttrBuilder builder = Builders.anyXmlBuilder() + .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument())); - return deSerializer.buildNormalizedNode(builder, node); - } + return deSerializer.buildNormalizedNode(builder, node); }); DESERIALIZATION_FUNCTIONS = Maps.immutableEnumMap(m); @@ -335,30 +287,33 @@ public class NormalizedNodeSerializer { public NormalizedNode deSerialize() { NormalizedNode deserializedNode = deSerialize(node); - if(path != null) { + if (path != null) { deserializedPath = InstanceIdentifierUtils.fromSerializable(path, this); } return deserializedNode; } - private NormalizedNode deSerialize(final NormalizedNodeMessages.Node node){ - Preconditions.checkNotNull(node, "node should not be null"); + private NormalizedNode deSerialize(final NormalizedNodeMessages.Node fromNode) { + Preconditions.checkNotNull(fromNode, "node should not be null"); DeSerializationFunction deSerializationFunction = DESERIALIZATION_FUNCTIONS.get( - NormalizedNodeType.values()[node.getIntType()]); + NormalizedNodeType.values()[fromNode.getIntType()]); - return deSerializationFunction.apply(this, node); + return deSerializationFunction.apply(this, fromNode); } + public YangInstanceIdentifier.PathArgument deSerialize(final NormalizedNodeMessages.PathArgument pathArgument) { + return PathArgumentSerializer.deSerialize(this, pathArgument); + } - private NormalizedNode buildCollectionNode( - final CollectionNodeBuilder builder, - final NormalizedNodeMessages.Node node) { + @SuppressWarnings("unchecked") + private NormalizedNode buildCollectionNode(final CollectionNodeBuilder builder, + final NormalizedNodeMessages.Node fromNode) { - builder.withNodeIdentifier(toNodeIdentifier(node.getPathArgument())); + builder.withNodeIdentifier(toNodeIdentifier(fromNode.getPathArgument())); - for(NormalizedNodeMessages.Node child : node.getChildList()){ + for (NormalizedNodeMessages.Node child : fromNode.getChildList()) { builder.withChild(deSerialize(child)); } @@ -366,21 +321,22 @@ public class NormalizedNodeSerializer { } - private NormalizedNode buildListNode( - final ListNodeBuilder> builder, - final NormalizedNodeMessages.Node node) { - builder.withNodeIdentifier(toNodeIdentifier(node.getPathArgument())); + @SuppressWarnings("unchecked") + private NormalizedNode buildListNode(final ListNodeBuilder> builder, + final NormalizedNodeMessages.Node fromNode) { + builder.withNodeIdentifier(toNodeIdentifier(fromNode.getPathArgument())); - for(NormalizedNodeMessages.Node child : node.getChildList()){ + for (NormalizedNodeMessages.Node child : fromNode.getChildList()) { builder.withChild((LeafSetEntryNode) deSerialize(child)); } return builder.build(); } - private NormalizedNode buildDataContainer(final DataContainerNodeBuilder builder, final NormalizedNodeMessages.Node node){ + private NormalizedNode buildDataContainer(final DataContainerNodeBuilder builder, + final NormalizedNodeMessages.Node fromNode) { - for(NormalizedNodeMessages.Node child : node.getChildList()){ + for (NormalizedNodeMessages.Node child : fromNode.getChildList()) { builder.withChild((DataContainerChild) deSerialize(child)); } @@ -389,9 +345,11 @@ public class NormalizedNodeSerializer { return builder.build(); } - private NormalizedNode buildNormalizedNode(final NormalizedNodeAttrBuilder builder, final NormalizedNodeMessages.Node node){ + @SuppressWarnings("unchecked") + private NormalizedNode buildNormalizedNode(final NormalizedNodeAttrBuilder builder, + final NormalizedNodeMessages.Node fromNode) { - builder.withValue(ValueSerializer.deSerialize(this, node)); + builder.withValue(ValueSerializer.deSerialize(this, fromNode)); //TODO : Also handle attributes @@ -400,25 +358,21 @@ public class NormalizedNodeSerializer { } private NodeIdentifierWithPredicates toNodeIdentifierWithPredicates( - final NormalizedNodeMessages.PathArgument path) { - return (NodeIdentifierWithPredicates) PathArgumentSerializer.deSerialize(this, path); + final NormalizedNodeMessages.PathArgument fromPath) { + return (NodeIdentifierWithPredicates) PathArgumentSerializer.deSerialize(this, fromPath); } - private AugmentationIdentifier toAugmentationIdentifier(final NormalizedNodeMessages.PathArgument path) { - return (AugmentationIdentifier) PathArgumentSerializer.deSerialize(this, path); + private AugmentationIdentifier toAugmentationIdentifier(final NormalizedNodeMessages.PathArgument fromPath) { + return (AugmentationIdentifier) PathArgumentSerializer.deSerialize(this, fromPath); } @SuppressWarnings("unchecked") - private NodeWithValue toNodeWithValue(final NormalizedNodeMessages.PathArgument path) { - return (NodeWithValue) PathArgumentSerializer.deSerialize(this, path); - } - - private NodeIdentifier toNodeIdentifier(final NormalizedNodeMessages.PathArgument path){ - return (NodeIdentifier) PathArgumentSerializer.deSerialize(this, path); + private NodeWithValue toNodeWithValue(final NormalizedNodeMessages.PathArgument fromPath) { + return (NodeWithValue) PathArgumentSerializer.deSerialize(this, fromPath); } - public YangInstanceIdentifier.PathArgument deSerialize(final NormalizedNodeMessages.PathArgument pathArgument) { - return PathArgumentSerializer.deSerialize(this, pathArgument); + private NodeIdentifier toNodeIdentifier(final NormalizedNodeMessages.PathArgument fromPath) { + return (NodeIdentifier) PathArgumentSerializer.deSerialize(this, fromPath); } private interface DeSerializationFunction { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java index 01e56e89d4..ab6b1b4cda 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeType.java @@ -39,34 +39,34 @@ public enum NormalizedNodeType { UNKEYED_LIST_ENTRY_NODE_TYPE, ANY_XML_NODE_TYPE; - public static NormalizedNodeType getSerializableNodeType(NormalizedNode node){ + public static NormalizedNodeType getSerializableNodeType(NormalizedNode node) { Preconditions.checkNotNull(node, "node should not be null"); - if(node instanceof LeafNode){ + if (node instanceof LeafNode) { return LEAF_NODE_TYPE; - } else if(node instanceof LeafSetEntryNode){ + } else if (node instanceof LeafSetEntryNode) { return LEAF_SET_ENTRY_NODE_TYPE; - } else if(node instanceof MapEntryNode){ + } else if (node instanceof MapEntryNode) { return MAP_ENTRY_NODE_TYPE; - } else if(node instanceof ContainerNode){ + } else if (node instanceof ContainerNode) { return CONTAINER_NODE_TYPE; - } else if(node instanceof AugmentationNode){ + } else if (node instanceof AugmentationNode) { return AUGMENTATION_NODE_TYPE; - } else if(node instanceof ChoiceNode){ + } else if (node instanceof ChoiceNode) { return CHOICE_NODE_TYPE; - } else if(node instanceof OrderedLeafSetNode){ + } else if (node instanceof OrderedLeafSetNode) { return ORDERED_LEAF_SET_NODE_TYPE; - } else if(node instanceof OrderedMapNode){ + } else if (node instanceof OrderedMapNode) { return ORDERED_MAP_NODE_TYPE; - } else if(node instanceof MapNode){ + } else if (node instanceof MapNode) { return MAP_NODE_TYPE; - } else if(node instanceof LeafSetNode){ + } else if (node instanceof LeafSetNode) { return LEAF_SET_NODE_TYPE; - } else if(node instanceof UnkeyedListNode){ + } else if (node instanceof UnkeyedListNode) { return UNKEYED_LIST_NODE_TYPE; - } else if(node instanceof UnkeyedListEntryNode){ + } else if (node instanceof UnkeyedListEntryNode) { return UNKEYED_LIST_ENTRY_NODE_TYPE; - } else if(node instanceof AnyXmlNode){ + } else if (node instanceof AnyXmlNode) { return ANY_XML_NODE_TYPE; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializer.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializer.java index 7bbb704c1c..ed9073b558 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializer.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializer.java @@ -8,12 +8,9 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; +import static org.opendaylight.controller.cluster.datastore.node.utils.serialization.PathArgumentType.getSerializablePathArgumentType; + import com.google.common.base.Preconditions; -import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFactory; -import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; -import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -23,14 +20,18 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import static org.opendaylight.controller.cluster.datastore.node.utils.serialization.PathArgumentType.getSerializablePathArgumentType; +import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFactory; +import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; +import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; +import org.opendaylight.yangtools.yang.common.QName; +import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class PathArgumentSerializer { private static final String REVISION_ARG = "?revision="; - private static final Map, PathArgumentAttributesGetter> pathArgumentAttributesGetters = new HashMap<>(); + private static final Map, PathArgumentAttributesGetter> PATH_ARGUMENT_ATTRIBUTES_GETTERS = new HashMap<>(); public static NormalizedNodeMessages.PathArgument serialize(QNameSerializationContext context, - YangInstanceIdentifier.PathArgument pathArgument){ + YangInstanceIdentifier.PathArgument pathArgument) { Preconditions.checkNotNull(context, "context should not be null"); Preconditions.checkNotNull(pathArgument, "pathArgument should not be null"); @@ -54,7 +55,7 @@ public class PathArgumentSerializer { public static YangInstanceIdentifier.PathArgument deSerialize(QNameDeSerializationContext context, - NormalizedNodeMessages.PathArgument pathArgument){ + NormalizedNodeMessages.PathArgument pathArgument) { Preconditions.checkNotNull(context, "context should not be null"); Preconditions.checkNotNull(pathArgument, "pathArgument should not be null"); @@ -68,74 +69,52 @@ public class PathArgumentSerializer { } static { - pathArgumentAttributesGetters.put(YangInstanceIdentifier.NodeWithValue.class, new PathArgumentAttributesGetter() { - @Override - public Iterable get( - QNameSerializationContext context, YangInstanceIdentifier.PathArgument pathArgument) { - - YangInstanceIdentifier.NodeWithValue identifier - = (YangInstanceIdentifier.NodeWithValue) pathArgument; + PATH_ARGUMENT_ATTRIBUTES_GETTERS.put(YangInstanceIdentifier.NodeWithValue.class, (context, pathArgument) -> { + YangInstanceIdentifier.NodeWithValue identifier = (YangInstanceIdentifier.NodeWithValue) pathArgument; - NormalizedNodeMessages.PathArgumentAttribute attribute = - buildAttribute(context, null, identifier.getValue()); + NormalizedNodeMessages.PathArgumentAttribute attribute = buildAttribute(context, null, + identifier.getValue()); - return Arrays.asList(attribute); - } + return Arrays.asList(attribute); }); - pathArgumentAttributesGetters.put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, new PathArgumentAttributesGetter() { - @Override - public Iterable get( - QNameSerializationContext context, YangInstanceIdentifier.PathArgument pathArgument) { - - YangInstanceIdentifier.NodeIdentifierWithPredicates identifier - = (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument; + PATH_ARGUMENT_ATTRIBUTES_GETTERS.put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, + (context, pathArgument) -> { + YangInstanceIdentifier.NodeIdentifierWithPredicates identifier = + (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument; Map keyValues = identifier.getKeyValues(); - List attributes = - new ArrayList<>(keyValues.size()); + List attributes = new ArrayList<>(keyValues.size()); for (Entry e : keyValues.entrySet()) { - NormalizedNodeMessages.PathArgumentAttribute attribute = - buildAttribute(context, e.getKey(), e.getValue()); + NormalizedNodeMessages.PathArgumentAttribute attribute = buildAttribute(context, e.getKey(), + e.getValue()); attributes.add(attribute); } return attributes; - } - }); + }); - pathArgumentAttributesGetters.put(YangInstanceIdentifier.AugmentationIdentifier.class, new PathArgumentAttributesGetter() { - @Override - public Iterable get( - QNameSerializationContext context, YangInstanceIdentifier.PathArgument pathArgument) { - - YangInstanceIdentifier.AugmentationIdentifier identifier - = (YangInstanceIdentifier.AugmentationIdentifier) pathArgument; + PATH_ARGUMENT_ATTRIBUTES_GETTERS.put(YangInstanceIdentifier.AugmentationIdentifier.class, + (context, pathArgument) -> { + YangInstanceIdentifier.AugmentationIdentifier identifier = + (YangInstanceIdentifier.AugmentationIdentifier) pathArgument; Set possibleChildNames = identifier.getPossibleChildNames(); - List attributes = - new ArrayList<>(possibleChildNames.size()); + List attributes = new ArrayList<>( + possibleChildNames.size()); for (QName key : possibleChildNames) { Object value = key; - NormalizedNodeMessages.PathArgumentAttribute attribute = - buildAttribute(context, key, value); + NormalizedNodeMessages.PathArgumentAttribute attribute = buildAttribute(context, key, value); attributes.add(attribute); } return attributes; - } - }); + }); - - pathArgumentAttributesGetters.put(YangInstanceIdentifier.NodeIdentifier.class, new PathArgumentAttributesGetter() { - @Override - public Iterable get( - QNameSerializationContext context, YangInstanceIdentifier.PathArgument pathArgument) { - return Collections.emptyList(); - } - }); + PATH_ARGUMENT_ATTRIBUTES_GETTERS.put(YangInstanceIdentifier.NodeIdentifier.class, + (context, pathArgument) -> Collections.emptyList()); } private static NormalizedNodeMessages.PathArgumentAttribute buildAttribute( @@ -150,45 +129,42 @@ public class PathArgumentSerializer { } - private static NormalizedNodeMessages.QName.Builder encodeQName(QNameSerializationContext context, - QName qName) { - if(qName == null) { + private static NormalizedNodeMessages.QName.Builder encodeQName(QNameSerializationContext context, QName qname) { + if (qname == null) { return NormalizedNodeMessages.QName.getDefaultInstance().toBuilder(); } - NormalizedNodeMessages.QName.Builder qNameBuilder = - NormalizedNodeMessages.QName.newBuilder(); + NormalizedNodeMessages.QName.Builder qnameBuilder = NormalizedNodeMessages.QName.newBuilder(); - qNameBuilder.setNamespace(context.addNamespace(qName.getNamespace())); + qnameBuilder.setNamespace(context.addNamespace(qname.getNamespace())); - qNameBuilder.setRevision(context.addRevision(qName.getRevision())); + qnameBuilder.setRevision(context.addRevision(qname.getRevision())); - qNameBuilder.setLocalName(context.addLocalName(qName.getLocalName())); + qnameBuilder.setLocalName(context.addLocalName(qname.getLocalName())); - return qNameBuilder; + return qnameBuilder; } private static Iterable getPathArgumentAttributes( QNameSerializationContext context, YangInstanceIdentifier.PathArgument pathArgument) { - return pathArgumentAttributesGetters.get(pathArgument.getClass()).get(context, pathArgument); + return PATH_ARGUMENT_ATTRIBUTES_GETTERS.get(pathArgument.getClass()).get(context, pathArgument); } - private static String qNameToString(QNameDeSerializationContext context, - NormalizedNodeMessages.QName qName){ + private static String qNameToString(QNameDeSerializationContext context, NormalizedNodeMessages.QName qname) { // If this serializer is used qName cannot be null (see encodeQName) // adding null check only in case someone tried to deSerialize a protocol buffer node // that was not serialized using the PathArgumentSerializer // Preconditions.checkNotNull(qName, "qName should not be null"); // Preconditions.checkArgument(qName.getNamespace() != -1, "qName.namespace should be valid"); - String namespace = context.getNamespace(qName.getNamespace()); - String localName = context.getLocalName(qName.getLocalName()); + String namespace = context.getNamespace(qname.getNamespace()); + String localName = context.getLocalName(qname.getLocalName()); StringBuilder sb; - if(qName.getRevision() != -1){ - String revision = context.getRevision(qName.getRevision()); - sb = new StringBuilder(namespace.length() + REVISION_ARG.length() + revision.length() + - localName.length() + 2); + if (qname.getRevision() != -1) { + String revision = context.getRevision(qname.getRevision()); + sb = new StringBuilder(namespace.length() + REVISION_ARG.length() + revision.length() + + localName.length() + 2); sb.append('(').append(namespace).append(REVISION_ARG).append( revision).append(')').append(localName); } else { @@ -200,7 +176,7 @@ public class PathArgumentSerializer { } /** - * Parse a protocol buffer PathArgument and return an MD-SAL PathArgument + * Parse a protocol buffer PathArgument and return an MD-SAL PathArgument. * * @param pathArgument protocol buffer PathArgument * @return MD-SAL PathArgument @@ -208,9 +184,8 @@ public class PathArgumentSerializer { private static YangInstanceIdentifier.PathArgument parsePathArgument( QNameDeSerializationContext context, NormalizedNodeMessages.PathArgument pathArgument) { - switch(PathArgumentType.values()[pathArgument.getIntType()]){ + switch (PathArgumentType.values()[pathArgument.getIntType()]) { case NODE_IDENTIFIER_WITH_VALUE : { - YangInstanceIdentifier.NodeWithValue nodeWithValue = new YangInstanceIdentifier.NodeWithValue<>( QNameFactory.create(qNameToString(context, pathArgument.getNodeType())), @@ -220,7 +195,6 @@ public class PathArgumentSerializer { } case NODE_IDENTIFIER_WITH_PREDICATES : { - YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates( @@ -231,14 +205,13 @@ public class PathArgumentSerializer { } case AUGMENTATION_IDENTIFIER: { + Set qnameSet = new HashSet<>(); - Set qNameSet = new HashSet<>(); - - for(NormalizedNodeMessages.PathArgumentAttribute attribute : pathArgument.getAttributeList()){ - qNameSet.add(QNameFactory.create(qNameToString(context, attribute.getName()))); + for (NormalizedNodeMessages.PathArgumentAttribute attribute : pathArgument.getAttributeList()) { + qnameSet.add(QNameFactory.create(qNameToString(context, attribute.getName()))); } - return new YangInstanceIdentifier.AugmentationIdentifier(qNameSet); + return new YangInstanceIdentifier.AugmentationIdentifier(qnameSet); } default: { @@ -254,7 +227,7 @@ public class PathArgumentSerializer { List attributesList) { Map map; - if(attributesList.size() == 1) { + if (attributesList.size() == 1) { NormalizedNodeMessages.PathArgumentAttribute attribute = attributesList.get(0); NormalizedNodeMessages.QName name = attribute.getName(); Object value = parseAttribute(context, attribute); @@ -262,7 +235,7 @@ public class PathArgumentSerializer { } else { map = new HashMap<>(); - for(NormalizedNodeMessages.PathArgumentAttribute attribute : attributesList){ + for (NormalizedNodeMessages.PathArgumentAttribute attribute : attributesList) { NormalizedNodeMessages.QName name = attribute.getName(); Object value = parseAttribute(context, attribute); @@ -274,8 +247,7 @@ public class PathArgumentSerializer { } private static Object parseAttribute(QNameDeSerializationContext context, - NormalizedNodeMessages.PathArgumentAttribute attribute){ + NormalizedNodeMessages.PathArgumentAttribute attribute) { return ValueSerializer.deSerialize(context, attribute); } - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentType.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentType.java index 58a09ae885..8209c9a583 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentType.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentType.java @@ -8,9 +8,9 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; +import com.google.common.collect.ImmutableMap; import java.util.Map; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import com.google.common.collect.ImmutableMap; public enum PathArgumentType { AUGMENTATION_IDENTIFIER, @@ -19,20 +19,19 @@ public enum PathArgumentType { NODE_IDENTIFIER_WITH_PREDICATES; private static Map, PathArgumentType> CLASS_TO_ENUM_MAP = - ImmutableMap., PathArgumentType>builder(). - put(YangInstanceIdentifier.AugmentationIdentifier.class, AUGMENTATION_IDENTIFIER). - put(YangInstanceIdentifier.NodeIdentifier.class, NODE_IDENTIFIER). - put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, NODE_IDENTIFIER_WITH_PREDICATES). - put(YangInstanceIdentifier.NodeWithValue.class, NODE_IDENTIFIER_WITH_VALUE).build(); + ImmutableMap., PathArgumentType>builder() + .put(YangInstanceIdentifier.AugmentationIdentifier.class, AUGMENTATION_IDENTIFIER) + .put(YangInstanceIdentifier.NodeIdentifier.class, NODE_IDENTIFIER) + .put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, NODE_IDENTIFIER_WITH_PREDICATES) + .put(YangInstanceIdentifier.NodeWithValue.class, NODE_IDENTIFIER_WITH_VALUE).build(); - public static int getSerializablePathArgumentType(YangInstanceIdentifier.PathArgument pathArgument){ + public static int getSerializablePathArgumentType(YangInstanceIdentifier.PathArgument pathArgument) { PathArgumentType type = CLASS_TO_ENUM_MAP.get(pathArgument.getClass()); - if(type == null) { + if (type == null) { throw new IllegalArgumentException("Unknown type of PathArgument = " + pathArgument); } return type.ordinal(); } - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/QNameSerializationContextImpl.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/QNameSerializationContextImpl.java index 09fe2efc3e..ff650a635a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/QNameSerializationContextImpl.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/QNameSerializationContextImpl.java @@ -32,19 +32,19 @@ public class QNameSerializationContextImpl implements QNameSerializationContext @Override public int addNamespace(URI namespace) { int namespaceInt = getCode(namespace); - if(namespaceInt == -1) { + if (namespaceInt == -1) { namespaceInt = addCode(namespace, namespace.toString()); } return namespaceInt; } @Override public int addRevision(Date revision) { - if(revision == null){ + if (revision == null) { return -1; } int revisionInt = getCode(revision); - if(revisionInt == -1) { + if (revisionInt == -1) { String formattedRevision = SimpleDateFormatUtil.getRevisionFormat().format(revision); revisionInt = addCode(revision, formattedRevision); @@ -54,21 +54,21 @@ public class QNameSerializationContextImpl implements QNameSerializationContext @Override public int addLocalName(String localName) { int localNameInt = getCode(localName); - if(localNameInt == -1) { + if (localNameInt == -1) { localNameInt = addCode(localName, localName); } return localNameInt; } - private int addCode(Object code, String codeStr){ + private int addCode(Object code, String codeStr) { int count = codes.size(); codes.add(codeStr); codeMap.put(code, Integer.valueOf(count)); return count; } - private int getCode(Object code){ + private int getCode(Object code) { Integer value = codeMap.get(code); return value == null ? -1 : value.intValue(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java index 9e3230a623..7523976a73 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializer.java @@ -22,24 +22,24 @@ public class ValueSerializer { QNameSerializationContext context, Object value) { builder.setIntValueType(ValueType.getSerializableType(value).ordinal()); - if(value instanceof YangInstanceIdentifier) { + if (value instanceof YangInstanceIdentifier) { builder.setInstanceIdentifierValue( InstanceIdentifierUtils.toSerializable((YangInstanceIdentifier) value, context)); - } else if(value instanceof Set) { + } else if (value instanceof Set) { Set set = (Set) value; if (!set.isEmpty()) { for (Object o : set) { if (o instanceof String) { builder.addBitsValue(o.toString()); } else { - throw new IllegalArgumentException("Expected value type to be Bits but was : " + - value.toString()); + throw new IllegalArgumentException("Expected value type to be Bits but was : " + + value.toString()); } } } - } else if(value instanceof byte[]) { + } else if (value instanceof byte[]) { builder.setBytesValue(ByteString.copyFrom((byte[]) value)); - } else if(value == null){ + } else if (value == null) { builder.setValue(NULL_VALUE); } else { builder.setValue(value.toString()); @@ -47,28 +47,28 @@ public class ValueSerializer { } public static void serialize(NormalizedNodeMessages.PathArgumentAttribute.Builder builder, - QNameSerializationContext context, Object value){ + QNameSerializationContext context, Object value) { builder.setType(ValueType.getSerializableType(value).ordinal()); - if(value instanceof YangInstanceIdentifier) { + if (value instanceof YangInstanceIdentifier) { builder.setInstanceIdentifierValue( InstanceIdentifierUtils.toSerializable((YangInstanceIdentifier) value, context)); - } else if(value instanceof Set) { + } else if (value instanceof Set) { Set set = (Set) value; if (!set.isEmpty()) { for (Object o : set) { if (o instanceof String) { builder.addBitsValue(o.toString()); } else { - throw new IllegalArgumentException("Expected value type to be Bits but was : " + - value.toString()); + throw new IllegalArgumentException("Expected value type to be Bits but was : " + + value.toString()); } } } - } else if(value instanceof byte[]){ + } else if (value instanceof byte[]) { builder.setBytesValue(ByteString.copyFrom((byte[]) value)); - } else if(value == null){ + } else if (value == null) { builder.setValue(NULL_VALUE); } else { builder.setValue(value.toString()); @@ -77,12 +77,11 @@ public class ValueSerializer { public static Object deSerialize(QNameDeSerializationContext context, NormalizedNodeMessages.Node node) { - if(node.getIntValueType() == ValueType.YANG_IDENTIFIER_TYPE.ordinal()){ - return InstanceIdentifierUtils.fromSerializable( - node.getInstanceIdentifierValue(), context); - } else if(node.getIntValueType() == ValueType.BITS_TYPE.ordinal()){ + if (node.getIntValueType() == ValueType.YANG_IDENTIFIER_TYPE.ordinal()) { + return InstanceIdentifierUtils.fromSerializable(node.getInstanceIdentifierValue(), context); + } else if (node.getIntValueType() == ValueType.BITS_TYPE.ordinal()) { return new HashSet<>(node.getBitsValueList()); - } else if(node.getIntValueType() == ValueType.BINARY_TYPE.ordinal()){ + } else if (node.getIntValueType() == ValueType.BINARY_TYPE.ordinal()) { return node.getBytesValue().toByteArray(); } return deSerializeBasicTypes(node.getIntValueType(), node.getValue()); @@ -91,12 +90,11 @@ public class ValueSerializer { public static Object deSerialize(QNameDeSerializationContext context, NormalizedNodeMessages.PathArgumentAttribute attribute) { - if(attribute.getType() == ValueType.YANG_IDENTIFIER_TYPE.ordinal()){ - return InstanceIdentifierUtils.fromSerializable( - attribute.getInstanceIdentifierValue(), context); - } else if(attribute.getType() == ValueType.BITS_TYPE.ordinal()){ + if (attribute.getType() == ValueType.YANG_IDENTIFIER_TYPE.ordinal()) { + return InstanceIdentifierUtils.fromSerializable(attribute.getInstanceIdentifierValue(), context); + } else if (attribute.getType() == ValueType.BITS_TYPE.ordinal()) { return new HashSet<>(attribute.getBitsValueList()); - } else if(attribute.getType() == ValueType.BINARY_TYPE.ordinal()){ + } else if (attribute.getType() == ValueType.BINARY_TYPE.ordinal()) { return attribute.getBytesValue().toByteArray(); } return deSerializeBasicTypes(attribute.getType(), attribute.getValue()); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java index 0015a06149..fe0c97b77f 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueType.java @@ -120,7 +120,7 @@ public enum ValueType { abstract Object deserialize(String str); public static final ValueType getSerializableType(Object node) { - if(node == null){ + if (node == null) { return NULL_TYPE; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/AbstractNormalizedNodeDataOutput.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/AbstractNormalizedNodeDataOutput.java index 3dc8f1c591..51a9c1c24e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/AbstractNormalizedNodeDataOutput.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/AbstractNormalizedNodeDataOutput.java @@ -56,95 +56,97 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } protected abstract short streamVersion(); + protected abstract void writeQName(QName qname) throws IOException; + protected abstract void writeString(String string) throws IOException; @Override - public final void write(final int b) throws IOException { + public final void write(final int value) throws IOException { ensureHeaderWritten(); - output.write(b); + output.write(value); } @Override - public final void write(final byte[] b) throws IOException { + public final void write(final byte[] bytes) throws IOException { ensureHeaderWritten(); - output.write(b); + output.write(bytes); } @Override - public final void write(final byte[] b, final int off, final int len) throws IOException { + public final void write(final byte[] bytes, final int off, final int len) throws IOException { ensureHeaderWritten(); - output.write(b, off, len); + output.write(bytes, off, len); } @Override - public final void writeBoolean(final boolean v) throws IOException { + public final void writeBoolean(final boolean value) throws IOException { ensureHeaderWritten(); - output.writeBoolean(v); + output.writeBoolean(value); } @Override - public final void writeByte(final int v) throws IOException { + public final void writeByte(final int value) throws IOException { ensureHeaderWritten(); - output.writeByte(v); + output.writeByte(value); } @Override - public final void writeShort(final int v) throws IOException { + public final void writeShort(final int value) throws IOException { ensureHeaderWritten(); - output.writeShort(v); + output.writeShort(value); } @Override - public final void writeChar(final int v) throws IOException { + public final void writeChar(final int value) throws IOException { ensureHeaderWritten(); - output.writeChar(v); + output.writeChar(value); } @Override - public final void writeInt(final int v) throws IOException { + public final void writeInt(final int value) throws IOException { ensureHeaderWritten(); - output.writeInt(v); + output.writeInt(value); } @Override - public final void writeLong(final long v) throws IOException { + public final void writeLong(final long value) throws IOException { ensureHeaderWritten(); - output.writeLong(v); + output.writeLong(value); } @Override - public final void writeFloat(final float v) throws IOException { + public final void writeFloat(final float value) throws IOException { ensureHeaderWritten(); - output.writeFloat(v); + output.writeFloat(value); } @Override - public final void writeDouble(final double v) throws IOException { + public final void writeDouble(final double value) throws IOException { ensureHeaderWritten(); - output.writeDouble(v); + output.writeDouble(value); } @Override - public final void writeBytes(final String s) throws IOException { + public final void writeBytes(final String str) throws IOException { ensureHeaderWritten(); - output.writeBytes(s); + output.writeBytes(str); } @Override - public final void writeChars(final String s) throws IOException { + public final void writeChars(final String str) throws IOException { ensureHeaderWritten(); - output.writeChars(s); + output.writeChars(str); } @Override - public final void writeUTF(final String s) throws IOException { + public final void writeUTF(final String str) throws IOException { ensureHeaderWritten(); - output.writeUTF(s); + output.writeUTF(str); } private NormalizedNodeWriter normalizedNodeWriter() { - if(normalizedNodeWriter == null) { + if (normalizedNodeWriter == null) { normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(this); } @@ -167,7 +169,9 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startLeafSet(final NodeIdentifier name, final int childSizeHint) + + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new leaf set"); @@ -176,7 +180,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startOrderedLeafSet(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new ordered leaf set"); @@ -192,7 +197,7 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut // lastLeafSetQName is set if the parent LeafSetNode was previously written. Otherwise this is a // stand alone LeafSetEntryNode so write out it's name here. - if(lastLeafSetQName == null) { + if (lastLeafSetQName == null) { writeQName(name); } @@ -200,7 +205,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startContainerNode(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startContainerNode(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new container node"); @@ -209,7 +215,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startYangModeledAnyXmlNode(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new yang modeled anyXml node"); @@ -218,7 +225,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new unkeyed list"); @@ -226,7 +234,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalStateException { + public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalStateException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new unkeyed list item"); @@ -234,7 +243,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startMapNode(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new map node"); @@ -242,7 +252,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(identifier, "Node identifier should not be null"); LOG.debug("Starting a new map entry node"); startNode(identifier.getNodeType(), NodeTypes.MAP_ENTRY_NODE); @@ -252,7 +263,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new ordered map node"); @@ -260,7 +272,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) throws IOException, IllegalArgumentException { + public void startChoiceNode(final NodeIdentifier name, final int childSizeHint) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(name, "Node identifier should not be null"); LOG.debug("Starting a new choice node"); @@ -268,7 +281,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } @Override - public void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException, IllegalArgumentException { + public void startAugmentationNode(final AugmentationIdentifier identifier) + throws IOException, IllegalArgumentException { Preconditions.checkNotNull(identifier, "Node identifier should not be null"); LOG.debug("Starting a new augmentation node"); @@ -311,16 +325,15 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut } } - private void startNode(final QName qName, final byte nodeType) throws IOException { - - Preconditions.checkNotNull(qName, "QName of node identifier should not be null."); + private void startNode(final QName qname, final byte nodeType) throws IOException { + Preconditions.checkNotNull(qname, "QName of node identifier should not be null."); ensureHeaderWritten(); // First write the type of node output.writeByte(nodeType); // Write Start Tag - writeQName(qName); + writeQName(qname); } private void writeObjSet(final Set set) throws IOException { @@ -343,7 +356,7 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut Collection pathArguments = identifier.getPathArguments(); output.writeInt(pathArguments.size()); - for(PathArgument pathArgument : pathArguments) { + for (PathArgument pathArgument : pathArguments) { writePathArgument(pathArgument); } } @@ -355,7 +368,7 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut output.writeByte(type); - switch(type) { + switch (type) { case PathArgumentTypes.NODE_IDENTIFIER: NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument; @@ -388,7 +401,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut writeQNameSet(augmentationIdentifier.getPossibleChildNames()); break; default : - throw new IllegalStateException("Unknown node identifier type is found : " + pathArgument.getClass().toString() ); + throw new IllegalStateException("Unknown node identifier type is found : " + + pathArgument.getClass().toString() ); } } @@ -396,9 +410,9 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut if (keyValueMap != null && !keyValueMap.isEmpty()) { output.writeInt(keyValueMap.size()); - for (QName qName : keyValueMap.keySet()) { - writeQName(qName); - writeObject(keyValueMap.get(qName)); + for (QName qname : keyValueMap.keySet()) { + writeQName(qname); + writeObject(keyValueMap.get(qname)); } } else { output.writeInt(0); @@ -409,8 +423,8 @@ abstract class AbstractNormalizedNodeDataOutput implements NormalizedNodeDataOut // Write each child's qname separately, if list is empty send count as 0 if (children != null && !children.isEmpty()) { output.writeInt(children.size()); - for (QName qName : children) { - writeQName(qName); + for (QName qname : children) { + writeQName(qname); } } else { LOG.debug("augmentation node does not have any child"); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeDataOutput.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeDataOutput.java index 10f412c9e2..0c34224883 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeDataOutput.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeDataOutput.java @@ -20,7 +20,9 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; @Beta public interface NormalizedNodeDataOutput extends AutoCloseable, DataOutput { void writeNormalizedNode(NormalizedNode normalizedNode) throws IOException; + void writePathArgument(PathArgument pathArgument) throws IOException; + void writeYangInstanceIdentifier(YangInstanceIdentifier identifier) throws IOException; @Override diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java index 8a114893e6..ec04356049 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeInputStreamReader.java @@ -46,12 +46,10 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** - * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes. - * This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except END_NODE. - * If a node can have children, then that node's end is calculated based on appearance of END_NODE. - * + * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children + * nodes. This process goes in recursive manner, where each NodeTypes object signifies the start of the object, except + * END_NODE. If a node can have children, then that node's end is calculated based on appearance of END_NODE. */ - public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput { private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class); @@ -67,6 +65,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput private NormalizedNodeAttrBuilder> leafBuilder; + @SuppressWarnings("rawtypes") private NormalizedNodeAttrBuilder> leafSetEntryBuilder; private final StringBuilder reusableStringBuilder = new StringBuilder(50); @@ -74,6 +73,8 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput private boolean readSignatureMarker = true; /** + * Constructs an instance. + * * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead. */ @Deprecated @@ -93,7 +94,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput } private void readSignatureMarkerAndVersionIfNeeded() throws IOException { - if(readSignatureMarker) { + if (readSignatureMarker) { readSignatureMarker = false; final byte marker = input.readByte(); @@ -113,24 +114,24 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput // each node should start with a byte byte nodeType = input.readByte(); - if(nodeType == NodeTypes.END_NODE) { + if (nodeType == NodeTypes.END_NODE) { LOG.debug("End node reached. return"); return null; } - switch(nodeType) { + switch (nodeType) { case NodeTypes.AUGMENTATION_NODE : YangInstanceIdentifier.AugmentationIdentifier augIdentifier = new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet()); LOG.debug("Reading augmentation node {} ", augIdentifier); - return addDataContainerChildren(Builders.augmentationBuilder(). - withNodeIdentifier(augIdentifier)).build(); + return addDataContainerChildren(Builders.augmentationBuilder() + .withNodeIdentifier(augIdentifier)).build(); case NodeTypes.LEAF_SET_ENTRY_NODE : QName name = lastLeafSetQName; - if(name == null) { + if (name == null) { name = readQName(); } @@ -147,8 +148,8 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput LOG.debug("Reading map entry node {} ", entryIdentifier); - return addDataContainerChildren(Builders.mapEntryBuilder(). - withNodeIdentifier(entryIdentifier)).build(); + return addDataContainerChildren(Builders.mapEntryBuilder() + .withNodeIdentifier(entryIdentifier)).build(); default : return readNodeIdentifierDependentNode(nodeType, new NodeIdentifier(readQName())); @@ -157,16 +158,17 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput private NormalizedNodeAttrBuilder> leafBuilder() { - if(leafBuilder == null) { + if (leafBuilder == null) { leafBuilder = Builders.leafBuilder(); } return leafBuilder; } + @SuppressWarnings("rawtypes") private NormalizedNodeAttrBuilder> leafSetEntryBuilder() { - if(leafSetEntryBuilder == null) { + if (leafSetEntryBuilder == null) { leafSetEntryBuilder = Builders.leafSetEntryBuilder(); } @@ -176,7 +178,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput private NormalizedNode readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier) throws IOException { - switch(nodeType) { + switch (nodeType) { case NodeTypes.LEAF_NODE : LOG.debug("Read leaf node {}", identifier); // Read the object value @@ -188,33 +190,28 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput case NodeTypes.MAP_NODE : LOG.debug("Read map node {}", identifier); - return addDataContainerChildren(Builders.mapBuilder(). - withNodeIdentifier(identifier)).build(); + return addDataContainerChildren(Builders.mapBuilder().withNodeIdentifier(identifier)).build(); - case NodeTypes.CHOICE_NODE : + case NodeTypes.CHOICE_NODE: LOG.debug("Read choice node {}", identifier); - return addDataContainerChildren(Builders.choiceBuilder(). - withNodeIdentifier(identifier)).build(); + return addDataContainerChildren(Builders.choiceBuilder().withNodeIdentifier(identifier)).build(); - case NodeTypes.ORDERED_MAP_NODE : + case NodeTypes.ORDERED_MAP_NODE: LOG.debug("Reading ordered map node {}", identifier); - return addDataContainerChildren(Builders.orderedMapBuilder(). - withNodeIdentifier(identifier)).build(); + return addDataContainerChildren(Builders.orderedMapBuilder().withNodeIdentifier(identifier)).build(); - case NodeTypes.UNKEYED_LIST : + case NodeTypes.UNKEYED_LIST: LOG.debug("Read unkeyed list node {}", identifier); - return addDataContainerChildren(Builders.unkeyedListBuilder(). - withNodeIdentifier(identifier)).build(); + return addDataContainerChildren(Builders.unkeyedListBuilder().withNodeIdentifier(identifier)).build(); - case NodeTypes.UNKEYED_LIST_ITEM : + case NodeTypes.UNKEYED_LIST_ITEM: LOG.debug("Read unkeyed list item node {}", identifier); - return addDataContainerChildren(Builders.unkeyedListEntryBuilder(). - withNodeIdentifier(identifier)).build(); + return addDataContainerChildren(Builders.unkeyedListEntryBuilder() + .withNodeIdentifier(identifier)).build(); - case NodeTypes.CONTAINER_NODE : + case NodeTypes.CONTAINER_NODE: LOG.debug("Read container node {}", identifier); - return addDataContainerChildren(Builders.containerBuilder(). - withNodeIdentifier(identifier)).build(); + return addDataContainerChildren(Builders.containerBuilder().withNodeIdentifier(identifier)).build(); case NodeTypes.LEAF_SET : LOG.debug("Read leaf set node {}", identifier); @@ -252,25 +249,24 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput String namespace = readCodedString(); String revision = readCodedString(); - String qName; - if(!Strings.isNullOrEmpty(revision)) { - qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG). - append(revision).append(')').append(localName).toString(); + String qname; + if (!Strings.isNullOrEmpty(revision)) { + qname = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).append(revision) + .append(')').append(localName).toString(); } else { - qName = reusableStringBuilder.append('(').append(namespace).append(')'). - append(localName).toString(); + qname = reusableStringBuilder.append('(').append(namespace).append(')').append(localName).toString(); } reusableStringBuilder.delete(0, reusableStringBuilder.length()); - return QNameFactory.create(qName); + return QNameFactory.create(qname); } private String readCodedString() throws IOException { byte valueType = input.readByte(); - if(valueType == TokenTypes.IS_CODE_VALUE) { + if (valueType == TokenTypes.IS_CODE_VALUE) { return codedStringMap.get(input.readInt()); - } else if(valueType == TokenTypes.IS_STRING_VALUE) { + } else if (valueType == TokenTypes.IS_STRING_VALUE) { String value = input.readUTF().intern(); codedStringMap.put(Integer.valueOf(codedStringMap.size()), value); return value; @@ -279,11 +275,11 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput return null; } - private Set readQNameSet() throws IOException{ + private Set readQNameSet() throws IOException { // Read the children count int count = input.readInt(); Set children = new HashSet<>(count); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { children.add(readQName()); } return children; @@ -293,7 +289,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput int count = input.readInt(); Map keyValueMap = new HashMap<>(count); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { keyValueMap.put(readQName(), readObject()); } @@ -302,7 +298,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput private Object readObject() throws IOException { byte objectType = input.readByte(); - switch(objectType) { + switch (objectType) { case ValueTypes.BITS_TYPE: return readObjSet(); @@ -366,7 +362,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput List pathArguments = new ArrayList<>(size); - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { pathArguments.add(readPathArgument()); } return YangInstanceIdentifier.create(pathArguments); @@ -375,7 +371,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput private Set readObjSet() throws IOException { int count = input.readInt(); Set children = new HashSet<>(count); - for(int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { children.add(readCodedString()); } return children; @@ -386,7 +382,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput // read Type int type = input.readByte(); - switch(type) { + switch (type) { case PathArgumentTypes.AUGMENTATION_IDENTIFIER : return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet()); @@ -415,7 +411,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput LeafSetEntryNode child = (LeafSetEntryNode)readNormalizedNodeInternal(); - while(child != null) { + while (child != null) { builder.withChild(child); child = (LeafSetEntryNode)readNormalizedNodeInternal(); } @@ -429,7 +425,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput NormalizedNode child = readNormalizedNodeInternal(); - while(child != null) { + while (child != null) { builder.addChild(child); child = readNormalizedNodeInternal(); } @@ -437,21 +433,21 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput } @Override - public void readFully(final byte[] b) throws IOException { + public void readFully(final byte[] value) throws IOException { readSignatureMarkerAndVersionIfNeeded(); - input.readFully(b); + input.readFully(value); } @Override - public void readFully(final byte[] b, final int off, final int len) throws IOException { + public void readFully(final byte[] str, final int off, final int len) throws IOException { readSignatureMarkerAndVersionIfNeeded(); - input.readFully(b, off, len); + input.readFully(str, off, len); } @Override - public int skipBytes(final int n) throws IOException { + public int skipBytes(final int num) throws IOException { readSignatureMarkerAndVersionIfNeeded(); - return input.skipBytes(n); + return input.skipBytes(num); } @Override diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java index 5eaa7fc1b7..94d1baddc5 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeOutputStreamWriter.java @@ -24,7 +24,7 @@ import org.opendaylight.yangtools.yang.common.QName; * then will call * {@link #leafNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, Object)} twice * and then, {@link #endNode()} to end container node. - * + *

    * Based on the each node, the node type is also written to the stream, that helps in reconstructing the object, * while reading. */ @@ -36,7 +36,7 @@ final class NormalizedNodeOutputStreamWriter extends AbstractNormalizedNodeDataO } @Override - protected final short streamVersion() { + protected short streamVersion() { return TokenTypes.LITHIUM_VERSION; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java index dd140ca410..b372d8f915 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/PathArgumentTypes.java @@ -23,12 +23,11 @@ final class PathArgumentTypes { throw new UnsupportedOperationException("Utility class"); } - private static final Map, Byte> CLASS_TO_ENUM_MAP = - ImmutableMap., Byte>builder(). - put(YangInstanceIdentifier.AugmentationIdentifier.class, AUGMENTATION_IDENTIFIER). - put(YangInstanceIdentifier.NodeIdentifier.class, NODE_IDENTIFIER). - put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, NODE_IDENTIFIER_WITH_PREDICATES). - put(YangInstanceIdentifier.NodeWithValue.class, NODE_IDENTIFIER_WITH_VALUE).build(); + private static final Map, Byte> CLASS_TO_ENUM_MAP = ImmutableMap., Byte>builder() + .put(YangInstanceIdentifier.AugmentationIdentifier.class, AUGMENTATION_IDENTIFIER) + .put(YangInstanceIdentifier.NodeIdentifier.class, NODE_IDENTIFIER) + .put(YangInstanceIdentifier.NodeIdentifierWithPredicates.class, NODE_IDENTIFIER_WITH_PREDICATES) + .put(YangInstanceIdentifier.NodeWithValue.class, NODE_IDENTIFIER_WITH_VALUE).build(); public static byte getSerializablePathArgumentType(YangInstanceIdentifier.PathArgument pathArgument) { final Byte type = CLASS_TO_ENUM_MAP.get(pathArgument.getClass()); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java index 1afc73a3c8..dd9e102464 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/ValueTypes.java @@ -59,14 +59,14 @@ final class ValueTypes { throw new UnsupportedOperationException("Utility class"); } - public static final byte getSerializableType(Object node) { - if(node == null){ + public static byte getSerializableType(Object node) { + if (node == null) { return NULL_TYPE; } final Byte type = TYPES.get(node.getClass()); if (type != null) { - if(type == STRING_TYPE && ((String) node).length() >= STRING_BYTES_LENGTH_THRESHOLD ){ + if (type == STRING_TYPE && ((String) node).length() >= STRING_BYTES_LENGTH_THRESHOLD) { return STRING_BYTES_TYPE; } return type; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodeBuilderWrapper.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodeBuilderWrapper.java index 259529eaa9..4654ec9cc1 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodeBuilderWrapper.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodeBuilderWrapper.java @@ -26,15 +26,16 @@ public class NormalizedNodeBuilderWrapper { this.schemaNode = schemaNode; } - public NormalizedNodeContainerBuilder builder(){ + @SuppressWarnings("rawtypes") + public NormalizedNodeContainerBuilder builder() { return builder; } - public QName nodeType(){ + public QName nodeType() { return identifier.getNodeType(); } - public YangInstanceIdentifier.PathArgument identifier(){ + public YangInstanceIdentifier.PathArgument identifier() { return identifier; } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodePruner.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodePruner.java index 91d323ea73..5363661c0e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodePruner.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/transformer/NormalizedNodePruner.java @@ -33,8 +33,7 @@ import org.slf4j.LoggerFactory; /** * The NormalizedNodePruner removes all nodes from the input NormalizedNode that do not have a corresponding - * schema element in the passed in SchemaContext - * + * schema element in the passed in SchemaContext. */ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodePruner.class); @@ -51,19 +50,20 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { @SuppressWarnings("unchecked") @Override - public void leafNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, Object o) throws IOException, IllegalArgumentException { + public void leafNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, Object value) + throws IOException, IllegalArgumentException { checkNotSealed(); NormalizedNodeBuilderWrapper parent = stack.peek(); - LeafNode leafNode = Builders.leafBuilder().withNodeIdentifier(nodeIdentifier).withValue(o).build(); - if(parent != null) { - if(hasValidSchema(nodeIdentifier.getNodeType(), parent)) { + LeafNode leafNode = Builders.leafBuilder().withNodeIdentifier(nodeIdentifier).withValue(value).build(); + if (parent != null) { + if (hasValidSchema(nodeIdentifier.getNodeType(), parent)) { parent.builder().addChild(leafNode); } } else { // If there's no parent node then this is a stand alone LeafNode. - if(nodePathSchemaNode != null) { + if (nodePathSchemaNode != null) { this.normalizedNode = leafNode; } @@ -72,16 +72,16 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { } @Override - public void startLeafSet(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startLeafSet(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.leafSetBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startOrderedLeafSet(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startOrderedLeafSet(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int str) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.orderedLeafSetBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); @@ -89,20 +89,22 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { @SuppressWarnings({ "unchecked" }) @Override - public void leafSetEntryNode(QName name, Object o) throws IOException, IllegalArgumentException { + public void leafSetEntryNode(QName name, Object value) throws IOException, IllegalArgumentException { checkNotSealed(); NormalizedNodeBuilderWrapper parent = stack.peek(); - if(parent != null) { - if(hasValidSchema(name, parent)) { - parent.builder().addChild(Builders.leafSetEntryBuilder().withValue(o).withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue<>(parent.nodeType(), o)).build()); + if (parent != null) { + if (hasValidSchema(name, parent)) { + parent.builder().addChild(Builders.leafSetEntryBuilder().withValue(value) + .withNodeIdentifier(new YangInstanceIdentifier.NodeWithValue<>(parent.nodeType(), value)) + .build()); } } else { - // If there's no parent LeafSetNode then this is a stand alone LeafSetEntryNode. - if(nodePathSchemaNode != null) { - this.normalizedNode = Builders.leafSetEntryBuilder().withValue(o).withNodeIdentifier( - new YangInstanceIdentifier.NodeWithValue<>(name, o)).build(); + // If there's no parent LeafSetNode then this is a stand alone + // LeafSetEntryNode. + if (nodePathSchemaNode != null) { + this.normalizedNode = Builders.leafSetEntryBuilder().withValue(value).withNodeIdentifier( + new YangInstanceIdentifier.NodeWithValue<>(name, value)).build(); } sealed = true; @@ -110,68 +112,71 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { } @Override - public void startContainerNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startContainerNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.containerBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startYangModeledAnyXmlNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { + public void startYangModeledAnyXmlNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { throw new UnsupportedOperationException("Not implemented yet"); } @Override - public void startUnkeyedList(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startUnkeyedList(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.unkeyedListBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalStateException { - + public void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalStateException { checkNotSealed(); addBuilder(Builders.unkeyedListEntryBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startMapNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startMapNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.mapBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates, int i) throws IOException, IllegalArgumentException { - + public void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifierWithPredicates, + int count) throws IOException, IllegalArgumentException { checkNotSealed(); - addBuilder(Builders.mapEntryBuilder().withNodeIdentifier(nodeIdentifierWithPredicates), nodeIdentifierWithPredicates); + addBuilder(Builders.mapEntryBuilder().withNodeIdentifier(nodeIdentifierWithPredicates), + nodeIdentifierWithPredicates); } @Override - public void startOrderedMapNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startOrderedMapNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.orderedMapBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startChoiceNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int i) throws IOException, IllegalArgumentException { - + public void startChoiceNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, int count) + throws IOException, IllegalArgumentException { checkNotSealed(); addBuilder(Builders.choiceBuilder().withNodeIdentifier(nodeIdentifier), nodeIdentifier); } @Override - public void startAugmentationNode(YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier) throws IOException, IllegalArgumentException { + public void startAugmentationNode(YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier) + throws IOException, IllegalArgumentException { checkNotSealed(); @@ -180,19 +185,20 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { @SuppressWarnings("unchecked") @Override - public void anyxmlNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, Object o) throws IOException, IllegalArgumentException { + public void anyxmlNode(YangInstanceIdentifier.NodeIdentifier nodeIdentifier, Object value) + throws IOException, IllegalArgumentException { checkNotSealed(); NormalizedNodeBuilderWrapper parent = stack.peek(); - AnyXmlNode anyXmlNode = Builders.anyXmlBuilder().withNodeIdentifier(nodeIdentifier). - withValue((DOMSource) o).build(); - if(parent != null) { - if(hasValidSchema(nodeIdentifier.getNodeType(), parent)) { + AnyXmlNode anyXmlNode = Builders.anyXmlBuilder().withNodeIdentifier(nodeIdentifier).withValue((DOMSource) value) + .build(); + if (parent != null) { + if (hasValidSchema(nodeIdentifier.getNodeType(), parent)) { parent.builder().addChild(anyXmlNode); } } else { // If there's no parent node then this is a stand alone AnyXmlNode. - if(nodePathSchemaNode != null) { + if (nodePathSchemaNode != null) { this.normalizedNode = anyXmlNode; } @@ -200,27 +206,27 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { } } + @SuppressWarnings("unchecked") @Override public void endNode() throws IOException, IllegalStateException { - checkNotSealed(); NormalizedNodeBuilderWrapper child = stack.pop(); Preconditions.checkState(child != null, "endNode called on an empty stack"); - if(!child.getSchema().isPresent()) { + if (!child.getSchema().isPresent()) { LOG.debug("Schema not found for {}", child.identifier()); return; } - NormalizedNode normalizedNode = child.builder().build(); + NormalizedNode newNode = child.builder().build(); - if(stack.size() > 0) { + if (stack.size() > 0) { NormalizedNodeBuilderWrapper parent = stack.peek(); - parent.builder().addChild(normalizedNode); + parent.builder().addChild(newNode); } else { - this.normalizedNode = normalizedNode; + this.normalizedNode = newNode; sealed = true; } } @@ -235,17 +241,17 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { } - public NormalizedNode normalizedNode(){ + public NormalizedNode normalizedNode() { return normalizedNode; } - private void checkNotSealed(){ + private void checkNotSealed() { Preconditions.checkState(!sealed, "Pruner can be used only once"); } private static boolean hasValidSchema(QName name, NormalizedNodeBuilderWrapper parent) { boolean valid = parent.getSchema().isPresent() && parent.getSchema().get().getChild(name) != null; - if(!valid) { + if (!valid) { LOG.debug("Schema not found for {}", name); } @@ -253,12 +259,12 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { } private NormalizedNodeBuilderWrapper addBuilder(NormalizedNodeContainerBuilder builder, - PathArgument identifier){ + PathArgument identifier) { final Optional> schemaNode; NormalizedNodeBuilderWrapper parent = stack.peek(); - if(parent == null) { + if (parent == null) { schemaNode = Optional.fromNullable(nodePathSchemaNode); - } else if(parent.getSchema().isPresent()) { + } else if (parent.getSchema().isPresent()) { schemaNode = Optional.fromNullable(parent.getSchema().get().getChild(identifier)); } else { schemaNode = Optional.absent(); @@ -272,9 +278,9 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { private static DataSchemaContextNode findSchemaNodeForNodePath(YangInstanceIdentifier nodePath, SchemaContext schemaContext) { DataSchemaContextNode schemaNode = DataSchemaContextTree.from(schemaContext).getRoot(); - for(PathArgument arg : nodePath.getPathArguments()) { + for (PathArgument arg : nodePath.getPathArguments()) { schemaNode = schemaNode.getChild(arg); - if(schemaNode == null) { + if (schemaNode == null) { break; } } @@ -286,26 +292,26 @@ public class NormalizedNodePruner implements NormalizedNodeStreamWriter { static class SimpleStack { List stack = new LinkedList<>(); - void push(E element){ + void push(E element) { stack.add(element); } - E pop(){ - if(size() == 0){ + E pop() { + if (size() == 0) { return null; } return stack.remove(stack.size() - 1); } - E peek(){ - if(size() == 0){ + E peek() { + if (size() == 0) { return null; } return stack.get(stack.size() - 1); } - int size(){ + int size() { return stack.size(); } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java index b72ca5800a..312eeef6d5 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java @@ -8,6 +8,12 @@ package org.opendaylight.controller.cluster.datastore.util; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFactory; import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory; import org.opendaylight.controller.cluster.datastore.node.utils.serialization.PathArgumentSerializer; @@ -25,17 +31,11 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithV import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; /** * This class contains utility methods for converting an MD-SAL * YangInstanceIdentifier to and from other representations. - *

    + *

    * The representations convered for now are, * *

      @@ -44,12 +44,10 @@ import java.util.Set; *
    */ public class InstanceIdentifierUtils { - - protected static final Logger logger = LoggerFactory - .getLogger(InstanceIdentifierUtils.class); + private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierUtils.class); /** - * Convert an MD-SAL YangInstanceIdentifier into a protocol buffer version of it + * Convert an MD-SAL YangInstanceIdentifier into a protocol buffer version of it. * * @param path an MD-SAL YangInstanceIdentifier * @return a protocol buffer version of the MD-SAL YangInstanceIdentifier @@ -65,6 +63,7 @@ public class InstanceIdentifierUtils { return toSerializableBuilder(path, context).build(); } + @SuppressWarnings("checkstyle:IllegalCatch") private static NormalizedNodeMessages.InstanceIdentifier.Builder toSerializableBuilder( YangInstanceIdentifier path, QNameSerializationContext context) { NormalizedNodeMessages.InstanceIdentifier.Builder builder = @@ -73,7 +72,7 @@ public class InstanceIdentifierUtils { try { for (PathArgument pathArgument : path.getPathArguments()) { NormalizedNodeMessages.PathArgument serializablePathArgument; - if(context == null) { + if (context == null) { String nodeType = ""; if (!(pathArgument instanceof AugmentationIdentifier)) { nodeType = pathArgument.getNodeType().toString(); @@ -90,8 +89,8 @@ public class InstanceIdentifierUtils { builder.addArguments(serializablePathArgument); } - } catch(Exception e){ - logger.error("An exception occurred", e); + } catch (Exception e) { + LOG.error("An exception occurred", e); } return builder; @@ -100,7 +99,7 @@ public class InstanceIdentifierUtils { /** * Convert a protocol buffer version of the MD-SAL YangInstanceIdentifier into - * the MD-SAL version of the YangInstanceIdentifier + * the MD-SAL version of the YangInstanceIdentifier. * * @param path a protocol buffer version of the MD-SAL YangInstanceIdentifier * @return an MD-SAL YangInstanceIdentifier @@ -114,8 +113,8 @@ public class InstanceIdentifierUtils { List pathArguments = new ArrayList<>(); - for(NormalizedNodeMessages.PathArgument pathArgument : path.getArgumentsList()) { - if(context == null || pathArgument.hasType()) { + for (NormalizedNodeMessages.PathArgument pathArgument : path.getArgumentsList()) { + if (context == null || pathArgument.hasType()) { pathArguments.add(parsePathArgument(pathArgument)); } else { pathArguments.add(PathArgumentSerializer.deSerialize(context, pathArgument)); @@ -128,8 +127,7 @@ public class InstanceIdentifierUtils { /** * Take the various attributes of a PathArgument and package them up as * protocol buffer attributes. - *

    - * + *

    * PathArguments have 4 subtypes and each of the various subtypes have * different attributes *

      @@ -154,8 +152,6 @@ public class InstanceIdentifierUtils { * an augmentation entry. * *
    - * @param pathArgument - * @return */ private static Iterable getPathArgumentAttributes( PathArgument pathArgument) { @@ -188,7 +184,7 @@ public class InstanceIdentifierUtils { } - } else if(pathArgument instanceof AugmentationIdentifier) { + } else if (pathArgument instanceof AugmentationIdentifier) { AugmentationIdentifier identifier = (AugmentationIdentifier) pathArgument; for (QName key : identifier.getPossibleChildNames()) { @@ -210,7 +206,7 @@ public class InstanceIdentifierUtils { /** - * Parse a protocol buffer PathArgument and return an MD-SAL PathArgument + * Parse a protocol buffer PathArgument and return an MD-SAL PathArgument. * * @param pathArgument protocol buffer PathArgument * @return MD-SAL PathArgument @@ -225,23 +221,23 @@ public class InstanceIdentifierUtils { return nodeWithValue; - } else if(NodeIdentifierWithPredicates.class.getSimpleName().equals(pathArgument.getType())){ + } else if (NodeIdentifierWithPredicates.class.getSimpleName().equals(pathArgument.getType())) { NodeIdentifierWithPredicates nodeIdentifierWithPredicates = - new NodeIdentifierWithPredicates( - QNameFactory.create(pathArgument.getNodeType().getValue()), toAttributesMap(pathArgument.getAttributesList())); + new NodeIdentifierWithPredicates(QNameFactory.create(pathArgument.getNodeType().getValue()), + toAttributesMap(pathArgument.getAttributesList())); return nodeIdentifierWithPredicates; - } else if(AugmentationIdentifier.class.getSimpleName().equals(pathArgument.getType())){ + } else if (AugmentationIdentifier.class.getSimpleName().equals(pathArgument.getType())) { - Set qNameSet = new HashSet<>(); + Set qnameSet = new HashSet<>(); - for(NormalizedNodeMessages.Attribute attribute : pathArgument.getAttributesList()){ - qNameSet.add(QNameFactory.create(attribute.getValue())); + for (NormalizedNodeMessages.Attribute attribute : pathArgument.getAttributesList()) { + qnameSet.add(QNameFactory.create(attribute.getValue())); } - return new AugmentationIdentifier(qNameSet); + return new AugmentationIdentifier(qnameSet); } return NodeIdentifierFactory.getArgument(pathArgument.getValue()); @@ -252,7 +248,7 @@ public class InstanceIdentifierUtils { Map map = new HashMap<>(); - for(NormalizedNodeMessages.Attribute attribute : attributesList){ + for (NormalizedNodeMessages.Attribute attribute : attributesList) { String name = attribute.getName(); Object value = parseAttribute(attribute); @@ -263,19 +259,16 @@ public class InstanceIdentifierUtils { } /** - * FIXME: This method only covers a subset of values that may go in an InstanceIdentifier - * - * @param attribute - * @return + * FIXME: This method only covers a subset of values that may go in an InstanceIdentifier. */ - private static Object parseAttribute(NormalizedNodeMessages.Attribute attribute){ - if(Short.class.getSimpleName().equals(attribute.getType())) { + private static Object parseAttribute(NormalizedNodeMessages.Attribute attribute) { + if (Short.class.getSimpleName().equals(attribute.getType())) { return Short.parseShort(attribute.getValue()); - } else if(Long.class.getSimpleName().equals(attribute.getType())){ + } else if (Long.class.getSimpleName().equals(attribute.getType())) { return Long.parseLong(attribute.getValue()); - } else if(Boolean.class.getSimpleName().equals(attribute.getType())){ + } else if (Boolean.class.getSimpleName().equals(attribute.getType())) { return Boolean.parseBoolean(attribute.getValue()); - } else if(Integer.class.getSimpleName().equals(attribute.getType())){ + } else if (Integer.class.getSimpleName().equals(attribute.getType())) { return Integer.parseInt(attribute.getValue()); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListener.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListener.java index b9ba36943c..4928679998 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListener.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListener.java @@ -11,9 +11,8 @@ package org.opendaylight.controller.cluster.notifications; import java.io.Serializable; /** - * Message sent from the listener of Role Change messages to register itself to the Role Change Notifier - * - * The Listener could be in a separate ActorSystem and hence this message needs to be Serializable + * Message sent from the listener of Role Change messages to register itself to the Role Change Notifier. + * The Listener could be in a separate ActorSystem and hence this message needs to be Serializable. */ public class RegisterRoleChangeListener implements Serializable { private static final long serialVersionUID = 8370459011119791506L; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListenerReply.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListenerReply.java index 608130dad2..eea87ae9d7 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListenerReply.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RegisterRoleChangeListenerReply.java @@ -11,8 +11,7 @@ package org.opendaylight.controller.cluster.notifications; import java.io.Serializable; /** - * Reply message sent from a RoleChangeNotifier to the Role Change Listener - * + * Reply message sent from a RoleChangeNotifier to the Role Change Listener. * Can be sent to a separate actor system and hence should be made serializable. */ public class RegisterRoleChangeListenerReply implements Serializable { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotification.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotification.java index 44b8bf4a53..370ce1f3bb 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotification.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotification.java @@ -11,17 +11,15 @@ package org.opendaylight.controller.cluster.notifications; import java.io.Serializable; /** - * Notification message representing a Role change of a cluster member - * - * Roles generally are Leader, Follower and Candidate. But can be based on the consensus strategy/implementation - * - * The Listener could be in a separate ActorSystem and hence this message needs to be Serializable + * Notification message representing a Role change of a cluster member. + * Roles generally are Leader, Follower and Candidate. But can be based on the consensus strategy/implementation. + * The Listener could be in a separate ActorSystem and hence this message needs to be Serializable. */ public class RoleChangeNotification implements Serializable { private static final long serialVersionUID = -2873869509490117116L; - private String memberId; - private String oldRole; - private String newRole; + private final String memberId; + private final String oldRole; + private final String newRole; public RoleChangeNotification(String memberId, String oldRole, String newRole) { this.memberId = memberId; diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotifier.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotifier.java index 1e07332e51..c41d707fd8 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotifier.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChangeNotifier.java @@ -63,7 +63,7 @@ public class RoleChangeNotifier extends AbstractUntypedActor implements AutoClos getSender().tell(new RegisterRoleChangeListenerReply(), getSelf()); - if(latestLeaderStateChanged != null) { + if (latestLeaderStateChanged != null) { getSender().tell(latestLeaderStateChanged, getSelf()); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChanged.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChanged.java index 6154e1f659..711025bfa9 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChanged.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/notifications/RoleChanged.java @@ -10,14 +10,12 @@ package org.opendaylight.controller.cluster.notifications; /** * Role Change message initiated internally from the Raft Actor when a the behavior/role changes. - * * Since its internal , need not be serialized - * */ public class RoleChanged { - private String memberId; - private String oldRole; - private String newRole; + private final String memberId; + private final String oldRole; + private final String newRole; public RoleChanged(String memberId, String oldRole, String newRole) { this.memberId = memberId; @@ -39,10 +37,6 @@ public class RoleChanged { @Override public String toString() { - return "RoleChanged{" + - "memberId='" + memberId + '\'' + - ", oldRole='" + oldRole + '\'' + - ", newRole='" + newRole + '\'' + - '}'; + return "RoleChanged [memberId=" + memberId + ", oldRole=" + oldRole + ", newRole=" + newRole + "]"; } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/Payload.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/Payload.java index bd48f1fd0d..1d0a10345a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/Payload.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/raft/protobuff/client/messages/Payload.java @@ -8,13 +8,10 @@ package org.opendaylight.controller.cluster.raft.protobuff.client.messages; - - /** * An instance of a Payload class is meant to be used as the Payload for * AppendEntries. - *

    - * + *

    * When an actor which is derived from RaftActor attempts to persistData it * must pass an instance of the Payload class. Similarly when state needs to * be applied to the derived RaftActor it will be passed an instance of the diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProvider.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProvider.java index e2a42b2f5e..3208e390a4 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProvider.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProvider.java @@ -38,8 +38,8 @@ public class RemoteSchemaProvider implements SchemaSourceProvider MAPPER = new ExceptionMapper( "schemaDownload", SchemaSourceException.class) { @Override - protected SchemaSourceException newWithCause(final String s, final Throwable throwable) { - return new SchemaSourceException(s, throwable); + protected SchemaSourceException newWithCause(final String message, final Throwable throwable) { + return new SchemaSourceException(message, throwable); } }; @@ -57,11 +57,12 @@ public class RemoteSchemaProvider implements SchemaSourceProvider res = SettableFuture.create(); result.onComplete(new OnComplete() { @Override - public void onComplete(Throwable throwable, YangTextSchemaSourceSerializationProxy yangTextSchemaSourceSerializationProxy) { - if(yangTextSchemaSourceSerializationProxy != null) { + public void onComplete(Throwable throwable, + YangTextSchemaSourceSerializationProxy yangTextSchemaSourceSerializationProxy) { + if (yangTextSchemaSourceSerializationProxy != null) { res.set(yangTextSchemaSourceSerializationProxy.getRepresentation()); } - if(throwable != null) { + if (throwable != null) { res.setException(throwable); } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java index 0b07eeb19b..882f2a84c9 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/main/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImpl.java @@ -48,7 +48,8 @@ public class RemoteYangTextSourceProviderImpl implements RemoteYangTextSourcePro LOG.trace("Sending yang schema source for {}", identifier); final Promise promise = akka.dispatch.Futures.promise(); - CheckedFuture future = repository.getSchemaSource(identifier, YangTextSchemaSource.class); + CheckedFuture future = + repository.getSchemaSource(identifier, YangTextSchemaSource.class); Futures.addCallback(future, new FutureCallback() { @Override @@ -62,9 +63,9 @@ public class RemoteYangTextSourceProviderImpl implements RemoteYangTextSourcePro } @Override - public void onFailure(Throwable t) { - LOG.warn("Unable to retrieve schema source from provider", t); - promise.failure(t); + public void onFailure(Throwable failure) { + LOG.warn("Unable to retrieve schema source from provider", failure); + promise.failure(failure); } }); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/CommonConfigTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/CommonConfigTest.java index 825b03c670..fb5ff64ae8 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/CommonConfigTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/CommonConfigTest.java @@ -8,19 +8,18 @@ package org.opendaylight.controller.cluster.common.actor; -import org.junit.Test; -import scala.concurrent.duration.FiniteDuration; - -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.util.concurrent.TimeUnit; +import org.junit.Test; +import scala.concurrent.duration.FiniteDuration; + public class CommonConfigTest { @Test - public void testCommonConfigDefaults(){ + public void testCommonConfigDefaults() { CommonConfig config = new CommonConfig.Builder<>("testsystem").build(); assertNotNull(config.getActorSystemName()); @@ -31,7 +30,7 @@ public class CommonConfigTest { } @Test - public void testCommonConfigOverride(){ + public void testCommonConfigOverride() { int expectedCapacity = 123; String timeoutValue = "1000ms"; @@ -48,4 +47,4 @@ public class CommonConfigTest { assertTrue(config.isMetricCaptureEnabled()); } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MessageTrackerTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MessageTrackerTest.java index 9c11c13c25..896fd3c939 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MessageTrackerTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MessageTrackerTest.java @@ -11,6 +11,7 @@ package org.opendaylight.controller.cluster.common.actor; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; + import java.util.List; import org.junit.Assert; import org.junit.Before; @@ -23,7 +24,7 @@ public class MessageTrackerTest { // Intentionally empty } - private final static Logger LOG = LoggerFactory.getLogger(MessageTrackerTest.class); + private static final Logger LOG = LoggerFactory.getLogger(MessageTrackerTest.class); private TestTicker ticker; private MessageTracker messageTracker; @@ -68,11 +69,11 @@ public class MessageTrackerTest { messageTracker.received("A").close(); messageTracker.received(10L).close(); - MessageTracker.Context c = messageTracker.received(100); + MessageTracker.Context context = messageTracker.received(100); ticker.increment(MILLISECONDS.toNanos(20)); - c.close(); + context.close(); MessageTracker.Context context2 = messageTracker.received(new Foo()); @@ -119,8 +120,8 @@ public class MessageTrackerTest { try { messageTracker.received(new Foo()); fail("Expected an IllegalStateException"); - } catch (IllegalStateException e){ - + } catch (IllegalStateException e) { + // expected } } @@ -131,7 +132,7 @@ public class MessageTrackerTest { } @Test - public void testDelayInFirstExpectedMessageArrival(){ + public void testDelayInFirstExpectedMessageArrival() { messageTracker.begin(); ticker.increment(MILLISECONDS.toNanos(20)); @@ -187,4 +188,4 @@ public class MessageTrackerTest { } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java index 9fe8a13222..6142bf3ec5 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/common/actor/MeteredBoundedMailboxTest.java @@ -13,7 +13,6 @@ import akka.actor.DeadLetter; import akka.actor.Props; import akka.actor.UntypedActor; import akka.testkit.JavaTestKit; -import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; @@ -30,12 +29,7 @@ public class MeteredBoundedMailboxTest { @BeforeClass public static void setUp() throws Exception { - config = new CommonConfig.Builder<>("testsystem").withConfigReader(new AkkaConfigurationReader() { - @Override - public Config read() { - return ConfigFactory.load(); - } - }).build(); + config = new CommonConfig.Builder<>("testsystem").withConfigReader(() -> ConfigFactory.load()).build(); actorSystem = ActorSystem.create("testsystem", config.get()); } @@ -52,8 +46,7 @@ public class MeteredBoundedMailboxTest { final JavaTestKit mockReceiver = new JavaTestKit(actorSystem); actorSystem.eventStream().subscribe(mockReceiver.getRef(), DeadLetter.class); - - final FiniteDuration TWENTY_SEC = new FiniteDuration(20, TimeUnit.SECONDS); + final FiniteDuration twentySeconds = new FiniteDuration(20, TimeUnit.SECONDS); ActorRef pingPongActor = actorSystem.actorOf(PingPongActor.props(lock).withMailbox(config.getMailBoxName()), "pingpongactor"); @@ -64,29 +57,29 @@ public class MeteredBoundedMailboxTest { //need to send 12 messages; 1 message is dequeued and actor waits on lock, //2nd to 11th messages are put on the queue //12th message is sent to dead letter. - for (int i=0;i<12;i++){ + for (int i = 0; i < 12; i++) { pingPongActor.tell("ping", mockReceiver.getRef()); } - mockReceiver.expectMsgClass(TWENTY_SEC, DeadLetter.class); + mockReceiver.expectMsgClass(twentySeconds, DeadLetter.class); lock.unlock(); - Object[] eleven = mockReceiver.receiveN(11, TWENTY_SEC); + mockReceiver.receiveN(11, twentySeconds); } /** - * For testing + * For testing. */ - public static class PingPongActor extends UntypedActor{ + public static class PingPongActor extends UntypedActor { ReentrantLock lock; - private PingPongActor(final ReentrantLock lock){ + private PingPongActor(final ReentrantLock lock) { this.lock = lock; } - public static Props props(final ReentrantLock lock){ + public static Props props(final ReentrantLock lock) { return Props.create(PingPongActor.class, lock); } @@ -102,4 +95,4 @@ public class MeteredBoundedMailboxTest { } } } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java index ac8fa418fc..2521d997f5 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java @@ -11,6 +11,7 @@ package org.opendaylight.controller.cluster.datastore.node; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; + import java.util.List; import org.junit.Before; import org.junit.Test; @@ -25,142 +26,116 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NormalizedNodeToNodeCodecTest { - private SchemaContext schemaContext; - - @Before - public void setUp() { - schemaContext = TestModel.createTestContext(); - assertNotNull("Schema context must not be null.", schemaContext); - } - - private static YangInstanceIdentifier instanceIdentifierFromString(String s) { - return PathUtils.toYangInstanceIdentifier(s); - } - - @Test - public void testNormalizeNodeAttributesToProtoBuffNode() { - final NormalizedNode documentOne = TestModel.createTestContainer(); - String id = - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" - + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list" - + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=2}]" - + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id"; - - NormalizedNodeGetter normalizedNodeGetter = new NormalizedNodeGetter(id); - new NormalizedNodeNavigator(normalizedNodeGetter).navigate( - PathUtils.toString(YangInstanceIdentifier.EMPTY), documentOne); + private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeToNodeCodecTest.class); - // Validate the value of id can be retrieved from the normalized node - NormalizedNode output = normalizedNodeGetter.getOutput(); - assertNotNull(output); + private SchemaContext schemaContext; + @Before + public void setUp() { + schemaContext = TestModel.createTestContext(); + assertNotNull("Schema context must not be null.", schemaContext); + } - NormalizedNodeToNodeCodec codec = - new NormalizedNodeToNodeCodec(schemaContext); - long start = System.currentTimeMillis(); - Container container = - codec.encode(output); - long end = System.currentTimeMillis(); + private static YangInstanceIdentifier instanceIdentifierFromString(String str) { + return PathUtils.toYangInstanceIdentifier(str); + } - System.out.println("Timetaken to encode :"+(end-start)); + @Test + public void testNormalizeNodeAttributesToProtoBuffNode() { + final NormalizedNode documentOne = TestModel.createTestContainer(); + String id = "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list[" + + "{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=2}]" + + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id"; - assertNotNull(container); + NormalizedNodeGetter normalizedNodeGetter = new NormalizedNodeGetter(id); + new NormalizedNodeNavigator(normalizedNodeGetter).navigate(PathUtils.toString(YangInstanceIdentifier.EMPTY), + documentOne); - // Decode the normalized node from the ProtocolBuffer form - // first get the node representation of normalized node - final Node node = container.getNormalizedNode(); + // Validate the value of id can be retrieved from the normalized node + NormalizedNode output = normalizedNodeGetter.getOutput(); + assertNotNull(output); - start = System.currentTimeMillis(); - NormalizedNode normalizedNode = - codec.decode(node); - end = System.currentTimeMillis(); + NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(); + long start = System.currentTimeMillis(); + Container container = codec.encode(output); + long end = System.currentTimeMillis(); - System.out.println("Timetaken to decode :"+(end-start)); + LOG.info("Time taken to encode: {}", end - start); - assertEquals(normalizedNode.getValue().toString(), output.getValue() - .toString()); - } + assertNotNull(container); - @Test - public void testThatANormalizedNodeToProtoBuffNodeEncodeDecode() - throws Exception { - final NormalizedNode documentOne = TestModel.createTestContainer(); + // Decode the normalized node from the ProtocolBuffer form + // first get the node representation of normalized node + final Node node = container.getNormalizedNode(); - final NormalizedNodeToNodeCodec normalizedNodeToNodeCodec = - new NormalizedNodeToNodeCodec(schemaContext); + start = System.currentTimeMillis(); + NormalizedNode normalizedNode = codec.decode(node); + end = System.currentTimeMillis(); - Container container = - normalizedNodeToNodeCodec.encode(documentOne); + LOG.info("Time taken to decode: {}", end - start); + assertEquals(normalizedNode.getValue().toString(), output.getValue().toString()); + } - final NormalizedNode decode = - normalizedNodeToNodeCodec - .decode( - container.getNormalizedNode()); - assertNotNull(decode); + @Test + public void testThatANormalizedNodeToProtoBuffNodeEncodeDecode() throws Exception { + final NormalizedNode documentOne = TestModel.createTestContainer(); - // let us ensure that the return decode normalized node encode returns same container - Container containerResult = - normalizedNodeToNodeCodec.encode(decode); + final NormalizedNodeToNodeCodec normalizedNodeToNodeCodec = new NormalizedNodeToNodeCodec(); - // check first level children are proper - List childrenResult = - containerResult.getNormalizedNode().getChildList(); - List childrenOriginal = container.getNormalizedNode().getChildList(); + Container container = normalizedNodeToNodeCodec.encode(documentOne); - System.out.println("-------------------------------------------------"); + final NormalizedNode decode = normalizedNodeToNodeCodec.decode(container.getNormalizedNode()); + assertNotNull(decode); - System.out.println(childrenOriginal.toString()); + // let us ensure that the return decode normalized node encode returns + // same container + Container containerResult = normalizedNodeToNodeCodec.encode(decode); - System.out.println("-------------------------------------------------"); + // check first level children are proper + List childrenResult = containerResult.getNormalizedNode().getChildList(); + List childrenOriginal = container.getNormalizedNode().getChildList(); - System.out.println(childrenResult.toString()); + LOG.info("\n-------------------------------------------------\n" + childrenOriginal + + "\n-------------------------------------------------\n" + childrenResult); - boolean bFound; - for (Node resultChild : childrenResult) { - bFound = false; - for (Node originalChild : childrenOriginal) { + boolean found; + for (Node resultChild : childrenResult) { + found = false; + for (Node originalChild : childrenOriginal) { - YangInstanceIdentifier.PathArgument result = NormalizedNodeSerializer.deSerialize( - containerResult.getNormalizedNode(), - resultChild.getPathArgument()); + YangInstanceIdentifier.PathArgument result = NormalizedNodeSerializer + .deSerialize(containerResult.getNormalizedNode(), resultChild.getPathArgument()); - YangInstanceIdentifier.PathArgument original = NormalizedNodeSerializer.deSerialize( - container.getNormalizedNode(), - originalChild.getPathArgument()); + YangInstanceIdentifier.PathArgument original = NormalizedNodeSerializer + .deSerialize(container.getNormalizedNode(), originalChild.getPathArgument()); - if (original.equals(result) - && resultChild.getIntType() == resultChild.getIntType()) { - bFound = true; - break; + if (original.equals(result) && resultChild.getIntType() == resultChild.getIntType()) { + found = true; + break; + } + } + assertTrue(found); } - } - assertTrue(bFound); - } - - } - - @Test - public void addAugmentations() { - String stringId = - "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" - + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list" - + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=1}]"; - YangInstanceIdentifier identifier = instanceIdentifierFromString(stringId); - - MapEntryNode uno = TestModel.createAugmentedListEntry(1, "Uno"); + } - NormalizedNodeToNodeCodec codec = - new NormalizedNodeToNodeCodec(schemaContext); + @Test + public void addAugmentations() { + MapEntryNode uno = TestModel.createAugmentedListEntry(1, "Uno"); - Container encode = codec.encode(uno); + NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(); - System.out.println(encode.getNormalizedNode()); + Container encode = codec.encode(uno); - codec.decode(encode.getNormalizedNode()); - } + LOG.info(encode.getNormalizedNode().toString()); + codec.decode(encode.getNormalizedNode()); + } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java index d9ad69e548..3f5ecc68f0 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java @@ -9,20 +9,19 @@ package org.opendaylight.controller.cluster.datastore.node.utils; import static org.junit.Assert.assertTrue; + import org.junit.Test; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public class NodeIdentifierFactoryTest { - @Test - public void validateAugmentationIdentifier() { - YangInstanceIdentifier.PathArgument argument = - NodeIdentifierFactory - .getArgument("AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}"); - - assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier); - + @Test + public void validateAugmentationIdentifier() { + YangInstanceIdentifier.PathArgument argument = NodeIdentifierFactory.getArgument( + "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)" + + "flow-table-statistics]}"); - } + assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier); + } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java index a12f15010c..d1b89b2de0 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtilsTest.java @@ -8,7 +8,12 @@ package org.opendaylight.controller.cluster.datastore.node.utils; +import static junit.framework.TestCase.assertEquals; + import com.google.common.collect.ImmutableSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.util.TestModel; import org.opendaylight.yangtools.yang.common.QName; @@ -18,25 +23,24 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import static junit.framework.TestCase.assertEquals; public class PathUtilsTest { @Test - public void toStringNodeIdentifier(){ + public void toStringNodeIdentifier() { PathArgument pathArgument = nodeIdentifier(); - String expected = "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"; + String expected = + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"; assertEquals(expected , PathUtils.toString(pathArgument)); } @Test - public void toStringAugmentationIdentifier(){ - String expected = "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}"; + public void toStringAugmentationIdentifier() { + String expected = + "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)" + + "flow-table-statistics]}"; PathArgument pathArgument = augmentationIdentifier(); @@ -44,28 +48,31 @@ public class PathUtilsTest { } @Test - public void toStringNodeWithValue(){ + public void toStringNodeWithValue() { PathArgument pathArgument = nodeWithValue(); - String expected = "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[100]"; + String expected = + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[100]"; assertEquals(expected, PathUtils.toString(pathArgument)); } @Test - public void toStringNodeIdentifierWithPredicates(){ + public void toStringNodeIdentifierWithPredicates() { PathArgument pathArgument = nodeIdentifierWithPredicates(); - String expected = "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=100}]"; + String expected = + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[" + + "{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=100}]"; assertEquals(expected, PathUtils.toString(pathArgument)); } @Test - public void toStringYangInstanceIdentifier(){ + public void toStringYangInstanceIdentifier() { YangInstanceIdentifier path = YangInstanceIdentifier.create(nodeIdentifier()) @@ -73,21 +80,27 @@ public class PathUtilsTest { .node(augmentationIdentifier()).node(nodeWithValue()); - String expected = "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/" + - "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=100}]/" + - "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}/" + - "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[100]"; + String expected = + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/" + + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[" + + "{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=100}]/" + + "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)" + + "flow-table-statistics]}/" + + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[100]"; assertEquals(expected, PathUtils.toString(path)); } @Test - public void toYangInstanceIdentifier(){ - String expected = "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/" + - "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=100}]/" + - "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}/" + - "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[100]"; + public void toYangInstanceIdentifier() { + String expected = + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/" + + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[" + + "{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=100}]/" + + "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)" + + "flow-table-statistics]}/" + + "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test[100]"; YangInstanceIdentifier yangInstanceIdentifier = PathUtils.toYangInstanceIdentifier(expected); @@ -98,21 +111,22 @@ public class PathUtilsTest { } - private static NodeIdentifier nodeIdentifier(){ + private static NodeIdentifier nodeIdentifier() { return new NodeIdentifier(TestModel.TEST_QNAME); } - private static AugmentationIdentifier augmentationIdentifier(){ - Set childNames = ImmutableSet.of(QNameFactory.create("(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics")); + private static AugmentationIdentifier augmentationIdentifier() { + Set childNames = ImmutableSet.of(QNameFactory.create( + "(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics")); return new AugmentationIdentifier(childNames); } - private static NodeWithValue nodeWithValue(){ + private static NodeWithValue nodeWithValue() { return new NodeWithValue<>(TestModel.TEST_QNAME, Integer.valueOf(100)); } - private static NodeIdentifierWithPredicates nodeIdentifierWithPredicates(){ + private static NodeIdentifierWithPredicates nodeIdentifierWithPredicates() { Map keys = new HashMap<>(); keys.put(TestModel.ID_QNAME, Integer.valueOf(100)); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java index c2b7c07fa5..1d551fc651 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactoryTest.java @@ -8,18 +8,18 @@ package org.opendaylight.controller.cluster.datastore.node.utils; -import org.junit.Test; -import org.opendaylight.controller.cluster.datastore.util.TestModel; -import org.opendaylight.yangtools.yang.common.QName; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.opendaylight.controller.cluster.datastore.util.TestModel; +import org.opendaylight.yangtools.yang.common.QName; + public class QNameFactoryTest { @Test - public void testBasic(){ + public void testBasic() { QName expected = TestModel.AUG_NAME_QNAME; QName created = QNameFactory.create(expected.toString()); @@ -33,5 +33,4 @@ public class QNameFactoryTest { assertTrue( cached == created ); } - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java index e03d546ea7..737d37c2d3 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/NormalizedNodeSerializerTest.java @@ -8,6 +8,10 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import com.google.common.base.Optional; import org.junit.Rule; import org.junit.Test; @@ -19,18 +23,17 @@ import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NormalizedNodeSerializerTest { + private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeSerializerTest.class); @Rule public ExpectedException expectedException = ExpectedException.none(); @Test - public void testSerializeDeSerialize(){ + public void testSerializeDeSerialize() { // This test basically serializes and deSerializes a largish document // which contains most of the types of nodes that go into a normalized @@ -45,25 +48,25 @@ public class NormalizedNodeSerializerTest { NormalizedNodeMessages.Node expected = NormalizedNodeSerializer .serialize(expectedNode); - System.out.println("Serialize Time = " + (System.nanoTime() - start)/1000000); + LOG.info("Serialize Time = {}", (System.nanoTime() - start) / 1000000); - System.out.println("Serialized Size = " + expected.getSerializedSize()); + LOG.info("Serialized Size = {}", expected.getSerializedSize()); - System.out.println(expected.toString()); + LOG.info(expected.toString()); start = System.nanoTime(); NormalizedNode actualNode = NormalizedNodeSerializer.deSerialize(expected); - System.out.println("DeSerialize Time = " + (System.nanoTime() - start)/1000000); + LOG.info("DeSerialize Time = {}", (System.nanoTime() - start) / 1000000); // Compare the original normalized node to the normalized node that was // created by serializing the original node and deSerializing it back. assertEquals(expectedNode, actualNode); byte[] binaryData = new byte[5]; - for(byte i=0;i<5;i++){ + for (byte i = 0; i < 5; i++) { binaryData[i] = i; } @@ -81,7 +84,8 @@ public class NormalizedNodeSerializerTest { // FIXME: This will not work due to BUG 2326. Once that is fixed we can uncomment this assertion // assertEquals(node1, node2); - Optional> child = node2.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.SOME_BINARY_DATA_QNAME)); + Optional> child = + node2.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.SOME_BINARY_DATA_QNAME)); Object value = child.get().getValue(); @@ -89,19 +93,19 @@ public class NormalizedNodeSerializerTest { byte[] bytesValue = (byte[]) value; - for(byte i=0;i<5;i++){ + for (byte i = 0; i < 5; i++) { assertEquals(i, bytesValue[i]); } } @Test(expected = NullPointerException.class) - public void testSerializeNullNormalizedNode(){ + public void testSerializeNullNormalizedNode() { assertNotNull(NormalizedNodeSerializer.serialize(null)); } @Test - public void testDeSerializeNullProtocolBufferNode(){ + public void testDeSerializeNullProtocolBufferNode() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("node should not be null"); @@ -109,7 +113,7 @@ public class NormalizedNodeSerializerTest { } @Test - public void testDeSerializePathArgumentNullNode(){ + public void testDeSerializePathArgumentNullNode() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("node should not be null"); @@ -118,7 +122,7 @@ public class NormalizedNodeSerializerTest { } @Test - public void testDeSerializePathArgumentNullPathArgument(){ + public void testDeSerializePathArgumentNullPathArgument() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("pathArgument should not be null"); @@ -126,7 +130,7 @@ public class NormalizedNodeSerializerTest { } @Test - public void testDeSerializePathArgument(){ + public void testDeSerializePathArgument() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); @@ -149,12 +153,12 @@ public class NormalizedNodeSerializerTest { pathBuilder.setIntType(PathArgumentType.NODE_IDENTIFIER.ordinal()); - NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); - qNameBuilder.setNamespace(1); - qNameBuilder.setRevision(4); - qNameBuilder.setLocalName(8); + NormalizedNodeMessages.QName.Builder qnameBuilder = NormalizedNodeMessages.QName.newBuilder(); + qnameBuilder.setNamespace(1); + qnameBuilder.setRevision(4); + qnameBuilder.setLocalName(8); - pathBuilder.setNodeType(qNameBuilder); + pathBuilder.setNodeType(qnameBuilder); YangInstanceIdentifier.PathArgument pathArgument = NormalizedNodeSerializer @@ -162,10 +166,9 @@ public class NormalizedNodeSerializerTest { assertNotNull(pathArgument); - assertEquals("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", pathArgument.getNodeType().getNamespace().toString()); + assertEquals("urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test", + pathArgument.getNodeType().getNamespace().toString()); assertEquals("2014-03-13", pathArgument.getNodeType().getFormattedRevision()); assertEquals("capability", pathArgument.getNodeType().getLocalName()); } - - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializerTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializerTest.java index 922bc1bfa6..d0041fe256 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializerTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/PathArgumentSerializerTest.java @@ -8,8 +8,18 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import java.net.URI; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -21,24 +31,14 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; -import java.net.URI; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -public class PathArgumentSerializerTest{ +public class PathArgumentSerializerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test - public void testSerializeNullContext(){ + public void testSerializeNullContext() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("context should not be null"); @@ -46,7 +46,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testSerializeNullPathArgument(){ + public void testSerializeNullPathArgument() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("pathArgument should not be null"); @@ -55,7 +55,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testDeSerializeNullContext(){ + public void testDeSerializeNullContext() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("context should not be null"); @@ -64,7 +64,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testDeSerializeNullPathArgument(){ + public void testDeSerializeNullPathArgument() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("pathArgument should not be null"); @@ -73,7 +73,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testSerializeNodeIdentifier(){ + public void testSerializeNodeIdentifier() { QNameSerializationContext serializationContext = mock(QNameSerializationContext.class); when(serializationContext.addLocalName(anyString())).thenReturn(5); @@ -94,7 +94,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testSerializeNodeIdentifierWithValue(){ + public void testSerializeNodeIdentifierWithValue() { QNameSerializationContext serializationContext = mock(QNameSerializationContext.class); when(serializationContext.addLocalName(anyString())).thenReturn(5); @@ -116,7 +116,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testSerializeNodeIdentifierWithPredicates(){ + public void testSerializeNodeIdentifierWithPredicates() { QNameSerializationContext serializationContext = mock(QNameSerializationContext.class); when(serializationContext.addLocalName("test")).thenReturn(5); @@ -153,7 +153,7 @@ public class PathArgumentSerializerTest{ } @Test - public void testSerializeAugmentationIdentifier(){ + public void testSerializeAugmentationIdentifier() { QNameSerializationContext serializationContext = mock(QNameSerializationContext.class); when(serializationContext.addLocalName(anyString())).thenReturn(55); @@ -173,11 +173,11 @@ public class PathArgumentSerializerTest{ } @Test - public void testDeSerializeNodeIdentifier(){ - - NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); - NormalizedNodeMessages.PathArgument.Builder pathBuilder = NormalizedNodeMessages.PathArgument.newBuilder(); - NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); + public void testDeSerializeNodeIdentifier() { + final NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); + final NormalizedNodeMessages.PathArgument.Builder pathBuilder = + NormalizedNodeMessages.PathArgument.newBuilder(); + final NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); qNameBuilder.setNamespace(0); qNameBuilder.setRevision(1); @@ -197,10 +197,11 @@ public class PathArgumentSerializerTest{ } @Test - public void testDeSerializeNodeWithValue(){ - NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); - NormalizedNodeMessages.PathArgument.Builder pathBuilder = NormalizedNodeMessages.PathArgument.newBuilder(); - NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); + public void testDeSerializeNodeWithValue() { + final NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); + final NormalizedNodeMessages.PathArgument.Builder pathBuilder = + NormalizedNodeMessages.PathArgument.newBuilder(); + final NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); qNameBuilder.setNamespace(0); qNameBuilder.setRevision(1); @@ -221,11 +222,13 @@ public class PathArgumentSerializerTest{ assertEquals(new NodeWithValue<>(TestModel.TEST_QNAME, "foo"), pathArgument); } + @Test - public void testDeSerializeNodeIdentifierWithPredicates(){ - NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); - NormalizedNodeMessages.PathArgument.Builder pathBuilder = NormalizedNodeMessages.PathArgument.newBuilder(); - NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); + public void testDeSerializeNodeIdentifierWithPredicates() { + final NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); + final NormalizedNodeMessages.PathArgument.Builder pathBuilder = + NormalizedNodeMessages.PathArgument.newBuilder(); + final NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); qNameBuilder.setNamespace(0); qNameBuilder.setRevision(1); @@ -233,8 +236,8 @@ public class PathArgumentSerializerTest{ pathBuilder.setNodeType(qNameBuilder); pathBuilder.setIntType(PathArgumentType.NODE_IDENTIFIER_WITH_PREDICATES.ordinal()); - pathBuilder.addAttribute(NormalizedNodeMessages.PathArgumentAttribute.newBuilder().setName(qNameBuilder).setValue( - "foo").setType(ValueType.STRING_TYPE.ordinal())); + pathBuilder.addAttribute(NormalizedNodeMessages.PathArgumentAttribute.newBuilder().setName(qNameBuilder) + .setValue("foo").setType(ValueType.STRING_TYPE.ordinal())); nodeBuilder.addCode(TestModel.TEST_QNAME.getNamespace().toString()); nodeBuilder.addCode(TestModel.TEST_QNAME.getFormattedRevision()); @@ -246,18 +249,21 @@ public class PathArgumentSerializerTest{ ImmutableMap.of(TestModel.TEST_QNAME, "foo")), pathArgument); } + @Test - public void testDeSerializeNodeAugmentationIdentifier(){ - NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); - NormalizedNodeMessages.PathArgument.Builder pathBuilder = NormalizedNodeMessages.PathArgument.newBuilder(); - NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); + public void testDeSerializeNodeAugmentationIdentifier() { + final NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); + final NormalizedNodeMessages.PathArgument.Builder pathBuilder = + NormalizedNodeMessages.PathArgument.newBuilder(); + final NormalizedNodeMessages.QName.Builder qNameBuilder = NormalizedNodeMessages.QName.newBuilder(); qNameBuilder.setNamespace(0); qNameBuilder.setRevision(1); qNameBuilder.setLocalName(2); pathBuilder.setIntType(PathArgumentType.AUGMENTATION_IDENTIFIER.ordinal()); - pathBuilder.addAttribute(NormalizedNodeMessages.PathArgumentAttribute.newBuilder().setName(qNameBuilder).setType(ValueType.STRING_TYPE.ordinal())); + pathBuilder.addAttribute(NormalizedNodeMessages.PathArgumentAttribute.newBuilder().setName(qNameBuilder) + .setType(ValueType.STRING_TYPE.ordinal())); nodeBuilder.addCode(TestModel.TEST_QNAME.getNamespace().toString()); nodeBuilder.addCode(TestModel.TEST_QNAME.getFormattedRevision()); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java index 69a6f0b695..014d86091a 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueSerializerTest.java @@ -11,6 +11,7 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; + import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.protobuf.ByteString; @@ -27,13 +28,13 @@ import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessa import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -public class ValueSerializerTest{ +public class ValueSerializerTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test - public void testSerializeShort(){ + public void testSerializeShort() { short v1 = 5; NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); @@ -52,7 +53,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeInteger(){ + public void testSerializeInteger() { String hexNumber = "f3"; Integer expected = Integer.valueOf(hexNumber, 16); @@ -77,7 +78,7 @@ public class ValueSerializerTest{ @Test - public void testSerializeLong(){ + public void testSerializeLong() { long v1 = 5; NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); @@ -85,7 +86,8 @@ public class ValueSerializerTest{ assertEquals(ValueType.LONG_TYPE.ordinal(), builder.getIntValueType()); assertEquals("5", builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class), v1); @@ -95,7 +97,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeByte(){ + public void testSerializeByte() { byte v1 = 5; NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); @@ -103,7 +105,8 @@ public class ValueSerializerTest{ assertEquals(ValueType.BYTE_TYPE.ordinal(), builder.getIntValueType()); assertEquals("5", builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class), v1); @@ -113,7 +116,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeBits(){ + public void testSerializeBits() { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), ImmutableSet.of("foo", "bar")); @@ -122,7 +125,8 @@ public class ValueSerializerTest{ assertTrue( "foo not in bits", builder.getBitsValueList().contains("foo")); assertTrue( "bar not in bits", builder.getBitsValueList().contains("bar")); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class), ImmutableSet.of("foo", "bar")); @@ -134,7 +138,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeWrongTypeOfSet(){ + public void testSerializeWrongTypeOfSet() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Expected value type to be Bits but was :"); NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); @@ -144,14 +148,15 @@ public class ValueSerializerTest{ } @Test - public void testSerializeEmptyString(){ + public void testSerializeEmptyString() { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),""); assertEquals(ValueType.STRING_TYPE.ordinal(), builder.getIntValueType()); assertEquals("", builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class),""); @@ -161,7 +166,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeString(){ + public void testSerializeString() { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),"foo"); @@ -180,7 +185,7 @@ public class ValueSerializerTest{ @Test - public void testSerializeBoolean(){ + public void testSerializeBoolean() { boolean v1 = true; NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); @@ -197,25 +202,28 @@ public class ValueSerializerTest{ } @Test - public void testSerializeQName(){ + public void testSerializeQName() { QName v1 = TestModel.TEST_QNAME; NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); assertEquals(ValueType.QNAME_TYPE.ordinal(), builder.getIntValueType()); - assertEquals("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test", builder.getValue()); + assertEquals("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test", + builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class), v1); assertEquals(ValueType.QNAME_TYPE.ordinal(), builder1.getType()); - assertEquals("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test", builder1.getValue()); + assertEquals("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test", + builder1.getValue()); } @Test - public void testSerializeYangIdentifier(){ + public void testSerializeYangIdentifier() { YangInstanceIdentifier v1 = TestModel.TEST_PATH; NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); @@ -247,7 +255,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeBigInteger(){ + public void testSerializeBigInteger() { BigInteger v1 = new BigInteger("1000000000000000000000000"); NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); @@ -255,7 +263,8 @@ public class ValueSerializerTest{ assertEquals(ValueType.BIG_INTEGER_TYPE.ordinal(), builder.getIntValueType()); assertEquals("1000000000000000000000000", builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class), v1); @@ -265,7 +274,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeBigDecimal(){ + public void testSerializeBigDecimal() { BigDecimal v1 = new BigDecimal("1000000000000000000000000.51616"); NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1); @@ -273,7 +282,8 @@ public class ValueSerializerTest{ assertEquals(ValueType.BIG_DECIMAL_TYPE.ordinal(), builder.getIntValueType()); assertEquals("1000000000000000000000000.51616", builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class), v1); assertEquals(ValueType.BIG_DECIMAL_TYPE.ordinal(), builder1.getType()); @@ -282,7 +292,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeBinary(){ + public void testSerializeBinary() { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); byte[] bytes = new byte[] {1,2,3,4}; ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),bytes); @@ -290,7 +300,8 @@ public class ValueSerializerTest{ assertEquals(ValueType.BINARY_TYPE.ordinal(), builder.getIntValueType()); assertEquals(ByteString.copyFrom(bytes), builder.getBytesValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class),bytes); @@ -300,7 +311,7 @@ public class ValueSerializerTest{ } @Test - public void testSerializeNull(){ + public void testSerializeNull() { NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder(); Object none = null; ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),none); @@ -308,7 +319,8 @@ public class ValueSerializerTest{ assertEquals(ValueType.NULL_TYPE.ordinal(), builder.getIntValueType()); assertEquals("", builder.getValue()); - NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); + NormalizedNodeMessages.PathArgumentAttribute.Builder builder1 = + NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); ValueSerializer.serialize(builder1, mock(QNameSerializationContext.class),none); @@ -319,107 +331,107 @@ public class ValueSerializerTest{ @Test - public void testDeSerializeShort(){ + public void testDeSerializeShort() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.SHORT_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof Short); - assertEquals(25, ((Short) o).shortValue()); + assertTrue(value instanceof Short); + assertEquals(25, ((Short) value).shortValue()); } @Test - public void testDeSerializeByte(){ + public void testDeSerializeByte() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.BYTE_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof Byte); - assertEquals(25, ((Byte) o).byteValue()); + assertTrue(value instanceof Byte); + assertEquals(25, ((Byte) value).byteValue()); } @Test - public void testDeSerializeInteger(){ + public void testDeSerializeInteger() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.INT_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof Integer); - assertEquals(25, ((Integer) o).intValue()); + assertTrue(value instanceof Integer); + assertEquals(25, ((Integer) value).intValue()); } @Test - public void testDeSerializeLong(){ + public void testDeSerializeLong() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.LONG_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof Long); - assertEquals(25, ((Long) o).longValue()); + assertTrue(value instanceof Long); + assertEquals(25, ((Long) value).longValue()); } @Test - public void testDeSerializeBoolean(){ + public void testDeSerializeBoolean() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.BOOL_TYPE.ordinal()); nodeBuilder.setValue("false"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof Boolean); - assertEquals(false, ((Boolean) o).booleanValue()); + assertTrue(value instanceof Boolean); + assertEquals(false, ((Boolean) value).booleanValue()); } @Test - public void testDeSerializeQName(){ + public void testDeSerializeQName() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.QNAME_TYPE.ordinal()); nodeBuilder.setValue(TestModel.TEST_QNAME.toString()); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof QName); - assertEquals(TestModel.TEST_QNAME, o); + assertTrue(value instanceof QName); + assertEquals(TestModel.TEST_QNAME, value); } @Test - public void testDeSerializeBits(){ + public void testDeSerializeBits() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.BITS_TYPE.ordinal()); nodeBuilder.addAllBitsValue(ImmutableList.of("foo", "bar")); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof Set); - assertTrue(((Set)o).contains("foo")); - assertTrue(((Set) o).contains("bar")); + assertTrue(value instanceof Set); + assertTrue(((Set)value).contains("foo")); + assertTrue(((Set) value).contains("bar")); NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); @@ -427,21 +439,23 @@ public class ValueSerializerTest{ argumentBuilder.setType(ValueType.BITS_TYPE.ordinal()); argumentBuilder.addAllBitsValue(ImmutableList.of("foo", "bar")); - o = ValueSerializer + value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), argumentBuilder.build()); - assertTrue(o instanceof Set); - assertTrue(((Set)o).contains("foo")); - assertTrue(((Set) o).contains("bar")); + assertTrue(value instanceof Set); + assertTrue(((Set)value).contains("foo")); + assertTrue(((Set) value).contains("bar")); } @Test - public void testDeSerializeYangIdentifier(){ - NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); - NormalizedNodeMessages.InstanceIdentifier.Builder idBuilder = NormalizedNodeMessages.InstanceIdentifier.newBuilder(); - NormalizedNodeMessages.PathArgument.Builder pathBuilder = NormalizedNodeMessages.PathArgument.newBuilder(); + public void testDeSerializeYangIdentifier() { + final NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); + final NormalizedNodeMessages.InstanceIdentifier.Builder idBuilder = + NormalizedNodeMessages.InstanceIdentifier.newBuilder(); + final NormalizedNodeMessages.PathArgument.Builder pathBuilder = + NormalizedNodeMessages.PathArgument.newBuilder(); pathBuilder.setIntType(PathArgumentType.NODE_IDENTIFIER.ordinal()); @@ -451,17 +465,15 @@ public class ValueSerializerTest{ nodeBuilder.setInstanceIdentifierValue(idBuilder); QNameDeSerializationContext mockContext = mock(QNameDeSerializationContext.class); - Mockito.doReturn(TestModel.TEST_QNAME.getNamespace().toString()).when(mockContext). - getNamespace(Mockito.anyInt()); - Mockito.doReturn(TestModel.TEST_QNAME.getLocalName()).when(mockContext). - getLocalName(Mockito.anyInt()); - Mockito.doReturn(TestModel.TEST_QNAME.getFormattedRevision()).when(mockContext). - getRevision(Mockito.anyInt()); + Mockito.doReturn(TestModel.TEST_QNAME.getNamespace().toString()).when(mockContext) + .getNamespace(Mockito.anyInt()); + Mockito.doReturn(TestModel.TEST_QNAME.getLocalName()).when(mockContext).getLocalName(Mockito.anyInt()); + Mockito.doReturn(TestModel.TEST_QNAME.getFormattedRevision()).when(mockContext).getRevision(Mockito.anyInt()); - Object o = ValueSerializer.deSerialize(mockContext, nodeBuilder.build()); + Object value = ValueSerializer.deSerialize(mockContext, nodeBuilder.build()); - assertTrue(o instanceof YangInstanceIdentifier); - assertEquals(TestModel.TEST_PATH, o); + assertTrue(value instanceof YangInstanceIdentifier); + assertEquals(TestModel.TEST_PATH, value); NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); @@ -469,93 +481,93 @@ public class ValueSerializerTest{ argumentBuilder.setType(ValueType.YANG_IDENTIFIER_TYPE.ordinal()); argumentBuilder.setInstanceIdentifierValue(idBuilder); - o = ValueSerializer.deSerialize(mockContext, argumentBuilder.build()); + value = ValueSerializer.deSerialize(mockContext, argumentBuilder.build()); - assertTrue(o instanceof YangInstanceIdentifier); - assertEquals(TestModel.TEST_PATH, o); + assertTrue(value instanceof YangInstanceIdentifier); + assertEquals(TestModel.TEST_PATH, value); } @Test - public void testDeSerializeString(){ + public void testDeSerializeString() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.STRING_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class), + Object value = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof String); - assertEquals("25", o); + assertTrue(value instanceof String); + assertEquals("25", value); } @Test - public void testDeSerializeBigInteger(){ + public void testDeSerializeBigInteger() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.BIG_INTEGER_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof BigInteger); - assertEquals(new BigInteger("25"), o); + assertTrue(value instanceof BigInteger); + assertEquals(new BigInteger("25"), value); } @Test - public void testDeSerializeBigDecimal(){ + public void testDeSerializeBigDecimal() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.BIG_DECIMAL_TYPE.ordinal()); nodeBuilder.setValue("25"); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertTrue(o instanceof BigDecimal); - assertEquals(new BigDecimal("25"), o); + assertTrue(value instanceof BigDecimal); + assertEquals(new BigDecimal("25"), value); } @Test - public void testDeSerializeBinaryType(){ + public void testDeSerializeBinaryType() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.BINARY_TYPE.ordinal()); byte[] bytes = new byte[] {1,2,3,4}; nodeBuilder.setBytesValue(ByteString.copyFrom(bytes)); - Object o = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class),nodeBuilder.build()); + Object value = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class),nodeBuilder.build()); - assertTrue("not a byte array", o instanceof byte[]); - assertTrue("bytes value does not match" , Arrays.equals(bytes, (byte[]) o)); + assertTrue("not a byte array", value instanceof byte[]); + assertTrue("bytes value does not match" , Arrays.equals(bytes, (byte[]) value)); NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); argumentBuilder.setType(ValueType.BINARY_TYPE.ordinal()); argumentBuilder.setBytesValue(ByteString.copyFrom(bytes)); - o = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class), argumentBuilder.build()); + value = ValueSerializer.deSerialize(mock(QNameDeSerializationContext.class), argumentBuilder.build()); - assertTrue("not a byte array", o instanceof byte[]); - assertTrue("bytes value does not match" ,Arrays.equals(bytes, (byte[]) o)); + assertTrue("not a byte array", value instanceof byte[]); + assertTrue("bytes value does not match" ,Arrays.equals(bytes, (byte[]) value)); } @Test - public void testDeSerializeNullType(){ + public void testDeSerializeNullType() { NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder(); nodeBuilder.setIntValueType(ValueType.NULL_TYPE.ordinal()); nodeBuilder.setValue(""); - Object o = ValueSerializer + Object value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), nodeBuilder.build()); - assertEquals(null, o); + assertEquals(null, value); NormalizedNodeMessages.PathArgumentAttribute.Builder argumentBuilder = NormalizedNodeMessages.PathArgumentAttribute.newBuilder(); @@ -563,13 +575,11 @@ public class ValueSerializerTest{ argumentBuilder.setType(ValueType.NULL_TYPE.ordinal()); argumentBuilder.setValue(""); - o = ValueSerializer + value = ValueSerializer .deSerialize(mock(QNameDeSerializationContext.class), argumentBuilder.build()); - assertEquals(null, o); + assertEquals(null, value); } - - } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java index 15805497ad..10bf090739 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/serialization/ValueTypeTest.java @@ -9,25 +9,26 @@ package org.opendaylight.controller.cluster.datastore.node.utils.serialization; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class ValueTypeTest { @Test - public void testGetSerializableType(){ - byte[] b = new byte[10]; - b[0] = 1; - b[2] = 2; + public void testGetSerializableType() { + byte[] bytes = new byte[10]; + bytes[0] = 1; + bytes[2] = 2; - ValueType serializableType = ValueType.getSerializableType(b); + ValueType serializableType = ValueType.getSerializableType(bytes); assertEquals(ValueType.BINARY_TYPE, serializableType); } @Test - public void testNullType(){ + public void testNullType() { ValueType serializableType = ValueType.getSerializableType(null); assertEquals(ValueType.NULL_TYPE, serializableType); assertEquals(null, ValueType.NULL_TYPE.deserialize("")); } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java index e2ce60e007..014202fb34 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/stream/NormalizedNodeStreamReaderWriterTest.java @@ -43,12 +43,12 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableCo import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder; import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder; import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; public class NormalizedNodeStreamReaderWriterTest { + @SuppressWarnings("deprecation") @Test public void testNormalizedNodeStreaming() throws IOException { @@ -62,15 +62,12 @@ public class NormalizedNodeStreamReaderWriterTest { QName toaster = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","toaster"); QName darknessFactor = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","darknessFactor"); QName description = QName.create("http://netconfcentral.org/ns/toaster","2009-11-20","description"); - ContainerNode toasterNode = Builders.containerBuilder(). - withNodeIdentifier(new NodeIdentifier(toaster)). - withChild(ImmutableNodes.leafNode(darknessFactor, "1000")). - withChild(ImmutableNodes.leafNode(description, largeString(20))) - .build(); - - ContainerNode toasterContainer = Builders.containerBuilder(). - withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)). - withChild(toasterNode).build(); + ContainerNode toasterNode = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(toaster)) + .withChild(ImmutableNodes.leafNode(darknessFactor, "1000")) + .withChild(ImmutableNodes.leafNode(description, largeString(20))).build(); + + ContainerNode toasterContainer = Builders.containerBuilder() + .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME)).withChild(toasterNode).build(); writer.writeNormalizedNode(toasterContainer); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( @@ -97,22 +94,22 @@ public class NormalizedNodeStreamReaderWriterTest { LeafSetEntryNode entry3 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, null)).withValue(null).build(); - return TestModel.createBaseTestContainerBuilder(). - withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier( - new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME)). - withChild(entry1).withChild(entry2).withChild(entry3).build()). - withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1,2,3,4})). - withChild(Builders.orderedMapBuilder(). - withNodeIdentifier(new NodeIdentifier(TestModel.ORDERED_LIST_QNAME)). - withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME, - TestModel.ID_QNAME, 11)).build()). - build(); + return TestModel.createBaseTestContainerBuilder() + .withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier( + new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME)) + .withChild(entry1).withChild(entry2).withChild(entry3).build()) + .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1,2,3,4})) + .withChild(Builders.orderedMapBuilder() + .withNodeIdentifier(new NodeIdentifier(TestModel.ORDERED_LIST_QNAME)) + .withChild(ImmutableNodes.mapEntry(TestModel.ORDERED_LIST_ENTRY_QNAME, + TestModel.ID_QNAME, 11)).build()).build(); } + @SuppressWarnings("deprecation") @Test public void testYangInstanceIdentifierStreaming() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey( + YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey( TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); @@ -129,6 +126,7 @@ public class NormalizedNodeStreamReaderWriterTest { writer.close(); } + @SuppressWarnings("deprecation") @Test public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException { @@ -139,8 +137,8 @@ public class NormalizedNodeStreamReaderWriterTest { NormalizedNode testContainer = TestModel.createBaseTestContainerBuilder().build(); writer.writeNormalizedNode(testContainer); - YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey( + YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.TEST_PATH) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey( TestModel.INNER_LIST_QNAME, TestModel.ID_QNAME, 10).build(); writer.writeYangInstanceIdentifier(path); @@ -157,9 +155,10 @@ public class NormalizedNodeStreamReaderWriterTest { writer.close(); } - @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) + @SuppressWarnings("deprecation") + @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000) public void testInvalidNormalizedNodeStream() throws IOException { - byte[] protobufBytes = new NormalizedNodeToNodeCodec(null).encode( + byte[] protobufBytes = new NormalizedNodeToNodeCodec().encode( TestModel.createBaseTestContainerBuilder().build()).getNormalizedNode().toByteArray(); NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( @@ -168,7 +167,8 @@ public class NormalizedNodeStreamReaderWriterTest { reader.readNormalizedNode(); } - @Test(expected=InvalidNormalizedNodeStreamException.class, timeout=10000) + @SuppressWarnings("deprecation") + @Test(expected = InvalidNormalizedNodeStreamException.class, timeout = 10000) public void testInvalidYangInstanceIdentifierStream() throws IOException { byte[] protobufBytes = {1,2,3}; NormalizedNodeInputStreamReader reader = new NormalizedNodeInputStreamReader( @@ -181,12 +181,14 @@ public class NormalizedNodeStreamReaderWriterTest { public void testWithSerializable() { NormalizedNode input = TestModel.createTestContainer(); SampleNormalizedNodeSerializable serializable = new SampleNormalizedNodeSerializable(input ); - SampleNormalizedNodeSerializable clone = (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable); + SampleNormalizedNodeSerializable clone = + (SampleNormalizedNodeSerializable)SerializationUtils.clone(serializable); Assert.assertEquals(input, clone.getInput()); } + @SuppressWarnings("deprecation") @Test public void testAnyXmlStreaming() throws Exception { String xml = "onetwo"; @@ -229,13 +231,13 @@ public class NormalizedNodeStreamReaderWriterTest { writer.close(); } - private static String largeString(final int pow){ - String s = "X"; - for(int i=0;i normalizedNode, final String namespaceFilter){ - if(normalizedNode == null){ + private static int countNodes(NormalizedNode normalizedNode, final String namespaceFilter) { + if (normalizedNode == null) { return 0; } final AtomicInteger count = new AtomicInteger(); new NormalizedNodeNavigator((level, parentPath, normalizedNode1) -> { - if(!(normalizedNode1.getIdentifier() instanceof AugmentationIdentifier)) { + if (!(normalizedNode1.getIdentifier() instanceof AugmentationIdentifier)) { if (normalizedNode1.getIdentifier().getNodeType().getNamespace().toString().contains(namespaceFilter)) { count.incrementAndGet(); } @@ -169,9 +170,9 @@ public class NormalizedNodePrunerTest { @Test public void testLeafNodePrunedWhenHasAugmentationParentAndSchemaMissing() throws IOException { AugmentationIdentifier augId = new AugmentationIdentifier(Sets.newHashSet(TestModel.AUG_CONT_QNAME)); - NormalizedNodePruner pruner = prunerFullSchema(YangInstanceIdentifier.builder(). - node(TestModel.TEST_QNAME).node(TestModel.AUGMENTED_LIST_QNAME). - node(TestModel.AUGMENTED_LIST_QNAME).node(augId).build()); + NormalizedNodePruner pruner = prunerFullSchema(YangInstanceIdentifier.builder() + .node(TestModel.TEST_QNAME).node(TestModel.AUGMENTED_LIST_QNAME) + .node(TestModel.AUGMENTED_LIST_QNAME).node(augId).build()); LeafNode child = Builders.leafBuilder().withNodeIdentifier( new NodeIdentifier(TestModel.INVALID_QNAME)).withValue("test").build(); NormalizedNode input = Builders.augmentationBuilder().withNodeIdentifier(augId).withChild(child).build(); @@ -279,10 +280,10 @@ public class NormalizedNodePrunerTest { @Test public void testInnerContainerNodeWithFullPathPathNotPruned() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - node(TestModel.INNER_LIST_QNAME).nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one"). - node(TestModel.INNER_CONTAINER_QNAME).build(); + YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .node(TestModel.INNER_LIST_QNAME).nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one") + .node(TestModel.INNER_CONTAINER_QNAME).build(); NormalizedNodePruner pruner = prunerFullSchema(path); NormalizedNode input = ImmutableNodes.containerNode(TestModel.INNER_CONTAINER_QNAME); @@ -294,10 +295,10 @@ public class NormalizedNodePrunerTest { @Test public void testInnerContainerNodeWithFullPathPrunedWhenSchemaMissing() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - node(TestModel.INNER_LIST_QNAME).nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one"). - node(TestModel.INVALID_QNAME).build(); + YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .node(TestModel.INNER_LIST_QNAME).nodeWithKey(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one") + .node(TestModel.INVALID_QNAME).build(); NormalizedNodePruner pruner = prunerFullSchema(path); NormalizedNode input = ImmutableNodes.containerNode(TestModel.INVALID_QNAME); @@ -309,29 +310,30 @@ public class NormalizedNodePrunerTest { @Test public void testInnerContainerNodeWithParentPathPrunedWhenSchemaMissing() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(); + YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .build(); NormalizedNodePruner pruner = prunerFullSchema(path); MapNode innerList = mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder( TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").withChild( ImmutableNodes.containerNode(TestModel.INVALID_QNAME)).build()).build(); - NormalizedNode input = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - withChild(innerList).build(); + NormalizedNode input = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .withChild(innerList).build(); NormalizedNodeWriter.forStreamWriter(pruner).write(input); - NormalizedNode expected = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - withChild(mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder( - TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").build()).build()).build(); + NormalizedNode expected = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .withChild(mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder( + TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").build()).build()).build(); NormalizedNode actual = pruner.normalizedNode(); assertEquals("normalizedNode", expected, actual); } @Test public void testInnerListNodeWithFullPathNotPruned() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - node(TestModel.INNER_LIST_QNAME).build(); + YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .node(TestModel.INNER_LIST_QNAME).build(); NormalizedNodePruner pruner = prunerFullSchema(path); MapNode input = mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder( @@ -345,9 +347,9 @@ public class NormalizedNodePrunerTest { @Test public void testInnerListNodeWithFullPathPrunedWhenSchemaMissing() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - node(TestModel.INVALID_QNAME).build(); + YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .node(TestModel.INVALID_QNAME).build(); NormalizedNodePruner pruner = prunerFullSchema(path); MapNode input = mapNodeBuilder(TestModel.INVALID_QNAME).withChild(mapEntryBuilder( @@ -361,15 +363,16 @@ public class NormalizedNodePrunerTest { @Test public void testInnerListNodeWithParentPathPrunedWhenSchemaMissing() throws IOException { - YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME). - node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1).build(); + YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(TestModel.TEST_QNAME) + .node(TestModel.OUTER_LIST_QNAME).nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .build(); NormalizedNodePruner pruner = prunerFullSchema(path); MapNode innerList = mapNodeBuilder(TestModel.INVALID_QNAME).withChild(mapEntryBuilder( TestModel.INVALID_QNAME, TestModel.NAME_QNAME, "one").withChild( ImmutableNodes.containerNode(TestModel.INNER_CONTAINER_QNAME)).build()).build(); - NormalizedNode input = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1). - withChild(innerList).build(); + NormalizedNode input = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1) + .withChild(innerList).build(); NormalizedNodeWriter.forStreamWriter(pruner).write(input); NormalizedNode expected = mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1); @@ -380,23 +383,21 @@ public class NormalizedNodePrunerTest { private static NormalizedNode createTestContainer() { byte[] bytes1 = {1,2,3}; LeafSetEntryNode entry1 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( - new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)). - withValue(bytes1).build(); + new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1)).withValue(bytes1).build(); byte[] bytes2 = {}; LeafSetEntryNode entry2 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( - new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)). - withValue(bytes2).build(); + new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2)).withValue(bytes2).build(); LeafSetEntryNode entry3 = ImmutableLeafSetEntryNodeBuilder.create().withNodeIdentifier( new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, null)).withValue(null).build(); - return TestModel.createBaseTestContainerBuilder(). - withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier( - new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME)). - withChild(entry1).withChild(entry2).withChild(entry3).build()). - withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1, 2, 3, 4})). - build(); + return TestModel.createBaseTestContainerBuilder() + .withChild(ImmutableLeafSetNodeBuilder.create().withNodeIdentifier( + new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME)) + .withChild(entry1).withChild(entry2).withChild(entry3).build()) + .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1, 2, 3, 4})) + .build(); } -} \ No newline at end of file +} diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java index 18b577f9d9..54c6c46af3 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java @@ -9,6 +9,9 @@ package org.opendaylight.controller.cluster.datastore.util; import com.google.common.collect.ImmutableSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.junit.Assert; import org.junit.Test; import org.opendaylight.controller.cluster.datastore.node.utils.serialization.QNameDeSerializationContext; @@ -17,9 +20,6 @@ import org.opendaylight.controller.cluster.datastore.node.utils.serialization.QN import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; public class InstanceIdentifierUtilsTest { diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java index e1607c09c4..bb572e3209 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java @@ -105,8 +105,8 @@ public class TestModel { public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_QNAME); - public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier. - builder(TEST_PATH).node(DESC_QNAME).build(); + public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier + .builder(TEST_PATH).node(DESC_QNAME).build(); public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier.builder(TEST_PATH).node(OUTER_LIST_QNAME).build(); public static final QName TWO_THREE_QNAME = QName.create(TEST_QNAME, "two"); @@ -118,13 +118,12 @@ public class TestModel { private static final String TWO_ONE_NAME = "one"; private static final String TWO_TWO_NAME = "two"; private static final String DESC = "Hello there"; - private static final Long LONG_ID = 1L; private static final Boolean ENABLED = true; private static final Short SHORT_ID = 1; private static final Byte BYTE_ID = 1; // Family specific constants public static final QName FAMILY_QNAME = QName.create( - "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test", "2014-04-17", "family"); + "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test", "2014-04-17", "family"); public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME, "children"); public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME, "grand-children"); public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME, "child-number"); @@ -212,7 +211,7 @@ public class TestModel { } /** - * Returns a test document + * Returns a test document. *

    *

    *

    @@ -227,8 +226,6 @@ public class TestModel {
          *                  name "two"
          *
          * 
    - * - * @return */ public static NormalizedNode createDocumentOne( SchemaContext schemaContext) { @@ -280,14 +277,14 @@ public class TestModel { ImmutableLeafSetEntryNodeBuilder .create() .withNodeIdentifier( - (new NodeWithValue<>(QName.create( - TEST_QNAME, "number"), 5))).withValue(5).build(); + new NodeWithValue<>(QName.create( + TEST_QNAME, "number"), 5)).withValue(5).build(); final LeafSetEntryNode fifteen = ImmutableLeafSetEntryNodeBuilder .create() .withNodeIdentifier( - (new NodeWithValue<>(QName.create( - TEST_QNAME, "number"), 15))).withValue(15).build(); + new NodeWithValue<>(QName.create( + TEST_QNAME, "number"), 15)).withValue(15).build(); final LeafSetNode numbers = ImmutableLeafSetNodeBuilder .create() @@ -308,8 +305,8 @@ public class TestModel { // Create unkeyed list entry UnkeyedListEntryNode unkeyedListEntry = - Builders.unkeyedListEntryBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(UNKEYED_LIST_QNAME)). - withChild(ImmutableNodes.leafNode(NAME_QNAME, "unkeyed-entry-name")).build(); + Builders.unkeyedListEntryBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier( + UNKEYED_LIST_QNAME)).withChild(ImmutableNodes.leafNode(NAME_QNAME, "unkeyed-entry-name")).build(); // Create YangInstanceIdentifier with all path arg types. YangInstanceIdentifier instanceID = YangInstanceIdentifier.create( @@ -343,11 +340,12 @@ public class TestModel { .withChild(Builders.choiceBuilder() .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TWO_THREE_QNAME)) .withChild(ImmutableNodes.leafNode(TWO_QNAME, "two")).build()) - .withChild(Builders.orderedMapBuilder(). - withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ORDERED_LIST_QNAME)). - withValue(ImmutableList.builder().add( + .withChild(Builders.orderedMapBuilder() + .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ORDERED_LIST_QNAME)) + .withValue(ImmutableList.builder().add( mapEntryBuilder(ORDERED_LIST_QNAME, ORDERED_LIST_ENTRY_QNAME, "1").build(), - mapEntryBuilder(ORDERED_LIST_QNAME, ORDERED_LIST_ENTRY_QNAME, "2").build()).build()).build()) + mapEntryBuilder(ORDERED_LIST_QNAME, ORDERED_LIST_ENTRY_QNAME, "2").build()).build()) + .build()) .withChild(shoes) .withChild(numbers) .withChild(switchFeatures) @@ -394,24 +392,24 @@ public class TestModel { public static ContainerNode createFamily() { - final DataContainerNodeAttrBuilder familyContainerBuilder = - ImmutableContainerNodeBuilder.create().withNodeIdentifier( + final DataContainerNodeAttrBuilder + familyContainerBuilder = ImmutableContainerNodeBuilder.create().withNodeIdentifier( new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME)); final CollectionNodeBuilder childrenBuilder = mapNodeBuilder(CHILDREN_QNAME); - final DataContainerNodeBuilder firstChildBuilder = - mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID); - final DataContainerNodeBuilder secondChildBuilder = - mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID); - - final DataContainerNodeBuilder firstGrandChildBuilder = - mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, - FIRST_GRAND_CHILD_ID); - final DataContainerNodeBuilder secondGrandChildBuilder = - mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, - SECOND_GRAND_CHILD_ID); + final DataContainerNodeBuilder + firstChildBuilder = mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID); + final DataContainerNodeBuilder + secondChildBuilder = mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID); + + final DataContainerNodeBuilder + firstGrandChildBuilder = mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, + FIRST_GRAND_CHILD_ID); + final DataContainerNodeBuilder + secondGrandChildBuilder = mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME, + SECOND_GRAND_CHILD_ID); firstGrandChildBuilder .withChild( diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProviderTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProviderTest.java index 1ba2ef0d8b..9b2032890e 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProviderTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteSchemaProviderTest.java @@ -23,13 +23,14 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider; +import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; public class RemoteSchemaProviderTest { - private static final SourceIdentifier ID = SourceIdentifier.create("Test", Optional.of("2015-10-30")); + private static final SourceIdentifier ID = RevisionSourceIdentifier.create("Test", Optional.of("2015-10-30")); private RemoteSchemaProvider remoteSchemaProvider; private RemoteYangTextSourceProvider mockedRemoteSchemaRepository; @@ -45,9 +46,11 @@ public class RemoteSchemaProviderTest { @Test public void getExistingYangTextSchemaSource() throws IOException, SchemaSourceException { String source = "Test"; - YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource(ID, ByteSource.wrap(source.getBytes())); + YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource( + ID, ByteSource.wrap(source.getBytes())); YangTextSchemaSourceSerializationProxy sourceProxy = new YangTextSchemaSourceSerializationProxy(schemaSource); - Mockito.when(mockedRemoteSchemaRepository.getYangTextSchemaSource(ID)).thenReturn(Futures.successful(sourceProxy)); + Mockito.when(mockedRemoteSchemaRepository.getYangTextSchemaSource(ID)) + .thenReturn(Futures.successful(sourceProxy)); YangTextSchemaSource providedSource = remoteSchemaProvider.getSource(ID).checkedGet(); assertEquals(providedSource.getIdentifier(), ID); @@ -59,7 +62,8 @@ public class RemoteSchemaProviderTest { Futures.failed(new Exception("halo")); Mockito.when(mockedRemoteSchemaRepository.getYangTextSchemaSource(ID)).thenReturn( - Futures.failed(new SchemaSourceException("Source not provided"))); + Futures.failed( + new SchemaSourceException("Source not provided"))); CheckedFuture sourceFuture = remoteSchemaProvider.getSource(ID); assertTrue(sourceFuture.isDone()); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImplTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImplTest.java index 5d97dba235..72170cad1b 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImplTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/RemoteYangTextSourceProviderImplTest.java @@ -20,6 +20,7 @@ import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; @@ -30,11 +31,11 @@ import scala.concurrent.duration.Duration; public class RemoteYangTextSourceProviderImplTest { - private static final SourceIdentifier ID = SourceIdentifier.create("Test", Optional.of("2015-10-30")); + private static final SourceIdentifier ID = RevisionSourceIdentifier.create("Test", Optional.of("2015-10-30")); private RemoteYangTextSourceProviderImpl remoteRepository; private SchemaRepository mockedLocalRepository; - private Set providedSources = Collections.singleton(ID); + private final Set providedSources = Collections.singleton(ID); @Before public void setUp() { @@ -46,13 +47,16 @@ public class RemoteYangTextSourceProviderImplTest { @Test public void testGetExistingYangTextSchemaSource() throws Exception { String source = "Test source."; - YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource(ID, ByteSource.wrap(source.getBytes())); + YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource( + ID, ByteSource.wrap(source.getBytes())); Mockito.when(mockedLocalRepository.getSchemaSource(ID, YangTextSchemaSource.class)).thenReturn( Futures.immediateCheckedFuture(schemaSource)); - Future retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID); + Future retrievedSourceFuture = + remoteRepository.getYangTextSchemaSource(ID); assertTrue(retrievedSourceFuture.isCompleted()); - YangTextSchemaSource resultSchemaSource = Await.result(retrievedSourceFuture, Duration.Zero()).getRepresentation(); + YangTextSchemaSource resultSchemaSource = Await.result(retrievedSourceFuture, + Duration.Zero()).getRepresentation(); assertEquals(resultSchemaSource.getIdentifier(), schemaSource.getIdentifier()); assertArrayEquals(resultSchemaSource.read(), schemaSource.read()); } @@ -63,15 +67,16 @@ public class RemoteYangTextSourceProviderImplTest { Futures.immediateFailedCheckedFuture( new SchemaSourceException("Source is not provided"))); - - Future retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID); + Future retrievedSourceFuture = + remoteRepository.getYangTextSchemaSource(ID); assertTrue(retrievedSourceFuture.isCompleted()); Await.result(retrievedSourceFuture, Duration.Zero()); } @Test public void testGetProvidedSources() throws Exception { - Set remoteProvidedSources = Await.result(remoteRepository.getProvidedSources(), Duration.Zero()); + Set remoteProvidedSources = Await.result(remoteRepository + .getProvidedSources(), Duration.Zero()); assertEquals(providedSources, remoteProvidedSources); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/YangTextSourceSerializationProxyTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/YangTextSourceSerializationProxyTest.java index 4ddd7dd3c7..95e141ae95 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/YangTextSourceSerializationProxyTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/cluster/schema/provider/impl/YangTextSourceSerializationProxyTest.java @@ -21,7 +21,7 @@ import java.io.ObjectOutputStream; import java.nio.charset.StandardCharsets; import org.junit.Before; import org.junit.Test; -import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; +import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; public class YangTextSourceSerializationProxyTest { @@ -32,7 +32,7 @@ public class YangTextSourceSerializationProxyTest { public void setUp() { String source = "Test source."; schemaSource = YangTextSchemaSource.delegateForByteSource( - SourceIdentifier.create("test", Optional.of("2015-10-30")), + RevisionSourceIdentifier.create("test", Optional.of("2015-10-30")), ByteSource.wrap(source.getBytes(StandardCharsets.UTF_8))); } @@ -47,7 +47,8 @@ public class YangTextSourceSerializationProxyTest { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); - YangTextSchemaSourceSerializationProxy deserializedProxy = (YangTextSchemaSourceSerializationProxy) ois.readObject(); + YangTextSchemaSourceSerializationProxy deserializedProxy = + (YangTextSchemaSourceSerializationProxy) ois.readObject(); assertEquals(deserializedProxy.getRepresentation().getIdentifier(), proxy.getRepresentation().getIdentifier()); assertArrayEquals(deserializedProxy.getRepresentation().read(), proxy.getRepresentation().read()); @@ -55,7 +56,8 @@ public class YangTextSourceSerializationProxyTest { @Test public void testProxyEqualsBackingYangTextSource() throws IOException { - YangTextSchemaSourceSerializationProxy serializationProxy = new YangTextSchemaSourceSerializationProxy(schemaSource); + YangTextSchemaSourceSerializationProxy serializationProxy = + new YangTextSchemaSourceSerializationProxy(schemaSource); assertEquals(serializationProxy.getRepresentation().getIdentifier(), schemaSource.getIdentifier()); assertArrayEquals(serializationProxy.getRepresentation().read(), schemaSource.read()); diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java index bef1f41b0a..d3c5f97881 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java @@ -18,60 +18,50 @@ import java.io.FileOutputStream; * @author: syedbahm Date: 7/31/14 */ public abstract class AbstractMessagesTest { - public final String VERSION_COMPATIBILTY_TEST_DATA_PATH = "." - + File.separator + "src" + File.separator + "test" + File.separator - + "resources" + File.separator + "version-compatibility-serialized-data"; - private File file; - private File testDataFile; - - protected AbstractMessagesTest() { - init(); - } - - protected void init() { - file = new File(getTestFileName()); - testDataFile = - new File(VERSION_COMPATIBILTY_TEST_DATA_PATH + File.separator - + getTestFileName() + "Data"); - } - - - - abstract public void verifySerialization() throws Exception; - - - protected void writeToFile( - com.google.protobuf.GeneratedMessage.Builder builder) throws Exception { - - FileOutputStream output = new FileOutputStream(file); - builder.build().writeTo(output); - output.close(); - - } - - protected com.google.protobuf.GeneratedMessage readFromFile( - com.google.protobuf.Parser parser) throws Exception { - com.google.protobuf.GeneratedMessage message = - (com.google.protobuf.GeneratedMessage) parser - .parseFrom(new FileInputStream(file)); - - /*Note: we will delete only the test file -- comment below if you want to capture the - version-compatibility-serialized-data test data file.The file will be generated at root of the - sal-protocolbuffer-encoding - and you need to move it to test/resources/version-compatbility-serialized-data folder renaming the file to include suffix "Data" - */ - file.delete(); - return message; - } - - protected com.google.protobuf.GeneratedMessage readFromTestDataFile( - com.google.protobuf.Parser parser) throws Exception { - return (com.google.protobuf.GeneratedMessage) parser - .parseFrom(new FileInputStream(testDataFile)); - } - - - public abstract String getTestFileName(); - - + public final String VERSION_COMPATIBILTY_TEST_DATA_PATH = "." + File.separator + "src" + File.separator + "test" + + File.separator + "resources" + File.separator + "version-compatibility-serialized-data"; + private File file; + private File testDataFile; + + protected AbstractMessagesTest() { + init(); + } + + protected void init() { + file = new File(getTestFileName()); + testDataFile = new File(VERSION_COMPATIBILTY_TEST_DATA_PATH + File.separator + getTestFileName() + "Data"); + } + + abstract public void verifySerialization() throws Exception; + + protected void writeToFile(com.google.protobuf.GeneratedMessage.Builder builder) throws Exception { + + FileOutputStream output = new FileOutputStream(file); + builder.build().writeTo(output); + output.close(); + + } + + protected com.google.protobuf.GeneratedMessage readFromFile(com.google.protobuf.Parser parser) throws Exception { + com.google.protobuf.GeneratedMessage message = (com.google.protobuf.GeneratedMessage) parser + .parseFrom(new FileInputStream(file)); + + /* + * Note: we will delete only the test file -- comment below if you want + * to capture the version-compatibility-serialized-data test data + * file.The file will be generated at root of the + * sal-protocolbuffer-encoding and you need to move it to + * test/resources/version-compatbility-serialized-data folder renaming + * the file to include suffix "Data" + */ + file.delete(); + return message; + } + + protected com.google.protobuf.GeneratedMessage readFromTestDataFile(com.google.protobuf.Parser parser) + throws Exception { + return (com.google.protobuf.GeneratedMessage) parser.parseFrom(new FileInputStream(testDataFile)); + } + + public abstract String getTestFileName(); } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java index d87341407b..37d41be182 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java @@ -28,31 +28,28 @@ import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest; public class NormalizedNodeMessagesTest extends AbstractMessagesTest { - @Override - @Test - public void verifySerialization() throws Exception { - NormalizedNodeMessages.Attribute.Builder builder = - NormalizedNodeMessages.Attribute.newBuilder(); - builder.setName("test"); - builder.setType("fake"); - builder.setValue("testValue"); - writeToFile(builder); - - NormalizedNodeMessages.Attribute attributeNew = - (NormalizedNodeMessages.Attribute) readFromFile(NormalizedNodeMessages.Attribute.PARSER); - Assert.assertEquals("test", attributeNew.getName()); - Assert.assertEquals("fake", attributeNew.getType()); - Assert.assertEquals("testValue", attributeNew.getValue()); - - NormalizedNodeMessages.Attribute attributeOriginal = - (NormalizedNodeMessages.Attribute) readFromTestDataFile(NormalizedNodeMessages.Attribute.PARSER); - Assert.assertEquals(attributeNew.getName(), attributeOriginal.getName()); - } - - @Override - public String getTestFileName() { - return NormalizedNodeMessagesTest.class.getSimpleName(); - } - - + @Override + @Test + public void verifySerialization() throws Exception { + NormalizedNodeMessages.Attribute.Builder builder = NormalizedNodeMessages.Attribute.newBuilder(); + builder.setName("test"); + builder.setType("fake"); + builder.setValue("testValue"); + writeToFile(builder); + + NormalizedNodeMessages.Attribute attributeNew = (NormalizedNodeMessages.Attribute) readFromFile( + NormalizedNodeMessages.Attribute.PARSER); + Assert.assertEquals("test", attributeNew.getName()); + Assert.assertEquals("fake", attributeNew.getType()); + Assert.assertEquals("testValue", attributeNew.getValue()); + + NormalizedNodeMessages.Attribute attributeOriginal = (NormalizedNodeMessages.Attribute) readFromTestDataFile( + NormalizedNodeMessages.Attribute.PARSER); + Assert.assertEquals(attributeNew.getName(), attributeOriginal.getName()); + } + + @Override + public String getTestFileName() { + return NormalizedNodeMessagesTest.class.getSimpleName(); + } } diff --git a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java index b82f534839..023d1fad8f 100644 --- a/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java +++ b/opendaylight/md-sal/sal-clustering-commons/src/test/java/org/opendaylight/controller/xml/codec/XmlUtilsTest.java @@ -13,10 +13,8 @@ import com.google.common.io.ByteSource; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import javax.xml.parsers.DocumentBuilderFactory; import org.junit.Before; import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor; @@ -24,47 +22,33 @@ import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline // FIXME : CompositeNode is not avaliable anymore so fix the test to use NormalizedNodeContainer ASAP public class XmlUtilsTest { - - private static final DocumentBuilderFactory BUILDERFACTORY; - - static { - final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setCoalescing(true); - factory.setIgnoringElementContentWhitespace(true); - factory.setIgnoringComments(true); - BUILDERFACTORY = factory; - } - - private SchemaContext schemaContext; - private RpcDefinition testRpc; - - public static final String XML_CONTENT = "" + - "flowid" + - "/ltha:node/ltha:node1[ltha:id='3@java.lang.Short']" + - ""; - - @Before - public void setUp() throws Exception { - final ByteSource byteSource = new ByteSource() { - @Override - public InputStream openStream() throws IOException { - return XmlUtilsTest.this.getClass().getResourceAsStream("rpcTest.yang"); - } - }; - - final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild(); - final ArrayList sources = Lists.newArrayList(byteSource); - - try { - - schemaContext = reactor.buildEffective(sources); - } catch (ReactorException e) { - throw new RuntimeException("Unable to build schema context from " + sources, e); + public static final String XML_CONTENT = "" + + "flowid" + + "/ltha:node/ltha:node1" + + "[ltha:id='3@java.lang.Short']"; + + private SchemaContext schemaContext; + + @Before + public void setUp() throws Exception { + final ByteSource byteSource = new ByteSource() { + @Override + public InputStream openStream() throws IOException { + return XmlUtilsTest.this.getClass().getResourceAsStream("rpcTest.yang"); + } + }; + + final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild(); + final ArrayList sources = Lists.newArrayList(byteSource); + + try { + + schemaContext = reactor.buildEffective(sources); + } catch (ReactorException e) { + throw new RuntimeException("Unable to build schema context from " + sources, e); + } + + final Module rpcTestModule = schemaContext.getModules().iterator().next(); + rpcTestModule.getRpcs().iterator().next(); } - - final Module rpcTestModule = schemaContext.getModules().iterator().next(); - testRpc = rpcTestModule.getRpcs().iterator().next(); - } - } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/SerializationUtils.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/SerializationUtils.java index 5ab0759915..f29b7d8b8b 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/SerializationUtils.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/SerializationUtils.java @@ -107,7 +107,7 @@ public final class SerializationUtils { // Probably from legacy protobuf serialization - try that. try { NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(bytes); - return new NormalizedNodeToNodeCodec(null).decode(serializedNode); + return new NormalizedNodeToNodeCodec().decode(serializedNode); } catch (InvalidProtocolBufferException e2) { throw new IllegalArgumentException("Error deserializing NormalizedNode", e); } diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/compat/PreLithiumShardTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/compat/PreLithiumShardTest.java index 1830523dce..2ad65a28c3 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/compat/PreLithiumShardTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/compat/PreLithiumShardTest.java @@ -38,7 +38,7 @@ public class PreLithiumShardTest extends AbstractShardTest { TestActorRef shard = TestActorRef.create(getSystem(), newShardProps(), "testApplyHelium2VersionSnapshot"); - NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(SCHEMA_CONTEXT); + NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(); DataTree store = InMemoryDataTreeFactory.getInstance().create(TreeType.OPERATIONAL); store.setSchemaContext(SCHEMA_CONTEXT); diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java index b814bc392e..74017eae6c 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java @@ -21,13 +21,13 @@ public class SampleModelsTest { final NormalizedNodeMessages.Container node = - new NormalizedNodeToNodeCodec(SchemaContextHelper.full()) + new NormalizedNodeToNodeCodec() .encode(expected); final NormalizedNodeMessages.Node normalizedNode = node.getNormalizedNode(); - final NormalizedNode actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(normalizedNode); + final NormalizedNode actual = new NormalizedNodeToNodeCodec().decode(normalizedNode); Assert.assertEquals(expected, actual); @@ -41,13 +41,13 @@ public class SampleModelsTest { final NormalizedNodeMessages.Container node = - new NormalizedNodeToNodeCodec(SchemaContextHelper.full()) + new NormalizedNodeToNodeCodec() .encode(expected); final NormalizedNodeMessages.Node normalizedNode = node.getNormalizedNode(); - final NormalizedNode actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode( + final NormalizedNode actual = new NormalizedNodeToNodeCodec().decode( normalizedNode);