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;
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);
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;
}
@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));
<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>
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.
/**
* 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
/**
* 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
*/
/**
* 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
*/
* 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) {
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) {
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()) {
}
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;
--- /dev/null
+/*
+ * 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
--- /dev/null
+/*
+ * 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);
+
+ }
+}
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();
--- /dev/null
+<!--
+ ~ 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
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;
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
revision "2015-02-26";
+ identity foo {
+ description "dummy identity";
+ }
container mapping-nodes {
list multiple-keys {
<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>
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);
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;
}
};
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();
element.setAttributeNS(XMLNS_URI, name, namespaceURI.get());
return element;
}
- return document.createElement(qName);
+ return document.createElement(qualifiedName);
}
}
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);
* {@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()) {
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));
}
}
}
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);
}
- @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;
}
}
- @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) {
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) {
/**
* Returns all available notification paths that matches given pattern.
+ *
* @param notificationPattern pattern
* @return notification paths
*/
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());
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;
}
/**
- * 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()) {
}
/**
- * Invoke by blueprint
- * @param streamMap
+ * Invoked by blueprint.
+ *
+ * @param streamMap Stream map
*/
public void setStreamMap(Map<String, String> streamMap) {
this.streamMap = streamMap;
return node.getAugmentation(NetconfNode.class) != null;
}
- @Override public void close() {
+ @Override
+ public void close() {
listenerRegistration.close();
for (final NetconfEventSourceRegistration reg : registrationMap.values()) {
reg.close();
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;
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();
}
/**
- * 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));
/**
* Invokes create-subscription rpc on mounted device stream.
+ *
* @param stream stream
* @return rpc result
*/
}
/**
- * Returns list of streams avaliable on device
+ * Returns list of streams avaliable on device.
+ *
* @return list of streams
* @throws ReadFailedException if data read fails
*/
.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();
}
/**
* 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);
}
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;
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);
return false;
}
for (final AvailableCapability capability : netconfNode.getAvailableCapabilities().getAvailableCapability()) {
- if (capability.getCapability().startsWith(NotificationCapabilityPrefix)) {
+ if (capability.getCapability().startsWith(NOTIFICATION_CAPABILITY_PREFIX)) {
return true;
}
}
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());
}
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() {
}
}
- @Override public void close() {
+ @Override
+ public void close() {
closeEventSourceRegistration();
}
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;
/**
* Returns registered topics for given notification path.
+ *
* @param notificationPath path
* @return topicIds
*/
/**
* Checks, if notification is from namespace belonging to this registration.
+ *
* @param notificationPath path
* @return true, if notification belongs to registration namespace
*/
}
String nameSpace = notificationPath.getLastComponent().getNamespace().toString();
LOG.debug("CheckNotification - name space {} - NotificationUrnPrefix {}", nameSpace,
- getNotificationUrnPrefix());
+ getNotificationUrnPrefix());
return nameSpace.startsWith(getNotificationUrnPrefix());
}
/**
* 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
*/
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();
}
/**
- * 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() {
}
}
- @Override void deActivateNotificationSource() {
+ @Override
+ void deActivateNotificationSource() {
// no operations need
}
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;
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);
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);
}
}
- @Override public void close() throws Exception {
+ @Override
+ public void close() throws Exception {
closeStream();
}
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));
/**
* 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();
@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,
@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<>();
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);
}
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);
}
.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()));
.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();
.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()));
}
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
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;
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
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,
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);
}
.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;
}
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);
}
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();
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)
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);
}
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;
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);
}
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));
</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>
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();
}
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,
}
@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");
}
}
@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);
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();
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";
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) {
}
}
- public static class NetconfMonitoringOperationServiceFactory implements NetconfOperationServiceFactory, AutoCloseable {
+ public static class NetconfMonitoringOperationServiceFactory implements NetconfOperationServiceFactory,
+ AutoCloseable {
private final NetconfMonitoringOperationService operationService;
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);
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();
}
}
} catch (final JAXBException e) {
throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e);
}
- return ((Document)res.getNode()).getDocumentElement();
+ return ((Document) res.getNode()).getDocumentElement();
}
}
private final Schema schema;
- public MonitoringSchema(Schema schema) {
+ MonitoringSchema(Schema schema) {
this.schema = schema;
}
@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";
}
}
@XmlTransient
private Session managementSession;
- public MonitoringSession(Session managementSession) {
+ MonitoringSession(Session managementSession) {
this.managementSession = managementSession;
}
- public MonitoringSession() {
+ MonitoringSession() {
}
public void setManagementSession(Session managementSession) {
@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();
}
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
});
}
- @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
@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
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)
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
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();
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;
}
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;
}
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;
}
@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"));
}
- 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());
}
}
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());
@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();
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();
}
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;
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
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)));
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;
});
}
- 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() {
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;
});
}
- 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
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;
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,
/* 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);
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;
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();
}
@Test
- public void testKeapAliveFacade() throws UnknownHostException {
+ public void testKeapAliveFacade() {
final ExecutorService executorService = mock(ExecutorService.class);
doReturn(executorService).when(processingExecutor).getExecutor();
.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));
}
@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);
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);
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;
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,
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;
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();
<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>
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";
* 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()));
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;
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
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);
}
@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?
}
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);
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
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())));
}
}
}
// 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 {}",
}
if (schemaResourcesDTO == null) {
- schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository, schemaContextFactory,
- new NetconfStateSchemasResolverImpl());
+ schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository,
+ schemaContextFactory, new NetconfStateSchemasResolverImpl());
}
return schemaResourcesDTO;
* @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());
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");
}
.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);
}
}
//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) {
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 {
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 {
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;
}
/**
* 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}
* @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);
}
import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
-public interface SchemaRepositoryProvider{
+public interface SchemaRepositoryProvider {
SharedSchemaRepository getSharedSchemaRepository();
}
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,
}
@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;
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);
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);
}
/**
- * Invoke by blueprint
+ * Invoked by blueprint.
*/
public void init() {
final WriteTransaction wtx = dataBroker.newWriteOnlyTransaction();
}
@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);
}
});
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());
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);
}
}
if (pathArgument instanceof InstanceIdentifier.IdentifiableItem<?, ?>) {
final Identifier key = ((InstanceIdentifier.IdentifiableItem) pathArgument).getKey();
- if(key instanceof NodeKey) {
+ if (key instanceof NodeKey) {
return ((NodeKey) key).getNodeId();
}
}
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,
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
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;
}
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);
}
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;
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;
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);