Merge "Bug 8153: Enforce check-style rules for netconf - sal-netconf-connector"
authorTomas Cere <tcere@cisco.com>
Wed, 3 May 2017 14:01:52 +0000 (14:01 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Wed, 3 May 2017 14:01:52 +0000 (14:01 +0000)
55 files changed:
netconf/callhome-provider/src/test/java/org/opendaylight/netconf/callhome/mount/CallHomeMountSessionContextTest.java
netconf/callhome-provider/src/test/java/org/opendaylight/netconf/callhome/mount/ContextKeyTest.java
netconf/mdsal-netconf-connector/pom.xml
netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidator.java
netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/UniversalNamespaceContextImpl.java [new file with mode: 0644]
netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java [new file with mode: 0644]
netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/FilterContentValidatorTest.java
netconf/mdsal-netconf-connector/src/test/resources/filter/bug8084.xml [new file with mode: 0644]
netconf/mdsal-netconf-connector/src/test/resources/yang/filter-validator-test-mod-0.yang
netconf/mdsal-netconf-connector/src/test/resources/yang/mdsal-netconf-mapping-test.yang
netconf/messagebus-netconf/pom.xml
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/ConnectionNotificationTopicRegistration.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManager.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceMount.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceRegistration.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NotificationTopicRegistration.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/StreamNotificationTopicRegistration.java
netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/ConnectionNotificationTopicRegistrationTest.java
netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManagerTest.java
netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceMountTest.java
netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceTest.java
netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfTestUtils.java
netconf/messagebus-netconf/src/test/java/org/opendaylight/netconf/messagebus/eventsources/netconf/StreamNotificationTopicRegistrationTest.java
netconf/netconf-monitoring/pom.xml
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/Get.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/GetSchema.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/MonitoringConstants.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/osgi/NetconfMonitoringActivator.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/osgi/NetconfMonitoringServiceTracker.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/JaxBSerializer.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSchema.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSession.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/NetconfState.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/package-info.java
netconf/netconf-monitoring/src/test/java/org/opendaylight/netconf/monitoring/GetSchemaTest.java
netconf/netconf-monitoring/src/test/java/org/opendaylight/netconf/monitoring/GetTest.java
netconf/netconf-monitoring/src/test/java/org/opendaylight/netconf/monitoring/osgi/NetconfMonitoringOperationServiceTest.java
netconf/netconf-monitoring/src/test/java/org/opendaylight/netconf/monitoring/osgi/NetconfMonitoringServiceTrackerTest.java
netconf/netconf-monitoring/src/test/java/org/opendaylight/netconf/monitoring/xml/JaxBSerializerTest.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java
netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/NetconfNorthboundTcpServer.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeActorTest.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImplTest.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadOnlyTransactionTest.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/WriteOnlyTransactionTest.java
netconf/netconf-topology/pom.xml
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/api/NetconfConnectorFactory.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/api/SchemaRepositoryProvider.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/impl/NetconfConnectorFactoryImpl.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/impl/NetconfTopologyImpl.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/impl/TopologyUtil.java
netconf/netconf-topology/src/test/java/org/opendaylight/netconf/topology/impl/NetconfTopologyImplTest.java
restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/impl/ModelGenerator.java

index ab833eaa4dacc00dacd4d40a0a9138575808d1d6..1551181eed89477cbaa37727aa68db792ff736be 100644 (file)
@@ -16,10 +16,9 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import com.google.common.net.InetAddresses;
 import java.net.Inet4Address;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.netconf.api.NetconfMessage;
@@ -39,8 +38,8 @@ public class CallHomeMountSessionContextTest {
     private CallHomeProtocolSessionContext mockProtocol;
 
     @Before
-    public void setup() throws UnknownHostException {
-        someAddressIpv4 = (Inet4Address) InetAddress.getByName("1.2.3.4");
+    public void setup() {
+        someAddressIpv4 = (Inet4Address) InetAddresses.forString("1.2.3.4");
         someSocketAddress = new InetSocketAddress(someAddressIpv4, 123);
 
         mockProtocol = mock(CallHomeProtocolSessionContext.class);
index c3a5da5fc098b2c4afeffa30c1f2a979cb970a97..eb65226b5271a84cec58c86c964e591477800e97 100644 (file)
@@ -16,11 +16,10 @@ import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.net.InetAddresses;
 import java.net.Inet4Address;
 import java.net.Inet6Address;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.netconf.client.NetconfClientSession;
@@ -89,10 +88,10 @@ public class ContextKeyTest {
     }
 
     @Test
-    public void newContextCanBeCreatedFromASocketAddress() throws UnknownHostException {
+    public void newContextCanBeCreatedFromASocketAddress() {
         // given
-        Inet4Address someAddressIpv4 = (Inet4Address) InetAddress.getByName("1.2.3.4");
-        Inet6Address someAddressIpv6 = (Inet6Address) InetAddress.getByName("::1");
+        Inet4Address someAddressIpv4 = (Inet4Address) InetAddresses.forString("1.2.3.4");
+        Inet6Address someAddressIpv6 = (Inet6Address) InetAddresses.forString("::1");
         // and
         ContextKey key1 = ContextKey.from(new InetSocketAddress(someAddressIpv4, 123));
         ContextKey key2 = ContextKey.from(new InetSocketAddress(someAddressIpv6, 123));
index 8e49b24ca07a47192554ce0b237e2266eed7b59c..97ed806fd4e1691c3927d5e76fd4b99ac731b053 100644 (file)
       <groupId>org.opendaylight.yangtools</groupId>
       <artifactId>yang-test-util</artifactId>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-data-codec-xml</artifactId>
+    </dependency>
   </dependencies>
 </project>
index 459ae7c8a443e8d9daa4547658bbe646df291305..de895bfa5d2712751940fe3414d060bdeadacfe2 100644 (file)
@@ -21,18 +21,25 @@ import java.util.Deque;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import javax.xml.namespace.NamespaceContext;
 import org.opendaylight.controller.config.util.xml.DocumentedException;
 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
 import org.opendaylight.controller.config.util.xml.XmlElement;
 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.codec.xml.XmlCodecFactory;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.util.codec.TypeAwareCodec;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
 
 /**
  * Class validates filter content against schema context.
@@ -52,6 +59,7 @@ public class FilterContentValidator {
     /**
      * Validates filter content against this validator schema context. If the filter is valid,
      * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
+     *
      * @param filterContent filter content
      * @return YangInstanceIdentifier
      * @throws DocumentedException if filter content is not valid
@@ -77,9 +85,10 @@ public class FilterContentValidator {
 
     /**
      * Returns module's child data node of given name space and name
-     * @param module module
+     *
+     * @param module    module
      * @param nameSpace name space
-     * @param name name
+     * @param name      name
      * @return child data node schema
      * @throws DocumentedException if child with given name is not present
      */
@@ -101,9 +110,10 @@ public class FilterContentValidator {
 
     /**
      * Recursively checks filter elements against the schema. Returns tree of nodes QNames as they appear in filter.
-     * @param element element to check
+     *
+     * @param element          element to check
      * @param parentNodeSchema parent node schema
-     * @param tree parent node tree
+     * @param tree             parent node tree
      * @return tree
      * @throws ValidationException if filter content is not valid
      */
@@ -134,9 +144,10 @@ public class FilterContentValidator {
      * Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
      * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
      * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
-     * @param tree QName tree
+     *
+     * @param tree          QName tree
      * @param filterContent filter element
-     * @param builder builder  @return YangInstanceIdentifier
+     * @param builder       builder  @return YangInstanceIdentifier
      */
     private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
                                                      final InstanceIdentifierBuilder builder) {
@@ -164,15 +175,15 @@ public class FilterContentValidator {
                                     final InstanceIdentifierBuilder builder) {
         Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
         final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
-        final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
-        final Map<QName, Object> map = getKeyValues(pathToList, filterContent, keyDefinition);
+
+        final Map<QName, Object> map = getKeyValues(pathToList, filterContent, listSchemaNode);
         if (!map.isEmpty()) {
             builder.nodeWithKey(tree.getName(), map);
         }
     }
 
     private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
-                                            final List<QName> keyDefinition) {
+                                            final ListSchemaNode listSchemaNode) {
         XmlElement current = filterContent;
         //find list element
         for (final String pathElement : path) {
@@ -184,6 +195,7 @@ public class FilterContentValidator {
             current = childElements.get(0);
         }
         final Map<QName, Object> keys = new HashMap<>();
+        final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
         for (final QName qName : keyDefinition) {
             final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
             if (!childElements.isPresent()) {
@@ -191,7 +203,23 @@ public class FilterContentValidator {
             }
             final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
             if (keyValue.isPresent()) {
-                keys.put(qName, keyValue.get());
+                final LeafSchemaNode listKey = (LeafSchemaNode) listSchemaNode.getDataChildByName(qName);
+                if (listKey instanceof IdentityrefTypeDefinition) {
+                    keys.put(qName, keyValue.get());
+                } else {
+                    if (listKey.getType() instanceof IdentityrefTypeDefinition) {
+                        final Document document = filterContent.getDomElement().getOwnerDocument();
+                        final NamespaceContext nsContext = new UniversalNamespaceContextImpl(document, false);
+                        final XmlCodecFactory xmlCodecFactory = XmlCodecFactory.create(schemaContext.getCurrentContext());
+                        final TypeAwareCodec identityrefTypeCodec = xmlCodecFactory.codecFor(listKey);
+                        final QName deserializedKey = (QName) identityrefTypeCodec.parseValue(nsContext, keyValue.get());
+                        keys.put(qName, deserializedKey);
+                    } else {
+                        final Object deserializedKey = TypeDefinitionAwareCodec.from(listKey.getType())
+                                .deserialize(keyValue.get());
+                        keys.put(qName, deserializedKey);
+                    }
+                }
             }
         }
         return keys;
diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/UniversalNamespaceContextImpl.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/get/UniversalNamespaceContextImpl.java
new file mode 100644 (file)
index 0000000..d092e96
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.netconf.mdsal.connector.ops.get;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+public class UniversalNamespaceContextImpl implements NamespaceContext {
+    private static final String DEFAULT_NS = "DEFAULT";
+    private final Map<String, String> prefix2Uri = new HashMap<>();
+    private final Map<String, String> uri2Prefix = new HashMap<>();
+
+    /**
+     * This constructor parses the document and stores all namespaces it can
+     * find. If toplevelOnly is true, only namespaces in the root are used.
+     *
+     * @param document     source document
+     * @param toplevelOnly restriction of the search to enhance performance
+     */
+    public UniversalNamespaceContextImpl(final Document document, final boolean toplevelOnly) {
+        readNode(document.getFirstChild(), toplevelOnly);
+    }
+
+    /**
+     * A single node is read, the namespace attributes are extracted and stored.
+     *
+     * @param node            to examine
+     * @param attributesOnly, if true no recursion happens
+     */
+    private void readNode(final Node node, final boolean attributesOnly) {
+        final NamedNodeMap attributes = node.getAttributes();
+        for (int i = 0; i < attributes.getLength(); i++) {
+            final Node attribute = attributes.item(i);
+            storeAttr((Attr) attribute);
+        }
+
+        if (!attributesOnly) {
+            final NodeList chields = node.getChildNodes();
+            for (int i = 0; i < chields.getLength(); i++) {
+                final Node chield = chields.item(i);
+                if (chield.getNodeType() == Node.ELEMENT_NODE)
+                    readNode(chield, false);
+            }
+        }
+    }
+
+    /**
+     * This method looks at an attribute and stores it, if it is a namespace
+     * attribute.
+     *
+     * @param attribute to examine
+     */
+    private void storeAttr(final Attr attribute) {
+        // examine the attributes in namespace xmlns
+        if (attribute.getNamespaceURI() != null
+                && attribute.getNamespaceURI().equals(
+                XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
+            // Default namespace xmlns="uri goes here"
+            if (attribute.getNodeName().equals(XMLConstants.XMLNS_ATTRIBUTE)) {
+                putInCache(DEFAULT_NS, attribute.getNodeValue());
+            } else {
+                // The defined prefixes are stored here
+                putInCache(attribute.getLocalName(), attribute.getNodeValue());
+            }
+        }
+
+    }
+
+    private void putInCache(final String prefix, final String uri) {
+        prefix2Uri.put(prefix, uri);
+        uri2Prefix.put(uri, prefix);
+    }
+
+    /**
+     * This method is called by XPath. It returns the default namespace, if the
+     * prefix is null or "".
+     *
+     * @param prefix to search for
+     * @return uri
+     */
+    public String getNamespaceURI(final String prefix) {
+        if (prefix == null || prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
+            return prefix2Uri.get(DEFAULT_NS);
+        } else {
+            return prefix2Uri.get(prefix);
+        }
+    }
+
+    /**
+     * This method is not needed in this context, but can be implemented in a
+     * similar way.
+     */
+    public String getPrefix(final String namespaceURI) {
+        return uri2Prefix.get(namespaceURI);
+    }
+
+    public Iterator getPrefixes(final String namespaceURI) {
+        // Not implemented
+        return null;
+    }
+
+}
\ No newline at end of file
diff --git a/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java b/netconf/mdsal-netconf-connector/src/test/java/org/opendaylight/netconf/mdsal/connector/ops/get/Bug8084.java
new file mode 100644 (file)
index 0000000..6a05108
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.netconf.mdsal.connector.ops.get;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import java.io.InputStream;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
+import org.w3c.dom.Document;
+
+public class Bug8084 {
+
+    private static final QName base = QName.create("urn:dummy:mod-0", "2016-03-01", "mainroot");
+
+    @Test
+    public void testValidateTypes() throws Exception {
+        final List<InputStream> sources = new ArrayList<>();
+        sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang"));
+        sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang"));
+        sources.add(getClass().getResourceAsStream("/yang/mdsal-netconf-mapping-test.yang"));
+        final SchemaContext context = YangParserTestUtils.parseYangStreams(sources);
+        final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
+        doReturn(context).when(currentContext).getCurrentContext();
+        final FilterContentValidator validator = new FilterContentValidator(currentContext);
+
+        final Document document = XmlUtil.readXmlToDocument(FilterContentValidatorTest.class
+                .getResourceAsStream("/filter/bug8084.xml"));
+
+        final XmlElement xmlElement = XmlElement.fromDomDocument(document);
+        final YangInstanceIdentifier actual = validator.validate(xmlElement);
+
+        final Map<QName, Object> inputs = new HashMap<>();
+        inputs.put(QName.create(base, "id1"), "aaa");
+        inputs.put(QName.create(base, "id2"), Byte.valueOf("-9"));
+        inputs.put(QName.create(base, "id3"), Short.valueOf("-30000"));
+        inputs.put(QName.create(base, "id4"), Integer.valueOf("-2000000000"));
+        inputs.put(QName.create(base, "id5"), Long.valueOf("-2000000000000000"));
+        inputs.put(QName.create(base, "id6"), Short.valueOf("9"));
+        inputs.put(QName.create(base, "id7"), Integer.valueOf("30000"));
+        inputs.put(QName.create(base, "id8"), Long.valueOf("2000000000"));
+        inputs.put(QName.create(base, "id9"), BigInteger.valueOf(Long.valueOf("2000000000000000")));
+        inputs.put(QName.create(base, "id10"), true);
+        inputs.put(QName.create(base, "id11"), BigDecimal.valueOf(128.55));
+        inputs.put(QName.create(base, "id12"), QName.create(base, "foo"));
+        inputs.put(QName.create(base, "id13"), QName.create("urn:opendaylight:mdsal:mapping:test", "2015-02-26", "foo"));
+        final QName idActual = (QName) ((YangInstanceIdentifier.NodeIdentifierWithPredicates) actual.getLastPathArgument()).
+                getKeyValues().get(QName.create(base, "id12"));
+
+
+        final YangInstanceIdentifier expected = YangInstanceIdentifier.builder()
+                .node(base)
+                .node(QName.create(base, "multi-key-list2"))
+                .nodeWithKey(QName.create(base, "multi-key-list2"), inputs)
+                .build();
+        final QName idExpected = (QName) ((YangInstanceIdentifier.NodeIdentifierWithPredicates) expected.getLastPathArgument()).
+                getKeyValues().get(QName.create(base, "id12"));
+        assertEquals(idExpected, idActual);
+        assertEquals(expected, actual);
+
+    }
+}
index c3656cfd4c4dcc9de769eb7285bd74290e950af9..223f5625e12b190ed460eeec43d0f25d9e97345e 100644 (file)
@@ -78,6 +78,7 @@ public class FilterContentValidatorTest {
         final List<InputStream> sources = new ArrayList<>();
         sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang"));
         sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang"));
+        sources.add(getClass().getResourceAsStream("/yang/mdsal-netconf-mapping-test.yang"));
         final SchemaContext context = YangParserTestUtils.parseYangStreams(sources);
         final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
         doReturn(context).when(currentContext).getCurrentContext();
diff --git a/netconf/mdsal-netconf-connector/src/test/resources/filter/bug8084.xml b/netconf/mdsal-netconf-connector/src/test/resources/filter/bug8084.xml
new file mode 100644 (file)
index 0000000..482db1a
--- /dev/null
@@ -0,0 +1,25 @@
+<!--
+  ~ Copyright (c) 2017 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
+  -->
+
+<mainroot xmlns="urn:dummy:mod-0">
+    <multi-key-list2>
+        <id1>aaa</id1>
+        <id2>-9</id2>
+        <id3>-30000</id3>
+        <id4>-2000000000</id4>
+        <id5>-2000000000000000</id5>
+        <id6>9</id6>
+        <id7>30000</id7>
+        <id8>2000000000</id8>
+        <id9>2000000000000000</id9>
+        <id10>true</id10>
+        <id11>128.55</id11>
+        <id12>foo</id12>
+        <id13 xmlns:map-test="urn:opendaylight:mdsal:mapping:test">map-test:foo</id13>
+    </multi-key-list2>
+</mainroot>
\ No newline at end of file
index a012a53410d69a8a9131eb57e10a167cbfdc8bbb..9b62160274d6c868d757b7250720407d22a70f89 100644 (file)
@@ -2,6 +2,16 @@ module filter-validator-test-mod-0 {
     namespace "urn:dummy:mod-0";
     prefix "mod-0";
     revision "2016-03-01";
+
+    import config {
+        prefix map-test;
+        revision-date "2015-02-26";
+    }
+
+    identity foo {
+        description "dummy identity";
+    }
+
     container mainroot {
         leaf maincontent {
             mandatory true;
@@ -48,5 +58,54 @@ module filter-validator-test-mod-0 {
                 type string;
             }
         }
+
+        list multi-key-list2 {
+            key "id1 id2 id3 id4 id5 id6 id7 id8 id9 id10 id11 id12 id13";
+            leaf id1 {
+                type string;
+            }
+            leaf id2 {
+                type int8;
+            }
+            leaf id3 {
+                type int16;
+            }
+            leaf id4 {
+                type int32;
+            }
+            leaf id5 {
+                type int64;
+            }
+            leaf id6 {
+                type uint8;
+            }
+            leaf id7 {
+                type uint16;
+            }
+            leaf id8 {
+                type uint32;
+            }
+            leaf id9 {
+                type uint64;
+            }
+            leaf id10 {
+                type boolean;
+            }
+            leaf id11 {
+                type decimal64{
+                    fraction-digits 2;
+                }
+            }
+            leaf id12 {
+                type identityref {
+                    base "foo";
+                }
+            }
+            leaf id13 {
+                type identityref {
+                    base "map-test:foo";
+                }
+            }
+        }
     }
 }
\ No newline at end of file
index 50c975e0b37efccd7cab639b4c10d319ed19329d..d338ac3e07fa044bb09a9248e4fb5e123debced8 100644 (file)
@@ -5,6 +5,9 @@ module config {
 
     revision "2015-02-26";
 
+    identity foo {
+            description "dummy identity";
+    }
     container mapping-nodes {
 
         list multiple-keys {
index d5876e69caf1f1f46876dc42e15192b5235a360f..b38ee885e41a39c92a76ef88606cb3ca38aba866 100644 (file)
@@ -93,4 +93,16 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
             <artifactId>hamcrest-core</artifactId>
         </dependency>
     </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+                <configuration>
+                    <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
 </project>
index cf340c60fe987764e67f2817d716cf661b40f469..3e6573d2438cca9e7b0ae53c3075d0eb53bc0c54 100644 (file)
@@ -39,18 +39,18 @@ class ConnectionNotificationTopicRegistration extends NotificationTopicRegistrat
     private static final Logger LOG = LoggerFactory.getLogger(ConnectionNotificationTopicRegistration.class);
 
     public static final SchemaPath EVENT_SOURCE_STATUS_PATH = SchemaPath
-        .create(true, QName.create(EventSourceStatusNotification.QNAME, "event-source-status"));
+            .create(true, QName.create(EventSourceStatusNotification.QNAME, "event-source-status"));
     private static final NodeIdentifier EVENT_SOURCE_STATUS_ARG = NodeIdentifier.create(
-        EventSourceStatusNotification.QNAME);
+            EventSourceStatusNotification.QNAME);
     private static final String XMLNS_ATTRIBUTE_KEY = "xmlns";
     private static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
 
     private final DOMNotificationListener domNotificationListener;
 
-    public ConnectionNotificationTopicRegistration(final String SourceName,
-            final DOMNotificationListener domNotificationListener) {
-        super(NotificationSourceType.ConnectionStatusChange, SourceName,
-            EVENT_SOURCE_STATUS_PATH.getLastComponent().getNamespace().toString());
+    ConnectionNotificationTopicRegistration(final String sourceName,
+                                            final DOMNotificationListener domNotificationListener) {
+        super(NotificationSourceType.ConnectionStatusChange, sourceName,
+                EVENT_SOURCE_STATUS_PATH.getLastComponent().getNamespace().toString());
         this.domNotificationListener = Preconditions.checkNotNull(domNotificationListener);
         LOG.info("Connection notification source has been initialized.");
         setActive(true);
@@ -117,20 +117,22 @@ class ConnectionNotificationTopicRegistration extends NotificationTopicRegistrat
     private void publishNotification(final EventSourceStatus eventSourceStatus) {
 
         final EventSourceStatusNotification notification = new EventSourceStatusNotificationBuilder()
-            .setStatus(eventSourceStatus).build();
+                .setStatus(eventSourceStatus).build();
         domNotificationListener.onNotification(createNotification(notification));
     }
 
     private static DOMNotification createNotification(final EventSourceStatusNotification notification) {
         final ContainerNode cn = Builders.containerBuilder().withNodeIdentifier(EVENT_SOURCE_STATUS_ARG)
-            .withChild(encapsulate(notification)).build();
+                .withChild(encapsulate(notification)).build();
         DOMNotification dn = new DOMNotification() {
 
-            @Override public SchemaPath getType() {
+            @Override
+            public SchemaPath getType() {
                 return EVENT_SOURCE_STATUS_PATH;
             }
 
-            @Override public ContainerNode getBody() {
+            @Override
+            public ContainerNode getBody() {
                 return cn;
             }
         };
@@ -148,14 +150,14 @@ class ConnectionNotificationTopicRegistration extends NotificationTopicRegistrat
         rootElement.appendChild(sourceElement);
 
         return Builders.anyXmlBuilder().withNodeIdentifier(EVENT_SOURCE_STATUS_ARG)
-            .withValue(new DOMSource(rootElement)).build();
+                .withValue(new DOMSource(rootElement)).build();
     }
 
     // Helper to create root XML element with correct namespace and attribute
-    private static Element createElement(final Document document, final String qName,
-            final Optional<String> namespaceURI) {
+    private static Element createElement(final Document document, final String qualifiedName,
+                                         final Optional<String> namespaceURI) {
         if (namespaceURI.isPresent()) {
-            final Element element = document.createElementNS(namespaceURI.get(), qName);
+            final Element element = document.createElementNS(namespaceURI.get(), qualifiedName);
             String name = XMLNS_ATTRIBUTE_KEY;
             if (element.getPrefix() != null) {
                 name += ":" + element.getPrefix();
@@ -163,6 +165,6 @@ class ConnectionNotificationTopicRegistration extends NotificationTopicRegistrat
             element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
             return element;
         }
-        return document.createElement(qName);
+        return document.createElement(qualifiedName);
     }
 }
index 31246bbea019fc6e4cc0f52261384acf55232d9a..347278c30135ce6f106e4e81c891a8e344d34168 100644 (file)
@@ -78,30 +78,34 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
 
     private static final NodeIdentifier TOPIC_NOTIFICATION_ARG = NodeIdentifier.create(TopicNotification.QNAME);
     private static final NodeIdentifier EVENT_SOURCE_ARG = NodeIdentifier.create(
-        QName.create(TopicNotification.QNAME, "node-id"));
+            QName.create(TopicNotification.QNAME, "node-id"));
     private static final NodeIdentifier TOPIC_ID_ARG = NodeIdentifier.create(
-        QName.create(TopicNotification.QNAME, "topic-id"));
+            QName.create(TopicNotification.QNAME, "topic-id"));
     private static final NodeIdentifier PAYLOAD_ARG = NodeIdentifier.create(
-        QName.create(TopicNotification.QNAME, "payload"));
-    private static final String ConnectionNotificationSourceName = "ConnectionNotificationSource";
+            QName.create(TopicNotification.QNAME, "payload"));
+    private static final String CONNECTION_NOTIFICATION_SOURCE_NAME = "ConnectionNotificationSource";
 
     private final DOMNotificationPublishService domPublish;
 
     private final Map<String, String> urnPrefixToStreamMap; // key = urnPrefix, value = StreamName
 
     /**
-     * Map notification uri -> registrations
+     * Map notification uri -> registrations.
      */
     private final Multimap<String, NotificationTopicRegistration>
             notificationTopicRegistrations = Multimaps.synchronizedListMultimap(ArrayListMultimap.create());
     private final NetconfEventSourceMount mount;
 
     /**
-     * Creates new NetconfEventSource for node. Topic notifications will be published via provided {@link DOMNotificationPublishService}
-     * @param streamMap netconf streams from device
+     * Creates new NetconfEventSource for node. Topic notifications will be published via provided
+     * {@link DOMNotificationPublishService}
+     *
+     * @param streamMap      netconf streams from device
      * @param publishService publish service
      */
-    public NetconfEventSource(final Map<String, String> streamMap, NetconfEventSourceMount mount, final DOMNotificationPublishService publishService) {
+    public NetconfEventSource(final Map<String, String> streamMap,
+                              final NetconfEventSourceMount mount,
+                              final DOMNotificationPublishService publishService) {
         this.mount = mount;
         this.urnPrefixToStreamMap = Preconditions.checkNotNull(streamMap);
         this.domPublish = Preconditions.checkNotNull(publishService);
@@ -115,9 +119,10 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
      * {@link StreamNotificationTopicRegistration} for every prefix and available stream as defined in config file.
      */
     private void initializeNotificationTopicRegistrationList() {
-        final ConnectionNotificationTopicRegistration cntr = new ConnectionNotificationTopicRegistration(ConnectionNotificationSourceName, this);
+        final ConnectionNotificationTopicRegistration cntr =
+                new ConnectionNotificationTopicRegistration(CONNECTION_NOTIFICATION_SOURCE_NAME, this);
         notificationTopicRegistrations
-            .put(cntr.getNotificationUrnPrefix(), cntr);
+                .put(cntr.getNotificationUrnPrefix(), cntr);
         Map<String, Stream> availableStreams = getAvailableStreams();
         LOG.debug("Stream configuration compare...");
         for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
@@ -126,7 +131,8 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
             if (availableStreams.containsKey(streamName)) {
                 LOG.debug("Stream containig on device");
                 notificationTopicRegistrations
-                    .put(urnPrefix, new StreamNotificationTopicRegistration(availableStreams.get(streamName), urnPrefix, this));
+                        .put(urnPrefix, new StreamNotificationTopicRegistration(availableStreams.get(streamName),
+                                urnPrefix, this));
             }
         }
     }
@@ -149,7 +155,8 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
         return streamMap;
     }
 
-    @Override public Future<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) {
+    @Override
+    public Future<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) {
         LOG.debug("Join topic {} on {}", input.getTopicId().getValue(), mount.getNodeId());
         final NotificationPattern notificationPattern = input.getNotificationPattern();
         final List<SchemaPath> matchingNotifications = getMatchingNotifications(notificationPattern);
@@ -157,15 +164,17 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
 
     }
 
-    @Override public Future<RpcResult<Void>> disJoinTopic(DisJoinTopicInput input) {
+    @Override
+    public Future<RpcResult<Void>> disJoinTopic(DisJoinTopicInput input) {
         for (NotificationTopicRegistration reg : notificationTopicRegistrations.values()) {
             reg.unRegisterNotificationTopic(input.getTopicId());
         }
         return Util.resultRpcSuccessFor((Void) null);
     }
 
-    private synchronized Future<RpcResult<JoinTopicOutput>> registerTopic(final TopicId topicId,
-        final List<SchemaPath> notificationsToSubscribe) {
+    private synchronized Future<RpcResult<JoinTopicOutput>> registerTopic(
+            final TopicId topicId,
+            final List<SchemaPath> notificationsToSubscribe) {
         Preconditions.checkNotNull(notificationsToSubscribe);
         LOG.debug("Join topic {} - register", topicId);
         JoinTopicStatus joinTopicStatus = JoinTopicStatus.Down;
@@ -206,7 +215,8 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
         }
     }
 
-    @Override public void onNotification(final DOMNotification notification) {
+    @Override
+    public void onNotification(final DOMNotification notification) {
         SchemaPath notificationPath = notification.getType();
         Date notificationEventTime = null;
         if (notification instanceof DOMEvent) {
@@ -219,16 +229,17 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
             for (TopicId topicId : topicIdsForNotification) {
                 publishNotification(notification, topicId);
                 LOG.debug("Notification {} has been published for TopicId {}", notification.getType(),
-                    topicId.getValue());
+                        topicId.getValue());
             }
         }
     }
 
     private void publishNotification(final DOMNotification notification, TopicId topicId) {
         final ContainerNode topicNotification = Builders.containerBuilder().withNodeIdentifier(TOPIC_NOTIFICATION_ARG)
-            .withChild(ImmutableNodes.leafNode(TOPIC_ID_ARG, topicId))
-            .withChild(ImmutableNodes.leafNode(EVENT_SOURCE_ARG, mount.getNodeId())).withChild(encapsulate(notification))
-            .build();
+                .withChild(ImmutableNodes.leafNode(TOPIC_ID_ARG, topicId))
+                .withChild(ImmutableNodes.leafNode(EVENT_SOURCE_ARG, mount.getNodeId()))
+                .withChild(encapsulate(notification))
+                .build();
         try {
             domPublish.putNotification(new TopicDOMNotification(topicNotification));
         } catch (final InterruptedException e) {
@@ -257,6 +268,7 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
 
     /**
      * Returns all available notification paths that matches given pattern.
+     *
      * @param notificationPattern pattern
      * @return notification paths
      */
@@ -268,24 +280,27 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener
         return Util.expandQname(availableNotifications, pattern);
     }
 
-    @Override public void close() throws Exception {
+    @Override
+    public void close() throws Exception {
         for (NotificationTopicRegistration streamReg : notificationTopicRegistrations.values()) {
             streamReg.close();
         }
     }
 
-    @Override public NodeKey getSourceNodeKey() {
+    @Override
+    public NodeKey getSourceNodeKey() {
         return mount.getNode().getKey();
     }
 
-    @Override public List<SchemaPath> getAvailableNotifications() {
+    @Override
+    public List<SchemaPath> getAvailableNotifications() {
 
         final List<SchemaPath> availNotifList = new ArrayList<>();
         // add Event Source Connection status notification
         availNotifList.add(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
 
         final Set<NotificationDefinition> availableNotifications = mount.getSchemaContext()
-            .getNotifications();
+                .getNotifications();
         // add all known notifications from netconf device
         for (final NotificationDefinition nd : availableNotifications) {
             availNotifList.add(nd.getPath());
index cdbd8d4e4386dba9cb104a74744073be57ccac46..516c595ef7e98a8e3f17d97100e6cb5088180d0d 100644 (file)
@@ -40,12 +40,13 @@ public final class NetconfEventSourceManager implements DataChangeListener, Auto
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSourceManager.class);
     private static final TopologyKey NETCONF_TOPOLOGY_KEY = new TopologyKey(
-        new TopologyId(TopologyNetconf.QNAME.getLocalName()));
+            new TopologyId(TopologyNetconf.QNAME.getLocalName()));
     private static final InstanceIdentifier<Node> NETCONF_DEVICE_PATH = InstanceIdentifier.create(NetworkTopology.class)
-        .child(Topology.class, NETCONF_TOPOLOGY_KEY).child(Node.class);
+            .child(Topology.class, NETCONF_TOPOLOGY_KEY).child(Node.class);
 
     private Map<String, String> streamMap;
-    private final ConcurrentHashMap<InstanceIdentifier<?>, NetconfEventSourceRegistration> registrationMap = new ConcurrentHashMap<>();
+    private final ConcurrentHashMap<InstanceIdentifier<?>, NetconfEventSourceRegistration> registrationMap =
+            new ConcurrentHashMap<>();
     private final DOMNotificationPublishService publishService;
     private final DOMMountPointService domMounts;
     private ListenerRegistration<DataChangeListener> listenerRegistration;
@@ -67,17 +68,18 @@ public final class NetconfEventSourceManager implements DataChangeListener, Auto
     }
 
     /**
-     * Invoke by blueprint
+     * Invoked by blueprint.
      */
     public void initialize() {
         Preconditions.checkNotNull(dataBroker);
         listenerRegistration = dataBroker
-            .registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, NETCONF_DEVICE_PATH, this,
-                DataChangeScope.SUBTREE);
+                .registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, NETCONF_DEVICE_PATH, this,
+                        DataChangeScope.SUBTREE);
         LOG.info("NetconfEventSourceManager initialized.");
     }
 
-    @Override public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event) {
+    @Override
+    public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event) {
 
         LOG.debug("[DataChangeEvent<InstanceIdentifier<?>, DataObject>: {}]", event);
         for (final Map.Entry<InstanceIdentifier<?>, DataObject> changeEntry : event.getCreatedData().entrySet()) {
@@ -166,8 +168,9 @@ public final class NetconfEventSourceManager implements DataChangeListener, Auto
     }
 
     /**
-     * Invoke by blueprint
-     * @param streamMap
+     * Invoked by blueprint.
+     *
+     * @param streamMap Stream map
      */
     public void setStreamMap(Map<String, String> streamMap) {
         this.streamMap = streamMap;
@@ -177,7 +180,8 @@ public final class NetconfEventSourceManager implements DataChangeListener, Auto
         return node.getAugmentation(NetconfNode.class) != null;
     }
 
-    @Override public void close() {
+    @Override
+    public void close() {
         listenerRegistration.close();
         for (final NetconfEventSourceRegistration reg : registrationMap.values()) {
             reg.close();
index 1701afea5331b84414f37d7d6069cca007b7f191..0524bdfbc62a7866f29bd98eb3d8b6da2e328322 100644 (file)
@@ -49,25 +49,28 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 
 /**
- * Facade of mounted netconf device
+ * Facade of mounted netconf device.
  */
 class NetconfEventSourceMount {
 
     private static final BindingNormalizedNodeCodecRegistry CODEC_REGISTRY;
-    private static final YangInstanceIdentifier STREAMS_PATH = YangInstanceIdentifier.builder().node(Netconf.QNAME).node(Streams.QNAME).build();
+    private static final YangInstanceIdentifier STREAMS_PATH = YangInstanceIdentifier.builder().node(Netconf.QNAME)
+            .node(Streams.QNAME).build();
     private static final SchemaPath CREATE_SUBSCRIPTION = SchemaPath
             .create(true, QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
 
-    static{
+    static {
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-        moduleInfoBackedContext.addModuleInfos(Collections.singletonList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.$YangModuleInfoImpl.getInstance()));
+        moduleInfoBackedContext.addModuleInfos(Collections.singletonList(org.opendaylight.yang.gen.v1.urn.ietf.params
+                .xml.ns.netmod.notification.rev080714.$YangModuleInfoImpl.getInstance()));
         final Optional<SchemaContext> schemaContextOptional = moduleInfoBackedContext.tryToCreateSchemaContext();
         Preconditions.checkState(schemaContextOptional.isPresent());
-        SchemaContext NOTIFICATIONS_SCHEMA_CTX = schemaContextOptional.get();
+        SchemaContext notificationsSchemaCtx = schemaContextOptional.get();
 
         final JavassistUtils javassist = JavassistUtils.forClassPool(ClassPool.getDefault());
         CODEC_REGISTRY = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(javassist));
-        CODEC_REGISTRY.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, NOTIFICATIONS_SCHEMA_CTX));
+        CODEC_REGISTRY.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext,
+                notificationsSchemaCtx));
     }
 
     private final DOMMountPoint mountPoint;
@@ -77,7 +80,7 @@ class NetconfEventSourceMount {
     private final Node node;
     private final String nodeId;
 
-    public NetconfEventSourceMount(final Node node, final DOMMountPoint mountPoint) {
+    NetconfEventSourceMount(final Node node, final DOMMountPoint mountPoint) {
         this.mountPoint = mountPoint;
         this.node = node;
         this.nodeId = node.getNodeId().getValue();
@@ -101,16 +104,19 @@ class NetconfEventSourceMount {
     }
 
     /**
-     * Invokes create-subscription rpc on mounted device stream. If lastEventTime is provided and stream supports replay,
+     * Invokes create-subscription rpc on mounted device stream. If lastEventTime is provided and stream supports
+     * replay,
      * rpc will be invoked with start time parameter.
-     * @param stream stream
+     *
+     * @param stream        stream
      * @param lastEventTime last event time
      * @return rpc result
      */
-    CheckedFuture<DOMRpcResult, DOMRpcException> invokeCreateSubscription(final Stream stream, final Optional<Date> lastEventTime) {
+    CheckedFuture<DOMRpcResult, DOMRpcException> invokeCreateSubscription(final Stream stream,
+                                                                          final Optional<Date> lastEventTime) {
         final CreateSubscriptionInputBuilder inputBuilder = new CreateSubscriptionInputBuilder()
                 .setStream(stream.getName());
-        if(lastEventTime.isPresent() && stream.isReplaySupport()) {
+        if (lastEventTime.isPresent() && stream.isReplaySupport()) {
             final ZonedDateTime dateTime = lastEventTime.get().toInstant().atZone(ZoneId.systemDefault());
             final String formattedDate = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(dateTime);
             inputBuilder.setStartTime(new DateAndTime(formattedDate));
@@ -122,6 +128,7 @@ class NetconfEventSourceMount {
 
     /**
      * Invokes create-subscription rpc on mounted device stream.
+     *
      * @param stream stream
      * @return rpc result
      */
@@ -130,7 +137,8 @@ class NetconfEventSourceMount {
     }
 
     /**
-     * Returns list of streams avaliable on device
+     * Returns list of streams avaliable on device.
+     *
      * @return list of streams
      * @throws ReadFailedException if data read fails
      */
@@ -140,8 +148,8 @@ class NetconfEventSourceMount {
                 .read(LogicalDatastoreType.OPERATIONAL, STREAMS_PATH);
         Optional<NormalizedNode<?, ?>> streams = checkFeature.checkedGet();
         if (streams.isPresent()) {
-            Streams s = (Streams) CODEC_REGISTRY.fromNormalizedNode(STREAMS_PATH, streams.get()).getValue();
-            return s.getStream();
+            Streams streams1 = (Streams) CODEC_REGISTRY.fromNormalizedNode(STREAMS_PATH, streams.get()).getValue();
+            return streams1.getStream();
         }
         return Collections.emptyList();
     }
@@ -152,12 +160,14 @@ class NetconfEventSourceMount {
 
     /**
      * Registers notification listener to receive a set of notifications.
-     * @see DOMNotificationService#registerNotificationListener(DOMNotificationListener, SchemaPath...)
-     * @param listener listener
+     *
+     * @param listener         listener
      * @param notificationPath notification path
-     * @return
+     * @return ListenerRegistration
+     * @see DOMNotificationService#registerNotificationListener(DOMNotificationListener, SchemaPath...)
      */
-    ListenerRegistration<DOMNotificationListener> registerNotificationListener(DOMNotificationListener listener, SchemaPath notificationPath) {
+    ListenerRegistration<DOMNotificationListener> registerNotificationListener(DOMNotificationListener listener,
+                                                                               SchemaPath notificationPath) {
         return notificationService.registerNotificationListener(listener, notificationPath);
     }
 
index c667976989922feccb06fc57c9c28ff5ac8b81f9..9089e92ee1ab999298f58200a88ccf7bb7876a51 100644 (file)
@@ -27,17 +27,18 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Helper class to keep connection status of netconf node  and event source registration object
+ * Helper class to keep connection status of netconf node  and event source registration object.
  */
 public class NetconfEventSourceRegistration implements AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSourceRegistration.class);
     private static final YangInstanceIdentifier NETCONF_DEVICE_DOM_PATH = YangInstanceIdentifier.builder()
-        .node(NetworkTopology.QNAME).node(Topology.QNAME)
-        .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME.getLocalName())
-        .node(Node.QNAME).build();
+            .node(NetworkTopology.QNAME).node(Topology.QNAME)
+            .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME
+                    .getLocalName())
+            .node(Node.QNAME).build();
     private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "node-id");
-    private static final String NotificationCapabilityPrefix = "(urn:ietf:params:xml:ns:netconf:notification";
+    private static final String NOTIFICATION_CAPABILITY_PREFIX = "(urn:ietf:params:xml:ns:netconf:notification";
 
     private final Node node;
     private final NetconfEventSourceManager netconfEventSourceManager;
@@ -45,7 +46,7 @@ public class NetconfEventSourceRegistration implements AutoCloseable {
     private EventSourceRegistration<NetconfEventSource> eventSourceRegistration;
 
     public static NetconfEventSourceRegistration create(final InstanceIdentifier<?> instanceIdent, final Node node,
-        final NetconfEventSourceManager netconfEventSourceManager) {
+                                                        final NetconfEventSourceManager netconfEventSourceManager) {
         Preconditions.checkNotNull(instanceIdent);
         Preconditions.checkNotNull(node);
         Preconditions.checkNotNull(netconfEventSourceManager);
@@ -71,7 +72,7 @@ public class NetconfEventSourceRegistration implements AutoCloseable {
             return false;
         }
         for (final AvailableCapability capability : netconfNode.getAvailableCapabilities().getAvailableCapability()) {
-            if (capability.getCapability().startsWith(NotificationCapabilityPrefix)) {
+            if (capability.getCapability().startsWith(NOTIFICATION_CAPABILITY_PREFIX)) {
                 return true;
             }
         }
@@ -140,14 +141,14 @@ public class NetconfEventSourceRegistration implements AutoCloseable {
 
     private void registrationEventSource() {
         final Optional<DOMMountPoint> domMountPoint = netconfEventSourceManager.getDomMounts()
-            .getMountPoint(domMountPath(node.getNodeId()));
+                .getMountPoint(domMountPath(node.getNodeId()));
         EventSourceRegistration<NetconfEventSource> registration = null;
         if (domMountPoint.isPresent()/* && mountPoint.isPresent()*/) {
             NetconfEventSourceMount mount = new NetconfEventSourceMount(node, domMountPoint.get());
             final NetconfEventSource netconfEventSource = new NetconfEventSource(
-                netconfEventSourceManager.getStreamMap(),
+                    netconfEventSourceManager.getStreamMap(),
                     mount,
-                netconfEventSourceManager.getPublishService());
+                    netconfEventSourceManager.getPublishService());
             registration = netconfEventSourceManager.getEventSourceRegistry().registerEventSource(netconfEventSource);
             LOG.info("Event source {} has been registered", node.getNodeId().getValue());
         }
@@ -156,7 +157,7 @@ public class NetconfEventSourceRegistration implements AutoCloseable {
 
     private YangInstanceIdentifier domMountPath(final NodeId nodeId) {
         return YangInstanceIdentifier.builder(NETCONF_DEVICE_DOM_PATH)
-            .nodeWithKey(Node.QNAME, NODE_ID_QNAME, nodeId.getValue()).build();
+                .nodeWithKey(Node.QNAME, NODE_ID_QNAME, nodeId.getValue()).build();
     }
 
     private void closeEventSourceRegistration() {
@@ -165,7 +166,8 @@ public class NetconfEventSourceRegistration implements AutoCloseable {
         }
     }
 
-    @Override public void close() {
+    @Override
+    public void close() {
         closeEventSourceRegistration();
     }
 
index b7bfda343277fbb95500912e591c6b16afbb501d..d10ce66249f73cedcc961b9516c22b9a69fd2534 100644 (file)
@@ -38,7 +38,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable {
     protected final ConcurrentHashMap<SchemaPath, Set<TopicId>> notificationTopicMap = new ConcurrentHashMap<>();
 
     protected NotificationTopicRegistration(NotificationSourceType notificationSourceType, String sourceName,
-        String notificationUrnPrefix) {
+                                            String notificationUrnPrefix) {
         this.notificationSourceType = notificationSourceType;
         this.sourceName = sourceName;
         this.notificationUrnPrefix = notificationUrnPrefix;
@@ -68,6 +68,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable {
 
     /**
      * Returns registered topics for given notification path.
+     *
      * @param notificationPath path
      * @return topicIds
      */
@@ -78,6 +79,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable {
 
     /**
      * Checks, if notification is from namespace belonging to this registration.
+     *
      * @param notificationPath path
      * @return true, if notification belongs to registration namespace
      */
@@ -87,7 +89,7 @@ abstract class NotificationTopicRegistration implements AutoCloseable {
         }
         String nameSpace = notificationPath.getLastComponent().getNamespace().toString();
         LOG.debug("CheckNotification - name space {} - NotificationUrnPrefix {}", nameSpace,
-            getNotificationUrnPrefix());
+                getNotificationUrnPrefix());
         return nameSpace.startsWith(getNotificationUrnPrefix());
     }
 
@@ -107,14 +109,16 @@ abstract class NotificationTopicRegistration implements AutoCloseable {
 
     /**
      * Registers associated event source notification to topic.
+     *
      * @param notificationPath notification path
-     * @param topicId topic id
+     * @param topicId          topic id
      * @return true, if successful
      */
     abstract boolean registerNotificationTopic(SchemaPath notificationPath, TopicId topicId);
 
     /**
      * Registers associated event source notification to topic.
+     *
      * @param topicId topic id
      * @return true, if successful
      */
index d163a777cd820a38582af4736d2b6a1da4f63b24..a77dbdc2e13b9a2fafe45b8d31a90b510209ec1e 100644 (file)
@@ -32,17 +32,19 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
     private final String nodeId;
     private final NetconfEventSource netconfEventSource;
     private final NetconfEventSourceMount mountPoint;
-    private final ConcurrentHashMap<SchemaPath, ListenerRegistration<DOMNotificationListener>> notificationRegistrationMap = new ConcurrentHashMap<>();
+    private final ConcurrentHashMap<SchemaPath, ListenerRegistration<DOMNotificationListener>>
+            notificationRegistrationMap = new ConcurrentHashMap<>();
     private final Stream stream;
 
     /**
      * Creates registration to notification stream.
-     * @param stream stream
+     *
+     * @param stream             stream
      * @param notificationPrefix notifications namespace
      * @param netconfEventSource event source
      */
-    public StreamNotificationTopicRegistration(final Stream stream, final String notificationPrefix,
-        NetconfEventSource netconfEventSource) {
+    StreamNotificationTopicRegistration(final Stream stream, final String notificationPrefix,
+                                        NetconfEventSource netconfEventSource) {
         super(NotificationSourceType.NetconfDeviceStream, stream.getName().getValue(), notificationPrefix);
         this.netconfEventSource = netconfEventSource;
         this.mountPoint = netconfEventSource.getMount();
@@ -73,7 +75,8 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
     }
 
     /**
-     * Subscribes to notification stream associated with this registration. If replay is supported, notifications from last
+     * Subscribes to notification stream associated with this registration. If replay is supported, notifications
+     * from last
      * received event time will be requested.
      */
     void reActivateNotificationSource() {
@@ -91,7 +94,8 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
         }
     }
 
-    @Override void deActivateNotificationSource() {
+    @Override
+    void deActivateNotificationSource() {
         // no operations need
     }
 
@@ -110,7 +114,8 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
         return getSourceName();
     }
 
-    @Override boolean registerNotificationTopic(SchemaPath notificationPath, TopicId topicId) {
+    @Override
+    boolean registerNotificationTopic(SchemaPath notificationPath, TopicId topicId) {
         if (!checkNotificationPath(notificationPath)) {
             LOG.debug("Bad SchemaPath for notification try to register");
             return false;
@@ -119,11 +124,12 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
         activateNotificationSource();
         if (!isActive()) {
             LOG.warn("Stream {} is not active, listener for notification {} is not registered.", getStreamName(),
-                notificationPath.toString());
+                    notificationPath.toString());
             return false;
         }
 
-        ListenerRegistration<DOMNotificationListener> registration = mountPoint.registerNotificationListener(netconfEventSource, notificationPath);
+        ListenerRegistration<DOMNotificationListener> registration =
+                mountPoint.registerNotificationListener(netconfEventSource, notificationPath);
         notificationRegistrationMap.put(notificationPath, registration);
         Set<TopicId> topicIds = getTopicsForNotification(notificationPath);
         topicIds.add(topicId);
@@ -132,7 +138,8 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
         return true;
     }
 
-    @Override synchronized void unRegisterNotificationTopic(TopicId topicId) {
+    @Override
+    synchronized void unRegisterNotificationTopic(TopicId topicId) {
         List<SchemaPath> notificationPathToRemove = new ArrayList<>();
         for (SchemaPath notifKey : notificationTopicMap.keySet()) {
             Set<TopicId> topicList = notificationTopicMap.get(notifKey);
@@ -152,7 +159,8 @@ class StreamNotificationTopicRegistration extends NotificationTopicRegistration
         }
     }
 
-    @Override public void close() throws Exception {
+    @Override
+    public void close() throws Exception {
         closeStream();
     }
 
index a19f13028e866724aab2d873bf921d736bba0b52..5d3669aa0540f5a46edc21c6a4f353d53e29823e 100644 (file)
@@ -71,12 +71,14 @@ public class ConnectionNotificationTopicRegistrationTest {
         final TopicId topic1 = registerTopic("topic1");
         final TopicId topic2 = registerTopic("topic2");
         final TopicId topic3 = registerTopic("topic3");
-        final Set<TopicId> notificationTopicIds = registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
+        final Set<TopicId> notificationTopicIds =
+                registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
         Assert.assertNotNull(notificationTopicIds);
         Assert.assertThat(notificationTopicIds, hasItems(topic1, topic2, topic3));
 
         registration.unRegisterNotificationTopic(topic3);
-        final Set<TopicId> afterUnregister = registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
+        final Set<TopicId> afterUnregister =
+                registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
         Assert.assertNotNull(afterUnregister);
         Assert.assertThat(afterUnregister, hasItems(topic1, topic2));
         Assert.assertFalse(afterUnregister.contains(topic3));
@@ -91,15 +93,17 @@ public class ConnectionNotificationTopicRegistrationTest {
 
     /**
      * Checks status node of notification received by listener.
+     *
      * @param listener listener
-     * @param status expected value
+     * @param status   expected value
      */
     private static void checkStatus(DOMNotificationListener listener, EventSourceStatus status) {
         ArgumentCaptor<DOMNotification> notificationCaptor = ArgumentCaptor.forClass(DOMNotification.class);
         verify(listener).onNotification(notificationCaptor.capture());
         final DOMNotification value = notificationCaptor.getValue();
         Assert.assertEquals(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH, value.getType());
-        final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> body = value.getBody().getValue();
+        final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> body = value.getBody()
+                .getValue();
         Assert.assertEquals(1, body.size());
         final DOMSource source = (DOMSource) body.iterator().next().getValue();
         final String statusNodeValue = source.getNode().getFirstChild().getFirstChild().getNodeValue();
index 13b855107d8d9a7ef9c2e2f95668e1c485e86600..6d9938cdc81f8f9674bacde70e4aca23786b4ddd 100644 (file)
@@ -66,30 +66,36 @@ public class NetconfEventSourceManagerTest {
 
     @Before
     public void setUp() throws Exception {
-        DataBroker dataBrokerMock = mock(DataBroker.class);
-        DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
+        final DataBroker dataBrokerMock = mock(DataBroker.class);
+        final DOMNotificationPublishService domNotificationPublishServiceMock =
+                mock(DOMNotificationPublishService.class);
         domMountPointServiceMock = mock(DOMMountPointService.class);
         eventSourceTopologyMock = mock(EventSourceRegistry.class);
         rpcProviderRegistryMock = mock(RpcProviderRegistry.class);
         eventSourceRegistry = mock(EventSourceRegistry.class);
 
         listenerRegistrationMock = mock(ListenerRegistration.class);
-        doReturn(listenerRegistrationMock).when(dataBrokerMock).registerDataChangeListener(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(NetconfEventSourceManager.class), eq(
-            AsyncDataBroker.DataChangeScope.SUBTREE));
+        doReturn(listenerRegistrationMock).when(dataBrokerMock).registerDataChangeListener(eq(LogicalDatastoreType
+                .OPERATIONAL), any(InstanceIdentifier.class), any(NetconfEventSourceManager.class), eq(
+                AsyncDataBroker.DataChangeScope.SUBTREE));
 
         DOMMountPoint domMountPointMock = mock(DOMMountPoint.class);
         Optional<DOMMountPoint> optionalDomMountServiceMock = Optional.of(domMountPointMock);
-        doReturn(optionalDomMountServiceMock).when(domMountPointServiceMock).getMountPoint((YangInstanceIdentifier)notNull());
+        doReturn(optionalDomMountServiceMock).when(domMountPointServiceMock).getMountPoint((YangInstanceIdentifier)
+                notNull());
         DOMDataBroker mpDataBroker = mock(DOMDataBroker.class);
         doReturn(Optional.of(mpDataBroker)).when(domMountPointMock).getService(DOMDataBroker.class);
         doReturn(Optional.of(mock(DOMRpcService.class))).when(domMountPointMock).getService(DOMRpcService.class);
-        doReturn(Optional.of(mock(DOMNotificationService.class))).when(domMountPointMock).getService(DOMNotificationService.class);
+        doReturn(Optional.of(mock(DOMNotificationService.class))).when(domMountPointMock)
+                .getService(DOMNotificationService.class);
 
         DOMDataReadOnlyTransaction rtx = mock(DOMDataReadOnlyTransaction.class);
         doReturn(rtx).when(mpDataBroker).newReadOnlyTransaction();
-        CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkFeature = Futures.immediateCheckedFuture(Optional.of(NetconfTestUtils.getStreamsNode("stream-1")));
+        CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkFeature = Futures
+                .immediateCheckedFuture(Optional.of(NetconfTestUtils.getStreamsNode("stream-1")));
 
-        YangInstanceIdentifier pathStream = YangInstanceIdentifier.builder().node(Netconf.QNAME).node(Streams.QNAME).build();
+        YangInstanceIdentifier pathStream = YangInstanceIdentifier.builder().node(Netconf.QNAME).node(Streams.QNAME)
+                .build();
         doReturn(checkFeature).when(rtx).read(LogicalDatastoreType.OPERATIONAL, pathStream);
 
         netconfEventSourceManager = new NetconfEventSourceManager(dataBrokerMock,
@@ -99,33 +105,34 @@ public class NetconfEventSourceManagerTest {
 
     @Test
     public void onDataChangedCreateEventSourceTestByCreateEntry() throws Exception {
-        onDataChangedTestHelper(true,false,true, NetconfTestUtils.notification_capability_prefix);
+        onDataChangedTestHelper(true, false, true, NetconfTestUtils.NOTIFICATION_CAPABILITY_PREFIX);
         netconfEventSourceManager.onDataChanged(asyncDataChangeEventMock);
         verify(eventSourceRegistry, times(1)).registerEventSource(any(EventSource.class));
     }
 
     @Test
     public void onDataChangedCreateEventSourceTestByUpdateEntry() throws Exception {
-        onDataChangedTestHelper(false,true,true, NetconfTestUtils.notification_capability_prefix);
+        onDataChangedTestHelper(false, true, true, NetconfTestUtils.NOTIFICATION_CAPABILITY_PREFIX);
         netconfEventSourceManager.onDataChanged(asyncDataChangeEventMock);
         verify(eventSourceRegistry, times(1)).registerEventSource(any(EventSource.class));
     }
 
     @Test
     public void onDataChangedCreateEventSourceTestNotNeconf() throws Exception {
-        onDataChangedTestHelper(false,true,false, NetconfTestUtils.notification_capability_prefix);
+        onDataChangedTestHelper(false, true, false, NetconfTestUtils.NOTIFICATION_CAPABILITY_PREFIX);
         netconfEventSourceManager.onDataChanged(asyncDataChangeEventMock);
         verify(eventSourceRegistry, times(0)).registerEventSource(any(EventSource.class));
     }
 
     @Test
     public void onDataChangedCreateEventSourceTestNotNotificationCapability() throws Exception {
-        onDataChangedTestHelper(true,false,true,"bad-prefix");
+        onDataChangedTestHelper(true, false, true, "bad-prefix");
         netconfEventSourceManager.onDataChanged(asyncDataChangeEventMock);
         verify(eventSourceRegistry, times(0)).registerEventSource(any(EventSource.class));
     }
 
-    private void onDataChangedTestHelper(boolean create, boolean update, boolean isNetconf, String notificationCapabilityPrefix) throws Exception{
+    private void onDataChangedTestHelper(boolean create, boolean update, boolean isNetconf, String
+            notificationCapabilityPrefix) throws Exception {
         asyncDataChangeEventMock = mock(AsyncDataChangeEvent.class);
         Map<InstanceIdentifier, DataObject> mapCreate = new HashMap<>();
         Map<InstanceIdentifier, DataObject> mapUpdate = new HashMap<>();
@@ -135,18 +142,19 @@ public class NetconfEventSourceManagerTest {
         doReturn(mapCreate).when(asyncDataChangeEventMock).getCreatedData();
         doReturn(mapUpdate).when(asyncDataChangeEventMock).getUpdatedData();
 
-        if(isNetconf){
+        if (isNetconf) {
             node01 = NetconfTestUtils
-                .getNetconfNode(nodeId, "node01.test.local", ConnectionStatus.Connected, notificationCapabilityPrefix);
+                    .getNetconfNode(nodeId, "node01.test.local", ConnectionStatus.Connected,
+                            notificationCapabilityPrefix);
 
         } else {
             node01 = NetconfTestUtils.getNode(nodeId);
         }
 
-        if(create){
+        if (create) {
             mapCreate.put(NetconfTestUtils.getInstanceIdentifier(node01), node01);
         }
-        if(update){
+        if (update) {
             mapUpdate.put(NetconfTestUtils.getInstanceIdentifier(node01), node01);
         }
 
index 369d6b4df8da162a46752a1e8cc971bcec7f814a..d64e1a6415f539584f67ac409a5fda2325d0f424 100644 (file)
@@ -66,11 +66,14 @@ public class NetconfEventSourceMountTest {
         MockitoAnnotations.initMocks(this);
         doReturn(Optional.of(dataBroker)).when(domMountPoint).getService(DOMDataBroker.class);
         doReturn(Optional.of(rpcService)).when(domMountPoint).getService(DOMRpcService.class);
-        doReturn(Optional.of(mock(DOMNotificationService.class))).when(domMountPoint).getService(DOMNotificationService.class);
+        doReturn(Optional.of(mock(DOMNotificationService.class))).when(domMountPoint)
+                .getService(DOMNotificationService.class);
         doReturn(tx).when(dataBroker).newReadOnlyTransaction();
-        final YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(Netconf.QNAME).node(Streams.QNAME).build();
+        final YangInstanceIdentifier path = YangInstanceIdentifier.builder().node(Netconf.QNAME).node(Streams.QNAME)
+                .build();
         final NormalizedNode<?, ?> streamsNode = NetconfTestUtils.getStreamsNode(STREAM_1, STREAM_2);
-        doReturn(Futures.immediateCheckedFuture(Optional.of(streamsNode))).when(tx).read(LogicalDatastoreType.OPERATIONAL, path);
+        doReturn(Futures.immediateCheckedFuture(Optional.of(streamsNode))).when(tx).read(LogicalDatastoreType
+                .OPERATIONAL, path);
         mount = new NetconfEventSourceMount(NetconfTestUtils.getNode("node-1"), domMountPoint);
     }
 
@@ -80,7 +83,8 @@ public class NetconfEventSourceMountTest {
                 .setName(new StreamNameType(STREAM_1))
                 .build();
         mount.invokeCreateSubscription(stream, Optional.absent());
-        final SchemaPath type = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
+        final SchemaPath type = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME,
+                "create-subscription"));
         ArgumentCaptor<ContainerNode> captor = ArgumentCaptor.forClass(ContainerNode.class);
         verify(rpcService).invokeRpc(eq(type), captor.capture());
         Assert.assertEquals(STREAM_1, getStreamName(captor.getValue()));
@@ -94,11 +98,13 @@ public class NetconfEventSourceMountTest {
                 .build();
         final Date date = new Date();
         mount.invokeCreateSubscription(stream, Optional.of(date));
-        final SchemaPath type = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
+        final SchemaPath type = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME,
+                "create-subscription"));
         ArgumentCaptor<ContainerNode> captor = ArgumentCaptor.forClass(ContainerNode.class);
         verify(rpcService).invokeRpc(eq(type), captor.capture());
         Assert.assertEquals(STREAM_1, getStreamName(captor.getValue()));
-        final String expDate = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(date.toInstant().atZone(ZoneId.systemDefault()));
+        final String expDate = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(date.toInstant().atZone(ZoneId
+                .systemDefault()));
         final Optional<LeafNode> actual = (Optional<LeafNode>) getDate(captor.getValue());
         Assert.assertTrue(actual.isPresent());
         String actualDate = (String) actual.get().getValue();
@@ -112,7 +118,8 @@ public class NetconfEventSourceMountTest {
                 .setReplaySupport(true)
                 .build();
         mount.invokeCreateSubscription(stream, Optional.absent());
-        final SchemaPath type = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
+        final SchemaPath type = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME,
+                "create-subscription"));
         ArgumentCaptor<ContainerNode> captor = ArgumentCaptor.forClass(ContainerNode.class);
         verify(rpcService).invokeRpc(eq(type), captor.capture());
         Assert.assertEquals(STREAM_1, getStreamName(captor.getValue()));
@@ -137,12 +144,14 @@ public class NetconfEventSourceMountTest {
     }
 
     private String getStreamName(ContainerNode value) {
-        YangInstanceIdentifier.NodeIdentifier STREAM = new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "stream"));
-        return (String) value.getChild(STREAM).get().getValue();
+        YangInstanceIdentifier.NodeIdentifier stream =
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "stream"));
+        return (String) value.getChild(stream).get().getValue();
     }
 
     private Optional<?> getDate(ContainerNode value) {
-        YangInstanceIdentifier.NodeIdentifier START_TIME = new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "startTime"));
-        return value.getChild(START_TIME);
+        YangInstanceIdentifier.NodeIdentifier startTime =
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME, "startTime"));
+        return value.getChild(startTime);
     }
 }
\ No newline at end of file
index 1a439b9ff66224cea5c85616f1bb490cee229aab..56ce4ee61ad9bfc3a29b01cf68928b738d96ee63 100644 (file)
@@ -54,8 +54,10 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 public class NetconfEventSourceTest {
 
 
-    private static final SchemaPath notification1Path = SchemaPath.create(true, QName.create("ns1", "1970-01-15", "not1"));
-    private static final SchemaPath notification2Path = SchemaPath.create(true, QName.create("ns2", "1980-02-18", "not2"));
+    private static final SchemaPath NOTIFICATION_1_PATH = SchemaPath.create(true, QName.create("ns1", "1970-01-15",
+            "not1"));
+    private static final SchemaPath NOTIFICATION_2_PATH = SchemaPath.create(true, QName.create("ns2", "1980-02-18",
+            "not2"));
 
     NetconfEventSource netconfEventSource;
 
@@ -72,14 +74,16 @@ public class NetconfEventSourceTest {
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         //init notification mocks
-        doReturn(notification1Path).when(matchnigNotification).getType();
-        doReturn(notification2Path).when(nonMachtingNotification).getType();
-        DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> body = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("ns1", "1970-01-15", "not1data")));
+        doReturn(NOTIFICATION_1_PATH).when(matchnigNotification).getType();
+        doReturn(NOTIFICATION_2_PATH).when(nonMachtingNotification).getType();
+        DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> body = Builders
+                .containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("ns1",
+                        "1970-01-15", "not1data")));
         doReturn(body.build()).when(matchnigNotification).getBody();
         //init schema context mock
         Set<NotificationDefinition> notifications = new HashSet<>();
-        notifications.add(getNotificationDefinitionMock(notification1Path.getLastComponent()));
-        notifications.add(getNotificationDefinitionMock(notification2Path.getLastComponent()));
+        notifications.add(getNotificationDefinitionMock(NOTIFICATION_1_PATH.getLastComponent()));
+        notifications.add(getNotificationDefinitionMock(NOTIFICATION_2_PATH.getLastComponent()));
         SchemaContext schemaContext = mock(SchemaContext.class);
         doReturn(notifications).when(schemaContext).getNotifications();
         //init mount point mock
@@ -91,11 +95,12 @@ public class NetconfEventSourceTest {
         doReturn(Futures.immediateCheckedFuture(null)).when(mount).invokeCreateSubscription(any(), any());
         doReturn(Futures.immediateCheckedFuture(null)).when(mount).invokeCreateSubscription(any());
         doReturn(mock(ListenerRegistration.class)).when(mount).registerNotificationListener(any(), any());
-        final Node nodeId1 = NetconfTestUtils.getNetconfNode("NodeId1", "node.test.local", ConnectionStatus.Connected, NetconfTestUtils.notification_capability_prefix);
+        final Node nodeId1 = NetconfTestUtils.getNetconfNode("NodeId1", "node.test.local", ConnectionStatus
+                .Connected, NetconfTestUtils.NOTIFICATION_CAPABILITY_PREFIX);
         doReturn(nodeId1).when(mount).getNode();
 
         Map<String, String> streamMap = new HashMap<>();
-        streamMap.put(notification1Path.getLastComponent().getNamespace().toString(), "stream-1");
+        streamMap.put(NOTIFICATION_1_PATH.getLastComponent().getNamespace().toString(), "stream-1");
         netconfEventSource = new NetconfEventSource(
                 streamMap,
                 mount,
@@ -121,7 +126,8 @@ public class NetconfEventSourceTest {
         final TopicDOMNotification value = (TopicDOMNotification) captor.getValue();
         final QName qname = TopicNotification.QNAME;
         final YangInstanceIdentifier.NodeIdentifier topicIdNode =
-                new YangInstanceIdentifier.NodeIdentifier(QName.create(qname.getNamespace().toString(), qname.getFormattedRevision(), "topic-id"));
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(qname.getNamespace().toString(), qname
+                        .getFormattedRevision(), "topic-id"));
         final Object actualTopicId = value.getBody().getChild(topicIdNode).get().getValue();
         Assert.assertEquals(topic1.getTopicId(), actualTopicId);
     }
@@ -152,10 +158,10 @@ public class NetconfEventSourceTest {
                 .build();
     }
 
-    private NotificationDefinition getNotificationDefinitionMock(QName qName) {
+    private NotificationDefinition getNotificationDefinitionMock(QName qualifiedName) {
         NotificationDefinition notification = mock(NotificationDefinition.class);
-        doReturn(qName).when(notification).getQName();
-        doReturn(SchemaPath.create(true, qName)).when(notification).getPath();
+        doReturn(qualifiedName).when(notification).getQName();
+        doReturn(SchemaPath.create(true, qualifiedName)).when(notification).getPath();
         return notification;
     }
 
index 3124d6b1f064071f0dafa3a859b8300e44f1d675..25c3a84756a0c80b3afcef498b65fd938bd3223b 100644 (file)
@@ -46,22 +46,23 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNo
 
 public final class NetconfTestUtils {
 
-    public static final String notification_capability_prefix = "(urn:ietf:params:xml:ns:netconf:notification";
+    public static final String NOTIFICATION_CAPABILITY_PREFIX = "(urn:ietf:params:xml:ns:netconf:notification";
 
     private NetconfTestUtils() {
     }
 
     public static Node getNetconfNode(String nodeIdent, String hostName, ConnectionStatus cs,
-        String notificationCapabilityPrefix) {
+                                      String notificationCapabilityPrefix) {
 
         DomainName dn = new DomainName(hostName);
         Host host = new Host(dn);
 
         List<AvailableCapability> avCapList = new ArrayList<>();
-        avCapList.add(new AvailableCapabilityBuilder().setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
+        avCapList.add(new AvailableCapabilityBuilder().setCapability(notificationCapabilityPrefix
+                + "_availableCapabilityString1").build());
         AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
         NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setAvailableCapabilities(avCaps)
-            .build();
+                .build();
 
         NodeId nodeId = new NodeId(nodeIdent);
         NodeKey nk = new NodeKey(nodeId);
@@ -81,14 +82,14 @@ public final class NetconfTestUtils {
     }
 
     public static InstanceIdentifier<Node> getInstanceIdentifier(Node node) {
-        TopologyKey NETCONF_TOPOLOGY_KEY = new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()));
+        TopologyKey netconfTopologyKey = new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()));
         InstanceIdentifier<Node> nodeII = InstanceIdentifier.create(NetworkTopology.class)
-            .child(Topology.class, NETCONF_TOPOLOGY_KEY).child(Node.class, node.getKey());
+                .child(Topology.class, netconfTopologyKey).child(Node.class, node.getKey());
         return nodeII;
     }
 
-    public static Optional<Streams> getAvailableStream(String Name, boolean replaySupport) {
-        Stream stream = new StreamBuilder().setName(new StreamNameType(Name)).setReplaySupport(replaySupport).build();
+    public static Optional<Streams> getAvailableStream(String name, boolean replaySupport) {
+        Stream stream = new StreamBuilder().setName(new StreamNameType(name)).setReplaySupport(replaySupport).build();
         List<Stream> streamList = new ArrayList<>();
         streamList.add(stream);
         Streams streams = new StreamsBuilder().setStream(streamList).build();
@@ -100,7 +101,8 @@ public final class NetconfTestUtils {
         Set<MapEntryNode> streamSet = new HashSet<>();
         for (String s : streamName) {
             MapEntryNode stream = Builders.mapEntryBuilder()
-                    .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifierWithPredicates(Stream.QNAME, nameNode, s))
+                    .withNodeIdentifier(new YangInstanceIdentifier
+                            .NodeIdentifierWithPredicates(Stream.QNAME, nameNode, s))
                     .withChild(Builders.leafBuilder()
                             .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(nameNode))
                             .withValue(s)
@@ -109,7 +111,8 @@ public final class NetconfTestUtils {
             streamSet.add(stream);
         }
 
-        CollectionNodeBuilder<MapEntryNode, MapNode> streams = Builders.mapBuilder().withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(Stream.QNAME));
+        CollectionNodeBuilder<MapEntryNode, MapNode> streams =
+                Builders.mapBuilder().withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(Stream.QNAME));
         for (MapEntryNode mapEntryNode : streamSet) {
             streams.withChild(mapEntryNode);
         }
index 2bf354b2c99758bf75baaac0639cd8016f6c138d..e68caa6a7fd4275d6efa44426559ba40bf889932 100644 (file)
@@ -36,7 +36,8 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration;
 public class StreamNotificationTopicRegistrationTest {
 
     private static final String STREAM_NAME = "stream-1";
-    private static final String PREFIX = ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH.getLastComponent().getNamespace().toString();
+    private static final String PREFIX = ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH
+            .getLastComponent().getNamespace().toString();
 
     @Mock
     private NetconfEventSource source;
@@ -56,13 +57,15 @@ public class StreamNotificationTopicRegistrationTest {
 
         Node node = new NodeBuilder().setNodeId(NodeId.getDefaultInstance("node-id")).build();
         when(mount.getNode()).thenReturn(node);
-        when(mount.registerNotificationListener(source, ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH))
+        when(mount.registerNotificationListener(source, ConnectionNotificationTopicRegistration
+                .EVENT_SOURCE_STATUS_PATH))
                 .thenReturn(listenerRegistration);
         when(mount.invokeCreateSubscription(any(), any())).thenReturn(Futures.immediateCheckedFuture(null));
         when(mount.invokeCreateSubscription(any())).thenReturn(Futures.immediateCheckedFuture(null));
 
         when(source.getMount()).thenReturn(mount);
-        stream = new StreamBuilder().setName(StreamNameType.getDefaultInstance(STREAM_NAME)).setReplaySupport(true).build();
+        stream = new StreamBuilder().setName(StreamNameType.getDefaultInstance(STREAM_NAME)).setReplaySupport(true)
+                .build();
 
         registration = new StreamNotificationTopicRegistration(stream, PREFIX, source);
     }
@@ -107,12 +110,14 @@ public class StreamNotificationTopicRegistrationTest {
         final TopicId topic1 = registerTopic("topic1");
         final TopicId topic2 = registerTopic("topic2");
         final TopicId topic3 = registerTopic("topic3");
-        final Set<TopicId> notificationTopicIds = registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
+        final Set<TopicId> notificationTopicIds =
+                registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
         Assert.assertNotNull(notificationTopicIds);
         Assert.assertThat(notificationTopicIds, hasItems(topic1, topic2, topic3));
 
         registration.unRegisterNotificationTopic(topic3);
-        final Set<TopicId> afterUnregister = registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
+        final Set<TopicId> afterUnregister =
+                registration.getTopicsForNotification(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
         Assert.assertNotNull(afterUnregister);
         Assert.assertThat(afterUnregister, hasItems(topic1, topic2));
         Assert.assertFalse(afterUnregister.contains(topic3));
index e0b03b607b0166138a3d479509f0f9530c2a5b72..af06bcebc492c80c39d8e9d7d0131b615c941470 100644 (file)
           </instructions>
         </configuration>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index fd58609fb3f9993bcdcfa0fa43fc691db3bbf695..a3601fe7b60da17bc88156bae70f366db0faf820 100644 (file)
@@ -36,7 +36,8 @@ public class Get extends AbstractNetconfOperation {
     private Element getPlaceholder(final Document innerResult)
             throws DocumentedException {
         final XmlElement rootElement = XmlElement.fromDomElementWithExpected(
-                innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+                innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY,
+                XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
         return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
     }
 
@@ -50,10 +51,11 @@ public class Get extends AbstractNetconfOperation {
         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
             throws DocumentedException {
-        if (subsequentOperation.isExecutionTermination()){
+        if (subsequentOperation.isExecutionTermination()) {
             throw new DocumentedException(String.format("Subsequent netconf operation expected by %s", this),
                     DocumentedException.ErrorType.APPLICATION,
                     DocumentedException.ErrorTag.OPERATION_FAILED,
@@ -83,7 +85,8 @@ public class Get extends AbstractNetconfOperation {
     }
 
     @Override
-    protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation)
+    protected Element handle(final Document document, final XmlElement message,
+                             final NetconfOperationChainedExecution subsequentOperation)
             throws DocumentedException {
         throw new UnsupportedOperationException("Never gets called");
     }
index ea6108edee87787fc5123b45cdbd1e3876246e65..1fb100368a98613118914634441030a0f93706a1 100644 (file)
@@ -46,7 +46,8 @@ public class GetSchema extends AbstractSingletonNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml)
+            throws DocumentedException {
         final GetSchemaEntry entry;
 
         entry = new GetSchemaEntry(xml);
@@ -83,7 +84,7 @@ public class GetSchema extends AbstractSingletonNetconfOperation {
             try {
                 identifierElement = getSchemaElement.getOnlyChildElementWithSameNamespace(IDENTIFIER);
             } catch (final DocumentedException e) {
-                LOG.trace("Can't get identifier element as only child element with same namespace due to ",e);
+                LOG.trace("Can't get identifier element as only child element with same namespace due to ", e);
                 throw DocumentedException.wrap(e);
             }
             identifier = identifierElement.getTextContent();
index 6680662d0bd0b042596666f85c37148266ee6dce..a6ae284ea1f745d5de3647d92ee055c8d52a117c 100644 (file)
@@ -9,9 +9,10 @@ package org.opendaylight.netconf.monitoring;
 
 public final class MonitoringConstants {
 
-    private MonitoringConstants(){
+    private MonitoringConstants() {
         // not called - private constructor for utility class
     }
+
     public static final String MODULE_NAME = "ietf-netconf-monitoring";
     public static final String MODULE_REVISION = "2010-10-04";
 
index 7fdda8cc83117df875ba31ab888fa00503226a37..24d9066ba231781f8c37a686a6513c86a576ea13 100644 (file)
@@ -26,14 +26,15 @@ public class NetconfMonitoringActivator implements BundleActivator {
     private NetconfMonitoringServiceTracker monitor;
 
     @Override
-    public void start(final BundleContext context)  {
+    public void start(final BundleContext context) {
         monitor = new NetconfMonitoringServiceTracker(context);
         monitor.open();
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public void stop(final BundleContext context) {
-        if(monitor!=null) {
+        if (monitor != null) {
             try {
                 monitor.close();
             } catch (final Exception e) {
@@ -42,7 +43,8 @@ public class NetconfMonitoringActivator implements BundleActivator {
         }
     }
 
-    public static class NetconfMonitoringOperationServiceFactory implements NetconfOperationServiceFactory, AutoCloseable {
+    public static class NetconfMonitoringOperationServiceFactory implements NetconfOperationServiceFactory,
+            AutoCloseable {
 
         private final NetconfMonitoringOperationService operationService;
 
index e407b7cc62504835203ff34a244b4fae0d053416..6a0a3cf98fd4298e1fa5d74af89b5dbb5abfd61c 100644 (file)
@@ -20,7 +20,8 @@ import org.osgi.util.tracker.ServiceTracker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonitoringService, NetconfMonitoringService> {
+public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonitoringService,
+        NetconfMonitoringService> {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfMonitoringServiceTracker.class);
 
@@ -49,17 +50,18 @@ public class NetconfMonitoringServiceTracker extends ServiceTracker<NetconfMonit
         return netconfMonitoringService;
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public void removedService(final ServiceReference<NetconfMonitoringService> reference,
-            final NetconfMonitoringService netconfMonitoringService) {
-        if(reg!=null) {
+                               final NetconfMonitoringService netconfMonitoringService) {
+        if (reg != null) {
             try {
                 reg.unregister();
             } catch (final Exception e) {
                 LOG.warn("Ignoring exception while unregistering {}", reg, e);
             }
         }
-        if(factory!=null) {
+        if (factory != null) {
             factory.close();
         }
     }
index 7a34437bc9851c87d66729e9768ff4d838356062..09deb7524d875cfaf5af69c1817a51de1f661240 100644 (file)
@@ -38,6 +38,6 @@ public class JaxBSerializer {
         } catch (final JAXBException e) {
             throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e);
         }
-        return ((Document)res.getNode()).getDocumentElement();
+        return ((Document) res.getNode()).getDocumentElement();
     }
 }
index a629ac374f0378ef66a3f616f8231c088577b3dc..b3e64c5bc7146914d9776eba9325d0371c33ed3d 100644 (file)
@@ -22,7 +22,7 @@ final class MonitoringSchema {
 
     private final Schema schema;
 
-    public MonitoringSchema(Schema schema) {
+    MonitoringSchema(Schema schema) {
         this.schema = schema;
     }
 
@@ -54,7 +54,8 @@ final class MonitoringSchema {
 
     @XmlElement(name = "format")
     public String getFormat() {
-        Preconditions.checkState(schema.getFormat() == Yang.class, "Only yang format permitted, but was %s", schema.getFormat());
+        Preconditions.checkState(schema.getFormat() == Yang.class, "Only yang format permitted, but was %s",
+                schema.getFormat());
         return "yang";
     }
 }
index b61ac13f2e2d9e5fe0e2c5dc4a915b84f1463ae9..7fb3fa11e2d5d5af232ee6fe37afc8d5aef2badc 100644 (file)
@@ -21,11 +21,11 @@ final class MonitoringSession {
     @XmlTransient
     private Session managementSession;
 
-    public MonitoringSession(Session managementSession) {
+    MonitoringSession(Session managementSession) {
         this.managementSession = managementSession;
     }
 
-    public MonitoringSession() {
+    MonitoringSession() {
     }
 
     public void setManagementSession(Session managementSession) {
@@ -75,19 +75,20 @@ final class MonitoringSession {
     @XmlElement(name = "transport")
     public String getTransport() {
         try {
-            QName qName = (QName) managementSession.getTransport().getField("QNAME").get(null);
+            QName qualifiedName = (QName) managementSession.getTransport().getField("QNAME").get(null);
             // Add extension prefix if transport type is from extension yang module
-            if (qName.getNamespace().toString().equals(MonitoringConstants.EXTENSION_NAMESPACE)) {
-                return Joiner.on(':').join(MonitoringConstants.EXTENSION_NAMESPACE_PREFIX, qName.getLocalName());
+            if (qualifiedName.getNamespace().toString().equals(MonitoringConstants.EXTENSION_NAMESPACE)) {
+                return Joiner.on(':').join(MonitoringConstants.EXTENSION_NAMESPACE_PREFIX,
+                        qualifiedName.getLocalName());
             } else {
-                return qName.getLocalName();
+                return qualifiedName.getLocalName();
             }
         } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
             throw new IllegalArgumentException("Unknown transport type " + managementSession.getTransport(), e);
         }
     }
 
-    @XmlElement(name= "session-identifier", namespace = MonitoringConstants.EXTENSION_NAMESPACE)
+    @XmlElement(name = "session-identifier", namespace = MonitoringConstants.EXTENSION_NAMESPACE)
     public String getSessionType() {
         return managementSession.getAugmentation(Session1.class).getSessionIdentifier();
     }
index f78321851d4bf0748a7273103d00734cb2712d46..12988086ca380135ddb0fbec9b3d636a058c4a2d 100644 (file)
@@ -34,8 +34,8 @@ public final class NetconfState {
 
     public NetconfState() {}
 
-    @XmlElementWrapper(name="schemas")
-    @XmlElement(name="schema")
+    @XmlElementWrapper(name = "schemas")
+    @XmlElement(name = "schema")
     public Collection<MonitoringSchema> getSchemas() {
         return Collections2.transform(schemas.getSchema(), new Function<Schema, MonitoringSchema>() {
             @Nullable
@@ -46,8 +46,8 @@ public final class NetconfState {
         });
     }
 
-    @XmlElementWrapper(name="sessions")
-    @XmlElement(name="session")
+    @XmlElementWrapper(name = "sessions")
+    @XmlElement(name = "session")
     public Collection<MonitoringSession> getSessions() {
         return Collections2.transform(sessions.getSession(), new Function<Session, MonitoringSession>() {
             @Nullable
index d4cccb35369abbbb1143b1698589d79cb5a2e6df..d42c789e508a09131792b689215aa65329c91b1b 100644 (file)
@@ -8,7 +8,8 @@
 @XmlSchema(
         elementFormDefault = XmlNsForm.QUALIFIED,
         xmlns = {
-                @XmlNs(namespaceURI = MonitoringConstants.EXTENSION_NAMESPACE, prefix = MonitoringConstants.EXTENSION_NAMESPACE_PREFIX),
+                @XmlNs(namespaceURI = MonitoringConstants.EXTENSION_NAMESPACE, prefix =
+                        MonitoringConstants.EXTENSION_NAMESPACE_PREFIX),
                 @XmlNs(namespaceURI = MonitoringConstants.NAMESPACE, prefix = "")
         },
         namespace = MonitoringConstants.NAMESPACE
index be33a8e71afa332385c2eba4683d285aa869679d..d452fd5a85c080c4bf2c7f5c475c14365c722999 100644 (file)
@@ -35,13 +35,13 @@ public class GetSchemaTest {
     public void setUp() throws Exception {
         cap = mock(NetconfMonitoringService.class);
         doc = XmlUtil.newDocument();
-        getSchema = "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                "        <identifier>threadpool-api</identifier>\n" +
-                "        <version>2010-09-24</version>\n" +
-                "        <format\n" +
-                "                xmlns:ncm=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">ncm:yang\n" +
-                "        </format>\n" +
-                "    </get-schema>";
+        getSchema = "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                + "        <identifier>threadpool-api</identifier>\n"
+                + "        <version>2010-09-24</version>\n"
+                + "        <format\n"
+                + "                xmlns:ncm=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">ncm:yang\n"
+                + "        </format>\n"
+                "    </get-schema>";
     }
 
     @Test(expected = DocumentedException.class)
@@ -55,7 +55,8 @@ public class GetSchemaTest {
     public void handleWithNoSubsequentOperations() throws Exception {
         GetSchema schema = new GetSchema(cap);
         doReturn("").when(cap).getSchemaForCapability(anyString(), any(Optional.class));
-        assertNotNull(schema.handleWithNoSubsequentOperations(doc, XmlElement.fromDomElement(XmlUtil.readXmlToElement(getSchema))));
+        assertNotNull(schema.handleWithNoSubsequentOperations(doc,
+                XmlElement.fromDomElement(XmlUtil.readXmlToElement(getSchema))));
     }
 
 }
\ No newline at end of file
index 3789bac278f8a3c18bbb688c0415bab917b7823d..397e1d21e1c053987ded2a97ac4749542c57359d 100644 (file)
@@ -49,10 +49,13 @@ public class GetTest {
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
 
-        incorrectSubsequentResult = XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
-        correctSubsequentResult = XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><data></data></rpc-reply>");
+        incorrectSubsequentResult = XmlUtil.readXmlToDocument("<rpc-reply "
+                + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
+        correctSubsequentResult = XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:"
+                + "1.0\"><data></data></rpc-reply>");
 
-        doReturn(new SessionsBuilder().setSession(Collections.<Session>emptyList()).build()).when(monitor).getSessions();
+        doReturn(new SessionsBuilder().setSession(Collections.<Session>emptyList()).build()).when(monitor)
+                .getSessions();
         doReturn(new SchemasBuilder().setSchema(Collections.<Schema>emptyList()).build()).when(monitor).getSchemas();
         doReturn(false).when(subsequentOperation).isExecutionTermination();
 
@@ -64,7 +67,8 @@ public class GetTest {
         try {
             get.handle(null, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
         } catch (final DocumentedException e) {
-            assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.ERROR, DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorType.APPLICATION);
+            assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.ERROR,
+                    DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorType.APPLICATION);
             return;
         }
 
@@ -77,7 +81,8 @@ public class GetTest {
         try {
             get.handle(request, subsequentOperation);
         } catch (final DocumentedException e) {
-            assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.ERROR, DocumentedException.ErrorTag.INVALID_VALUE, DocumentedException.ErrorType.APPLICATION);
+            assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.ERROR,
+                    DocumentedException.ErrorTag.INVALID_VALUE, DocumentedException.ErrorType.APPLICATION);
             return;
         }
 
@@ -90,7 +95,8 @@ public class GetTest {
         try {
             get.handle(request, subsequentOperation);
         } catch (final DocumentedException e) {
-            assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.ERROR, DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorType.APPLICATION);
+            assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.ERROR,
+                    DocumentedException.ErrorTag.OPERATION_FAILED, DocumentedException.ErrorType.APPLICATION);
             assertEquals(1, e.getErrorInfo().size());
             return;
         }
@@ -101,7 +107,8 @@ public class GetTest {
     @Test
     public void testSuccessHandle() throws Exception {
         doReturn(correctSubsequentResult).when(subsequentOperation).execute(request);
-        assertTrue(get.getHandlingPriority().getPriority().get() > HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.getPriority().get());
+        assertTrue(get.getHandlingPriority().getPriority().get()
+                > HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.getPriority().get());
         final Document result = get.handle(request, subsequentOperation);
         assertThat(XmlUtil.toString(result), CoreMatchers.containsString("sessions"));
         assertThat(XmlUtil.toString(result), CoreMatchers.containsString("schemas"));
@@ -114,9 +121,10 @@ public class GetTest {
 
     }
 
-    private void assertNetconfDocumentedEx(final DocumentedException e, final DocumentedException.ErrorSeverity severity, final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorType type) {
-        assertEquals(severity, e.getErrorSeverity());
-        assertEquals(errorTag, e.getErrorTag());
-        assertEquals(type, e.getErrorType());
+    private void assertNetconfDocumentedEx(final DocumentedException exception, final DocumentedException.ErrorSeverity
+            severity, final DocumentedException.ErrorTag errorTag, final DocumentedException.ErrorType type) {
+        assertEquals(severity, exception.getErrorSeverity());
+        assertEquals(errorTag, exception.getErrorTag());
+        assertEquals(type, exception.getErrorType());
     }
 }
index a2cf4a8a4aa75d1c64b3e4bb9cd351e37696e44f..aab90661060c128ff8ff9eb0e4c543b2b20e8da0 100644 (file)
@@ -19,7 +19,8 @@ public class NetconfMonitoringOperationServiceTest {
     public void testGetters() throws Exception {
         NetconfMonitoringService monitor = mock(NetconfMonitoringService.class);
         NetconfMonitoringOperationService service = new NetconfMonitoringOperationService(monitor);
-        NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory serviceFactory = new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(service);
+        NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory serviceFactory =
+                new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(service);
 
         assertEquals(2, service.getNetconfOperations().size());
 
index 034603cdf24452eccdf5c08c02139c3cd75b1ee0..6623be43369100c95f0fb10ce745efcc65bafc4e 100644 (file)
@@ -43,7 +43,8 @@ public class NetconfMonitoringServiceTrackerTest {
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        doReturn(serviceRegistration).when(context).registerService(any(Class.class), any(NetconfOperationServiceFactory.class), any(Hashtable.class));
+        doReturn(serviceRegistration).when(context).registerService(any(Class.class),
+                any(NetconfOperationServiceFactory.class), any(Hashtable.class));
         doNothing().when(serviceRegistration).unregister();
         doReturn(filter).when(context).createFilter(anyString());
         doReturn("").when(reference).toString();
@@ -54,7 +55,8 @@ public class NetconfMonitoringServiceTrackerTest {
     public void testAddingService() throws Exception {
         NetconfMonitoringServiceTracker tracker = new NetconfMonitoringServiceTracker(context);
         tracker.addingService(reference);
-        verify(context, times(1)).registerService(any(Class.class), any(NetconfOperationServiceFactory.class), any(Hashtable.class));
+        verify(context, times(1)).registerService(any(Class.class), any(NetconfOperationServiceFactory.class),
+                any(Hashtable.class));
         tracker.removedService(reference, null);
         verify(serviceRegistration, times(1)).unregister();
     }
index 11d269a3eadd45f469c28425e56cbac12b69d6bf..bfc0f8504f7c53efa27ab75de74325ab5f3fb2c3 100644 (file)
@@ -43,18 +43,18 @@ public class JaxBSerializerTest {
 
     private static final String IPV4 = "192.168.1.1";
     private static final String IPV6 = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329";
-    private static final String SESSION_XML = "<session>" +
-            "<session-id>1</session-id>" +
-            "<in-bad-rpcs>0</in-bad-rpcs>" +
-            "<in-rpcs>0</in-rpcs>" +
-            "<login-time>2010-10-10T12:32:32Z</login-time>" +
-            "<out-notifications>0</out-notifications>" +
-            "<out-rpc-errors>0</out-rpc-errors>" +
-            "<ncme:session-identifier>client</ncme:session-identifier>" +
-            "<source-host>%s</source-host>" +
-            "<transport>ncme:netconf-tcp</transport>" +
-            "<username>username</username>" +
-            "</session>";
+    private static final String SESSION_XML = "<session>"
+            + "<session-id>1</session-id>"
+            + "<in-bad-rpcs>0</in-bad-rpcs>"
+            + "<in-rpcs>0</in-rpcs>"
+            + "<login-time>2010-10-10T12:32:32Z</login-time>"
+            + "<out-notifications>0</out-notifications>"
+            + "<out-rpc-errors>0</out-rpc-errors>"
+            + "<ncme:session-identifier>client</ncme:session-identifier>"
+            + "<source-host>%s</source-host>"
+            + "<transport>ncme:netconf-tcp</transport>"
+            + "<username>username</username>"
+            "</session>";
 
     @Mock
     private NetconfMonitoringService monitoringService;
@@ -69,8 +69,8 @@ public class JaxBSerializerTest {
                 getMockIPv6Session(NetconfSsh.class)
         )).build())
                 .when(monitoringService).getSessions();
-        doReturn(new SchemasBuilder().setSchema(Lists.newArrayList(getMockSchema("id", "v1", Yang.class), getMockSchema("id2", "", Yang.class))).build())
-                .when(monitoringService).getSchemas();
+        doReturn(new SchemasBuilder().setSchema(Lists.newArrayList(getMockSchema("id", "v1", Yang.class),
+                getMockSchema("id2", "", Yang.class))).build()).when(monitoringService).getSchemas();
     }
 
     @Test
@@ -79,13 +79,13 @@ public class JaxBSerializerTest {
         final NetconfState model = new NetconfState(monitoringService);
         final String xml = XmlUtil.toString(new JaxBSerializer().toXml(model)).replaceAll("\\s", "");
         assertThat(xml, CoreMatchers.containsString(
-                "<schema>" +
-                "<format>yang</format>" +
-                "<identifier>id</identifier>" +
-                "<location>NETCONF</location>" +
-                "<namespace>localhost</namespace>" +
-                "<version>v1</version>" +
-                "</schema>"));
+                "<schema>"
+                        + "<format>yang</format>"
+                        + "<identifier>id</identifier>"
+                        + "<location>NETCONF</location>"
+                        + "<namespace>localhost</namespace>"
+                        + "<version>v1</version>"
+                        + "</schema>"));
 
         assertThat(xml, CoreMatchers.containsString(
                 String.format(SESSION_XML, IPV4)));
index 300e19f594368cd7d224fe7da4aa23dde88a81e0..f7b6a443d586819943b16c8a8826cdf7ff5c8378 100644 (file)
@@ -14,11 +14,11 @@ import io.netty.util.concurrent.EventExecutor;
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import java.util.concurrent.Executors;
 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
 import org.opendaylight.netconf.api.NetconfServerDispatcher;
 import org.opendaylight.netconf.auth.AuthProvider;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
 import org.slf4j.Logger;
@@ -67,15 +67,10 @@ public class NetconfNorthboundSshServer {
         });
     }
 
-    private InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
-        try {
-            IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
-            final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null
-                    ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
-            return new InetSocketAddress(inetAd, Integer.valueOf(portNumber));
-        } catch (final UnknownHostException e) {
-            throw new IllegalArgumentException("Unable to bind netconf endpoint to address " + bindingAddress, e);
-        }
+    private static InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
+        IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
+        final InetAddress inetAd = IetfInetUtil.INSTANCE.inetAddressFor(ipAddress);
+        return new InetSocketAddress(inetAd, Integer.parseInt(portNumber));
     }
 
     public void close() {
index f45f7ba80f5a073328ad612b53364926e03d244d..8b9caef47b15388755bb308e23d608fe81351c14 100644 (file)
@@ -10,8 +10,8 @@ package org.opendaylight.netconf.tcp;
 import io.netty.channel.ChannelFuture;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import org.opendaylight.netconf.api.NetconfServerDispatcher;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressBuilder;
 import org.slf4j.Logger;
@@ -41,15 +41,10 @@ public class NetconfNorthboundTcpServer implements AutoCloseable {
         });
     }
 
-    private InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
-        try {
-            IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
-            final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null
-                    ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
-            return new InetSocketAddress(inetAd, Integer.valueOf(portNumber));
-        } catch (final UnknownHostException e) {
-            throw new IllegalArgumentException("Unable to bind netconf tcp endpoint to address " + bindingAddress, e);
-        }
+    private static InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
+        IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
+        final InetAddress inetAd = IetfInetUtil.INSTANCE.inetAddressFor(ipAddress);
+        return new InetSocketAddress(inetAd, Integer.parseInt(portNumber));
     }
 
     @Override
index 3bb0125c700dfeee95de8f3bb6500cfc6150664c..88441a1b067f33b0047e0a06fca165b987b30192 100644 (file)
@@ -32,15 +32,14 @@ import com.google.common.base.MoreObjects;
 import com.google.common.base.Optional;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
+import com.google.common.net.InetAddresses;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.SettableFuture;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import org.junit.After;
@@ -110,11 +109,11 @@ public class NetconfNodeActorTest {
     private DataBroker dataBroker;
 
     @Before
-    public void setup() throws UnknownHostException {
+    public void setup() {
         initMocks
                 (this);
         remoteDeviceId = new RemoteDeviceId("netconf-topology",
-                new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+                new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
 
         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
@@ -150,7 +149,7 @@ public class NetconfNodeActorTest {
         /* Test refresh master data */
 
         final RemoteDeviceId remoteDeviceId2 = new RemoteDeviceId("netconf-topology2",
-                new InetSocketAddress(InetAddress.getByName("127.0.0.2"), 9999));
+                new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 9999));
 
         final NetconfTopologySetup setup2 = mock(NetconfTopologySetup.class);
 
index a8df0afd38dc9eb590dceb7815448179917ed883..3d1f5ec2b936ac344e864853bfc34c81971dbfd3 100644 (file)
@@ -23,9 +23,9 @@ import static org.mockito.MockitoAnnotations.initMocks;
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
 import akka.util.Timeout;
+import com.google.common.net.InetAddresses;
 import com.google.common.util.concurrent.Futures;
 import io.netty.util.concurrent.EventExecutor;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.UnknownHostException;
 import java.util.concurrent.ExecutorService;
@@ -109,11 +109,11 @@ public class RemoteDeviceConnectorImplTest {
     private RemoteDeviceId remoteDeviceId;
 
     @Before
-    public void setUp() throws UnknownHostException {
+    public void setUp() {
         initMocks(this);
 
         remoteDeviceId = new RemoteDeviceId(TOPOLOGY_ID,
-                new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+                new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
 
         doReturn(txChain).when(dataBroker).createTransactionChain(any(TransactionChainListener.class));
         doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
@@ -199,7 +199,7 @@ public class RemoteDeviceConnectorImplTest {
     }
 
     @Test
-    public void testKeapAliveFacade() throws UnknownHostException {
+    public void testKeapAliveFacade() {
         final ExecutorService executorService = mock(ExecutorService.class);
         doReturn(executorService).when(processingExecutor).getExecutor();
 
@@ -217,7 +217,7 @@ public class RemoteDeviceConnectorImplTest {
                 .build();
 
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(TOPOLOGY_ID,
-                new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+                new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
         final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
         builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node));
 
@@ -233,7 +233,7 @@ public class RemoteDeviceConnectorImplTest {
     }
 
     @Test
-    public void testGetClientConfig() throws UnknownHostException {
+    public void testGetClientConfig() {
         final NetconfClientSessionListener listener = mock(NetconfClientSessionListener.class);
         final Host host = new Host(new IpAddress(new Ipv4Address("127.0.0.1")));
         final PortNumber portNumber = new PortNumber(9999);
@@ -255,7 +255,8 @@ public class RemoteDeviceConnectorImplTest {
                 remoteDeviceConnection.getClientConfig(listener, testingNode);
 
         assertEquals(defaultClientConfig.getConnectionTimeoutMillis().longValue(), 1000L);
-        assertEquals(defaultClientConfig.getAddress(), new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+        assertEquals(defaultClientConfig.getAddress(), new InetSocketAddress(InetAddresses.forString("127.0.0.1"),
+            9999));
         assertSame(defaultClientConfig.getSessionListener(), listener);
         assertEquals(defaultClientConfig.getAuthHandler().getUsername(), "testuser");
         assertEquals(defaultClientConfig.getProtocol(), NetconfClientConfiguration.NetconfClientProtocol.TCP);
index b214a51899326eb3c78afcac1e164338939c234d..366a75b26752893f5a997edd0ed25967aaf67d7a 100644 (file)
@@ -24,9 +24,9 @@ import akka.testkit.TestActorRef;
 import akka.util.Timeout;
 import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
+import com.google.common.net.InetAddresses;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
@@ -88,7 +88,7 @@ public class ReadOnlyTransactionTest {
         system = ActorSystem.create();
 
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("netconf-topology",
-                new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+                new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
 
         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
index 9cd9adcaeecbd337ab43f2576a278414e7fc3815..3457b309e27c02113b6a42e0ec5f83f682622432 100644 (file)
@@ -27,9 +27,9 @@ import akka.testkit.JavaTestKit;
 import akka.testkit.TestActorRef;
 import akka.util.Timeout;
 import com.google.common.collect.Lists;
+import com.google.common.net.InetAddresses;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
@@ -92,7 +92,7 @@ public class WriteOnlyTransactionTest {
         system = ActorSystem.create();
 
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("netconf-topology",
-                new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+                new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
 
         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
         doReturn(Duration.apply(0, TimeUnit.SECONDS)).when(setup).getIdleTimeout();
index e11ac1c23f4ba1efbfdc304e4175e823ae7f9e87..21e9b36108b465343be78d8c1f5755f16c728bd2 100644 (file)
             <artifactId>yang-model-api</artifactId>
         </dependency>
     </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+                <configuration>
+                    <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
 </project>
index 68a6f11f9fd7319abafd8ece766d76dc5263a173..ad4bfa9029425205ccab65efdf3bc4600395a493 100644 (file)
@@ -96,17 +96,18 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
     private static final String CACHE_DIRECTORY = "cache";
 
     /**
-     * The default cache directory relative to <code>CACHE_DIRECTORY</code>
+     * The default cache directory relative to <code>CACHE_DIRECTORY</code>.
      */
     private static final String DEFAULT_CACHE_DIRECTORY = "schema";
 
     /**
-     * The qualified schema cache directory <code>cache/schema</code>
+     * The qualified schema cache directory <code>cache/schema</code>.
      */
-    private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
+    private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY =
+            CACHE_DIRECTORY + File.separator + DEFAULT_CACHE_DIRECTORY;
 
     /**
-     * The name for the default schema repository
+     * The name for the default schema repository.
      */
     private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
 
@@ -134,15 +135,15 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
      * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>.  The
      * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
      * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
-     * Netconf mount.  Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
+     * Netconf mount.  Access to <code>SCHEMA_RESOURCES_DTO_MAP</code> should be surrounded by appropriate
      * synchronization locks.
      */
-    private static final Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
+    private static final Map<String, NetconfDevice.SchemaResourcesDTO> SCHEMA_RESOURCES_DTO_MAP = new HashMap<>();
 
     // Initializes default constant instances for the case when the default schema repository
     // directory cache/schema is used.
     static {
-        schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
+        SCHEMA_RESOURCES_DTO_MAP.put(DEFAULT_CACHE_DIRECTORY,
                 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
                         DEFAULT_SCHEMA_CONTEXT_FACTORY,
                         new NetconfStateSchemasResolverImpl()));
@@ -168,7 +169,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
 
     protected AbstractNetconfTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
                                       final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
-                                      final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
+                                      final ThreadPool processingExecutor,
+                                      final SchemaRepositoryProvider schemaRepositoryProvider,
                                       final DataBroker dataBroker, final DOMMountPointService mountPointService) {
         this.topologyId = topologyId;
         this.clientDispatcher = clientDispatcher;
@@ -198,7 +200,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
     public ListenableFuture<Void> disconnectNode(final NodeId nodeId) {
         LOG.debug("Disconnecting RemoteDevice{{}}", nodeId.getValue());
         if (!activeConnectors.containsKey(nodeId)) {
-            return Futures.immediateFailedFuture(new IllegalStateException("Unable to disconnect device that is not connected"));
+            return Futures.immediateFailedFuture(
+                    new IllegalStateException("Unable to disconnect device that is not connected"));
         }
 
         // retrieve connection, and disconnect it
@@ -219,8 +222,10 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
         final NetconfConnectorDTO deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode);
         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
-        final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(netconfClientSessionListener, netconfNode);
-        final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator.initializeRemoteConnection(clientDispatcher, clientConfig);
+        final NetconfReconnectingClientConfiguration clientConfig =
+                getClientConfig(netconfClientSessionListener, netconfNode);
+        final ListenableFuture<NetconfDeviceCapabilities> future =
+                deviceCommunicator.initializeRemoteConnection(clientDispatcher, clientConfig);
 
         activeConnectors.put(nodeId, deviceCommunicatorDTO);
 
@@ -231,7 +236,7 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
+            public void onFailure(final Throwable throwable) {
                 LOG.error("Connector for : " + nodeId.getValue() + " failed");
                 // remove this node from active connectors?
             }
@@ -243,13 +248,16 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
     protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
                                                          final NetconfNode node) {
         //setup default values since default value is not supported in mdsal
-        final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
-        final Long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
-        final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
+        final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
+                ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
+        final Long keepaliveDelay = node.getKeepaliveDelay() == null
+                ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
+        final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
+                ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
 
         final IpAddress ipAddress = node.getHost().getIpAddress();
-        final InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null ?
-                ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
+        final InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null
+                ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
                 node.getPort().getValue());
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
 
@@ -258,7 +266,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
 
         if (keepaliveDelay > 0) {
             LOG.warn("Adding keepalive facade, for device {}", nodeId);
-            salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(), keepaliveDelay, defaultRequestTimeoutMillis);
+            salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(),
+                    keepaliveDelay, defaultRequestTimeoutMillis);
         }
 
         // pre register yang library sources as fallback schemas to schema registry
@@ -269,20 +278,21 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
             final String yangLigPassword = node.getYangLibrary().getPassword();
 
             final LibraryModulesSchemas libraryModulesSchemas;
-            if(yangLibURL != null) {
-                if(yangLibUsername != null && yangLigPassword != null) {
+            if (yangLibURL != null) {
+                if (yangLibUsername != null && yangLigPassword != null) {
                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
                 } else {
                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
                 }
 
-                for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
-                    registeredYangLibSources.
-                            add(schemaRegistry.registerSchemaSource(
-                                    new YangLibrarySchemaYangSourceProvider(remoteDeviceId, libraryModulesSchemas.getAvailableModels()),
-                                    PotentialSchemaSource
-                                            .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
-                                            PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
+                for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry
+                        : libraryModulesSchemas.getAvailableModels().entrySet()) {
+                    registeredYangLibSources
+                        .add(schemaRegistry.registerSchemaSource(
+                                new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
+                                        libraryModulesSchemas.getAvailableModels()),
+                                PotentialSchemaSource.create(sourceIdentifierURLEntry.getKey(),
+                                        YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
                 }
             }
         }
@@ -318,22 +328,25 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
         final String moduleSchemaCacheDirectory = node.getSchemaCacheDirectory();
-        // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
-        // are handled during the FilesystemSchemaSourceCache initialization.
+        // Only checks to ensure the String is not empty or null; further checks related to directory
+        // accessibility and file permissionsare handled during the FilesystemSchemaSourceCache initialization.
         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
-            // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
-            // SchemaContextFactory remain the default values.
+            // If a custom schema cache directory is specified, create the backing DTO; otherwise,
+            // the SchemaRegistry and SchemaContextFactory remain the default values.
             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
-                // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
-                synchronized(schemaResourcesDTOs) {
-                    // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
-                    schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
+                // Multiple modules may be created at once;
+                // synchronize to avoid issues with data consistency among threads.
+                synchronized (SCHEMA_RESOURCES_DTO_MAP) {
+                    // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables
+                    // if they already exist
+                    schemaResourcesDTO = SCHEMA_RESOURCES_DTO_MAP.get(moduleSchemaCacheDirectory);
                     if (schemaResourcesDTO == null) {
                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
                         schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
-                                TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(), schemaResourcesDTO.getSchemaRegistry())
+                                TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(),
+                                        schemaResourcesDTO.getSchemaRegistry())
                         );
-                        schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
+                        SCHEMA_RESOURCES_DTO_MAP.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
                     }
                 }
                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
@@ -345,8 +358,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
         }
 
         if (schemaResourcesDTO == null) {
-            schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository, schemaContextFactory,
-                    new NetconfStateSchemasResolverImpl());
+            schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository,
+                    schemaContextFactory, new NetconfStateSchemasResolverImpl());
         }
 
         return schemaResourcesDTO;
@@ -377,17 +390,23 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
      * @param schemaCacheDirectory The custom cache directory relative to "cache"
      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
      */
-    private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
+    private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(
+            final String schemaCacheDirectory) {
         final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
-        return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
+        return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class,
+                new File(relativeSchemaCacheDirectory));
     }
 
-    public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener, final NetconfNode node) {
+    public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
+                                                                  final NetconfNode node) {
 
         //setup default values since default value is not supported in mdsal
-        final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null ? DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
-        final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
-        final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
+        final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
+                ? DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
+        final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
+                ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
+        final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
+                ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
         final BigDecimal sleepFactor = node.getSleepFactor() == null ? DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
 
         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
@@ -398,10 +417,13 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
 
         final AuthenticationHandler authHandler;
         final Credentials credentials = node.getCredentials();
-        if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
+        if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114
+                .netconf.node.credentials.credentials.LoginPassword) {
             authHandler = new LoginPassword(
-                    ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
-                    ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
+                    ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114
+                            .netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
+                    ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114
+                            .netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
         } else {
             throw new IllegalStateException("Only login/password authentification is supported");
         }
@@ -411,22 +433,22 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
                 .withReconnectStrategy(strategy)
                 .withAuthHandler(authHandler)
-                .withProtocol(node.isTcpOnly() ?
-                        NetconfClientConfiguration.NetconfClientProtocol.TCP :
+                .withProtocol(node.isTcpOnly() ? NetconfClientConfiguration.NetconfClientProtocol.TCP :
                         NetconfClientConfiguration.NetconfClientProtocol.SSH)
                 .withConnectStrategyFactory(sf)
                 .withSessionListener(listener)
                 .build();
     }
 
-    protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id);
+    protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(RemoteDeviceId id);
 
     private InetSocketAddress getSocketAddress(final Host host, final int port) {
-        if(host.getDomainName() != null) {
+        if (host.getDomainName() != null) {
             return new InetSocketAddress(host.getDomainName().getValue(), port);
         } else {
             final IpAddress ipAddress = host.getIpAddress();
-            final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
+            final String ip = ipAddress.getIpv4Address() != null
+                    ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
             return new InetSocketAddress(ip, port);
         }
     }
@@ -448,9 +470,9 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
 
         //non-module capabilities should not exist in yang module capabilities
         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
-        Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(), "List yang-module-capabilities/capability " +
-                "should contain only module based capabilities. Non-module capabilities used: " +
-                netconfSessionPreferences.getNonModuleCaps());
+        Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
+                "List yang-module-capabilities/capability should contain only module based capabilities. "
+                        + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
 
         boolean overrideNonModuleCaps = false;
         if (node.getNonModuleCapabilities() != null) {
@@ -458,8 +480,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
             overrideNonModuleCaps = node.getNonModuleCapabilities().isOverride();
         }
 
-        return Optional.of(new UserPreferences(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined),
-                overrideYangModuleCaps, overrideNonModuleCaps));
+        return Optional.of(new UserPreferences(NetconfSessionPreferences
+            .fromStrings(capabilities, CapabilityOrigin.UserDefined), overrideYangModuleCaps, overrideNonModuleCaps));
     }
 
     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
@@ -468,7 +490,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
         private final double sleepFactor;
         private final int minSleep;
 
-        TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
+        TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
+                                      final int minSleep, final BigDecimal sleepFactor) {
             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
                 connectionAttempts = maxConnectionAttempts;
             } else {
@@ -495,7 +518,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
         private final NetconfDeviceCommunicator communicator;
         private final RemoteDeviceHandler<NetconfSessionPreferences> facade;
 
-        public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator, final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
+        public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator,
+                                   final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
             this.communicator = communicator;
             this.facade = facade;
         }
index 632c2f9e597ca13f0f3047ee6b05e32fdc487178..0f99262b7069eaa9283e7bb8a69c2cfc267a18de 100644 (file)
@@ -18,9 +18,11 @@ public interface NetconfConnectorFactory {
 
     /**
      * Create a new netconf connector with default values.
+     *
      * <p>
-     * This method will create a {@link Node} and a {@link NetconfNode} that will be added as an augmentation to the
-     * {@link Node}. Afterward, that {@link Node} will be written in the MDSAL datastore under the {@link NetconfTopology}.
+     * This method will create a {@link Node} and a {@link NetconfNode}
+     * that will be added as an augmentation to the {@link Node}.
+     * Afterward, that {@link Node} will be written in the MDSAL datastore under the {@link NetconfTopology}.
      * Listeners of that subtree located within network-topology bundle will setup the session.
      *
      * @param dataBroker Instance of the {@link DataBroker}
@@ -33,12 +35,12 @@ public interface NetconfConnectorFactory {
      * @param reconnectOnSchemaChange Whether to enable ietf-netconf-monitoring and register the NETCONF stream.
      * @return The created {@link Node}
      */
-    Node newInstance(final DataBroker dataBroker,
-                     final String instanceName,
-                     final String address,
-                     final Integer port,
-                     final String username,
-                     final String password,
-                     final Boolean tcpOnly,
-                     final Boolean reconnectOnSchemaChange);
+    Node newInstance(DataBroker dataBroker,
+                     String instanceName,
+                     String address,
+                     Integer port,
+                     String username,
+                     String password,
+                     Boolean tcpOnly,
+                     Boolean reconnectOnSchemaChange);
 }
index 2ceee2bd072dd7e829d2e671402c3f3c520a449a..cb3e2d06d8b686f1cdd79c1374eac594bc09e357 100644 (file)
@@ -10,7 +10,7 @@ package org.opendaylight.netconf.topology.api;
 
 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
 
-public interface SchemaRepositoryProvider{
+public interface SchemaRepositoryProvider {
 
     SharedSchemaRepository getSharedSchemaRepository();
 }
index dc5649f49a1dd7b4d84c6e52a107885034641ae8..c925a8828f012ceaa3ca7d4e6315cdb37205ba55 100644 (file)
@@ -45,9 +45,6 @@ public class NetconfConnectorFactoryImpl implements NetconfConnectorFactory {
     private static final InstanceIdentifier<Topology> TOPOLOGY_PATH = InstanceIdentifier.create(NetworkTopology.class)
             .child(Topology.class, new TopologyKey(new TopologyId("topology-netconf")));
 
-    /**
-     * {@inheritDoc}
-     */
     @Override
     public Node newInstance(final DataBroker dataBroker,
                             final String instanceName,
@@ -90,8 +87,8 @@ public class NetconfConnectorFactoryImpl implements NetconfConnectorFactory {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.error("Node {} creation failed: {}", instanceName, t);
+            public void onFailure(final Throwable throwable) {
+                LOG.error("Node {} creation failed: {}", instanceName, throwable);
             }
         });
         return node;
index 243f09a77f8e1a49837e686d7ce102f27a825096..97bf00a5fdbce8e4385447f046c23c79da3c5cb6 100644 (file)
@@ -42,7 +42,8 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfTopologyImpl extends AbstractNetconfTopology implements DataTreeChangeListener<Node>, AutoCloseable {
+public class NetconfTopologyImpl extends AbstractNetconfTopology
+        implements DataTreeChangeListener<Node>, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfTopologyImpl.class);
 
@@ -50,7 +51,8 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
 
     public NetconfTopologyImpl(final String topologyId, final NetconfClientDispatcher clientDispatcher,
                                final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
-                               final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
+                               final ThreadPool processingExecutor,
+                               final SchemaRepositoryProvider schemaRepositoryProvider,
                                final DataBroker dataBroker, final DOMMountPointService mountPointService) {
         super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor, processingExecutor,
                 schemaRepositoryProvider, dataBroker, mountPointService);
@@ -76,7 +78,7 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
     }
 
     /**
-     * Invoke by blueprint
+     * Invoked by blueprint.
      */
     public void init() {
         final WriteTransaction wtx = dataBroker.newWriteOnlyTransaction();
@@ -89,8 +91,8 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.error("Unable to initialize netconf-topology, {}", t);
+            public void onFailure(final Throwable throwable) {
+                LOG.error("Unable to initialize netconf-topology, {}", throwable);
             }
         });
 
@@ -116,7 +118,8 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
                 case WRITE:
                     LOG.debug("Config for node {} created", TopologyUtil.getNodeId(rootNode.getIdentifier()));
                     if (activeConnectors.containsKey(TopologyUtil.getNodeId(rootNode.getIdentifier()))) {
-                        LOG.warn("RemoteDevice{{}} was already configured, reconfiguring..", TopologyUtil.getNodeId(rootNode.getIdentifier()));
+                        LOG.warn("RemoteDevice{{}} was already configured, reconfiguring..",
+                                TopologyUtil.getNodeId(rootNode.getIdentifier()));
                         disconnectNode(TopologyUtil.getNodeId(rootNode.getIdentifier()));
                     }
                     connectNode(TopologyUtil.getNodeId(rootNode.getIdentifier()), rootNode.getDataAfter());
@@ -125,16 +128,20 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
                     LOG.debug("Config for node {} deleted", TopologyUtil.getNodeId(rootNode.getIdentifier()));
                     disconnectNode(TopologyUtil.getNodeId(rootNode.getIdentifier()));
                     break;
+                default:
+                    LOG.debug("Unsupported modification type: {}.", rootNode.getModificationType());
             }
         }
     }
 
     private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType) {
         final NetworkTopology networkTopology = new NetworkTopologyBuilder().build();
-        final InstanceIdentifier<NetworkTopology> networkTopologyId = InstanceIdentifier.builder(NetworkTopology.class).build();
+        final InstanceIdentifier<NetworkTopology> networkTopologyId =
+                InstanceIdentifier.builder(NetworkTopology.class).build();
         wtx.merge(datastoreType, networkTopologyId, networkTopology);
         final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(topologyId)).build();
-        wtx.merge(datastoreType, networkTopologyId.child(Topology.class, new TopologyKey(new TopologyId(topologyId))), topology);
+        wtx.merge(datastoreType,
+                networkTopologyId.child(Topology.class, new TopologyKey(new TopologyId(topologyId))), topology);
     }
 
 }
index 082d868fb177d8aa315f0bfd335b23ac6c68b52f..1a58dbee7daa65aba74fef410f488326b92dd29d 100644 (file)
@@ -35,7 +35,7 @@ public final class TopologyUtil {
         if (pathArgument instanceof InstanceIdentifier.IdentifiableItem<?, ?>) {
 
             final Identifier key = ((InstanceIdentifier.IdentifiableItem) pathArgument).getKey();
-            if(key instanceof NodeKey) {
+            if (key instanceof NodeKey) {
                 return ((NodeKey) key).getNodeId();
             }
         }
index 235086f4cf17e5542663048b831cb1daf23f09cc..52272916356f669dbdff8d814e05a262c4608c84 100644 (file)
@@ -96,10 +96,12 @@ public class NetconfTopologyImplTest {
     public void setUp() {
         MockitoAnnotations.initMocks(this);
 
-        when(mockedSchemaRepositoryProvider.getSharedSchemaRepository()).thenReturn(new SharedSchemaRepository("testingSharedSchemaRepo"));
+        when(mockedSchemaRepositoryProvider.getSharedSchemaRepository())
+                .thenReturn(new SharedSchemaRepository("testingSharedSchemaRepo"));
         when(mockedProcessingExecutor.getExecutor()).thenReturn(MoreExecutors.newDirectExecutorService());
         final Future future = new SucceededFuture(ImmediateEventExecutor.INSTANCE, new NetconfDeviceCapabilities());
-        when(mockedClientDispatcher.createReconnectingClient(any(NetconfReconnectingClientConfiguration.class))).thenReturn(future);
+        when(mockedClientDispatcher.createReconnectingClient(any(NetconfReconnectingClientConfiguration.class)))
+                .thenReturn(future);
 
         topology = new TestingNetconfTopologyImpl(TOPOLOGY_ID, mockedClientDispatcher,
                 mockedEventExecutor, mockedKeepaliveExecutor, mockedProcessingExecutor, mockedSchemaRepositoryProvider,
@@ -112,18 +114,22 @@ public class NetconfTopologyImplTest {
     public void testInit() {
         final WriteTransaction wtx = mock(WriteTransaction.class);
         when(dataBroker.newWriteOnlyTransaction()).thenReturn(wtx);
-        doNothing().when(wtx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class));
+        doNothing().when(wtx)
+                .merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class));
         when(wtx.submit()).thenReturn(Futures.<Void, TransactionCommitFailedException>immediateCheckedFuture(null));
         topology.init();
 
         //verify initialization of topology
-        final InstanceIdentifier<NetworkTopology> networkTopologyId = InstanceIdentifier.builder(NetworkTopology.class).build();
+        final InstanceIdentifier<NetworkTopology> networkTopologyId =
+                InstanceIdentifier.builder(NetworkTopology.class).build();
         final Topology topo = new TopologyBuilder().setTopologyId(new TopologyId(TOPOLOGY_ID)).build();
         final NetworkTopology networkTopology = new NetworkTopologyBuilder().build();
         verify(wtx).merge(LogicalDatastoreType.CONFIGURATION, networkTopologyId, networkTopology);
         verify(wtx).merge(LogicalDatastoreType.OPERATIONAL, networkTopologyId, networkTopology);
-        verify(wtx).merge(LogicalDatastoreType.CONFIGURATION, networkTopologyId.child(Topology.class, new TopologyKey(new TopologyId(TOPOLOGY_ID))), topo);
-        verify(wtx).merge(LogicalDatastoreType.OPERATIONAL, networkTopologyId.child(Topology.class, new TopologyKey(new TopologyId(TOPOLOGY_ID))), topo);
+        verify(wtx).merge(LogicalDatastoreType.CONFIGURATION,
+                networkTopologyId.child(Topology.class, new TopologyKey(new TopologyId(TOPOLOGY_ID))), topo);
+        verify(wtx).merge(LogicalDatastoreType.OPERATIONAL,
+                networkTopologyId.child(Topology.class, new TopologyKey(new TopologyId(TOPOLOGY_ID))), topo);
     }
 
     @Test
@@ -134,7 +140,9 @@ public class NetconfTopologyImplTest {
 
         InstanceIdentifier.PathArgument pa = null;
 
-        for (final InstanceIdentifier.PathArgument p : TopologyUtil.createTopologyListPath(TOPOLOGY_ID).child(Node.class, new NodeKey(NODE_ID)).getPathArguments()) {
+        for (final InstanceIdentifier.PathArgument p
+                : TopologyUtil.createTopologyListPath(TOPOLOGY_ID)
+                    .child(Node.class, new NodeKey(NODE_ID)).getPathArguments()) {
             pa = p;
         }
 
@@ -180,10 +188,11 @@ public class NetconfTopologyImplTest {
 
     public static class TestingNetconfTopologyImpl extends NetconfTopologyImpl {
 
-        public TestingNetconfTopologyImpl(final String topologyId, final NetconfClientDispatcher clientDispatcher,
-                                          final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
-                                          final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
-                                          final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+        public TestingNetconfTopologyImpl(
+                final String topologyId, final NetconfClientDispatcher clientDispatcher,
+                final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
+                final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
+                final DataBroker dataBroker, final DOMMountPointService mountPointService) {
             super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
                     processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService);
         }
index a0e07adaf03726ad447965007d0a53ae39a39e16..75bfe75d0cd3d5ca00c586851690dd91f031633b 100644 (file)
@@ -12,9 +12,7 @@ import static org.opendaylight.netconf.sal.rest.doc.util.RestDocgenUtil.resolveN
 import com.google.common.base.Optional;
 import com.mifmif.common.regex.Generex;
 import java.io.IOException;
-import java.net.URI;
 import java.util.ArrayList;
-import java.util.Date;
 import java.util.List;
 import java.util.Set;
 import java.util.regex.Pattern;
@@ -24,6 +22,7 @@ import org.json.JSONException;
 import org.json.JSONObject;
 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder;
 import org.opendaylight.netconf.sal.rest.doc.model.builder.OperationBuilder.Post;
+import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
@@ -506,23 +505,27 @@ public class ModelGenerator {
     private String processLeafRef(final DataSchemaNode node, final JSONObject property, final SchemaContext schemaContext,
                                   final TypeDefinition<?> leafTypeDef) {
         RevisionAwareXPath xPath = ((LeafrefTypeDefinition) leafTypeDef).getPathStatement();
-        final URI namespace = leafTypeDef.getQName().getNamespace();
-        final Date revision = leafTypeDef.getQName().getRevision();
-        final Module module = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
         final SchemaNode schemaNode;
 
         final String xPathString = STRIP_PATTERN.matcher(xPath.toString()).replaceAll("");
         xPath = new RevisionAwareXPathImpl(xPathString, xPath.isAbsolute());
 
+        final Module module;
         if (xPath.isAbsolute()) {
+            module = findModule(schemaContext, leafTypeDef.getQName());
             schemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xPath);
         } else {
+            module = findModule(schemaContext, node.getQName());
             schemaNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, node, xPath);
         }
 
         return processTypeDef(((TypedSchemaNode) schemaNode).getType(), (DataSchemaNode) schemaNode, property, schemaContext);
     }
 
+    private static Module findModule(final SchemaContext schemaContext, final QName qName) {
+        return schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(), qName.getRevision());
+    }
+
     private static String processBinaryType(final JSONObject property) throws JSONException {
         final JSONObject media = new JSONObject();
         media.put(BINARY_ENCODING_KEY, BASE_64);