</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
</project>
* @author Thomas Pantelis
*/
public interface ActorSystemProvider {
+
/**
- * @return the current ActorSystem.
+ * Returns the ActorSystem.
+ *
+ * @return the ActorSystem.
*/
@Nonnull
ActorSystem getActorSystem();
* 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 <T>
+ * @param entry the journal entry to persist
+ * @param procedure the callback when persistence is complete
+ * @param <T> the type of the journal entry
*/
- <T> void persist(T o, Procedure<T> procedure);
+ <T> void persist(T entry, Procedure<T> 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();
}
}
@Override
- public <T> void persist(T o, Procedure<T> procedure) {
- delegate.persist(o, procedure);
+ public <T> void persist(T entry, Procedure<T> procedure) {
+ delegate.persist(entry, procedure);
}
@Override
- public void saveSnapshot(Object o) {
- delegate.saveSnapshot(o);
+ public void saveSnapshot(Object entry) {
+ delegate.saveSnapshot(entry);
}
@Override
}
@Override
- public <T> void persist(T o, Procedure<T> procedure) {
+ @SuppressWarnings("checkstyle:IllegalCatch")
+ public <T> void persist(T entry, Procedure<T> 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
+}
}
@Override
- public <T> void persist(T o, Procedure<T> procedure) {
- persistentActor.persist(o, procedure);
+ public <T> void persist(T entry, Procedure<T> procedure) {
+ persistentActor.persist(entry, procedure);
}
@Override
- public void saveSnapshot(Object o) {
- persistentActor.saveSnapshot(o);
+ public void saveSnapshot(Object snapshot) {
+ persistentActor.saveSnapshot(snapshot);
}
@Override
public long getLastSequenceNumber() {
return persistentActor.lastSequenceNr();
}
-}
\ No newline at end of file
+}
private final Config config;
- public AbstractConfig(Config config){
+ public AbstractConfig(Config config) {
this.config = config;
}
return config;
}
- public static abstract class Builder<T extends Builder<T>> {
+ public abstract static class Builder<T extends Builder<T>> {
protected Map<String, Object> 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;
}
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() {
* 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;
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();
}
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() {
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();
}
*/
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 {
return get().getString(TAG_ACTOR_SYSTEM_NAME);
}
- public boolean isMetricCaptureEnabled(){
- if (cachedMetricCaptureEnableFlag != null){
+ public boolean isMetricCaptureEnabled() {
+ if (cachedMetricCaptureEnableFlag != null) {
return cachedMetricCaptureEnableFlag;
}
return cachedMailBoxPushTimeout;
}
- public static class Builder<T extends Builder<T>> extends AbstractConfig.Builder<T>{
+ public static class Builder<T extends Builder<T>> extends AbstractConfig.Builder<T> {
public Builder(String actorSystemName) {
super(actorSystemName);
configHolder.put(TAG_MAILBOX, new HashMap<String, Object>());
}
+ @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");
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");
return ASK_SUPPORT.ask(actor, (Function1<ActorRef, Object>)function, timeout);
}
- public static Future<Object> ask(final ActorRef actor, final Function<ActorRef, ?> function, final Timeout timeout) {
+ public static Future<Object> ask(final ActorRef actor, final Function<ActorRef, ?> function,
+ final Timeout timeout) {
return ask(actor, toScala(function), timeout);
}
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));
}
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;
@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
}
public interface Error {
Object getLastExpectedMessage();
+
Object getCurrentExpectedMessage();
+
List<MessageProcessingTime> getMessageProcessingTimesSinceLastExpectedMessage();
}
@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;
}
}
/**
+ * 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) {
private abstract class AbstractTimedContext extends Context {
abstract Object message();
+
abstract Stopwatch stopTimer();
@Override
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();
}
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.FiniteDuration;
-public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue<MeteredBoundedMailbox.MeteredMessageQueue> {
-
- private final Logger LOG = LoggerFactory.getLogger(MeteredBoundedMailbox.class);
+public class MeteredBoundedMailbox implements MailboxType,
+ ProducesMessageQueue<MeteredBoundedMailbox.MeteredMessageQueue> {
+ 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());
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
}
}
}
- private static Gauge<Integer> getQueueSizeGuage(final MeteredMessageQueue monitoredQueue ){
- return new Gauge<Integer>() {
- @Override
- public Integer getValue() {
- return monitoredQueue.size();
- }
- };
+ private static Gauge<Integer> getQueueSizeGuage(final MeteredMessageQueue monitoredQueue ) {
+ return () -> monitoredQueue.size();
}
- private void registerQueueSizeMetric(String metricName, Gauge<Integer> metric){
+ private void registerQueueSizeMetric(String metricName, Gauge<Integer> metric) {
try {
registry.register(metricName,metric);
} catch (IllegalArgumentException e) {
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;
/**
* <li>message processing rate of actor's receive block</li>
* <li>message processing rate by message type</li>
* </ul>
- *
* The information is reported to {@link org.opendaylight.controller.cluster.reporting.MetricsReporter}
*/
public class MeteringBehavior implements Procedure<Object> {
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
*/
}
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);
}
/**
* @see <a href="http://dropwizard.github.io/metrics/manual/core/#timers">
* http://dropwizard.github.io/metrics/manual/core/#timers</a>
*
- * @param message
- * @throws Exception
+ * @param message the message to process
+ * @throws Exception on message failure
*/
@Override
public void apply(final Object message) throws Exception {
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();
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;
}
* quarantined by another. Once this node gets quarantined, restart the ActorSystem to allow this
* node to rejoin the cluster.
*
- * @author Gary Wu <gary.wu1@huawei.com>
+ * @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";
// check to see if we got quarantined by another node
- if(quarantined) {
+ if (quarantined) {
return;
}
* <li>Config subsystem</li>
* <li>Akka configuration files</li>
* </ul>
- *
* 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();
}
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 {
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();
}
// 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);
}
- 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);
}
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;
}
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;
return new YangInstanceIdentifier.AugmentationIdentifier(childNames);
}
-
}
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<String, YangInstanceIdentifier.PathArgument> 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<String, YangInstanceIdentifier.PathArgument> 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();
}
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);
}
}
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;
}
- 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<QName, Object> 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);
}
}
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;
}
+
+}
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;
}
}
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<DataContainerChild<? extends YangInstanceIdentifier.PathArgument,?>> 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<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> 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<? extends NormalizedNode<?, ?>> 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<? extends NormalizedNode<?, ?>> 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);
+ }
}
- }
}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore.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<n;i++){
- builder.append(' ');
- }
- return builder.toString();
- }
-
- @Override
- public void visitNode(int level, String parentPath, NormalizedNode<?, ?> 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());
- }
- }
-}
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<PathArgument> 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<PathArgument> it = path.getPathArguments().iterator();
/**
* 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<PathArgument> 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<QName> childNames = pathArgument.getPossibleChildNames();
final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
sb.append("childNames=").append(childNames).append('}');
return pathArgument.getNodeType().toString() + "[" + pathArgument.getValue() + "]";
}
- private static String toString(NodeIdentifierWithPredicates pathArgument){
+ private static String toString(NodeIdentifierWithPredicates pathArgument) {
return pathArgument.getNodeType().toString() + '[' + pathArgument.getKeyValues() + ']';
}
-
}
);
- public static QName create(String name){
+ public static QName create(String name) {
return CACHE.getUnchecked(name);
}
}
/**
* 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);
}
/**
* NormalizedNodeSerializationContext provides methods which help in encoding
- * certain components of a NormalizedNode properly
+ * certain components of a NormalizedNode properly.
*/
public interface NormalizedNodeSerializationContext {
}
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;
/**
* Serialize a NormalizedNode into a protocol buffer message
- * <p>
+ * <p/>
* The significant things to be aware of the Serialization process are
* <ul>
* <li>Repeated strings like namespaces, revisions and localNames are
* figure out how to decode values
* </li>
* </ul>
- *
* 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();
}
}
/**
- * 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
* 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 {
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
// 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);
}
}
+ @SuppressWarnings("rawtypes")
public static class DeSerializer extends QNameDeSerializationContextImpl
implements NormalizedNodeDeSerializationContext {
private static final Map<NormalizedNodeType, DeSerializationFunction> DESERIALIZATION_FUNCTIONS;
+
static {
final EnumMap<NormalizedNodeType, DeSerializationFunction> m = new EnumMap<>(NormalizedNodeType.class);
- m.put(CONTAINER_NODE_TYPE, new DeSerializationFunction() {
- @Override
- public NormalizedNode<?, ?> apply(final DeSerializer deSerializer, final NormalizedNodeMessages.Node node) {
- DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = Builders.containerBuilder()
- .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument()));
+ m.put(CONTAINER_NODE_TYPE, (deSerializer, node) -> {
+ DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> 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<NodeIdentifier, Object, LeafNode<Object>> builder = Builders.leafBuilder()
- .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument()));
+ m.put(LEAF_NODE_TYPE, (deSerializer, node) -> {
+ NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> 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<NodeIdentifierWithPredicates, MapEntryNode> 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<AugmentationIdentifier, AugmentationNode> 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<NodeWithValue, Object, LeafSetEntryNode<Object>> 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<NodeIdentifier, ChoiceNode> 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<NodeIdentifierWithPredicates, MapEntryNode> 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<AugmentationIdentifier, AugmentationNode> 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<NodeWithValue, Object, LeafSetEntryNode<Object>> 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<NodeIdentifier, ChoiceNode> 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<NodeIdentifier, UnkeyedListEntryNode> 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<NodeIdentifier, UnkeyedListEntryNode> 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<NodeIdentifier, DOMSource, AnyXmlNode> builder = Builders.anyXmlBuilder()
- .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument()));
+ m.put(ANY_XML_NODE_TYPE, (deSerializer, node) -> {
+ NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> builder = Builders.anyXmlBuilder()
+ .withNodeIdentifier(deSerializer.toNodeIdentifier(node.getPathArgument()));
- return deSerializer.buildNormalizedNode(builder, node);
- }
+ return deSerializer.buildNormalizedNode(builder, node);
});
DESERIALIZATION_FUNCTIONS = Maps.immutableEnumMap(m);
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));
}
}
- private NormalizedNode<?, ?> buildListNode(
- final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder,
- final NormalizedNodeMessages.Node node) {
- builder.withNodeIdentifier(toNodeIdentifier(node.getPathArgument()));
+ @SuppressWarnings("unchecked")
+ private NormalizedNode<?, ?> buildListNode(final ListNodeBuilder<Object, LeafSetEntryNode<Object>> 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<Object>) 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));
}
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
}
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 <T> NodeWithValue<T> toNodeWithValue(final NormalizedNodeMessages.PathArgument path) {
- return (NodeWithValue<T>) PathArgumentSerializer.deSerialize(this, path);
- }
-
- private NodeIdentifier toNodeIdentifier(final NormalizedNodeMessages.PathArgument path){
- return (NodeIdentifier) PathArgumentSerializer.deSerialize(this, path);
+ private <T> NodeWithValue<T> toNodeWithValue(final NormalizedNodeMessages.PathArgument fromPath) {
+ return (NodeWithValue<T>) 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 {
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;
}
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;
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<Class<?>, PathArgumentAttributesGetter> pathArgumentAttributesGetters = new HashMap<>();
+ private static final Map<Class<?>, 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");
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");
}
static {
- pathArgumentAttributesGetters.put(YangInstanceIdentifier.NodeWithValue.class, new PathArgumentAttributesGetter() {
- @Override
- public Iterable<? extends NormalizedNodeMessages.PathArgumentAttribute> 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<? extends NormalizedNodeMessages.PathArgumentAttribute> 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<QName, Object> keyValues = identifier.getKeyValues();
- List<NormalizedNodeMessages.PathArgumentAttribute> attributes =
- new ArrayList<>(keyValues.size());
+ List<NormalizedNodeMessages.PathArgumentAttribute> attributes = new ArrayList<>(keyValues.size());
for (Entry<QName, Object> 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<? extends NormalizedNodeMessages.PathArgumentAttribute> 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<QName> possibleChildNames = identifier.getPossibleChildNames();
- List<NormalizedNodeMessages.PathArgumentAttribute> attributes =
- new ArrayList<>(possibleChildNames.size());
+ List<NormalizedNodeMessages.PathArgumentAttribute> 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<? extends NormalizedNodeMessages.PathArgumentAttribute> 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(
}
- 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<? extends NormalizedNodeMessages.PathArgumentAttribute> 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 {
}
/**
- * 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
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())),
}
case NODE_IDENTIFIER_WITH_PREDICATES : {
-
YangInstanceIdentifier.NodeIdentifierWithPredicates
nodeIdentifierWithPredicates =
new YangInstanceIdentifier.NodeIdentifierWithPredicates(
}
case AUGMENTATION_IDENTIFIER: {
+ Set<QName> qnameSet = new HashSet<>();
- Set<QName> 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: {
List<NormalizedNodeMessages.PathArgumentAttribute> attributesList) {
Map<QName, Object> 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);
} else {
map = new HashMap<>();
- for(NormalizedNodeMessages.PathArgumentAttribute attribute : attributesList){
+ for (NormalizedNodeMessages.PathArgumentAttribute attribute : attributesList) {
NormalizedNodeMessages.QName name = attribute.getName();
Object value = parseAttribute(context, attribute);
}
private static Object parseAttribute(QNameDeSerializationContext context,
- NormalizedNodeMessages.PathArgumentAttribute attribute){
+ NormalizedNodeMessages.PathArgumentAttribute attribute) {
return ValueSerializer.deSerialize(context, attribute);
}
-
}
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,
NODE_IDENTIFIER_WITH_PREDICATES;
private static Map<Class<?>, PathArgumentType> CLASS_TO_ENUM_MAP =
- ImmutableMap.<Class<?>, 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.<Class<?>, 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();
}
-
}
@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);
@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();
}
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());
}
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());
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());
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());
abstract Object deserialize(String str);
public static final ValueType getSerializableType(Object node) {
- if(node == null){
+ if (node == null) {
return NULL_TYPE;
}
}
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);
}
}
@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");
}
@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");
// 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);
}
}
@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");
}
@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");
}
@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");
}
@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");
}
@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");
}
@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);
}
@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");
}
@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");
}
@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");
}
}
- 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 {
Collection<PathArgument> pathArguments = identifier.getPathArguments();
output.writeInt(pathArguments.size());
- for(PathArgument pathArgument : pathArguments) {
+ for (PathArgument pathArgument : pathArguments) {
writePathArgument(pathArgument);
}
}
output.writeByte(type);
- switch(type) {
+ switch (type) {
case PathArgumentTypes.NODE_IDENTIFIER:
NodeIdentifier nodeIdentifier = (NodeIdentifier) pathArgument;
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() );
}
}
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);
// 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");
@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
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);
private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
Object, LeafNode<Object>> leafBuilder;
+ @SuppressWarnings("rawtypes")
private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
private final StringBuilder reusableStringBuilder = new StringBuilder(50);
private boolean readSignatureMarker = true;
/**
+ * Constructs an instance.
+ *
* @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
*/
@Deprecated
}
private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
- if(readSignatureMarker) {
+ if (readSignatureMarker) {
readSignatureMarker = false;
final byte marker = input.readByte();
// 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();
}
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()));
private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
Object, LeafNode<Object>> leafBuilder() {
- if(leafBuilder == null) {
+ if (leafBuilder == null) {
leafBuilder = Builders.leafBuilder();
}
return leafBuilder;
}
+ @SuppressWarnings("rawtypes")
private NormalizedNodeAttrBuilder<NodeWithValue, Object,
LeafSetEntryNode<Object>> leafSetEntryBuilder() {
- if(leafSetEntryBuilder == null) {
+ if (leafSetEntryBuilder == null) {
leafSetEntryBuilder = Builders.leafSetEntryBuilder();
}
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
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);
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;
return null;
}
- private Set<QName> readQNameSet() throws IOException{
+ private Set<QName> readQNameSet() throws IOException {
// Read the children count
int count = input.readInt();
Set<QName> children = new HashSet<>(count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
children.add(readQName());
}
return children;
int count = input.readInt();
Map<QName, Object> keyValueMap = new HashMap<>(count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
keyValueMap.put(readQName(), readObject());
}
private Object readObject() throws IOException {
byte objectType = input.readByte();
- switch(objectType) {
+ switch (objectType) {
case ValueTypes.BITS_TYPE:
return readObjSet();
List<PathArgument> 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);
private Set<String> readObjSet() throws IOException {
int count = input.readInt();
Set<String> children = new HashSet<>(count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
children.add(readCodedString());
}
return children;
// read Type
int type = input.readByte();
- switch(type) {
+ switch (type) {
case PathArgumentTypes.AUGMENTATION_IDENTIFIER :
return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
- while(child != null) {
+ while (child != null) {
builder.withChild(child);
child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
}
NormalizedNode<?, ?> child = readNormalizedNodeInternal();
- while(child != null) {
+ while (child != null) {
builder.addChild(child);
child = readNormalizedNodeInternal();
}
}
@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
* then will call
* {@link #leafNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, Object)} twice
* and then, {@link #endNode()} to end container node.
- *
+ * <p/>
* Based on the each node, the node type is also written to the stream, that helps in reconstructing the object,
* while reading.
*/
}
@Override
- protected final short streamVersion() {
+ protected short streamVersion() {
return TokenTypes.LITHIUM_VERSION;
}
throw new UnsupportedOperationException("Utility class");
}
- private static final Map<Class<?>, Byte> CLASS_TO_ENUM_MAP =
- ImmutableMap.<Class<?>, 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<Class<?>, Byte> CLASS_TO_ENUM_MAP = ImmutableMap.<Class<?>, 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());
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;
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;
}
/**
* 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);
@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<Object> leafNode = Builders.leafBuilder().withNodeIdentifier(nodeIdentifier).withValue(o).build();
- if(parent != null) {
- if(hasValidSchema(nodeIdentifier.getNodeType(), parent)) {
+ LeafNode<Object> 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;
}
}
@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);
@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;
}
@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();
@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;
}
}
}
+ @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;
}
}
}
- 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);
}
}
private NormalizedNodeBuilderWrapper addBuilder(NormalizedNodeContainerBuilder<?,?,?,?> builder,
- PathArgument identifier){
+ PathArgument identifier) {
final Optional<DataSchemaContextNode<?>> 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();
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;
}
}
static class SimpleStack<E> {
List<E> 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();
}
}
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;
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.
- * <p>
+ * <p/>
* The representations convered for now are,
*
* <ul>
* </ul>
*/
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
return toSerializableBuilder(path, context).build();
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private static NormalizedNodeMessages.InstanceIdentifier.Builder toSerializableBuilder(
YangInstanceIdentifier path, QNameSerializationContext context) {
NormalizedNodeMessages.InstanceIdentifier.Builder builder =
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();
builder.addArguments(serializablePathArgument);
}
- } catch(Exception e){
- logger.error("An exception occurred", e);
+ } catch (Exception e) {
+ LOG.error("An exception occurred", e);
}
return builder;
/**
* 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
List<PathArgument> 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));
/**
* Take the various attributes of a PathArgument and package them up as
* protocol buffer attributes.
- * <p>
- *
+ * <p/>
* PathArguments have 4 subtypes and each of the various subtypes have
* different attributes
* <ul>
* an augmentation entry.
* </li>
* </ul>
- * @param pathArgument
- * @return
*/
private static Iterable<? extends NormalizedNodeMessages.Attribute> getPathArgumentAttributes(
PathArgument pathArgument) {
}
- } else if(pathArgument instanceof AugmentationIdentifier) {
+ } else if (pathArgument instanceof AugmentationIdentifier) {
AugmentationIdentifier identifier = (AugmentationIdentifier) pathArgument;
for (QName key : identifier.getPossibleChildNames()) {
/**
- * 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
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<QName> qNameSet = new HashSet<>();
+ Set<QName> 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());
Map<QName, Object> map = new HashMap<>();
- for(NormalizedNodeMessages.Attribute attribute : attributesList){
+ for (NormalizedNodeMessages.Attribute attribute : attributesList) {
String name = attribute.getName();
Object value = parseAttribute(attribute);
}
/**
- * 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());
}
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;
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 {
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;
getSender().tell(new RegisterRoleChangeListenerReply(), getSelf());
- if(latestLeaderStateChanged != null) {
+ if (latestLeaderStateChanged != null) {
getSender().tell(latestLeaderStateChanged, getSelf());
}
/**
* 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;
@Override
public String toString() {
- return "RoleChanged{" +
- "memberId='" + memberId + '\'' +
- ", oldRole='" + oldRole + '\'' +
- ", newRole='" + newRole + '\'' +
- '}';
+ return "RoleChanged [memberId=" + memberId + ", oldRole=" + oldRole + ", newRole=" + newRole + "]";
}
}
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.
- * <p>
- *
+ * <p/>
* 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
private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
"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);
}
};
final SettableFuture<YangTextSchemaSource> res = SettableFuture.create();
result.onComplete(new OnComplete<YangTextSchemaSourceSerializationProxy>() {
@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);
}
}
LOG.trace("Sending yang schema source for {}", identifier);
final Promise<YangTextSchemaSourceSerializationProxy> promise = akka.dispatch.Futures.promise();
- CheckedFuture<YangTextSchemaSource, ?> future = repository.getSchemaSource(identifier, YangTextSchemaSource.class);
+ CheckedFuture<YangTextSchemaSource, ?> future =
+ repository.getSchemaSource(identifier, YangTextSchemaSource.class);
Futures.addCallback(future, new FutureCallback<YangTextSchemaSource>() {
@Override
}
@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);
}
});
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());
}
@Test
- public void testCommonConfigOverride(){
+ public void testCommonConfigOverride() {
int expectedCapacity = 123;
String timeoutValue = "1000ms";
assertTrue(config.isMetricCaptureEnabled());
}
-}
\ No newline at end of file
+}
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;
// 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;
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());
try {
messageTracker.received(new Foo());
fail("Expected an IllegalStateException");
- } catch (IllegalStateException e){
-
+ } catch (IllegalStateException e) {
+ // expected
}
}
}
@Test
- public void testDelayInFirstExpectedMessageArrival(){
+ public void testDelayInFirstExpectedMessageArrival() {
messageTracker.begin();
ticker.increment(MILLISECONDS.toNanos(20));
}
-}
\ No newline at end of file
+}
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;
@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());
}
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");
//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);
}
}
}
}
-}
\ No newline at end of file
+}
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;
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<Node> childrenResult =
- containerResult.getNormalizedNode().getChildList();
- List<Node> 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<Node> childrenResult = containerResult.getNormalizedNode().getChildList();
+ List<Node> 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());
+ }
}
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);
+ }
}
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;
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();
}
@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())
.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);
}
- private static NodeIdentifier nodeIdentifier(){
+ private static NodeIdentifier nodeIdentifier() {
return new NodeIdentifier(TestModel.TEST_QNAME);
}
- private static AugmentationIdentifier augmentationIdentifier(){
- Set<QName> childNames = ImmutableSet.of(QNameFactory.create("(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics"));
+ private static AugmentationIdentifier augmentationIdentifier() {
+ Set<QName> 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<QName, Object> keys = new HashMap<>();
keys.put(TestModel.ID_QNAME, Integer.valueOf(100));
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());
assertTrue( cached == created );
}
-
}
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;
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
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;
}
// FIXME: This will not work due to BUG 2326. Once that is fixed we can uncomment this assertion
// assertEquals(node1, node2);
- Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = node2.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.SOME_BINARY_DATA_QNAME));
+ Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ node2.getChild(new YangInstanceIdentifier.NodeIdentifier(TestModel.SOME_BINARY_DATA_QNAME));
Object value = child.get().getValue();
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");
}
@Test
- public void testDeSerializePathArgumentNullNode(){
+ public void testDeSerializePathArgumentNullNode() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("node should not be null");
}
@Test
- public void testDeSerializePathArgumentNullPathArgument(){
+ public void testDeSerializePathArgumentNullPathArgument() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("pathArgument should not be null");
}
@Test
- public void testDeSerializePathArgument(){
+ public void testDeSerializePathArgument() {
NormalizedNodeMessages.Node.Builder nodeBuilder = NormalizedNodeMessages.Node.newBuilder();
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
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());
}
-
-
}
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;
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");
}
@Test
- public void testSerializeNullPathArgument(){
+ public void testSerializeNullPathArgument() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("pathArgument should not be null");
}
@Test
- public void testDeSerializeNullContext(){
+ public void testDeSerializeNullContext() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("context should not be null");
}
@Test
- public void testDeSerializeNullPathArgument(){
+ public void testDeSerializeNullPathArgument() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("pathArgument should not be null");
}
@Test
- public void testSerializeNodeIdentifier(){
+ public void testSerializeNodeIdentifier() {
QNameSerializationContext serializationContext = mock(QNameSerializationContext.class);
when(serializationContext.addLocalName(anyString())).thenReturn(5);
}
@Test
- public void testSerializeNodeIdentifierWithValue(){
+ public void testSerializeNodeIdentifierWithValue() {
QNameSerializationContext serializationContext = mock(QNameSerializationContext.class);
when(serializationContext.addLocalName(anyString())).thenReturn(5);
}
@Test
- public void testSerializeNodeIdentifierWithPredicates(){
+ public void testSerializeNodeIdentifierWithPredicates() {
QNameSerializationContext serializationContext = mock(QNameSerializationContext.class);
when(serializationContext.addLocalName("test")).thenReturn(5);
}
@Test
- public void testSerializeAugmentationIdentifier(){
+ public void testSerializeAugmentationIdentifier() {
QNameSerializationContext serializationContext = mock(QNameSerializationContext.class);
when(serializationContext.addLocalName(anyString())).thenReturn(55);
}
@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);
}
@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);
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);
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());
ImmutableMap.<QName, Object>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());
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;
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);
}
@Test
- public void testSerializeInteger(){
+ public void testSerializeInteger() {
String hexNumber = "f3";
Integer expected = Integer.valueOf(hexNumber, 16);
@Test
- public void testSerializeLong(){
+ public void testSerializeLong() {
long v1 = 5;
NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder();
ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1);
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);
}
@Test
- public void testSerializeByte(){
+ public void testSerializeByte() {
byte v1 = 5;
NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder();
ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1);
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);
}
@Test
- public void testSerializeBits(){
+ public void testSerializeBits() {
NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder();
ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),
ImmutableSet.of("foo", "bar"));
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"));
}
@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();
}
@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),"");
}
@Test
- public void testSerializeString(){
+ public void testSerializeString() {
NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder();
ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),"foo");
@Test
- public void testSerializeBoolean(){
+ public void testSerializeBoolean() {
boolean v1 = true;
NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder();
ValueSerializer.serialize(builder, mock(QNameSerializationContext.class), v1);
}
@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();
}
@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);
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);
}
@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);
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());
}
@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);
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);
}
@Test
- public void testSerializeNull(){
+ public void testSerializeNull() {
NormalizedNodeMessages.Node.Builder builder = NormalizedNodeMessages.Node.newBuilder();
Object none = null;
ValueSerializer.serialize(builder, mock(QNameSerializationContext.class),none);
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);
@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();
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());
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();
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();
argumentBuilder.setType(ValueType.NULL_TYPE.ordinal());
argumentBuilder.setValue("");
- o = ValueSerializer
+ value = ValueSerializer
.deSerialize(mock(QNameDeSerializationContext.class),
argumentBuilder.build());
- assertEquals(null, o);
+ assertEquals(null, value);
}
-
-
}
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
+}
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 {
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(
LeafSetEntryNode<Object> 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();
writer.close();
}
+ @SuppressWarnings("deprecation")
@Test
public void testNormalizedNodeAndYangInstanceIdentifierStreaming() throws IOException {
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);
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(
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(
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 = "<foo xmlns=\"http://www.w3.org/TR/html4/\" x=\"123\"><bar>one</bar><bar>two</bar></foo>";
writer.close();
}
- private static String largeString(final int pow){
- String s = "X";
- for(int i=0;i<pow;i++){
- StringBuilder b = new StringBuilder();
- b.append(s).append(s);
- s = b.toString();
+ private static String largeString(final int pow) {
+ String str = "X";
+ for (int i = 0; i < pow; i++) {
+ StringBuilder buf = new StringBuilder();
+ buf.append(str).append(str);
+ str = buf.toString();
}
- return s;
+ return str;
}
}
return input;
}
- private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException, URISyntaxException {
+ private void readObject(final ObjectInputStream stream)
+ throws IOException, ClassNotFoundException, URISyntaxException {
NormalizedNodeDataInput reader = new NormalizedNodeInputStreamReader(stream);
this.input = reader.readNormalizedNode();
}
package org.opendaylight.controller.cluster.datastore.node.utils.stream;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
public class ValueTypesTest {
@Test
- public void testStringType(){
+ public void testStringType() {
assertEquals(ValueTypes.STRING_TYPE, ValueTypes.getSerializableType("foobar"));
final String largeString = largeString(ValueTypes.STRING_BYTES_LENGTH_THRESHOLD);
assertEquals(ValueTypes.STRING_BYTES_TYPE, ValueTypes.getSerializableType(largeString));
}
- private static String largeString(int minSize){
+ private static String largeString(int minSize) {
final int pow = (int) (Math.log(minSize * 2) / Math.log(2));
- String s = "X";
- for(int i=0;i<pow;i++){
- StringBuilder b = new StringBuilder();
- b.append(s).append(s);
- s = b.toString();
+ String str = "X";
+ for (int i = 0; i < pow; i++) {
+ StringBuilder buf = new StringBuilder();
+ buf.append(str).append(str);
+ str = buf.toString();
}
- return s;
+ return str;
}
-
-}
\ No newline at end of file
+}
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
+
import com.google.common.collect.Sets;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
private static final SchemaContext FULL_SCHEMA = TestModel.createTestContext();
@Before
- public void setUp(){
+ public void setUp() {
MockitoAnnotations.initMocks(this);
}
}
- private static int countNodes(NormalizedNode<?,?> 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();
}
@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<Object> child = Builders.leafBuilder().withNodeIdentifier(
new NodeIdentifier(TestModel.INVALID_QNAME)).withValue("test").build();
NormalizedNode<?, ?> input = Builders.augmentationBuilder().withNodeIdentifier(augId).withChild(child).build();
@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);
@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);
@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(
@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(
@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);
private static NormalizedNode<?, ?> createTestContainer() {
byte[] bytes1 = {1,2,3};
LeafSetEntryNode<Object> 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<Object> 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<Object> 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
+}
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;
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 {
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");
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");
}
/**
- * Returns a test document
+ * Returns a test document.
* <p/>
* <p/>
* <pre>
* name "two"
*
* </pre>
- *
- * @return
*/
public static NormalizedNode<?, ?> createDocumentOne(
SchemaContext schemaContext) {
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<Object> 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<Object> numbers =
ImmutableLeafSetNodeBuilder
.create()
// 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(
.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.<MapEntryNode>builder().add(
+ .withChild(Builders.orderedMapBuilder()
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ORDERED_LIST_QNAME))
+ .withValue(ImmutableList.<MapEntryNode>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)
public static ContainerNode createFamily() {
- final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> familyContainerBuilder =
- ImmutableContainerNodeBuilder.create().withNodeIdentifier(
+ final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode>
+ familyContainerBuilder = ImmutableContainerNodeBuilder.create().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME));
final CollectionNodeBuilder<MapEntryNode, MapNode> childrenBuilder =
mapNodeBuilder(CHILDREN_QNAME);
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstChildBuilder =
- mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondChildBuilder =
- mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID);
-
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstGrandChildBuilder =
- mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
- FIRST_GRAND_CHILD_ID);
- final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondGrandChildBuilder =
- mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
- SECOND_GRAND_CHILD_ID);
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ firstChildBuilder = mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ secondChildBuilder = mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID);
+
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ firstGrandChildBuilder = mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+ FIRST_GRAND_CHILD_ID);
+ final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
+ secondGrandChildBuilder = mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+ SECOND_GRAND_CHILD_ID);
firstGrandChildBuilder
.withChild(
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;
@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);
Futures.failed(new Exception("halo"));
Mockito.when(mockedRemoteSchemaRepository.getYangTextSchemaSource(ID)).thenReturn(
- Futures.<YangTextSchemaSourceSerializationProxy>failed(new SchemaSourceException("Source not provided")));
+ Futures.<YangTextSchemaSourceSerializationProxy>failed(
+ new SchemaSourceException("Source not provided")));
CheckedFuture<?, ?> sourceFuture = remoteSchemaProvider.getSource(ID);
assertTrue(sourceFuture.isDone());
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;
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<SourceIdentifier> providedSources = Collections.singleton(ID);
+ private final Set<SourceIdentifier> providedSources = Collections.singleton(ID);
@Before
public void setUp() {
@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.<YangTextSchemaSource, SchemaSourceException>immediateCheckedFuture(schemaSource));
- Future<YangTextSchemaSourceSerializationProxy> retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID);
+ Future<YangTextSchemaSourceSerializationProxy> 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());
}
Futures.<YangTextSchemaSource, SchemaSourceException>immediateFailedCheckedFuture(
new SchemaSourceException("Source is not provided")));
-
- Future<YangTextSchemaSourceSerializationProxy> retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID);
+ Future<YangTextSchemaSourceSerializationProxy> retrievedSourceFuture =
+ remoteRepository.getYangTextSchemaSource(ID);
assertTrue(retrievedSourceFuture.isCompleted());
Await.result(retrievedSourceFuture, Duration.Zero());
}
@Test
public void testGetProvidedSources() throws Exception {
- Set<SourceIdentifier> remoteProvidedSources = Await.result(remoteRepository.getProvidedSources(), Duration.Zero());
+ Set<SourceIdentifier> remoteProvidedSources = Await.result(remoteRepository
+ .getProvidedSources(), Duration.Zero());
assertEquals(providedSources, remoteProvidedSources);
}
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 {
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)));
}
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());
@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());
* @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 <TestFileName>"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 <TestFileName>"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 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();
+ }
}
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;
// 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 = "<add-flow xmlns=\"urn:opendaylight:controller:rpc:test\"><input xmlns=\"urn:opendaylight:controller:rpc:test\">" +
- "<id>flowid</id>" +
- "<flow xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">/ltha:node/ltha:node1[ltha:id='3@java.lang.Short']</flow>" +
- "</input></add-flow>";
-
- @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<ByteSource> 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 = "<add-flow xmlns=\"urn:opendaylight:controller:rpc:test\">"
+ + "<input xmlns=\"urn:opendaylight:controller:rpc:test\"><id>flowid</id>"
+ + "<flow xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">/ltha:node/ltha:node1"
+ + "[ltha:id='3@java.lang.Short']</flow></input></add-flow>";
+
+ 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<ByteSource> 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();
- }
-
}
// 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);
}
TestActorRef<Shard> 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);
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);
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);