Merge "bug 344 interpretation of slashes ('/') in URI"
authorTony Tkacik <ttkacik@cisco.com>
Tue, 18 Feb 2014 15:18:53 +0000 (15:18 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Tue, 18 Feb 2014 15:18:53 +0000 (15:18 +0000)
55 files changed:
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractSessionNegotiator.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryMapping.java [new file with mode: 0644]
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryMapping.xtend [deleted file]
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java [new file with mode: 0644]
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.xtend [deleted file]
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChange.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangeEvent.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangeListener.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangePublisher.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataCommitHandler.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataModification.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataModificationTransactionFactory.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataProvider.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataReader.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataStore.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChain.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChainFactory.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/MutableRoutingTable.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/RoutedRegistration.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/RoutingTable.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPersisterNotificationHandler.java
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/AbstractNetconfSession.java
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/NetconfSessionPreferences.java
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/CommitJMXNotification.java
opendaylight/netconf/netconf-api/src/main/java/org/opendaylight/controller/netconf/api/jmx/DefaultCommitOperationMXBean.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/DefaultCommitNotificationProducer.java
opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/NetconfServerSessionNegotiator.java
opendaylight/netconf/netconf-impl/src/test/java/org/opendaylight/controller/netconf/impl/MessageParserTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/AbstractNetconfSessionNegotiator.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/NetconfUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ChunkedFramingMechanismEncoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/FramingMechanismHandlerFactory.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfHelloMessageToXMLEncoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfMessageToXMLEncoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/NetconfXMLToHelloMessageDecoder.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/SshHandler.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/authentication/LoginPassword.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/Invoker.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClient.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshClientAdapter.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/client/SshSession.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelInputStream.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/ChannelOutputStream.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/handler/ssh/virtualsocket/VirtualSocket.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfHelloMessageAdditionalHeader.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageConstants.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/NetconfMessageUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/messages/SendErrorExceptionUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/osgi/NetconfConfigUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XMLNetconfUtil.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlElement.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfConstants.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlNetconfValidator.java
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java

index 9f9f811e889f85c20352db331187f008b812bd85..d41e8106c5aec85166b43d72241b7fb600921801 100644 (file)
@@ -8,6 +8,8 @@
 package org.opendaylight.protocol.framework;
 
 import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;
 import io.netty.util.concurrent.Promise;
@@ -26,7 +28,7 @@ import com.google.common.base.Preconditions;
  * @param <S> Protocol session type, has to extend ProtocolSession<M>
  */
 public abstract class AbstractSessionNegotiator<M, S extends AbstractProtocolSession<?>> extends ChannelInboundHandlerAdapter implements SessionNegotiator<S> {
-    private final Logger logger = LoggerFactory.getLogger(AbstractSessionNegotiator.class);
+    private final Logger LOG = LoggerFactory.getLogger(AbstractSessionNegotiator.class);
     private final Promise<S> promise;
     protected final Channel channel;
 
@@ -39,42 +41,63 @@ public abstract class AbstractSessionNegotiator<M, S extends AbstractProtocolSes
     protected abstract void handleMessage(M msg) throws Exception;
 
     protected final void negotiationSuccessful(final S session) {
-        logger.debug("Negotiation on channel {} successful with session {}", channel, session);
+        LOG.debug("Negotiation on channel {} successful with session {}", channel, session);
         channel.pipeline().replace(this, "session", session);
         promise.setSuccess(session);
     }
 
     protected final void negotiationFailed(final Throwable cause) {
-        logger.debug("Negotiation on channel {} failed", channel, cause);
+        LOG.debug("Negotiation on channel {} failed", channel, cause);
         channel.close();
         promise.setFailure(cause);
     }
 
+    /**
+     * Send a message to peer and fail negotiation if it does not reach
+     * the peer.
+     *
+     * @param msg Message which should be sent.
+     */
+    protected final void sendMessage(final M msg) {
+        this.channel.writeAndFlush(msg).addListener(
+                new ChannelFutureListener() {
+                    @Override
+                    public void operationComplete(final ChannelFuture f) {
+                        if (!f.isSuccess()) {
+                            LOG.info("Failed to send message {}", msg, f.cause());
+                            negotiationFailed(f.cause());
+                        } else {
+                            LOG.trace("Message {} sent to socket", msg);
+                        }
+                    }
+                });
+    }
+
     @Override
     public final void channelActive(final ChannelHandlerContext ctx) {
-        logger.debug("Starting session negotiation on channel {}", channel);
+        LOG.debug("Starting session negotiation on channel {}", channel);
         try {
             startNegotiation();
         } catch (Exception e) {
-            logger.warn("Unexpected negotiation failure", e);
+            LOG.warn("Unexpected negotiation failure", e);
             negotiationFailed(e);
         }
     }
 
     @Override
     public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
-        logger.debug("Negotiation read invoked on channel {}", channel);
+        LOG.debug("Negotiation read invoked on channel {}", channel);
         try {
             handleMessage((M)msg);
         } catch (Exception e) {
-            logger.debug("Unexpected error while handling negotiation message {}", msg, e);
+            LOG.debug("Unexpected error while handling negotiation message {}", msg, e);
             negotiationFailed(e);
         }
     }
 
     @Override
     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
-        logger.info("Unexpected error during negotiation", cause);
+        LOG.info("Unexpected error during negotiation", cause);
         negotiationFailed(cause);
     }
 }
diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryMapping.java
new file mode 100644 (file)
index 0000000..2dce505
--- /dev/null
@@ -0,0 +1,105 @@
+/**
+ * Copyright (c) 2013 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.sal.compatibility;
+
+import org.eclipse.xtend2.lib.StringConcatenation;
+import org.eclipse.xtext.xbase.lib.Conversions;
+import org.eclipse.xtext.xbase.lib.IterableExtensions;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
+
+import java.util.List;
+
+@SuppressWarnings("all")
+public class InventoryMapping {
+  public static NodeConnector toAdNodeConnector(final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector> identifier) {
+    final List<PathArgument> path = identifier.getPath();
+    final PathArgument lastPathArgument = IterableExtensions.<PathArgument>last(path);
+    final NodeConnectorKey tpKey = ((IdentifiableItem<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector,NodeConnectorKey>) lastPathArgument).getKey();
+    return InventoryMapping.nodeConnectorFromId(tpKey.getId().getValue());
+  }
+  
+  public static Node toAdNode(final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> identifier) {
+    final List<PathArgument> path = identifier.getPath();
+    final PathArgument lastPathArgument = IterableExtensions.<PathArgument>last(path);
+    final NodeKey tpKey = ((IdentifiableItem<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node,NodeKey>) lastPathArgument).getKey();
+    return InventoryMapping.nodeFromNodeId(tpKey.getId().getValue());
+  }
+  
+  public static NodeRef toNodeRef(final Node node) {
+    final NodeId nodeId = new NodeId(InventoryMapping.toNodeId(node));
+    final NodeKey nodeKey = new NodeKey(nodeId);
+    final InstanceIdentifierBuilder<? extends Object> builder = InstanceIdentifier.builder();
+    final InstanceIdentifierBuilder<Nodes> nodes = builder.<Nodes>node(Nodes.class);
+    final InstanceIdentifierBuilder<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> child =
+            nodes.<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node, NodeKey>child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class, nodeKey);
+    final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> path = child.toInstance();
+    return new NodeRef(path);
+  }
+  
+  public static NodeKey toNodeKey(final Node node) {
+    final NodeId nodeId = new NodeId(InventoryMapping.toNodeId(node));
+    return new NodeKey(nodeId);
+  }
+  
+  public static NodeConnectorKey toNodeConnectorKey(final NodeConnector nc) {
+    final NodeConnectorId nodeConnectorId = new NodeConnectorId(InventoryMapping.toNodeConnectorId(nc));
+    return new NodeConnectorKey(nodeConnectorId);
+  }
+  
+  public static String toNodeId(final Node node) {
+    final StringConcatenation builder = new StringConcatenation();
+    builder.append("ad-sal:");
+    builder.append(node.getType(), "");
+    builder.append("::");
+    builder.append(node.getNodeIDString(), "");
+    return builder.toString();
+  }
+  
+  public static String toNodeConnectorId(final NodeConnector nc) {
+    final StringConcatenation builder = new StringConcatenation();
+    builder.append(InventoryMapping.toNodeId(nc.getNode()), "");
+    builder.append("::");
+    builder.append(nc.getNodeConnectorIDString(), "");
+    return builder.toString();
+  }
+  
+  public static Node nodeFromNodeId(final String nodeId) {
+    final String[] split = nodeId.split("::");
+    return InventoryMapping.nodeFromString(split);
+  }
+  
+  public static NodeConnector nodeConnectorFromId(final String invId) {
+    final String[] split = invId.split("::");
+    return InventoryMapping.nodeConnectorFromString(split);
+  }
+  
+  private static NodeConnector nodeConnectorFromString(final String[] string) {
+    final List<String> subList = ((List<String>)Conversions.doWrapArray(string)).subList(0, 1);
+    final Node node = InventoryMapping.nodeFromString(((String[])Conversions.unwrapArray(subList, String.class)));
+    final String index3 = string[2];
+    return NodeConnector.fromStringNoNode(index3, node);
+  }
+  
+  private static Node nodeFromString(final String[] strings) {
+      String index0 = strings[0];
+      final String type = index0.substring(6);
+      String id = strings[1];
+      return Node.fromString(type, id);
+  }
+}
diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryMapping.xtend b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryMapping.xtend
deleted file mode 100644 (file)
index 0ea9918..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2013 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.sal.compatibility
-
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef
-
-class InventoryMapping {
-
-    static def org.opendaylight.controller.sal.core.NodeConnector toAdNodeConnector(
-        InstanceIdentifier<NodeConnector> identifier) {
-        val tpKey = (identifier.path.last as IdentifiableItem<NodeConnector,NodeConnectorKey>).key;
-        return nodeConnectorFromId(tpKey.id.value);
-    }
-
-    static def org.opendaylight.controller.sal.core.Node toAdNode(InstanceIdentifier<Node> identifier) {
-        val tpKey = (identifier.path.last as IdentifiableItem<Node,NodeKey>).key;
-        return nodeFromNodeId(tpKey.id.value);
-    }
-    
-    
-     static def NodeRef toNodeRef(org.opendaylight.controller.sal.core.Node node) {
-        val nodeId = new NodeKey(new NodeId(node.toNodeId))
-        val path = InstanceIdentifier.builder().node(Nodes).child(Node,nodeId).toInstance;
-        return new NodeRef(path);
-    }
-
-    static def NodeKey toNodeKey(org.opendaylight.controller.sal.core.Node node) {
-        val nodeId = new NodeId(node.toNodeId)
-        return new NodeKey(nodeId);
-    }
-
-    static def NodeConnectorKey toNodeConnectorKey(org.opendaylight.controller.sal.core.NodeConnector nc) {
-        val nodeId = new NodeConnectorId(nc.toNodeConnectorId)
-        return new NodeConnectorKey(nodeId);
-    }
-
-    static def String toNodeId(org.opendaylight.controller.sal.core.Node node) {
-        '''ad-sal:«node.type»::«node.nodeIDString»'''
-    }
-
-    static def String toNodeConnectorId(org.opendaylight.controller.sal.core.NodeConnector nc) {
-        '''«nc.node.toNodeId»::«nc.nodeConnectorIDString»'''
-    }
-
-    static def org.opendaylight.controller.sal.core.Node nodeFromNodeId(String nodeId) {
-        return nodeFromString(nodeId.split("::"))
-    }
-
-    static def nodeConnectorFromId(String invId) {
-        return nodeConnectorFromString(invId.split("::"));
-    }
-
-    private static def org.opendaylight.controller.sal.core.NodeConnector nodeConnectorFromString(String[] string) {
-        val node = nodeFromString(string.subList(0, 1));
-        return org.opendaylight.controller.sal.core.NodeConnector.fromStringNoNode(string.get(2), node);
-    }
-
-    private static def org.opendaylight.controller.sal.core.Node nodeFromString(String[] strings) {
-        val type = strings.get(0).substring(6);
-        org.opendaylight.controller.sal.core.Node.fromString(type, strings.get(1))
-    }
-
-}
diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java
new file mode 100644 (file)
index 0000000..0486f34
--- /dev/null
@@ -0,0 +1,396 @@
+/**
+ * Copyright (c) 2014 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.sal.compatibility;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Preconditions;
+import org.eclipse.xtext.xbase.lib.Exceptions;
+import org.opendaylight.controller.sal.common.util.Arguments;
+import org.opendaylight.controller.sal.core.AdvertisedBandwidth;
+import org.opendaylight.controller.sal.core.Bandwidth;
+import org.opendaylight.controller.sal.core.Buffers;
+import org.opendaylight.controller.sal.core.Capabilities;
+import org.opendaylight.controller.sal.core.Config;
+import org.opendaylight.controller.sal.core.ConstructionException;
+import org.opendaylight.controller.sal.core.MacAddress;
+import org.opendaylight.controller.sal.core.Name;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+import org.opendaylight.controller.sal.core.PeerBandwidth;
+import org.opendaylight.controller.sal.core.Property;
+import org.opendaylight.controller.sal.core.SupportedBandwidth;
+import org.opendaylight.controller.sal.core.Tables;
+import org.opendaylight.controller.sal.core.TimeStamp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FeatureCapability;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorUpdated;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityArpMatchIp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityFlowStats;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityIpReasm;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityPortStats;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityQueueStats;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityStp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityTableStats;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowNodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SwitchFeatures;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.Identifier;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+
+@SuppressWarnings("all")
+public class NodeMapping {
+  public final static String MD_SAL_TYPE = "MD_SAL";
+  
+  private final static Class<Node> NODE_CLASS = Node.class;
+  
+  private final static Class<NodeConnector> NODECONNECTOR_CLASS = NodeConnector.class;
+  
+  private NodeMapping() {
+    throw new UnsupportedOperationException("Utility class. Instantiation is not allowed.");
+  }
+  
+  public static org.opendaylight.controller.sal.core.Node toADNode(final InstanceIdentifier<? extends Object> node) throws ConstructionException {
+    NodeId nodeId = NodeMapping.toNodeId(node);
+    return NodeMapping.toADNode(nodeId);
+  }
+  
+  public static org.opendaylight.controller.sal.core.Node toADNode(final NodeId id) {
+    try {
+      String aDNodeId = NodeMapping.toADNodeId(id);
+      return  new org.opendaylight.controller.sal.core.Node(NodeMapping.MD_SAL_TYPE, aDNodeId);
+    } catch (Throwable e) {
+      throw Exceptions.sneakyThrow(e);
+    }
+  }
+  
+  public static NodeId toNodeId(final InstanceIdentifier<? extends Object> node) {
+    Preconditions.<InstanceIdentifier<? extends Object>>checkNotNull(node);
+    List<PathArgument> path = node.getPath();
+    Preconditions.<List<PathArgument>>checkNotNull(path);
+    int size = path.size();
+    Preconditions.checkArgument(size >= 2);
+    final PathArgument arg = path.get(1);
+    final IdentifiableItem item = Arguments.<IdentifiableItem>checkInstanceOf(arg, IdentifiableItem.class);
+    Identifier key = item.getKey();
+    final NodeKey nodeKey = Arguments.<NodeKey>checkInstanceOf(key, NodeKey.class);
+    return nodeKey.getId();
+  }
+  
+  public static String toADNodeId(final NodeId nodeId) {
+    Preconditions.<NodeId>checkNotNull(nodeId);
+    return nodeId.getValue();
+  }
+  
+  public static org.opendaylight.controller.sal.core.NodeConnector toADNodeConnector(final NodeConnectorRef source) throws ConstructionException {
+    Preconditions.<NodeConnectorRef>checkNotNull(source);
+    final InstanceIdentifier<?> path = Preconditions.<InstanceIdentifier<? extends Object>>checkNotNull(source.getValue());
+    Preconditions.checkArgument(path.getPath().size() >= 3);
+    final PathArgument arg = path.getPath().get(2);
+    final IdentifiableItem item = Arguments.<IdentifiableItem>checkInstanceOf(arg,IdentifiableItem.class);
+    final NodeConnectorKey connectorKey = Arguments.<NodeConnectorKey>checkInstanceOf(item.getKey(), NodeConnectorKey.class);
+    return NodeMapping.toADNodeConnector(connectorKey.getId(), NodeMapping.toNodeId(path));
+  }
+  
+  public static org.opendaylight.controller.sal.core.NodeConnector toADNodeConnector(final NodeConnectorId ncid, final NodeId nid) {
+    try {
+      String nodeConnectorType = NodeMapping.toNodeConnectorType(ncid, nid);
+      Object aDNodeConnectorId = NodeMapping.toADNodeConnectorId(ncid, nid);
+      org.opendaylight.controller.sal.core.Node aDNode = NodeMapping.toADNode(nid);
+      return new org.opendaylight.controller.sal.core.NodeConnector(nodeConnectorType, aDNodeConnectorId, aDNode);
+    } catch (Throwable e) {
+      throw Exceptions.sneakyThrow(e);
+    }
+  }
+  
+  public static String toNodeConnectorType(final NodeConnectorId ncId, final NodeId nodeId) {
+    if (ncId.equals(toLocalNodeConnectorId(nodeId))) {
+        return NodeConnectorIDType.SWSTACK;
+    } else if (ncId.equals(toNormalNodeConnectorId(nodeId))) {
+        return NodeConnectorIDType.HWPATH;
+    } else if (ncId.equals(toControllerNodeConnectorId(nodeId))) {
+        return NodeConnectorIDType.CONTROLLER;
+    }
+    return MD_SAL_TYPE;
+  }
+
+  public static Object toADNodeConnectorId(final NodeConnectorId nodeConnectorId, final NodeId nodeId) {
+    if (nodeConnectorId.equals(toLocalNodeConnectorId(nodeId)) ||
+        nodeConnectorId.equals(toNormalNodeConnectorId(nodeId)) ||
+        nodeConnectorId.equals(toControllerNodeConnectorId(nodeId))) {
+        return org.opendaylight.controller.sal.core.NodeConnector.SPECIALNODECONNECTORID;
+    }
+    return nodeConnectorId.getValue();
+  }
+  
+  public static NodeConnectorId toControllerNodeConnectorId(final NodeId node) {
+    return new NodeConnectorId(node.getValue() + ":" + 4294967293L);
+  }
+  
+  public static NodeConnectorId toLocalNodeConnectorId(final NodeId node) {
+    return new NodeConnectorId(node.getValue() + ":" + 4294967294L);
+  }
+  
+  public static NodeConnectorId toNormalNodeConnectorId(final NodeId node) {
+    return new NodeConnectorId(node.getValue() + ":" + 4294967290L);
+  }
+  
+  public static NodeRef toNodeRef(final org.opendaylight.controller.sal.core.Node node) {
+    Preconditions.checkArgument(MD_SAL_TYPE.equals(node.getType()));
+    final String nodeId = Arguments.<String>checkInstanceOf(node.getID(), String.class);
+    final NodeKey nodeKey = new NodeKey(new NodeId(nodeId));
+    final InstanceIdentifier<Node> nodePath = InstanceIdentifier.builder().node(Nodes.class).child(NODE_CLASS, nodeKey).toInstance();
+    return new NodeRef(nodePath);
+  }
+  
+  public static NodeConnectorRef toNodeConnectorRef(final org.opendaylight.controller.sal.core.NodeConnector nodeConnector) {
+
+    final NodeRef node = NodeMapping.toNodeRef(nodeConnector.getNode());
+    final InstanceIdentifier<Node> nodePath = ((InstanceIdentifier<Node>) node.getValue());
+    NodeConnectorId nodeConnectorId = null;
+
+    if (nodeConnector.getID().equals(org.opendaylight.controller.sal.core.NodeConnector.SPECIALNODECONNECTORID)) {
+        final NodeId nodeId = toNodeId(nodePath);
+        final String nodeConnectorType = nodeConnector.getType();
+        if (nodeConnectorType.equals(NodeConnectorIDType.SWSTACK)) {
+            nodeConnectorId = toLocalNodeConnectorId(nodeId);
+        } else if (nodeConnectorType.equals(NodeConnectorIDType.HWPATH)) {
+            nodeConnectorId = toNormalNodeConnectorId(nodeId);
+        } else if (nodeConnectorType.equals(NodeConnectorIDType.CONTROLLER)) {
+            nodeConnectorId = toControllerNodeConnectorId(nodeId);
+        }
+    } else {
+        nodeConnectorId = new NodeConnectorId(Arguments.<String>checkInstanceOf(nodeConnector.getID(), String.class));
+    }
+    final NodeConnectorKey connectorKey = new NodeConnectorKey(nodeConnectorId);
+    final InstanceIdentifier<NodeConnector> path = InstanceIdentifier.builder(nodePath).child(NODECONNECTOR_CLASS, connectorKey).toInstance();
+    return new NodeConnectorRef(path);
+  }
+  
+  public static org.opendaylight.controller.sal.core.Node toADNode(final NodeRef node) throws ConstructionException {
+    return NodeMapping.toADNode(node.getValue());
+  }
+  
+  public static HashSet<Property> toADNodeConnectorProperties(final NodeConnectorUpdated nc) {
+    final FlowCapableNodeConnectorUpdated fcncu = nc.<FlowCapableNodeConnectorUpdated>getAugmentation(FlowCapableNodeConnectorUpdated.class);
+    if (!Objects.equal(fcncu, null)) {
+      return NodeMapping.toADNodeConnectorProperties(fcncu);
+    }
+    return new HashSet<Property>();
+  }
+  
+  public static HashSet<Property> toADNodeConnectorProperties(final NodeConnector nc) {
+    final FlowCapableNodeConnector fcnc = nc.<FlowCapableNodeConnector>getAugmentation(FlowCapableNodeConnector.class);
+    if (!Objects.equal(fcnc, null)) {
+      return NodeMapping.toADNodeConnectorProperties(fcnc);
+    }
+    return new HashSet<Property>();
+  }
+  
+  public static HashSet<Property> toADNodeConnectorProperties(final FlowNodeConnector fcncu) {
+
+    final HashSet<org.opendaylight.controller.sal.core.Property> props = new HashSet<>();
+    if (fcncu != null) {
+        if (fcncu.getCurrentFeature() != null && toAdBandwidth(fcncu.getCurrentFeature()) != null) {
+            props.add(toAdBandwidth(fcncu.getCurrentFeature()));
+        }
+        if (fcncu.getAdvertisedFeatures() != null && toAdAdvertizedBandwidth(fcncu.getAdvertisedFeatures()) != null) {
+            props.add(toAdAdvertizedBandwidth(fcncu.getAdvertisedFeatures()));
+        }
+        if (fcncu.getSupported() != null && toAdSupportedBandwidth(fcncu.getSupported()) != null) {
+            props.add(toAdSupportedBandwidth(fcncu.getSupported()));
+        }
+        if (fcncu.getPeerFeatures() != null && toAdPeerBandwidth(fcncu.getPeerFeatures()) != null) {
+            props.add(toAdPeerBandwidth(fcncu.getPeerFeatures()));
+        }
+        if (fcncu.getName() != null && toAdName(fcncu.getName()) != null) {
+            props.add(toAdName(fcncu.getName()));
+        }
+        if (fcncu.getConfiguration() != null && toAdConfig(fcncu.getConfiguration()) != null) {
+            props.add(toAdConfig(fcncu.getConfiguration()));
+        }
+        if (fcncu.getState() != null && toAdState(fcncu.getState()) != null) {
+            props.add(toAdState(fcncu.getState()));
+        }
+    }
+    return props;
+  }
+  
+  public static Name toAdName(final String name) {
+    return new Name(name);
+  }
+  
+  public static Config toAdConfig(final PortConfig pc) {
+    Config config = null;
+    if (pc.isPORTDOWN()) {
+        config = new Config(Config.ADMIN_DOWN);
+    } else {
+        config = new Config(Config.ADMIN_UP);
+    }
+    return config;
+  }
+  
+  public static org.opendaylight.controller.sal.core.State toAdState(final State s) {
+
+    org.opendaylight.controller.sal.core.State state = null;
+    if (s.isLinkDown()) {
+        state = new org.opendaylight.controller.sal.core.State(org.opendaylight.controller.sal.core.State.EDGE_DOWN);
+    } else {
+        state = new org.opendaylight.controller.sal.core.State(org.opendaylight.controller.sal.core.State.EDGE_UP);
+    }
+    return state;
+  }
+  
+  public static Bandwidth toAdBandwidth(final PortFeatures pf) {
+    Bandwidth bw = null;
+    if (pf.isTenMbHd() || pf.isTenMbFd()) {
+        bw = new Bandwidth(Bandwidth.BW10Mbps);
+    } else if (pf.isHundredMbHd() || pf.isHundredMbFd()) {
+        bw = new Bandwidth(Bandwidth.BW100Mbps);
+    } else if (pf.isOneGbHd() || pf.isOneGbFd()) {
+        bw = new Bandwidth(Bandwidth.BW1Gbps);
+    } else if (pf.isOneGbFd()) {
+        bw = new Bandwidth(Bandwidth.BW10Gbps);
+    } else if (pf.isTenGbFd()) {
+        bw = new Bandwidth(Bandwidth.BW10Gbps);
+    } else if (pf.isFortyGbFd()) {
+        bw = new Bandwidth(Bandwidth.BW40Gbps);
+    } else if (pf.isHundredGbFd()) {
+        bw = new Bandwidth(Bandwidth.BW100Gbps);
+    } else if (pf.isOneTbFd()) {
+        bw = new Bandwidth(Bandwidth.BW1Tbps);
+    }
+    return bw;
+  }
+  
+  public static AdvertisedBandwidth toAdAdvertizedBandwidth(final PortFeatures pf) {
+    AdvertisedBandwidth abw = null;
+    final Bandwidth bw = toAdBandwidth(pf);
+    if (bw != null) {
+        abw = new AdvertisedBandwidth(bw.getValue());
+    }
+    return abw;
+  }
+  
+  public static SupportedBandwidth toAdSupportedBandwidth(final PortFeatures pf) {
+    SupportedBandwidth sbw = null;
+    final Bandwidth bw = toAdBandwidth(pf);
+    if (bw != null) {
+        sbw = new SupportedBandwidth(bw.getValue());
+    }
+    return sbw;
+  }
+  
+  public static PeerBandwidth toAdPeerBandwidth(final PortFeatures pf) {
+    PeerBandwidth pbw = null;
+    final Bandwidth bw = toAdBandwidth(pf);
+    if (bw != null) {
+        pbw = new PeerBandwidth(bw.getValue());
+    }
+    return pbw;
+  }
+  
+  public static HashSet<Property> toADNodeProperties(final NodeUpdated nu) {
+    final FlowCapableNodeUpdated fcnu = nu.getAugmentation(FlowCapableNodeUpdated.class);
+    if (fcnu != null) {
+        return toADNodeProperties(fcnu, nu.getId());
+    }
+    return new HashSet<org.opendaylight.controller.sal.core.Property>();
+  }
+  
+  public static HashSet<Property> toADNodeProperties(final FlowNode fcnu, final NodeId id) {
+
+    final HashSet<org.opendaylight.controller.sal.core.Property> props = new HashSet<>();
+
+    if (fcnu != null) {
+        props.add(toADTimestamp());
+
+        // props.add(fcnu.supportedActions.toADActions) - TODO
+        if (id != null) {
+            props.add(toADMacAddress(id));
+        }
+        SwitchFeatures switchFeatures = fcnu.getSwitchFeatures();
+        if (switchFeatures != null) {
+            if (switchFeatures.getMaxTables() != null) {
+                props.add(toADTables(switchFeatures.getMaxTables()));
+            }
+            if (switchFeatures.getCapabilities() != null) {
+                props.add(toADCapabiliities(switchFeatures.getCapabilities()));
+            }
+            if (switchFeatures.getMaxBuffers() != null) {
+                props.add(toADBuffers(switchFeatures.getMaxBuffers()));
+            }
+        }
+    }
+    return props;
+  }
+  
+  public static TimeStamp toADTimestamp() {
+    final Date date = new Date();
+    final TimeStamp timestamp = new TimeStamp(date.getTime(), "connectedSince");
+    return timestamp;
+  }
+  
+  public static MacAddress toADMacAddress(final NodeId id) {
+    final String nodeId = id.getValue().replaceAll("openflow:", "");
+    long lNodeId = Long.parseLong(nodeId);
+    lNodeId = Long.valueOf(lNodeId).longValue();
+    byte[] bytesFromDpid = ToSalConversionsUtils.bytesFromDpid(lNodeId);
+    return new MacAddress(bytesFromDpid);
+  }
+  
+  public static Tables toADTables(final Short tables) {
+    return new Tables(tables.byteValue());
+  }
+  
+  public static Capabilities toADCapabiliities(final List<Class<? extends FeatureCapability>> capabilities) {
+
+    int b = 0;
+    for (Class<? extends FeatureCapability> capability : capabilities) {
+        if (capability.equals(FlowFeatureCapabilityFlowStats.class)) {
+            b = Capabilities.CapabilitiesType.FLOW_STATS_CAPABILITY.getValue() | b;
+        } else if (capability.equals(FlowFeatureCapabilityTableStats.class)) {
+            b = Capabilities.CapabilitiesType.TABLE_STATS_CAPABILITY.getValue() | b;
+        } else if (capability.equals(FlowFeatureCapabilityPortStats.class)) {
+            b = Capabilities.CapabilitiesType.PORT_STATS_CAPABILITY.getValue() | b;
+        } else if (capability.equals(FlowFeatureCapabilityStp.class)) {
+            b = Capabilities.CapabilitiesType.STP_CAPABILITY.getValue() | b;
+        } else if (capability.equals(FlowFeatureCapabilityIpReasm.class)) {
+            b = Capabilities.CapabilitiesType.IP_REASSEM_CAPABILITY.getValue() | b;
+        } else if (capability.equals(FlowFeatureCapabilityQueueStats.class)) {
+            b = Capabilities.CapabilitiesType.QUEUE_STATS_CAPABILITY.getValue() | b;
+        } else if (capability.equals(FlowFeatureCapabilityArpMatchIp.class)) {
+            b = Capabilities.CapabilitiesType.ARP_MATCH_IP_CAPABILITY.getValue() | b;
+        }
+    }
+    return new Capabilities(b);
+  }
+  
+  public static Buffers toADBuffers(final Long buffers) {
+    return new Buffers(buffers.intValue());
+  }
+}
diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.xtend b/opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.xtend
deleted file mode 100644 (file)
index debcbac..0000000
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * Copyright (c) 2014 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.sal.compatibility
-
-import org.opendaylight.controller.sal.core.Node
-import org.opendaylight.controller.sal.core.NodeConnector
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem
-
-import static com.google.common.base.Preconditions.*;
-import static extension org.opendaylight.controller.sal.common.util.Arguments.*;
-import static extension org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils.*;
-
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey
-import org.opendaylight.controller.sal.core.ConstructionException
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorUpdated
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures
-import org.opendaylight.controller.sal.core.Bandwidth
-import org.opendaylight.controller.sal.core.AdvertisedBandwidth
-import org.opendaylight.controller.sal.core.SupportedBandwidth
-import org.opendaylight.controller.sal.core.PeerBandwidth
-import org.opendaylight.controller.sal.core.Name
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig
-import org.opendaylight.controller.sal.core.Config
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated
-import java.util.HashSet
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated
-import org.opendaylight.controller.sal.core.Tables
-import java.util.List
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FeatureCapability
-import org.opendaylight.controller.sal.core.Buffers
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityFlowStats
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityTableStats
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityIpReasm
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityPortStats
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityStp
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityQueueStats
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityArpMatchIp
-import org.opendaylight.controller.sal.core.Capabilities
-import org.opendaylight.controller.sal.core.MacAddress
-import java.util.Date
-import org.opendaylight.controller.sal.core.TimeStamp
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowNodeConnector
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowNode
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector
-
-public class NodeMapping {
-
-    public static val MD_SAL_TYPE = "MD_SAL";
-    private static val NODE_CLASS = org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-    private static val NODECONNECTOR_CLASS = org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.
-        NodeConnector;
-
-    private new() {
-        throw new UnsupportedOperationException("Utility class. Instantiation is not allowed.");
-    }
-
-    public static def toADNode(InstanceIdentifier<?> node) throws ConstructionException {
-        return node.toNodeId.toADNode
-    }
-
-    public static def toADNode(NodeId id) {
-        return new Node(MD_SAL_TYPE, id.toADNodeId);
-    }
-
-    public static def toNodeId(InstanceIdentifier<?> node) {
-        checkNotNull(node);
-        checkNotNull(node.getPath());
-        checkArgument(node.getPath().size() >= 2);
-        val arg = node.getPath().get(1);
-        val item = arg.checkInstanceOf(IdentifiableItem);
-        val nodeKey = item.getKey().checkInstanceOf(NodeKey);
-        return nodeKey.id
-    }
-
-    public static def toADNodeId(NodeId nodeId) {
-        checkNotNull(nodeId);
-        return nodeId.value
-    }
-
-    public static def toADNodeConnector(NodeConnectorRef source) throws ConstructionException {
-        checkNotNull(source);
-        val InstanceIdentifier<?> path = checkNotNull(source.getValue());
-        checkArgument(path.path.size() >= 3);
-        val arg = path.getPath().get(2);
-        val item = arg.checkInstanceOf(IdentifiableItem);
-        val connectorKey = item.getKey().checkInstanceOf(NodeConnectorKey);
-        return connectorKey.id.toADNodeConnector(path.toNodeId)
-    }
-    
-    public static def toADNodeConnector(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId ncid,
-        org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId nid) {
-            return new NodeConnector(ncid.toNodeConnectorType(nid),
-            ncid.toADNodeConnectorId(nid), nid.toADNode);
-     }
-
-    public static def toNodeConnectorType(NodeConnectorId ncId, NodeId nodeId) {
-        if (ncId.equals(nodeId.toLocalNodeConnectorId)) {
-            return NodeConnector.NodeConnectorIDType.SWSTACK
-        } else if (ncId.equals(nodeId.toNormalNodeConnectorId)) {
-            return NodeConnector.NodeConnectorIDType.HWPATH
-        } else if (ncId.equals(nodeId.toControllerNodeConnectorId)) {
-            return NodeConnector.NodeConnectorIDType.CONTROLLER
-        }
-        return MD_SAL_TYPE
-    }
-
-    public static def toADNodeConnectorId(NodeConnectorId nodeConnectorId, NodeId nodeId) {
-        if (nodeConnectorId.equals(nodeId.toLocalNodeConnectorId) ||
-            nodeConnectorId.equals(nodeId.toNormalNodeConnectorId) ||
-            nodeConnectorId.equals(nodeId.toControllerNodeConnectorId)) {
-            return NodeConnector.SPECIALNODECONNECTORID
-        }
-        return nodeConnectorId.value
-    }
-
-    public static def toControllerNodeConnectorId(NodeId node) {
-        return new NodeConnectorId(node.value + ":" + 4294967293L)
-    }
-
-    public static def toLocalNodeConnectorId(NodeId node) {
-        return new NodeConnectorId(node.value + ":" + 4294967294L)
-    }
-
-    public static def toNormalNodeConnectorId(NodeId node) {
-        return new NodeConnectorId(node.value + ":" + 4294967290L)
-    }
-
-    public static def toNodeRef(Node node) {
-        checkArgument(MD_SAL_TYPE.equals(node.getType()));
-        var nodeId = node.ID.checkInstanceOf(String)
-        val nodeKey = new NodeKey(new NodeId(nodeId));
-        val nodePath = InstanceIdentifier.builder().node(Nodes).child(NODE_CLASS, nodeKey).toInstance();
-        return new NodeRef(nodePath);
-    }
-
-    public static def toNodeConnectorRef(NodeConnector nodeConnector) {
-        val node = nodeConnector.node.toNodeRef();
-        val nodePath = node.getValue() as InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
-        var NodeConnectorId nodeConnectorId
-        if (nodeConnector.ID.equals(NodeConnector.SPECIALNODECONNECTORID)) {
-            if (nodeConnector.type.equals(NodeConnector.NodeConnectorIDType.SWSTACK)) {
-                nodeConnectorId = nodePath.toNodeId.toLocalNodeConnectorId
-            } else if (nodeConnector.type.equals(NodeConnector.NodeConnectorIDType.HWPATH)) {
-                nodeConnectorId = nodePath.toNodeId.toNormalNodeConnectorId
-            } else if (nodeConnector.type.equals(NodeConnector.NodeConnectorIDType.CONTROLLER)) {
-                nodeConnectorId = nodePath.toNodeId.toControllerNodeConnectorId
-            }
-        } else {
-            nodeConnectorId = new NodeConnectorId(nodeConnector.ID.checkInstanceOf(String))
-        }
-        val connectorKey = new NodeConnectorKey(nodeConnectorId);
-        val path = InstanceIdentifier.builder(nodePath).child(NODECONNECTOR_CLASS, connectorKey).toInstance();
-        return new NodeConnectorRef(path);
-    }
-
-    public static def toADNode(NodeRef node) throws ConstructionException {
-        return toADNode(node.getValue());
-    }
-
-    public static def toADNodeConnectorProperties(NodeConnectorUpdated nc) {
-        val fcncu = nc.getAugmentation(FlowCapableNodeConnectorUpdated)
-        if (fcncu != null) {
-            return fcncu.toADNodeConnectorProperties
-        }
-        return new HashSet<org.opendaylight.controller.sal.core.Property>();
-    }
-
-    public static def toADNodeConnectorProperties(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector nc) {
-        val fcnc = nc.getAugmentation(FlowCapableNodeConnector)
-        if (fcnc != null) {
-            return fcnc.toADNodeConnectorProperties
-        }
-        return new HashSet<org.opendaylight.controller.sal.core.Property>();
-    }
-
-    public static def toADNodeConnectorProperties(FlowNodeConnector fcncu) {
-        val props = new HashSet<org.opendaylight.controller.sal.core.Property>();
-        if (fcncu != null) {
-            if (fcncu.currentFeature != null && fcncu.currentFeature.toAdBandwidth != null) {
-                props.add(fcncu.currentFeature.toAdBandwidth)
-            }
-            if (fcncu.advertisedFeatures != null && fcncu.advertisedFeatures.toAdAdvertizedBandwidth != null) {
-                props.add(fcncu.advertisedFeatures.toAdAdvertizedBandwidth)
-            }
-            if (fcncu.supported != null && fcncu.supported.toAdSupportedBandwidth != null) {
-                props.add(fcncu.supported.toAdSupportedBandwidth)
-            }
-            if (fcncu.peerFeatures != null && fcncu.peerFeatures.toAdPeerBandwidth != null) {
-                props.add(fcncu.peerFeatures.toAdPeerBandwidth)
-            }
-            if (fcncu.name != null && fcncu.name.toAdName != null) {
-                props.add(fcncu.name.toAdName)
-            }
-            if (fcncu.configuration != null && fcncu.configuration.toAdConfig != null) {
-                props.add(fcncu.configuration.toAdConfig)
-            }
-            if (fcncu.state != null && fcncu.state.toAdState != null) {
-                props.add(fcncu.state.toAdState)
-            }
-        }
-        return props
-    }
-
-    public static def toAdName(String name) {
-        return new Name(name)
-    }
-
-    public static def toAdConfig(PortConfig pc) {
-        var Config config;
-        if (pc.PORTDOWN) {
-            config = new Config(Config.ADMIN_DOWN)
-        } else {
-            config = new Config(Config.ADMIN_UP)
-        }
-        return config
-    }
-
-    public static def toAdState(State s) {
-        var org.opendaylight.controller.sal.core.State state
-        if (s.linkDown) {
-            state = new org.opendaylight.controller.sal.core.State(org.opendaylight.controller.sal.core.State.EDGE_DOWN)
-        } else {
-            state = new org.opendaylight.controller.sal.core.State(org.opendaylight.controller.sal.core.State.EDGE_UP)
-        }
-        return state
-    }
-
-    public static def toAdBandwidth(PortFeatures pf) {
-        var Bandwidth bw = null
-        if (pf.isTenMbHd || pf.isTenMbFd) {
-            bw = new Bandwidth(Bandwidth.BW10Mbps)
-        } else if (pf.isHundredMbHd || pf.isHundredMbFd) {
-            bw = new Bandwidth(Bandwidth.BW100Mbps)
-        } else if (pf.isOneGbHd || pf.isOneGbFd) {
-            bw = new Bandwidth(Bandwidth.BW1Gbps)
-        } else if (pf.isOneGbFd) {
-            bw = new Bandwidth(Bandwidth.BW10Gbps)
-        } else if (pf.isTenGbFd) {
-            bw = new Bandwidth(Bandwidth.BW10Gbps)
-        } else if (pf.isFortyGbFd) {
-            bw = new Bandwidth(Bandwidth.BW40Gbps)
-        } else if (pf.isHundredGbFd) {
-            bw = new Bandwidth(Bandwidth.BW100Gbps)
-        } else if (pf.isOneTbFd) {
-            bw = new Bandwidth(Bandwidth.BW1Tbps)
-        }
-        return bw;
-    }
-
-    public static def toAdAdvertizedBandwidth(PortFeatures pf) {
-        var AdvertisedBandwidth abw
-        val bw = pf.toAdBandwidth
-        if (bw != null) {
-            abw = new AdvertisedBandwidth(bw.value)
-        }
-        return abw
-    }
-
-    public static def toAdSupportedBandwidth(PortFeatures pf) {
-        var SupportedBandwidth sbw
-        val bw = pf.toAdBandwidth
-        if (bw != null) {
-            sbw = new SupportedBandwidth(bw.value)
-        }
-        return sbw
-    }
-
-    public static def toAdPeerBandwidth(PortFeatures pf) {
-        var PeerBandwidth pbw
-        val bw = pf.toAdBandwidth
-        if (bw != null) {
-            pbw = new PeerBandwidth(bw.value)
-        }
-        return pbw
-    }
-
-    public static def toADNodeProperties(NodeUpdated nu) {
-        val fcnu = nu.getAugmentation(FlowCapableNodeUpdated)
-        if (fcnu != null) {
-            return fcnu.toADNodeProperties(nu.id)
-        }
-        return new HashSet<org.opendaylight.controller.sal.core.Property>();
-
-    }
-
-    public static def toADNodeProperties(FlowNode fcnu, NodeId id) {
-        val props = new HashSet<org.opendaylight.controller.sal.core.Property>();
-        if (fcnu != null) {
-            props.add(toADTimestamp)
-
-            // props.add(fcnu.supportedActions.toADActions) - TODO
-            if (id != null) {
-                props.add(id.toADMacAddress)
-            }
-            if (fcnu.switchFeatures != null) {
-                if (fcnu.switchFeatures.maxTables != null) {
-                    props.add(fcnu.switchFeatures.maxTables.toADTables)
-                }
-                if (fcnu.switchFeatures.capabilities != null) {
-                    props.add(fcnu.switchFeatures.capabilities.toADCapabiliities)
-                }
-                if (fcnu.switchFeatures.maxBuffers != null) {
-                    props.add(fcnu.switchFeatures.maxBuffers.toADBuffers)
-                }
-            }
-        }
-        return props;
-    }
-
-    public static def toADTimestamp() {
-        val date = new Date();
-        val timestamp = new TimeStamp(date.time, "connectedSince")
-        return timestamp;
-    }
-
-    public static def toADMacAddress(NodeId id) {
-        return new MacAddress(Long.parseLong(id.value.replaceAll("openflow:", "")).longValue.bytesFromDpid)
-    }
-
-    public static def toADTables(Short tables) {
-        return new Tables(tables.byteValue)
-    }
-
-    public static def toADCapabiliities(List<Class<? extends FeatureCapability>> capabilities) {
-        var int b
-        for (capability : capabilities) {
-            if (capability.equals(FlowFeatureCapabilityFlowStats)) {
-                b = Capabilities.CapabilitiesType.FLOW_STATS_CAPABILITY.value.bitwiseOr(b)
-            } else if (capability.equals(FlowFeatureCapabilityTableStats)) {
-                b = Capabilities.CapabilitiesType.TABLE_STATS_CAPABILITY.value.bitwiseOr(b)
-            } else if (capability.equals(FlowFeatureCapabilityPortStats)) {
-                b = Capabilities.CapabilitiesType.PORT_STATS_CAPABILITY.value.bitwiseOr(b)
-            } else if (capability.equals(FlowFeatureCapabilityStp)) {
-                b = Capabilities.CapabilitiesType.STP_CAPABILITY.value.bitwiseOr(b)
-            } else if (capability.equals(FlowFeatureCapabilityIpReasm)) {
-                b = Capabilities.CapabilitiesType.IP_REASSEM_CAPABILITY.value.bitwiseOr(b)
-            } else if (capability.equals(FlowFeatureCapabilityQueueStats)) {
-                b = Capabilities.CapabilitiesType.QUEUE_STATS_CAPABILITY.value.bitwiseOr(b)
-            } else if (capability.equals(FlowFeatureCapabilityArpMatchIp)) {
-                b = Capabilities.CapabilitiesType.ARP_MATCH_IP_CAPABILITY.value.bitwiseOr(b)
-            }
-        }
-        return new Capabilities(b)
-    }
-
-    public static def toADBuffers(Long buffers) {
-        return new Buffers(buffers.intValue)
-    }
-
-}
index 30a607d95b6a025619e836dd26097707704ecae3..ebffbcc811747307f2a3a67a7b83cb403d5757c2 100644 (file)
@@ -10,41 +10,40 @@ package org.opendaylight.controller.md.sal.common.api.data;
 import java.util.Map;
 import java.util.Set;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface DataChange<P/* extends Path<P> */, D> {
+public interface DataChange<P extends Path<P>, D> {
 
     /**
      * Returns a map of paths and newly created objects
-     * 
+     *
      * @return map of paths and newly created objects
      */
     Map<P, D> getCreatedOperationalData();
 
     /**
      * Returns a map of paths and newly created objects
-     * 
+     *
      * @return map of paths and newly created objects
      */
     Map<P, D> getCreatedConfigurationData();
 
     /**
      * Returns a map of paths and respective updated objects after update.
-     * 
+     *
      * Original state of the object is in
      * {@link #getOriginalOperationalData()}
-     * 
+     *
      * @return map of paths and newly created objects
      */
     Map<P, D> getUpdatedOperationalData();
 
     /**
      * Returns a map of paths and respective updated objects after update.
-     * 
+     *
      * Original state of the object is in
      * {@link #getOriginalConfigurationData()}
-     * 
+     *
      * @return map of paths and newly created objects
      */
     Map<P, D> getUpdatedConfigurationData();
@@ -53,34 +52,34 @@ public interface DataChange<P/* extends Path<P> */, D> {
 
     /**
      * Returns a set of paths of removed objects.
-     * 
+     *
      * Original state of the object is in
      * {@link #getOriginalConfigurationData()}
-     * 
+     *
      * @return map of paths and newly created objects
      */
     Set<P> getRemovedConfigurationData();
 
     /**
      * Returns a set of paths of removed objects.
-     * 
+     *
      * Original state of the object is in
      * {@link #getOriginalOperationalData()}
-     * 
+     *
      * @return map of paths and newly created objects
      */
     Set<P> getRemovedOperationalData();
 
     /**
      * Return a map of paths and original state of updated and removed objectd.
-     * 
+     *
      * @return map of paths and original state of updated and removed objectd.
      */
     Map<P, D> getOriginalConfigurationData();
 
     /**
      * Return a map of paths and original state of updated and removed objectd.
-     * 
+     *
      * @return map of paths and original state of updated and removed objectd.
      */
     Map<P, D> getOriginalOperationalData();
index d62e176e62d1beeb22c934f7c82aa3a713909b91..15d1daa1bbe882393f863e892728490c212f5e71 100644 (file)
@@ -8,36 +8,37 @@
 package org.opendaylight.controller.md.sal.common.api.data;
 
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface DataChangeEvent<P,D> extends DataChange<P, D>, Immutable {
+public interface DataChangeEvent<P extends Path<P>,D> extends DataChange<P, D>, Immutable {
 
     /**
      * Returns a orignal subtree of data, which starts at the path
      * where listener was registered.
-     * 
+     *
      */
     D getOriginalConfigurationSubtree();
 
     /**
      * Returns a new subtree of data, which starts at the path
      * where listener was registered.
-     * 
+     *
      */
     D getOriginalOperationalSubtree();
-    
-    
-    
+
+
+
     /**
      * Returns a updated subtree of data, which starts at the path
      * where listener was registered.
-     * 
+     *
      */
     D getUpdatedConfigurationSubtree();
 
     /**
      * Returns a udpated subtree of data, which starts at the path
      * where listener was registered.
-     * 
+     *
      */
     D getUpdatedOperationalSubtree();
 }
index 8b87139c7f97e78d09be1fad70fd192af52e48b2..8787a3fe8d82de85bc7e064177501e017d041cca 100644 (file)
@@ -9,10 +9,9 @@ package org.opendaylight.controller.md.sal.common.api.data;
 
 import java.util.EventListener;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface DataChangeListener<P/* extends Path<P> */,D> extends EventListener {
+public interface DataChangeListener<P extends Path<P>, D> extends EventListener {
 
     void onDataChanged(DataChangeEvent<P, D> change);
 }
index 66645e5538d6efb0935231100c0a72890ed09a70..0c4c6d179ff84faf955fb6989d8ca900cbb8722e 100644 (file)
@@ -7,12 +7,10 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
-
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Path;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
-public interface DataChangePublisher<P/* extends Path<P> */,D, L extends DataChangeListener<P,D>> {
+public interface DataChangePublisher<P extends Path<P>, D, L extends DataChangeListener<P,D>> {
 
     ListenerRegistration<L> registerDataChangeListener(P path, L listener);
 
index 90de13d15e8229238f36c5ec59b1180babcff1ae..939ff9513513ff1de802746facfdd09844952b76 100644 (file)
@@ -8,30 +8,29 @@
 package org.opendaylight.controller.md.sal.common.api.data;
 
 import org.opendaylight.controller.sal.common.DataStoreIdentifier;
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 /**
  * Two phase commit handler (cohort) of the two-phase commit protocol of data.
- * 
+ *
  * <p>
  * The provider should expose the implementation of DataCommitHandler if it's
  * functionality depends on any subset of data stored in data repositories, in
  * order to participate in {@link DataBrokerService#commit(DataStoreIdentifier)
  * operation.
- * 
+ *
  * <p>
  * Operations of two-phase commit handlers should not change data in data store,
  * this is responsibility of the coordinator (broker or some component of the
  * broker).
- * 
+ *
  * The commit handlers are responsible for changing the internal state of the
  * provider to reflect the commited changes in data.
- * 
+ *
  * <h3>Two-phase commit</h3>
- * 
+ *
  * <h4>Commit Request Phase</h4>
- * 
+ *
  * <ol>
  * <li> <code>Consumer</code> edits data by invocation of
  * <code>DataBrokerService.editCandidateData(DataStoreIdentifier, DataRoot)</code>
@@ -51,9 +50,9 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
  * </ol>
  * <li><code>Broker</code> starts a commit finish phase
  * </ol>
- * 
+ *
  * <h4>Commit Finish Phase</h4>
- * 
+ *
  * <ol>
  * <li>For each <code>CommitTransaction</code> from Commit Request phase
  * <ol>
@@ -69,7 +68,7 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
  * <li>If error occured, the broker starts a commit rollback phase.
  * </ul>
  * </ol>
- * 
+ *
  * <h4>Commit Rollback Phase</h4>
  * <li>For each <code>DataCommitTransaction</code> from Commit Request phase
  * <ol>
@@ -78,43 +77,43 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
  * <li>The provider rollbacks a commit and returns an {@link RpcResult} of
  * rollback. </ol>
  * <li>Broker returns a error result to the consumer.
- * 
+ *
  * @param <P> Class representing a path
  * @param <D> Superclass from which all data objects are derived from.
  */
-public interface DataCommitHandler<P/* extends Path<P> */,D> {
+public interface DataCommitHandler<P extends Path<P>, D> {
+
 
-    
     DataCommitTransaction<P, D> requestCommit(DataModification<P,D> modification);
 
-    public interface DataCommitTransaction<P/* extends Path<P> */,D> {
+    public interface DataCommitTransaction<P extends Path<P>, D> {
 
         DataModification<P,D> getModification();
 
         /**
-         * 
+         *
          * Finishes a commit.
-         * 
+         *
          * This callback is invoked by commit coordinator to finish commit action.
-         * 
+         *
          * The implementation is required to finish transaction or return unsuccessful
          * rpc result if something went wrong.
-         * 
+         *
          * The provider (commit handler) should apply all changes to its state
          * which are a result of data change-
-         * 
+         *
          * @return
          */
         RpcResult<Void> finish() throws IllegalStateException;
 
         /**
          * Rollbacks a commit.
-         * 
+         *
          * This callback is invoked by commit coordinator to finish commit action.
-         * 
+         *
          * The provider (commit handler) should rollback all changes to its state
          * which were a result of previous request commit.
-         * 
+         *
          * @return
          * @throws IllegalStateException
          *             If the method is invoked after {@link #finish()}
index 00db6064aa3bb54fa2a1f123be45d67289e63c52..f6662c388aa36e0092cf0ec8b5f262dcf981d163 100644 (file)
@@ -10,11 +10,10 @@ package org.opendaylight.controller.md.sal.common.api.data;
 import java.util.concurrent.Future;
 
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
-//FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-//import org.opendaylight.yangtools.concepts.Path;
-public interface DataModification<P/* extends Path<P> */, D> extends DataChange<P, D>, DataReader<P, D> {
+public interface DataModification<P extends Path<P>, D> extends DataChange<P, D>, DataReader<P, D> {
 
     /**
      * Returns transaction identifier
index 64d90f6fd5e8ae0ceb471c051287eb8fb298bdbc..34f6fe970dd2e0105e6a21d32ca7049815ea87e7 100644 (file)
@@ -7,10 +7,9 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface DataModificationTransactionFactory<P/* extends Path<P> */,D> {
+public interface DataModificationTransactionFactory<P extends Path<P> ,D> {
 
     DataModification<P, D> beginTransaction();
 }
index 6c108bf5e49c1c6cb7fc3717e5f77649558e830f..dae9a1144b966a2e3c5e61884c1281e09a6229f3 100644 (file)
@@ -7,9 +7,8 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface DataProvider<P/* extends Path<P> */,D> extends DataReader<P, D> {
+public interface DataProvider<P extends Path<P>, D> extends DataReader<P, D> {
 
 }
index 7240a506bea5c0612f1c75424b85d544a09f9ec6..14731d688c964adaf264d8909a4c3e90ccc4484e 100644 (file)
@@ -7,23 +7,22 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
 /**
  * Reader for reading YANG subtrees based on their path.
- * 
+ *
  * Reader is requested to return object at specified path and all it's subnodes
  * known to the reader or null if node is not found in this reader.
  *
  * @param <P> Path Type
  * @param <D> Data Type
  */
-public interface DataReader<P/* extends Path<P> */,D> {
+public interface DataReader<P extends Path<P> ,D> {
 
     /**
      * Reads data from Operational data store located at provided path
-     * 
+     *
      * @param path Path to data
      * @return
      */
index ed5499870a9402cb0a8ef6f625a7528d14f8797a..3520ba1819b42fb0ce37ae3548631cd80753334b 100644 (file)
@@ -7,7 +7,9 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
-public interface DataStore<P, D> extends //
+import org.opendaylight.yangtools.concepts.Path;
+
+public interface DataStore<P extends Path<P>, D> extends //
         DataReader<P, D>, //
         DataModificationTransactionFactory<P, D> {
 
index ff3aa2e325af0146d5cd878ea9aed88c350d4a6c..d542935dd6dbf0fdb91ce72b273d6bc9c87b2668 100644 (file)
@@ -7,12 +7,14 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
+import org.opendaylight.yangtools.concepts.Path;
+
 /**
  * A chain of transactions. Transactions in a chain need to be committed in sequence and each
  * transaction should see the effects of previous transactions as if they happened. A chain
  * makes no guarantees of atomicity, in fact transactions are committed as soon as possible.
  */
-public interface TransactionChain<P/* extends Path<P> */, D> extends AutoCloseable {
+public interface TransactionChain<P extends Path<P>, D> extends AutoCloseable {
     /**
      * Create a new transaction which will continue the chain. The previous transaction
      * has to be either COMMITTED or CANCELLED.
index 4e7e12e0a15e3c5060a59eff76c35d9896ff00eb..94d21f5fd6bb02736a360592dc6826a3c70e4ae4 100644 (file)
@@ -7,10 +7,12 @@
  */
 package org.opendaylight.controller.md.sal.common.api.data;
 
+import org.opendaylight.yangtools.concepts.Path;
+
 /**
  * Interface for creating transaction chains.
  */
-public interface TransactionChainFactory<P/* extends Path<P> */, D> {
+public interface TransactionChainFactory<P extends Path<P>, D> {
     /**
      * Create a new transaction chain. The chain will be initialized to read
      * from its backing datastore, with no outstanding transaction. Listener
index 1139d03357999f5d71d3b0326ab1c621a14da984..f99c13ecf53499ab6770d9107025cb7f91828b8a 100644 (file)
@@ -8,10 +8,9 @@
 package org.opendaylight.controller.md.sal.common.api.routing;
 
 import org.opendaylight.yangtools.concepts.Mutable;
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface MutableRoutingTable<C,P/* extends Path<P> */,T> extends RoutingTable<C,P,T>, Mutable {
+public interface MutableRoutingTable<C, P extends Path<P>, T> extends RoutingTable<C,P,T>, Mutable {
     
     void setDefaultRoute(T target);
     void updateRoute(P path,T target);
index 37ec2f6f1f90d4bae0e681d40e5674c1076ec504..5200c90561ecdb464060e0ba112a687de065c9ec 100644 (file)
@@ -7,11 +7,10 @@
  */
 package org.opendaylight.controller.md.sal.common.api.routing;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.concepts.Registration;
 
-public interface RoutedRegistration<C,P/* extends Path<P> */,S> extends Registration<S> {
+public interface RoutedRegistration<C, P extends Path<P>, S> extends Registration<S> {
 
     void registerPath(C context, P path);
     void unregisterPath(C context, P path);
index 211cf188795a1feee2d2abe11a028ff0b6a0786f..4402f69a5f73896f8f905c190a7743f3f0b28e80 100644 (file)
@@ -9,10 +9,9 @@ package org.opendaylight.controller.md.sal.common.api.routing;
 
 import java.util.Map;
 
-// FIXME: After 0.6 Release of YANGTools refactor to use Path marker interface for arguments.
-// import org.opendaylight.yangtools.concepts.Path;
+import org.opendaylight.yangtools.concepts.Path;
 
-public interface RoutingTable<C,P/* extends Path<P> */,T> {
+public interface RoutingTable<C, P extends Path<P>, T> {
 
     C getIdentifier();
     
index e319d2cb679260718c9eade75234b9996170007c..2d89bbc55c03d59d3ad7e648426df91562fc6fde 100644 (file)
@@ -49,7 +49,7 @@ public class ConfigPersisterNotificationHandler implements Closeable {
     private static void registerAsJMXListener(MBeanServerConnection mBeanServerConnection, ConfigPersisterNotificationListener listener) {
         logger.trace("Called registerAsJMXListener");
         try {
-            mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.objectName, listener, null, null);
+            mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.OBJECT_NAME, listener, null, null);
         } catch (InstanceNotFoundException | IOException e) {
             throw new RuntimeException("Cannot register as JMX listener to netconf", e);
         }
@@ -58,7 +58,7 @@ public class ConfigPersisterNotificationHandler implements Closeable {
     @Override
     public synchronized void close() {
         // unregister from JMX
-        ObjectName on = DefaultCommitOperationMXBean.objectName;
+        ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME;
         try {
             if (mBeanServerConnection.isRegistered(on)) {
                 mBeanServerConnection.removeNotificationListener(on, listener);
index bd75c27dd6abf36c794f85459accdcaa2bb3b35d..f85d9b9f304f8cf8de63e90f185d63fb64e82811 100644 (file)
@@ -22,13 +22,13 @@ public abstract class AbstractNetconfSession<S extends NetconfSession, L extends
     private final long sessionId;
     private boolean up = false;
 
-    protected final Channel channel;
+    private final Channel channel;
 
     protected AbstractNetconfSession(L sessionListener, Channel channel, long sessionId) {
         this.sessionListener = sessionListener;
         this.channel = channel;
         this.sessionId = sessionId;
-        logger.debug("Session {} created", toString());
+        logger.debug("Session {} created", sessionId);
     }
 
     protected abstract S thisInstance();
index 1ec46c8d6f1e58912e76c57bd4674f7d70e8c37c..be3040802cdfdc4ab7eaf3ac266914e936de82b0 100644 (file)
@@ -9,7 +9,7 @@
 package org.opendaylight.controller.netconf.api;
 
 public class NetconfSessionPreferences {
-    protected final NetconfMessage helloMessage;
+    private final NetconfMessage helloMessage;
 
     public NetconfSessionPreferences(final NetconfMessage helloMessage) {
         this.helloMessage = helloMessage;
index 0c4174000fe80dc231efd9aeb5702a2832834580..74cd4a4e05a5186cf6c4df5543b03a106c61fa3e 100644 (file)
@@ -17,12 +17,12 @@ public class CommitJMXNotification extends NetconfJMXNotification {
 
     private final Element configSnapshot;
 
-    private static final String afterCommitMessageTemplate = "Commit successful: %s";
+    private static final String AFTER_COMMIT_MESSAGE_TEMPLATE = "Commit successful: %s";
     private final Set<String> capabilities;
 
     CommitJMXNotification(NotificationBroadcasterSupport source, String message, Element cfgSnapshot,
             Set<String> capabilities) {
-        super(TransactionProviderJMXNotificationType.commit, source, String.format(afterCommitMessageTemplate, message));
+        super(TransactionProviderJMXNotificationType.commit, source, String.format(AFTER_COMMIT_MESSAGE_TEMPLATE, message));
         this.configSnapshot = cfgSnapshot;
         this.capabilities = capabilities;
     }
index a170d2905fee69135ab904525d266aa638d61331..e45d3c38a209ee26f0ba2b92e63637ad155f6c01 100644 (file)
@@ -14,7 +14,7 @@ import javax.management.ObjectName;
 
 public interface DefaultCommitOperationMXBean {
 
-    static String typeName = "NetconfNotificationProvider";
-    public static ObjectName objectName = ObjectNameUtil.createONWithDomainAndType(typeName);
+    String TYPE_NAME = "NetconfNotificationProvider";
+    ObjectName OBJECT_NAME = ObjectNameUtil.createONWithDomainAndType(TYPE_NAME);
 
 }
index 693fc1378390abcd89c0f582e75a055d10580c98..4461054437ce61ef47fd2eea76a9b23ae15b5ef3 100644 (file)
@@ -31,7 +31,7 @@ public class DefaultCommitNotificationProducer extends NotificationBroadcasterSu
 
     private final MBeanServer mbeanServer;
 
-    private final ObjectName on = DefaultCommitOperationMXBean.objectName;
+    private final ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME;
 
     public DefaultCommitNotificationProducer(MBeanServer mBeanServer) {
         this.mbeanServer = mBeanServer;
index 1b4dfff42baeb0423597af3c90168592db146724..f8024922cfc5a5ba021e97b519493ae80a02c4d2 100644 (file)
@@ -49,7 +49,7 @@ public class NetconfServerSessionNegotiator extends
 
         logger.debug("Additional header from hello parsed as {} from {}", parsedHeader, additionalHeader);
 
-        return new NetconfServerSession(sessionListener, channel, sessionPreferences.getSessionId(), parsedHeader);
+        return new NetconfServerSession(sessionListener, channel, getSessionPreferences().getSessionId(), parsedHeader);
     }
 
    }
index 8f9d89f1f10fb86fb37cf03fe9c83a536a2a5a82..d1c0b066d7a0a5ef15399a0544deb380177b0b01 100644 (file)
@@ -69,10 +69,10 @@ public class MessageParserTest {
             int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE;
             if (i == chunkCount) {
                 exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
-                byte[] eom = new byte[NetconfMessageConstants.endOfChunk.length];
-                recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.endOfChunk.length,
+                byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
+                recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length,
                         eom);
-                assertArrayEquals(NetconfMessageConstants.endOfChunk, eom);
+                assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
             }
 
             byte[] header = new byte[String.valueOf(exptHeaderLength).length()
index ff2efed128676b1da367442b67c4789185132ea7..1035c9f9fe3afd9c8a0bda0e3b3709ff2800df1d 100644 (file)
@@ -161,7 +161,7 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
 
     private VerifyingNotificationListener createCommitNotificationListener() throws InstanceNotFoundException {
         VerifyingNotificationListener listener = new VerifyingNotificationListener();
-        platformMBeanServer.addNotificationListener(DefaultCommitNotificationProducer.objectName, listener, null, null);
+        platformMBeanServer.addNotificationListener(DefaultCommitNotificationProducer.OBJECT_NAME, listener, null, null);
         return listener;
     }
 
index ea9fc5dce49209bc00daa277a93f877864f6d918..7f2d8c30f045fb6830458aa7fd461cc7885e8349 100644 (file)
@@ -21,6 +21,7 @@ import io.netty.util.concurrent.Promise;
 
 import java.util.concurrent.TimeUnit;
 
+import io.netty.channel.ChannelInboundHandlerAdapter;
 import org.opendaylight.controller.netconf.api.AbstractNetconfSession;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfSessionListener;
@@ -47,7 +48,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     private static final Logger logger = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
     public static final String NAME_OF_EXCEPTION_HANDLER = "lastExceptionHandler";
 
-    protected final P sessionPreferences;
+    private final P sessionPreferences;
 
     private final L sessionListener;
     private Timeout timeout;
@@ -79,14 +80,15 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
             Future<Channel> future = sslHandler.get().handshakeFuture();
             future.addListener(new GenericFutureListener<Future<? super Channel>>() {
                 @Override
-                public void operationComplete(Future<? super Channel> future) throws Exception {
+                public void operationComplete(Future<? super Channel> future) {
                     Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
                     logger.debug("Ssl handshake complete");
                     start();
                 }
             });
-        } else
+        } else {
             start();
+        }
     }
 
     private static Optional<SslHandler> getSslHandler(Channel channel) {
@@ -94,31 +96,19 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
         return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
     }
 
+    public P getSessionPreferences() {
+        return sessionPreferences;
+    }
+
     private void start() {
         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
         logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
 
-        channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ChannelHandler() {
-            @Override
-            public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
-            }
-
-            @Override
-            public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
-            }
-
-            @Override
-            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-                logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
-                cancelTimeout();
-                negotiationFailed(cause);
-                changeState(State.FAILED);
-            }
-        });
+        channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
 
         timeout = this.timer.newTimeout(new TimerTask() {
             @Override
-            public void run(final Timeout timeout) throws Exception {
+            public void run(final Timeout timeout) {
                 synchronized (this) {
                     if (state != State.ESTABLISHED) {
                         logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
@@ -138,8 +128,9 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     }
 
     private void cancelTimeout() {
-        if(timeout!=null)
+        if(timeout!=null) {
             timeout.cancel();
+        }
     }
 
     private void sendMessage(NetconfMessage message) {
@@ -148,27 +139,20 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
 
     @Override
     protected void handleMessage(NetconfHelloMessage netconfMessage) {
-        final Document doc = netconfMessage.getDocument();
+        Preconditions.checkNotNull(netconfMessage != null, "netconfMessage");
 
-        // Only Hello message should arrive during negotiation
-        if (netconfMessage instanceof NetconfHelloMessage) {
+        final Document doc = netconfMessage.getDocument();
 
-            replaceHelloMessageHandlers();
+        replaceHelloMessageHandlers();
 
-            if (shouldUseChunkFraming(doc)) {
-                insertChunkFramingToPipeline();
-            }
+        if (shouldUseChunkFraming(doc)) {
+            insertChunkFramingToPipeline();
+        }
 
-            changeState(State.ESTABLISHED);
-            S session = getSession(sessionListener, channel, netconfMessage);
+        changeState(State.ESTABLISHED);
+        S session = getSession(sessionListener, channel, netconfMessage);
 
-            negotiationSuccessful(session);
-        } else {
-            final IllegalStateException cause = new IllegalStateException(
-                    "Received message was not hello as expected, but was " + XmlUtil.toString(doc));
-            logger.warn("Negotiation of netconf session failed", cause);
-            negotiationFailed(cause);
-        }
+        negotiationSuccessful(session);
     }
 
     /**
@@ -218,14 +202,31 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     }
 
     private static boolean isStateChangePermitted(State state, State newState) {
-        if (state == State.IDLE && newState == State.OPEN_WAIT)
+        if (state == State.IDLE && newState == State.OPEN_WAIT) {
             return true;
-        if (state == State.OPEN_WAIT && newState == State.ESTABLISHED)
+        }
+        if (state == State.OPEN_WAIT && newState == State.ESTABLISHED) {
             return true;
-        if (state == State.OPEN_WAIT && newState == State.FAILED)
+        }
+        if (state == State.OPEN_WAIT && newState == State.FAILED) {
             return true;
+        }
 
         logger.debug("Transition from {} to {} is not allowed", state, newState);
         return false;
     }
+
+    /**
+     * Handler to catch exceptions in pipeline during negotiation
+     */
+    private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
+
+        @Override
+        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+            logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
+            cancelTimeout();
+            negotiationFailed(cause);
+            changeState(State.FAILED);
+        }
+    }
 }
index aae2f71b86b6f67aa08d57bd374407c59d17651d..796ab91a504040e87197f9032d85e4699d4c80b5 100644 (file)
@@ -27,10 +27,12 @@ import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
 
-public class NetconfUtil {
+public final class NetconfUtil {
 
     private static final Logger logger = LoggerFactory.getLogger(NetconfUtil.class);
 
+    private NetconfUtil() {}
+
     public static NetconfMessage createMessage(final File f) {
         Preconditions.checkNotNull(f, "File parameter was null");
         try {
index f7d1ba2b7e3b378f964ddbf68c87db567ffd837a..ccc80a7b71248758cc2ce9a3c00225a0dab3fc49 100644 (file)
@@ -49,7 +49,7 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf
         }
         out.writeBytes(createChunkHeader(msg.readableBytes()));
         out.writeBytes(msg.readBytes(msg.readableBytes()));
-        out.writeBytes(NetconfMessageConstants.endOfChunk);
+        out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
     }
 
     private ByteBuf createChunkHeader(int chunkSize) {
index 0d98084343a49355e22210868d5c08310dca460a..1f7a32dc704ca2698112b0e5e9d90c9cdb503a87 100644 (file)
@@ -17,7 +17,9 @@ import io.netty.handler.codec.MessageToByteEncoder;
 
 public class FramingMechanismHandlerFactory {
 
-    private final static Logger logger = LoggerFactory.getLogger(FramingMechanismHandlerFactory.class);
+    private static final Logger logger = LoggerFactory.getLogger(FramingMechanismHandlerFactory.class);
+
+    private FramingMechanismHandlerFactory() {}
 
     public static MessageToByteEncoder<ByteBuf> createHandler(FramingMechanism framingMechanism) {
         logger.debug("{} framing mechanism was selected.", framingMechanism);
index a87d175d78e2f901d70de1efd5a7466223a21001..65d5b270254dcbd9503a98791c4c9f878d3442f9 100644 (file)
@@ -7,12 +7,18 @@
  */
 package org.opendaylight.controller.netconf.util.handler;
 
-import java.nio.ByteBuffer;
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+
+import java.io.IOException;
+
+import javax.xml.transform.TransformerException;
 
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Charsets;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
@@ -39,9 +45,9 @@ import com.google.common.base.Preconditions;
  * </pre>
  */
 public final class NetconfHelloMessageToXMLEncoder extends NetconfMessageToXMLEncoder {
-
     @Override
-    protected ByteBuffer encodeMessage(NetconfMessage msg) {
+    @VisibleForTesting
+    public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException {
         Preconditions.checkState(msg instanceof NetconfHelloMessage, "Netconf message of type %s expected, was %s",
                 NetconfHelloMessage.class, msg.getClass());
         Optional<NetconfHelloMessageAdditionalHeader> headerOptional = ((NetconfHelloMessage) msg)
@@ -50,15 +56,9 @@ public final class NetconfHelloMessageToXMLEncoder extends NetconfMessageToXMLEn
         // If additional header present, serialize it along with netconf hello
         // message
         if (headerOptional.isPresent()) {
-            byte[] bytesFromHeader = headerOptional.get().toFormattedString().getBytes(Charsets.UTF_8);
-            byte[] bytesFromMessage = xmlToString(msg.getDocument()).getBytes(Charsets.UTF_8);
-
-            ByteBuffer byteBuffer = ByteBuffer.allocate(bytesFromHeader.length + bytesFromMessage.length)
-                    .put(bytesFromHeader).put(bytesFromMessage);
-            byteBuffer.flip();
-            return byteBuffer;
+            out.writeBytes(headerOptional.get().toFormattedString().getBytes(Charsets.UTF_8));
         }
 
-        return super.encodeMessage(msg);
+        super.encode(ctx, msg, out);
     }
 }
index df0f7ef46a72b30318cfa2a75e5c8e8d6564c4b8..f9792a6c5bf0e2965bead5df9b1c8671ce7d600e 100644 (file)
@@ -8,24 +8,32 @@
 package org.opendaylight.controller.netconf.util.handler;
 
 import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufOutputStream;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.MessageToByteEncoder;
 
-import java.nio.ByteBuffer;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
 
 import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Comment;
-import org.w3c.dom.Document;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Charsets;
 import com.google.common.base.Optional;
 
 public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMessage> {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageToXMLEncoder.class);
+    private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
 
     private final Optional<String> clientId;
 
@@ -39,7 +47,7 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
 
     @Override
     @VisibleForTesting
-    public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws Exception {
+    public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException {
         LOG.debug("Sent to encode : {}", msg);
 
         if (clientId.isPresent()) {
@@ -47,17 +55,14 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
             msg.getDocument().appendChild(comment);
         }
 
-        final ByteBuffer msgBytes = encodeMessage(msg);
-
-        LOG.trace("Putting message \n{}", xmlToString(msg.getDocument()));
-        out.writeBytes(msgBytes);
-    }
-
-    protected ByteBuffer encodeMessage(NetconfMessage msg) {
-        return Charsets.UTF_8.encode(xmlToString(msg.getDocument()));
-    }
+        try (OutputStream os = new ByteBufOutputStream(out)) {
+            Transformer transformer = FACTORY.newTransformer();
+            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 
-    protected String xmlToString(Document doc) {
-        return XmlUtil.toString(doc, false);
+            StreamResult result = new StreamResult(new OutputStreamWriter(os));
+            DOMSource source = new DOMSource(msg.getDocument());
+            transformer.transform(source, result);
+        }
     }
 }
index 248871a7aa3b4b6f3c60efffae0022791dad4624..c4808e0868d0f59b1378f5900b5151933edf696e 100644 (file)
@@ -135,11 +135,13 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
         for (byte[] possibleStart : POSSIBLE_STARTS) {
             int i = 0;
             for (byte b : possibleStart) {
-                if(bytes[i++] != b)
+                if(bytes[i++] != b) {
                     break;
+                }
 
-                if(i == possibleStart.length)
+                if(i == possibleStart.length) {
                     return true;
+                }
             }
         }
 
index 0d9096c02a3abd1b33204665cb72dc4cbd10e805..49d5a05ae22a6939f992c4637f123f550fb3a4e7 100644 (file)
@@ -29,6 +29,8 @@ import org.opendaylight.controller.netconf.util.handler.ssh.virtualsocket.Virtua
  * stops at instance of this class. All downstream events are handed of to wrapped {@link org.opendaylight.controller.netconf.util.handler.ssh.client.SshClientAdapter};
  */
 public class SshHandler extends ChannelOutboundHandlerAdapter {
+    private static final String SOCKET = "socket";
+
     private final VirtualSocket virtualSocket = new VirtualSocket();
     private final SshClientAdapter sshClientAdapter;
 
@@ -39,20 +41,20 @@ public class SshHandler extends ChannelOutboundHandlerAdapter {
 
     @Override
     public void handlerAdded(ChannelHandlerContext ctx){
-        if (ctx.channel().pipeline().get("socket") == null) {
-            ctx.channel().pipeline().addFirst("socket", virtualSocket);
+        if (ctx.channel().pipeline().get(SOCKET) == null) {
+            ctx.channel().pipeline().addFirst(SOCKET, virtualSocket);
         }
     }
 
     @Override
-    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
-        if (ctx.channel().pipeline().get("socket") != null) {
-            ctx.channel().pipeline().remove("socket");
+    public void handlerRemoved(ChannelHandlerContext ctx) {
+        if (ctx.channel().pipeline().get(SOCKET) != null) {
+            ctx.channel().pipeline().remove(SOCKET);
         }
     }
 
     @Override
-    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
+    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws IOException {
         this.sshClientAdapter.write((ByteBuf) msg);
     }
 
@@ -60,18 +62,18 @@ public class SshHandler extends ChannelOutboundHandlerAdapter {
     public void connect(final ChannelHandlerContext ctx,
                         SocketAddress remoteAddress,
                         SocketAddress localAddress,
-                        ChannelPromise promise) throws Exception {
+                        ChannelPromise promise) {
         ctx.connect(remoteAddress, localAddress, promise);
 
         promise.addListener(new ChannelFutureListener() {
-            public void operationComplete(ChannelFuture channelFuture) throws Exception {
+            public void operationComplete(ChannelFuture channelFuture) {
                 sshClientAdapter.start(ctx);
             }}
         );
     }
 
     @Override
-    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
+    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) {
         sshClientAdapter.stop(promise);
     }
 }
index 2f1b260bd087fd0f48dccdb0af1911157395d7cf..4aa274c6df34f2f2e9d4151454c4b84f53a41bdb 100644 (file)
@@ -29,7 +29,8 @@ public class LoginPassword extends AuthenticationHandler {
     public void authenticate(Connection connection) throws IOException {
         boolean isAuthenticated = connection.authenticateWithPassword(username, password);
 
-        if (isAuthenticated == false)
+        if (isAuthenticated == false) {
             throw new IOException("Authentication failed.");
+        }
     }
 }
index 8636e5ecb5fe55f22ce01cf9a19fb537397c9b0e..fffb304d26be7b3b32787fa1ae43e5392023bbd8 100644 (file)
@@ -19,6 +19,7 @@ public abstract class Invoker {
     private Invoker(){}
 
     protected boolean isInvoked() {
+        // TODO invoked is always false
         return invoked;
     }
 
@@ -34,7 +35,9 @@ public abstract class Invoker {
         return new Invoker() {
             @Override
             void invoke(SshSession session) throws IOException {
-                if (isInvoked() == true) throw new IllegalStateException("Already invoked.");
+                if (isInvoked()) {
+                    throw new IllegalStateException("Already invoked.");
+                }
 
                 session.startSubSystem(subsystem);
             }
index 3cb608db6a87c3ef121cc6a4edf0f0676fab9912..7beee649abfe0501e60850fda0db79dd96c7bb86 100644 (file)
@@ -23,7 +23,7 @@ import java.util.Map;
  */
 public class SshClient {
     private final VirtualSocket socket;
-    private final Map<Integer, SshSession> openSessions = new HashMap();
+    private final Map<Integer, SshSession> openSessions = new HashMap<>();
     private final AuthenticationHandler authenticationHandler;
     private Connection connection;
 
@@ -33,8 +33,9 @@ public class SshClient {
     }
 
     public SshSession openSession() throws IOException {
-        if (connection == null)
+        if (connection == null) {
             connect();
+        }
 
         Session session = connection.openSession();
         SshSession sshSession = new SshSession(session);
@@ -52,7 +53,7 @@ public class SshClient {
 
     public void closeSession(SshSession session) {
         if (session.getState() == Channel.STATE_OPEN || session.getState() == Channel.STATE_OPENING) {
-            session.session.close();
+            session.close();
         }
     }
 
@@ -62,7 +63,8 @@ public class SshClient {
 
         openSessions.clear();
 
-        if (connection != null)
+        if (connection != null) {
             connection.close();
+        }
     }
 }
index 4213fe3e0642db6257b3e655c407a4394785fca3..6350dd154415b510515f919d94c88d06ecac5314 100644 (file)
@@ -27,16 +27,14 @@ import org.opendaylight.controller.netconf.util.handler.ssh.virtualsocket.Virtua
  * pipeline.
  */
 public class SshClientAdapter implements Runnable {
+    private static final int BUFFER_SIZE = 1024;
+
     private final SshClient sshClient;
     private final Invoker invoker;
 
-    private SshSession session;
-    private InputStream stdOut;
-    private InputStream stdErr;
     private OutputStream stdIn;
 
-    private Queue<ByteBuf> postponned = new LinkedList<>();
-
+    private Queue<ByteBuf> postponed = new LinkedList<>();
 
     private ChannelHandlerContext ctx;
     private ChannelPromise disconnectPromise;
@@ -52,22 +50,22 @@ public class SshClientAdapter implements Runnable {
 
     public void run() {
         try {
-            session = sshClient.openSession();
+            SshSession session = sshClient.openSession();
             invoker.invoke(session);
-            stdOut = session.getStdout();
-            stdErr = session.getStderr();
+            InputStream stdOut = session.getStdout();
+            session.getStderr();
 
             synchronized (lock) {
 
                 stdIn = session.getStdin();
-                ByteBuf message = null;
-                while ((message = postponned.poll()) != null) {
+                ByteBuf message;
+                while ((message = postponed.poll()) != null) {
                     writeImpl(message);
                 }
             }
 
             while (stopRequested.get() == false) {
-                byte[] readBuff = new byte[1024];
+                byte[] readBuff = new byte[BUFFER_SIZE];
                 int c = stdOut.read(readBuff);
                 if (c == -1) {
                     continue;
@@ -89,8 +87,9 @@ public class SshClientAdapter implements Runnable {
             sshClient.close();
 
             synchronized (lock) {
-                if (disconnectPromise != null)
+                if (disconnectPromise != null) {
                     ctx.disconnect(disconnectPromise);
+                }
             }
         }
     }
@@ -99,7 +98,7 @@ public class SshClientAdapter implements Runnable {
     public void write(ByteBuf message) throws IOException {
         synchronized (lock) {
             if (stdIn == null) {
-                postponned.add(message);
+                postponed.add(message);
                 return;
             }
             writeImpl(message);
@@ -119,8 +118,10 @@ public class SshClientAdapter implements Runnable {
     }
 
     public void start(ChannelHandlerContext ctx) {
-        if (this.ctx != null)
-            return; // context is already associated.
+        if (this.ctx != null) {
+            // context is already associated.
+            return;
+        }
         this.ctx = ctx;
         new Thread(this).start();
     }
index df400aa1413e64108dab66190dd763b4778dc0ce..411036c975baf2f29b9f98e4c69b8956acf64474 100644 (file)
@@ -11,6 +11,7 @@ package org.opendaylight.controller.netconf.util.handler.ssh.client;
 import ch.ethz.ssh2.Session;
 import ch.ethz.ssh2.StreamGobbler;
 
+import java.io.Closeable;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -18,8 +19,8 @@ import java.io.OutputStream;
 /**
  * Wrapper class for proprietary SSH sessions implementations
  */
-public class SshSession {
-    final Session session;
+public class SshSession implements Closeable {
+    private final Session session;
 
     public SshSession(Session session) {
         this.session = session;
@@ -61,8 +62,8 @@ public class SshSession {
         return session.waitUntilDataAvailable(timeout);
     }
 
-    public int waitForCondition(int condition_set, long timeout) {
-        return session.waitForCondition(condition_set, timeout);
+    public int waitForCondition(int conditionSet, long timeout) {
+        return session.waitForCondition(conditionSet, timeout);
     }
 
     public Integer getExitStatus() {
@@ -72,4 +73,9 @@ public class SshSession {
     public String getExitSignal() {
         return session.getExitSignal();
     }
+
+    @Override
+    public void close() {
+        session.close();
+    }
 }
index 4b9bfbf5f826ee13c34127d902c2ad583d5f8eb4..313ea932413b63b36c5d20cc6cb1a9570205ab2a 100644 (file)
@@ -39,7 +39,9 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan
 
             b[off] = (byte)c;
 
-            if(this.bb.readableBytes() == 0) return bytesRead;
+            if(this.bb.readableBytes() == 0) {
+                return bytesRead;
+            }
 
             int ltr = len-1;
             ltr = (ltr <= bb.readableBytes()) ? ltr : bb.readableBytes();
@@ -72,28 +74,23 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan
         }
     }
 
-    public void channelRegistered(ChannelHandlerContext ctx)
-            throws Exception {
+    public void channelRegistered(ChannelHandlerContext ctx) {
         ctx.fireChannelRegistered();
     }
 
-    public void channelUnregistered(ChannelHandlerContext ctx)
-            throws Exception {
+    public void channelUnregistered(ChannelHandlerContext ctx) {
         ctx.fireChannelUnregistered();
     }
 
-    public void channelActive(ChannelHandlerContext ctx)
-            throws Exception {
+    public void channelActive(ChannelHandlerContext ctx) {
         ctx.fireChannelActive();
     }
 
-    public void channelInactive(ChannelHandlerContext ctx)
-            throws Exception {
+    public void channelInactive(ChannelHandlerContext ctx) {
         ctx.fireChannelInactive();
     }
 
-    public void channelRead(ChannelHandlerContext ctx, Object o)
-            throws Exception {
+    public void channelRead(ChannelHandlerContext ctx, Object o) {
         synchronized(lock) {
             this.bb.discardReadBytes();
             this.bb.writeBytes((ByteBuf) o);
@@ -101,31 +98,25 @@ public class ChannelInputStream extends InputStream implements ChannelInboundHan
         }
     }
 
-    public void channelReadComplete(ChannelHandlerContext ctx)
-            throws Exception {
+    public void channelReadComplete(ChannelHandlerContext ctx) {
         ctx.fireChannelReadComplete();
     }
 
-    public void userEventTriggered(ChannelHandlerContext ctx, Object o)
-            throws Exception {
+    public void userEventTriggered(ChannelHandlerContext ctx, Object o) {
         ctx.fireUserEventTriggered(o);
     }
 
-    public void channelWritabilityChanged(ChannelHandlerContext ctx)
-            throws Exception {
+    public void channelWritabilityChanged(ChannelHandlerContext ctx) {
         ctx.fireChannelWritabilityChanged();
     }
 
-    public void handlerAdded(ChannelHandlerContext ctx)
-            throws Exception {
+    public void handlerAdded(ChannelHandlerContext ctx) {
     }
 
-    public void handlerRemoved(ChannelHandlerContext ctx)
-            throws Exception {
+    public void handlerRemoved(ChannelHandlerContext ctx) {
     }
 
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable)
-            throws Exception {
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
         ctx.fireExceptionCaught(throwable);
     }
 }
index b1314a6eedfde68f71ccb26e27b0c6d73b8e51cd..cd7ec5439bc422e492b874b64e1be89211213d88 100644 (file)
@@ -14,7 +14,6 @@ import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelOutboundHandler;
 import io.netty.channel.ChannelPromise;
 
-import java.io.IOException;
 import java.io.OutputStream;
 import java.net.SocketAddress;
 
@@ -27,7 +26,7 @@ public class ChannelOutputStream extends OutputStream implements ChannelOutbound
     private ChannelHandlerContext ctx;
 
     @Override
-    public void flush() throws IOException {
+    public void flush() {
         synchronized(lock) {
             ctx.writeAndFlush(buff).awaitUninterruptibly();
             buff = Unpooled.buffer();
@@ -35,51 +34,44 @@ public class ChannelOutputStream extends OutputStream implements ChannelOutbound
     }
 
     @Override
-    public void write(int b) throws IOException {
+    public void write(int b) {
         synchronized(lock) {
             buff.writeByte(b);
         }
     }
 
     public void bind(ChannelHandlerContext ctx, SocketAddress localAddress,
-                     ChannelPromise promise) throws Exception {
+                     ChannelPromise promise) {
         ctx.bind(localAddress, promise);
     }
 
     public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress,
-                        SocketAddress localAddress, ChannelPromise promise)
-            throws Exception {
+                        SocketAddress localAddress, ChannelPromise promise) {
         this.ctx = ctx;
         ctx.connect(remoteAddress, localAddress, promise);
     }
 
-    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise)
-            throws Exception {
+    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) {
         ctx.disconnect(promise);
     }
 
-    public void close(ChannelHandlerContext ctx, ChannelPromise promise)
-            throws Exception {
+    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
         ctx.close(promise);
     }
 
-    public void deregister(ChannelHandlerContext ctx, ChannelPromise channelPromise)
-            throws Exception {
+    public void deregister(ChannelHandlerContext ctx, ChannelPromise channelPromise) {
         ctx.deregister(channelPromise);
     }
 
-    public void read(ChannelHandlerContext ctx)
-            throws Exception {
+    public void read(ChannelHandlerContext ctx) {
         ctx.read();
     }
 
-    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
-            throws Exception {
+    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
         // pass
     }
 
-    public void flush(ChannelHandlerContext ctx)
-            throws Exception {
+    public void flush(ChannelHandlerContext ctx) {
         // pass
     }
 
@@ -91,8 +83,7 @@ public class ChannelOutputStream extends OutputStream implements ChannelOutbound
             throws Exception {
     }
 
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
-            throws Exception {
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
         ctx.fireExceptionCaught(cause);
     }
 }
index 1011ca16be84803d4bfbe6f8f083335782de6538..36c2c1c3295736bf9cc183fbe53256ac847ff15b 100644 (file)
@@ -26,6 +26,9 @@ import java.nio.channels.SocketChannel;
  * are able to use full potential of NIO environment.
  */
 public class VirtualSocket extends Socket implements ChannelHandler {
+    private static final String INPUT_STREAM = "inputStream";
+    private static final String OUTPUT_STREAM = "outputStream";
+
     private final ChannelInputStream chis = new ChannelInputStream();
     private final ChannelOutputStream chos = new ChannelOutputStream();
     private ChannelHandlerContext ctx;
@@ -39,29 +42,30 @@ public class VirtualSocket extends Socket implements ChannelHandler {
         return this.chos;
     }
 
-    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
+    public void handlerAdded(ChannelHandlerContext ctx) {
         this.ctx = ctx;
 
-        if (ctx.channel().pipeline().get("outputStream") == null) {
-            ctx.channel().pipeline().addFirst("outputStream", chos);
+        if (ctx.channel().pipeline().get(OUTPUT_STREAM) == null) {
+            ctx.channel().pipeline().addFirst(OUTPUT_STREAM, chos);
         }
 
-        if (ctx.channel().pipeline().get("inputStream") == null) {
-            ctx.channel().pipeline().addFirst("inputStream", chis);
+        if (ctx.channel().pipeline().get(INPUT_STREAM) == null) {
+            ctx.channel().pipeline().addFirst(INPUT_STREAM, chis);
         }
     }
 
-    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
-        if (ctx.channel().pipeline().get("outputStream") != null) {
-            ctx.channel().pipeline().remove("outputStream");
+    public void handlerRemoved(ChannelHandlerContext ctx) {
+        if (ctx.channel().pipeline().get(OUTPUT_STREAM) != null) {
+            ctx.channel().pipeline().remove(OUTPUT_STREAM);
         }
 
-        if (ctx.channel().pipeline().get("inputStream") != null) {
-            ctx.channel().pipeline().remove("inputStream");
+        if (ctx.channel().pipeline().get(INPUT_STREAM) != null) {
+            ctx.channel().pipeline().remove(INPUT_STREAM);
         }
     }
 
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) throws Exception {
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
+        // TODO exceptionCaught is deprecated transform this handler
         ctx.fireExceptionCaught(throwable);
     }
 
@@ -80,7 +84,9 @@ public class VirtualSocket extends Socket implements ChannelHandler {
     public InetAddress getInetAddress() {
         InetSocketAddress isa = getInetSocketAddress();
 
-        if (isa == null) throw new VirtualSocketException();
+        if (isa == null) {
+            throw new VirtualSocketException();
+        }
 
         return getInetSocketAddress().getAddress();
     }
index f3ca30d2c40a4f924b0b35b5d196ba53295acb57..d1e064eaeb51cac6ed5462e11ccf0600214fd12d 100644 (file)
@@ -18,7 +18,7 @@ import java.util.regex.Pattern;
  * session's connection. Provided information can be reported via netconf
  * monitoring.
  * <pre>
- * It has pattern "[username; host-address:port; transport; session-identifier;]"
+ * It has PATTERN "[username; host-address:port; transport; session-identifier;]"
  * username - name of account on a remote
  * host-address - client's IP address
  * port - port number
@@ -92,20 +92,20 @@ public class NetconfHelloMessageAdditionalHeader {
     }
 
     // TODO IPv6
-    private static final Pattern pattern = Pattern
+    private static final Pattern PATTERN = Pattern
             .compile("\\[(?<username>[^;]+);(?<address>[0-9\\.]+)[:/](?<port>[0-9]+);(?<transport>[a-z]+)[^\\]]+\\]");
-    private static final Pattern customHeaderPattern = Pattern
+    private static final Pattern CUSTOM_HEADER_PATTERN = Pattern
             .compile("\\[(?<username>[^;]+);(?<address>[0-9\\.]+)[:/](?<port>[0-9]+);(?<transport>[a-z]+);(?<sessionIdentifier>[a-z]+)[^\\]]+\\]");
 
     /**
      * Parse additional header from a formatted string
      */
     public static NetconfHelloMessageAdditionalHeader fromString(String additionalHeader) {
-        additionalHeader = additionalHeader.trim();
-        Matcher matcher = pattern.matcher(additionalHeader);
-        Matcher matcher2 = customHeaderPattern.matcher(additionalHeader);
+        String additionalHeaderTrimmed = additionalHeader.trim();
+        Matcher matcher = PATTERN.matcher(additionalHeaderTrimmed);
+        Matcher matcher2 = CUSTOM_HEADER_PATTERN.matcher(additionalHeaderTrimmed);
         Preconditions.checkArgument(matcher.matches(), "Additional header in wrong format %s, expected %s",
-                additionalHeader, pattern);
+                additionalHeaderTrimmed, PATTERN);
 
         String username = matcher.group("username");
         String address = matcher.group("address");
index c111998e0ae8c271cd7fbd4c22383930a5a411c3..8bd6b8865933d7191a063055834ce3fb98b0bbe4 100644 (file)
@@ -17,9 +17,13 @@ public class NetconfMessageConstants {
      */
     public static final byte[] END_OF_MESSAGE = "]]>]]>".getBytes(Charsets.UTF_8);
 
-    public static final byte[] endOfChunk = "\n##\n".getBytes(Charsets.UTF_8);
+    // bytes
 
-    public static final int MIN_HEADER_LENGTH = 4; // bytes
+    public static final int MIN_HEADER_LENGTH = 4;
 
-    public static final int MAX_HEADER_LENGTH = 13; // bytes
+    // bytes
+
+    public static final int MAX_HEADER_LENGTH = 13;
+
+    public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(Charsets.UTF_8);
 }
index 46053e734ebf006154e26d5c8b7564ff6a36eedd..91eb86908b169ca9ecff8a77fb803b2d7ee60184 100644 (file)
@@ -13,7 +13,9 @@ import org.opendaylight.controller.netconf.util.xml.XmlElement;
 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
 import org.w3c.dom.Document;
 
-public class NetconfMessageUtil {
+public final class NetconfMessageUtil {
+
+    private NetconfMessageUtil() {}
 
     public static boolean isOKMessage(NetconfMessage message) {
         return isOKMessage(message.getDocument());
index 6dc00bb1509e97b0a485b89e90b0248a642e7a1a..de2d6d7e0c354ada3bcf1fb4f1b630b186c34e3c 100644 (file)
@@ -29,9 +29,11 @@ import javax.xml.xpath.XPathExpression;
 import java.io.InputStream;
 import java.util.Map.Entry;
 
-public class SendErrorExceptionUtil {
+public final class SendErrorExceptionUtil {
     private static final Logger logger = LoggerFactory.getLogger(SendErrorExceptionUtil.class);
 
+    private SendErrorExceptionUtil() {}
+
     public static void sendErrorMessage(final NetconfSession session,
             final NetconfDocumentedException sendErrorException) {
         logger.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
@@ -68,8 +70,9 @@ public class SendErrorExceptionUtil {
             for (int i = 0; i < incomingAttributes.getLength(); i++) {
                 final Attr attr = (Attr) incomingAttributes.item(i);
                 // skip namespace
-                if (attr.getNodeName().equals(XmlUtil.XMLNS_ATTRIBUTE_KEY))
+                if (attr.getNodeName().equals(XmlUtil.XMLNS_ATTRIBUTE_KEY)) {
                     continue;
+                }
                 rpcReply.setAttributeNode((Attr) errorDocument.importNode(attr, true));
             }
         } catch (final Exception e) {
index 38563cba93eef1f727330b17ff72879a012f70ff..80eaa26de184ddc29993bd847d1c34b0e7becd09 100644 (file)
@@ -17,12 +17,12 @@ import java.net.InetSocketAddress;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
-public class NetconfConfigUtil {
+public final class NetconfConfigUtil {
     private static final Logger logger = LoggerFactory.getLogger(NetconfConfigUtil.class);
 
     private static final String PREFIX_PROP = "netconf.";
 
-
+    private NetconfConfigUtil() {}
 
     private enum InfixProp {
         tcp, ssh
index d9303228f95b55773c3a15e7ef6e0bc7b01cef71..3247e0f7a0e034402fcedda91b2b1e5ece7a1fe8 100644 (file)
@@ -13,7 +13,9 @@ import javax.xml.xpath.XPathExpression;
 import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
 
-public class XMLNetconfUtil {
+public final class XMLNetconfUtil {
+
+    private XMLNetconfUtil() {}
 
     public static XPathExpression compileXPath(String xPath) {
         final XPathFactory xPathfactory = XPathFactory.newInstance();
index 18a94c6d07ff7cf74289bfb5d3e057967a61e86c..1fbae1ee2d6e52c404742655ccd059e9038fd803 100644 (file)
@@ -31,9 +31,9 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-public class XmlElement {
+public final class XmlElement {
 
-    public final Element element;
+    private final Element element;
 
     private XmlElement(Element element) {
         this.element = element;
@@ -123,9 +123,6 @@ public class XmlElement {
 
     public void appendChild(Element element) {
         this.element.appendChild(element);
-        // Element newElement = (Element) element.cloneNode(true);
-        // newElement.appendChild(configElement);
-        // return XmlElement.fromDomElement(newElement);
     }
 
     public Element getDomElement() {
@@ -153,10 +150,12 @@ public class XmlElement {
         final List<XmlElement> result = new ArrayList<>();
         for (int i = 0; i < childNodes.getLength(); i++) {
             Node item = childNodes.item(i);
-            if (item instanceof Element == false)
+            if (item instanceof Element == false) {
                 continue;
-            if (strat.accept((Element) item))
+            }
+            if (strat.accept((Element) item)) {
                 result.add(new XmlElement((Element) item));
+            }
         }
 
         return result;
@@ -290,12 +289,12 @@ public class XmlElement {
     public String getNamespace() {
         String namespaceURI = element.getNamespaceURI();
         Preconditions.checkState(namespaceURI != null, "No namespace defined for %s", this);
-        return namespaceURI.toString();
+        return namespaceURI;
     }
 
     @Override
     public String toString() {
-        final StringBuffer sb = new StringBuffer("XmlElement{");
+        final StringBuilder sb = new StringBuilder("XmlElement{");
         sb.append("name='").append(getName()).append('\'');
         if (element.getNamespaceURI() != null) {
             sb.append(", namespace='").append(getNamespace()).append('\'');
@@ -320,7 +319,7 @@ public class XmlElement {
     public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() {
         Map<String, String> namespaces = extractNamespaces(element);
         String textContent = getTextContent();
-        int indexOfColon = textContent.indexOf(":");
+        int indexOfColon = textContent.indexOf(':');
         String prefix;
         if (indexOfColon > -1) {
             prefix = textContent.substring(0, indexOfColon);
@@ -360,15 +359,18 @@ public class XmlElement {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o)
+        if (this == o) {
             return true;
-        if (o == null || getClass() != o.getClass())
+        }
+        if (o == null || getClass() != o.getClass()) {
             return false;
+        }
 
         XmlElement that = (XmlElement) o;
 
-        if (!element.isEqualNode(that.element))
+        if (!element.isEqualNode(that.element)) {
             return false;
+        }
 
         return true;
     }
@@ -392,7 +394,7 @@ public class XmlElement {
         return true;
     }
 
-    private static interface ElementFilteringStrategy {
+    private interface ElementFilteringStrategy {
         boolean accept(Element e);
     }
 }
index c410cf30b0abd00290bbc178c5ea3c9cbc7c0a21..4a6586cd1d8bf8ee0e9e4cbef66e62048cf1e5e6 100644 (file)
@@ -7,7 +7,9 @@
  */
 package org.opendaylight.controller.netconf.util.xml;
 
-public class XmlNetconfConstants {
+public final class XmlNetconfConstants {
+
+    private XmlNetconfConstants() {}
 
     public static final String MOUNTPOINTS = "mountpoints";
     public static final String MOUNTPOINT = "mountpoint";
index de0ebccdca428d8285d26d74b2f4e9fd54b5d353..8108c8e7402fac29469cf7804efd96e1dc6455df 100644 (file)
@@ -21,8 +21,11 @@ import org.xml.sax.SAXException;
 
 import com.google.common.base.Preconditions;
 
-public class XmlNetconfValidator {
-    static final Schema schema;
+public final class XmlNetconfValidator {
+
+    private static final Schema SCHEMA;
+
+    private XmlNetconfValidator() {}
 
     static {
         final InputStream xmlSchema = XmlNetconfValidator.class.getResourceAsStream("/xml.xsd");
@@ -30,11 +33,11 @@ public class XmlNetconfValidator {
 
         final InputStream rfc4714Schema = XmlNetconfValidator.class.getResourceAsStream("/rfc4741.xsd");
         Preconditions.checkNotNull(rfc4714Schema, "Cannot find rfc4741.xsd");
-        schema = XmlUtil.loadSchema(xmlSchema, rfc4714Schema);
+        SCHEMA = XmlUtil.loadSchema(xmlSchema, rfc4714Schema);
     }
 
     public static void validate(Document inputDocument) throws SAXException, IOException {
-        final Validator validator = schema.newValidator();
+        final Validator validator = SCHEMA.newValidator();
         final Source source = new DOMSource(inputDocument);
         validator.validate(source);
     }
index bb6c35130ef81bd87b3b190914bb105404b3237a..238249dbbd8d49086b38c1696cb6d0cb685909fe 100644 (file)
@@ -41,7 +41,8 @@ import org.xml.sax.SAXException;
 
 import com.google.common.base.Charsets;
 
-public class XmlUtil {
+public final class XmlUtil {
+
     public static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
     private static final DocumentBuilderFactory BUILDERFACTORY;
 
@@ -54,6 +55,8 @@ public class XmlUtil {
         BUILDERFACTORY = factory;
     }
 
+    private XmlUtil() {}
+
     public static Element readXmlToElement(String xmlContent) throws SAXException, IOException {
         Document doc = readXmlToDocument(xmlContent);
         return doc.getDocumentElement();
@@ -68,6 +71,9 @@ public class XmlUtil {
         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
     }
 
+    // TODO improve exceptions throwing
+    // along with XmlElement
+
     public static Document readXmlToDocument(InputStream xmlContent) throws SAXException, IOException {
         DocumentBuilder dBuilder;
         try {
@@ -133,14 +139,13 @@ public class XmlUtil {
         try {
             Transformer transformer = TransformerFactory.newInstance().newTransformer();
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration == true ? "no" : "yes");
+            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, addXmlDeclaration ? "no" : "yes");
 
             StreamResult result = new StreamResult(new StringWriter());
             DOMSource source = new DOMSource(xml);
             transformer.transform(source, result);
 
-            String xmlString = result.getWriter().toString();
-            return xmlString;
+            return result.getWriter().toString();
         } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
             throw new RuntimeException("Unable to serialize xml element " + xml, e);
         }