* @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);
}
});