<name>OpenDaylight :: Netconf :: Netty Util</name>
<dependencies>
+ <dependency>
+ <groupId>org.apache.karaf.features</groupId>
+ <artifactId>standard</artifactId>
+ <version>${karaf4.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>odl-netconf-api</artifactId>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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
+ -->
+<features name="odl-netconf-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.4.0">
+ <feature name="odl-netconf-netty-util" version="${project.version}">
+ <feature version="${karaf4.version}">ssh</feature>
+ </feature>
+</features>
<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)));
</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>
package org.opendaylight.netconf.topology.singleton.api;
/**
- * Provides API for advertising services for blue print service
+ * Provides API for advertising services for blue print service.
*/
public interface NetconfTopologySingletonService {
}
import akka.actor.ActorRef;
/**
- * Provides API for connection odl (master) with device
+ * Provides API for connection odl (master) with device.
*/
public interface RemoteDeviceConnector {
/**
- * Create device communicator and open device connection
+ * Create device communicator and open device connection.
* @param masterActorRef master actor reference
*/
void startRemoteDeviceConnection(ActorRef masterActorRef);
/**
- * Stop device communicator
+ * Stop device communicator.
*/
void stopRemoteDeviceConnection();
}
salProvider.getMountInstance().onTopologyDeviceDisconnected();
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void closeGracefully(final AutoCloseable resource) {
if (resource != null) {
try {
import java.util.Collection;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
+import org.opendaylight.netconf.topology.singleton.messages.RefreshSlaveActor;
import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
break;
case WRITE:
if (rootNode.getDataBefore() != null) {
- LOG.debug("{}: Operational for node {} rewrited. Trying to register slave mount point", id, nodeId);
+ LOG.debug("{}: Operational for node {} rewrited. Trying to register slave mount point",
+ id, nodeId);
} else {
- LOG.debug("{}: Operational for node {} created. Trying to register slave mount point", id, nodeId);
+ LOG.debug("{}: Operational for node {} created. Trying to register slave mount point",
+ id, nodeId);
}
handleSlaveMountPoint(rootNode);
break;
case DELETE:
- LOG.debug("{}: Operational for node {} deleted. Trying to remove slave mount point", id, nodeId);
- closeActor();
+ LOG.debug("{}: Operational for node {} deleted.", id, nodeId);
+ unregisterSlaveMountpoint();
break;
default:
LOG.debug("{}: Uknown operation for node: {}", id, nodeId);
@Override
public void close() {
+ unregisterSlaveMountpoint();
closeActor();
-
if (dataChangeListenerRegistration != null) {
dataChangeListenerRegistration.close();
dataChangeListenerRegistration = null;
private void closeActor() {
if (slaveActorRef != null) {
- slaveActorRef.tell(new UnregisterSlaveMountPoint(), ActorRef.noSender());
+ LOG.debug("{}: Sending poison pill to {}", id, slaveActorRef);
slaveActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
slaveActorRef = null;
}
}
+ private void unregisterSlaveMountpoint() {
+ if (slaveActorRef != null) {
+ LOG.debug("{}: Sending message to unregister slave mountpoint to {}", id, slaveActorRef);
+ slaveActorRef.tell(new UnregisterSlaveMountPoint(), ActorRef.noSender());
+ }
+ }
+
void registerDataTreeChangeListener(final String topologyId, final NodeKey key) {
LOG.debug("{}: Registering data tree change listener on node {}", id, key);
dataChangeListenerRegistration = setup.getDataBroker().registerDataTreeChangeListener(
final NetconfNode netconfNodeAfter = rootNode.getDataAfter().getAugmentation(NetconfNode.class);
if (NetconfNodeConnectionStatus.ConnectionStatus.Connected.equals(netconfNodeAfter.getConnectionStatus())) {
- createActorRef();
+ createOrUpdateActorRef();
final String masterAddress = netconfNodeAfter.getClusteredConnectionStatus().getNetconfMasterNode();
final String path = NetconfTopologyUtils.createActorPath(masterAddress,
NetconfTopologyUtils.createMasterActorName(id.getName(),
netconfNodeAfter.getClusteredConnectionStatus().getNetconfMasterNode()));
setup.getActorSystem().actorSelection(path).tell(new AskForMasterMountPoint(), slaveActorRef);
} else {
- closeActor();
+ unregisterSlaveMountpoint();
}
}
- private void createActorRef() {
+ private void createOrUpdateActorRef() {
if (slaveActorRef == null) {
slaveActorRef = setup.getActorSystem().actorOf(NetconfNodeActor.props(setup, id, schemaRegistry,
- schemaRepository, actorResponseWaitTime, mountPointService), id.getName());
+ schemaRepository, actorResponseWaitTime, mountPointService));
+ LOG.debug("{}: Slave actor created with name {}", id, slaveActorRef);
+ } else {
+ slaveActorRef
+ .tell(new RefreshSlaveActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime),
+ ActorRef.noSender());
}
}
}
if (!finalClose) {
- final String masterAddress = Cluster.get(netconfTopologyDeviceSetup.getActorSystem()).selfAddress().toString();
+ final String masterAddress =
+ Cluster.get(netconfTopologyDeviceSetup.getActorSystem()).selfAddress().toString();
masterActorRef = netconfTopologyDeviceSetup.getActorSystem().actorOf(NetconfNodeActor.props(
netconfTopologyDeviceSetup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
actorResponseWaitTime, mountService),
}
/**
- * If configuration data was changed
+ * Refresh, if configuration data was changed.
* @param setup new setup
*/
void refresh(@Nonnull final NetconfTopologySetup setup) {
context.refresh(createSetup(instanceIdentifier, node));
}
+ // ClusterSingletonServiceRegistration registerClusterSingletonService method throws a Runtime exception if there
+ // are problems with registration and client has to deal with it. Only thing we can do if this error occurs is to
+ // retry registration several times and log the error.
+ // TODO change to a specific documented Exception when changed in ClusterSingletonServiceProvider
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void startNetconfDeviceContext(final InstanceIdentifier<Node> instanceIdentifier, final Node node) {
final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
Preconditions.checkNotNull(netconfNode);
new NetconfTopologyContext(createSetup(instanceIdentifier, node), serviceGroupIdent,
actorResponseWaitTime, mountPointService);
- final ClusterSingletonServiceRegistration clusterSingletonServiceRegistration =
- clusterSingletonServiceProvider.registerClusterSingletonService(newNetconfTopologyContext);
+ int tries = 3;
+ while (true) {
+ try {
+ final ClusterSingletonServiceRegistration clusterSingletonServiceRegistration =
+ clusterSingletonServiceProvider.registerClusterSingletonService(newNetconfTopologyContext);
+ clusterRegistrations.put(instanceIdentifier, clusterSingletonServiceRegistration);
+ contexts.put(instanceIdentifier, newNetconfTopologyContext);
+ break;
+ } catch (final RuntimeException e) {
+ LOG.warn("Unable to register cluster singleton service {}, trying again", newNetconfTopologyContext, e);
+
+ if (--tries <= 0) {
+ LOG.error("Unable to register cluster singleton service {} - done trying, closing topology context",
+ newNetconfTopologyContext, e);
+ close();
+ break;
+ }
+ }
+ }
- clusterRegistrations.put(instanceIdentifier, clusterSingletonServiceRegistration);
- contexts.put(instanceIdentifier, newNetconfTopologyContext);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void stopNetconfDeviceContext(final InstanceIdentifier<Node> instanceIdentifier) {
if (contexts.containsKey(instanceIdentifier)) {
try {
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void close() {
if (dataChangeListenerRegistration != null) {
NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this);
}
- private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType, final String topologyId) {
+ private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType,
+ final String topologyId) {
final NetworkTopology networkTopology = new NetworkTopologyBuilder().build();
final InstanceIdentifier<NetworkTopology> networkTopologyId =
InstanceIdentifier.builder(NetworkTopology.class).build();
private final ActorSystem actorSystem;
/**
+ * Constructor for {@code ProxyDOMDataBroker}.
+ *
* @param actorSystem system
* @param id id
* @param masterNode {@link org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor} ref
this.askTimeout = askTimeout;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
final Future<Object> txActorFuture = Patterns.ask(masterNode, new NewReadTransactionRequest(), askTimeout);
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public DOMDataReadWriteTransaction newReadWriteTransaction() {
final Future<Object> txActorFuture = Patterns.ask(masterNode, new NewReadWriteTransactionRequest(), askTimeout);
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public DOMDataWriteTransaction newWriteOnlyTransaction() {
final Future<Object> txActorFuture = Patterns.ask(masterNode, new NewWriteTransactionRequest(), askTimeout);
final CheckedFuture<DOMRpcResult, DOMRpcException> checkedFuture = Futures.makeChecked(settableFuture,
new Function<Exception, DOMRpcException>() {
- @Nullable
- @Override
- public DOMRpcException apply(@Nullable final Exception exception) {
- return new ClusteringRpcException(id + ": Exception during remote rpc invocation.",
- exception);
- }
- });
+ @Nullable
+ @Override
+ public DOMRpcException apply(@Nullable final Exception exception) {
+ return new ClusteringRpcException(id + ": Exception during remote rpc invocation.",
+ exception);
+ }
+ });
scalaFuture.onComplete(new OnComplete<Object>() {
@Override
final NormalizedNodeMessage normalizedNodeMessageResult =
((InvokeRpcMessageReply) success).getNormalizedNodeMessage();
final DOMRpcResult result;
- if (normalizedNodeMessageResult == null ){
+ if (normalizedNodeMessageResult == null) {
result = new DefaultDOMRpcResult(errors);
} else {
if (errors == null) {
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
});
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void stopRemoteDeviceConnection() {
Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
}
return new NetconfConnectorDTO(
- userCapabilities.isPresent()
- ? new NetconfDeviceCommunicator(
- remoteDeviceId, device, new UserPreferences(userCapabilities.get(),
- node.getYangModuleCapabilities().isOverride(), node.getNonModuleCapabilities().isOverride()),
- rpcMessageLimit)
+ userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
+ new UserPreferences(userCapabilities.get(),
+ Objects.isNull(node.getYangModuleCapabilities())
+ ? false : node.getYangModuleCapabilities().isOverride(),
+ Objects.isNull(node.getNonModuleCapabilities())
+ ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
: new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
}
//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());
if (node.getNonModuleCapabilities() != null) {
capabilities.addAll(node.getNonModuleCapabilities().getCapability());
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(remoteDeviceId + ": Only login/password authentication is supported");
}
salProvider.getMountInstance().onTopologyDeviceDisconnected();
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void close() {
unregisterSlaveMountPoint();
try {
import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
+import org.opendaylight.netconf.topology.singleton.messages.RefreshSlaveActor;
import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
import org.opendaylight.netconf.topology.singleton.messages.YangTextSchemaSourceRequest;
private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeActor.class);
- private final SchemaSourceRegistry schemaRegistry;
- private final SchemaRepository schemaRepository;
- private final Timeout actorResponseWaitTime;
private final Duration writeTxIdleTimeout;
private final DOMMountPointService mountPointService;
+ private SchemaSourceRegistry schemaRegistry;
+ private SchemaRepository schemaRepository;
+ private Timeout actorResponseWaitTime;
private RemoteDeviceId id;
private NetconfTopologySetup setup;
private List<SourceIdentifier> sourceIdentifiers;
this.mountPointService = mountPointService;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public void onReceive(final Object message) throws Exception {
if (message instanceof CreateInitialMasterActorData) { // master
slaveSalManager.close();
slaveSalManager = null;
}
-
+ } else if (message instanceof RefreshSlaveActor) { //slave
+ actorResponseWaitTime = ((RefreshSlaveActor) message).getActorResponseWaitTime();
+ id = ((RefreshSlaveActor) message).getId();
+ schemaRegistry = ((RefreshSlaveActor) message).getSchemaRegistry();
+ setup = ((RefreshSlaveActor) message).getSetup();
+ schemaRepository = ((RefreshSlaveActor) message).getSchemaRepository();
}
+
}
@Override
private final DOMDataReadTransaction tx;
- public ReadAdapter(final DOMDataReadTransaction tx) {
+ ReadAdapter(final DOMDataReadTransaction tx) {
this.tx = tx;
}
+ @SuppressWarnings("checkstyle:IllegalThrows")
public void handle(final Object message, final ActorRef sender, final ActorRef self) throws Throwable {
if (message instanceof ReadRequest) {
class WriteAdapter {
private final DOMDataWriteTransaction tx;
- public WriteAdapter(final DOMDataWriteTransaction tx) {
+ WriteAdapter(final DOMDataWriteTransaction tx) {
this.tx = tx;
}
private final ActorSystem actorSystem;
private final Timeout askTimeout;
- public ProxyReadAdapter(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
+ ProxyReadAdapter(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
final Timeout askTimeout) {
this.masterTxActor = masterTxActor;
this.id = id;
private final ProxyReadAdapter delegate;
/**
+ * Constructor for {@code ProxyReadTransaction}.
+ *
* @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadTransactionActor} ref
* @param id device id
* @param actorSystem system
- * @param askTimeout
+ * @param askTimeout timeout
*/
public ProxyReadTransaction(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
final Timeout askTimeout) {
private final ProxyWriteAdapter delegateWrite;
/**
- * @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadWriteTransactionActor} ref
+ * Constructor for {@code ProxyReadWriteTransaction}.
+ *
+ * @param masterTxActor
+ * {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadWriteTransactionActor} ref
* @param id device id
* @param actorSystem system
- * @param askTimeout
+ * @param askTimeout timeout
*/
public ProxyReadWriteTransaction(final ActorRef masterTxActor, final RemoteDeviceId id,
final ActorSystem actorSystem, final Timeout askTimeout) {
this.askTimeout = askTimeout;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public boolean cancel() {
if (!opened.compareAndSet(true, false)) {
return false;
private final ProxyWriteAdapter proxyWriteAdapter;
/**
+ * Constructor for {@code ProxyWriteTransaction}.
+ *
* @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.WriteTransactionActor} ref
* @param id device id
* @param actorSystem system
- * @param askTimeout
+ * @param askTimeout timeout
*/
public ProxyWriteTransaction(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
final Timeout askTimeout) {
proxyWriteAdapter = new ProxyWriteAdapter(masterTxActor, id, actorSystem, askTimeout);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public boolean cancel() {
return proxyWriteAdapter.cancel();
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.util.HashMap;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
import java.util.Map;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemasResolverImpl;
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
* 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()));
DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
// Multiple modules may be created at once; synchronize to avoid issues with data consistency among
// threads.
- synchronized (schemaResourcesDTOs) {
+ synchronized (SCHEMA_RESOURCES_DTO_MAP) {
// Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if
// they already exist
- schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
+ schemaResourcesDTO = SCHEMA_RESOURCES_DTO_MAP.get(moduleSchemaCacheDirectory);
if (schemaResourcesDTO == null) {
schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(),
schemaResourcesDTO.getSchemaRegistry())
);
- schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
+ SCHEMA_RESOURCES_DTO_MAP.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
}
}
LOG.info("{} : netconf connector will use schema cache directory {} instead of {}",
}
if (schemaResourcesDTO == null) {
- synchronized (schemaResourcesDTOs) {
- schemaResourcesDTO = schemaResourcesDTOs.get(DEFAULT_CACHE_DIRECTORY);
+ synchronized (SCHEMA_RESOURCES_DTO_MAP) {
+ schemaResourcesDTO = SCHEMA_RESOURCES_DTO_MAP.get(DEFAULT_CACHE_DIRECTORY);
}
LOG.info("{} : using the default directory {}",
deviceId, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
/**
- * Master sends this message to the own actor to refresh setup data
+ * Master sends this message to the own actor to refresh setup data.
*/
public class RefreshSetupMasterActorData implements Serializable {
private static final long serialVersionUID = 1L;
--- /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.topology.singleton.messages;
+
+import akka.util.Timeout;
+import java.io.Serializable;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
+import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
+
+public class RefreshSlaveActor implements Serializable {
+
+ private final SchemaRepository schemaRepository;
+ private final RemoteDeviceId id;
+ private final SchemaSourceRegistry schemaRegistry;
+ private final NetconfTopologySetup setup;
+ private final Timeout actorResponseWaitTime;
+
+ public RefreshSlaveActor(final NetconfTopologySetup setup, final RemoteDeviceId id,
+ final SchemaSourceRegistry schemaRegistry, final SchemaRepository schemaRepository,
+ final Timeout actorResponseWaitTime) {
+ this.setup = setup;
+ this.id = id;
+ this.schemaRegistry = schemaRegistry;
+ this.schemaRepository = schemaRepository;
+ this.actorResponseWaitTime = actorResponseWaitTime;
+ }
+
+ public Timeout getActorResponseWaitTime() {
+ return actorResponseWaitTime;
+ }
+
+ public SchemaRepository getSchemaRepository() {
+ return schemaRepository;
+ }
+
+ public RemoteDeviceId getId() {
+ return id;
+ }
+
+ public SchemaSourceRegistry getSchemaRegistry() {
+ return schemaRegistry;
+ }
+
+ public NetconfTopologySetup getSetup() {
+ return setup;
+ }
+}
private SchemaPathMessage schemaPathMessage;
- public Proxy() {
+ Proxy() {
//due to Externalizable
}
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeInt(Iterables.size(schemaPathMessage.getSchemaPath().getPathTowardsRoot()));
- for (final QName qName : schemaPathMessage.getSchemaPath().getPathTowardsRoot()) {
- out.writeObject(qName);
+ for (final QName qualifiedName : schemaPathMessage.getSchemaPath().getPathTowardsRoot()) {
+ out.writeObject(qualifiedName);
}
out.writeBoolean(schemaPathMessage.getSchemaPath().isAbsolute());
this.schemaPathMessage = schemaPathMessage;
this.normalizedNodeMessage = normalizedNodeMessage;
}
+
private SchemaPathMessage getSchemaPathMessage() {
return schemaPathMessage;
}
private InvokeRpcMessage invokeRpcMessage;
- public Proxy() {
+ Proxy() {
//due to Externalizable
}
private InvokeRpcMessageReply invokeRpcMessageReply;
- public Proxy() {
+ Proxy() {
//due to Externalizable
}
import java.io.Serializable;
/**
- * Message is sended when RPC result does not exist or is empty
+ * Message is sended when RPC result does not exist or is empty.
*/
public class EmptyResultResponse implements Serializable {
private static final long serialVersionUID = 1L;
import java.io.Serializable;
/**
- * Message sent from master back to the slave when submit is not performed, tx is closed
+ * Message sent from master back to the slave when submit is not performed, tx is closed.
*/
public class SubmitFailedReply implements Serializable {
private static final long serialVersionUID = 1L;
@Before
public void setup() {
- initMocks
- (this);
+ initMocks(this);
remoteDeviceId = new RemoteDeviceId("netconf-topology",
new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
final YangTextSchemaSource yangTextSchemaSource = new YangTextSchemaSource(sourceIdentifier) {
@Override
- protected MoreObjects.ToStringHelper addToStringAttributes(final MoreObjects.ToStringHelper toStringHelper) {
+ protected MoreObjects.ToStringHelper addToStringAttributes(
+ final MoreObjects.ToStringHelper toStringHelper) {
return null;
}
// test if slave get right identifiers from master
- final ProxyDOMRpcService slaveDomRPCService = new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT);
+ final ProxyDOMRpcService slaveDomRPCService =
+ new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT);
final SchemaPath schemaPath = SchemaPath.create(true, QName.create("TestQname"));
final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
// InvokeRpcMessageReply message
- doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode))).
- when(domRpcService).invokeRpc(any(), any());
+ doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode)))
+ .when(domRpcService).invokeRpc(any(), any());
final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureNn =
slaveDomRPCService.invokeRpc(schemaPath, outputNode);
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@Test
public void testWriteConfiguration() throws Exception {
+ writeConfiguration(false);
+ }
- final ClusterSingletonServiceRegistration clusterRegistration = mock(ClusterSingletonServiceRegistration.class);
+ @Test
+ public void testWriteConfigurationFail() throws Exception {
+ writeConfiguration(true);
+ }
+
+ @Test
+ public void testRegisterDataTreeChangeListener() {
+
+ final WriteTransaction wtx = mock(WriteTransaction.class);
+
+ doReturn(wtx).when(dataBroker).newWriteOnlyTransaction();
+ doNothing().when(wtx).merge(any(), any(), any());
+ doReturn(Futures.immediateCheckedFuture(null)).when(wtx).submit();
+ doReturn(null).when(dataBroker).registerDataChangeListener(any(), any(), any(), any());
+
+ netconfTopologyManager.init();
+
+ // verify if listener is called with right parameters = registered on right path
+
+ verify(dataBroker, times(1)).registerDataTreeChangeListener(
+ new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, NetconfTopologyUtils
+ .createTopologyListPath(topologyId).child(Node.class)), netconfTopologyManager);
+
+ }
+
+ @Test
+ public void testClose() throws Exception {
final Field fieldContexts = NetconfTopologyManager.class.getDeclaredField("contexts");
fieldContexts.setAccessible(true);
+ @SuppressWarnings("unchecked") final Map<InstanceIdentifier<Node>, NetconfTopologyContext> contexts =
+ (Map<InstanceIdentifier<Node>, NetconfTopologyContext>) fieldContexts.get(netconfTopologyManager);
+
+ final Field fieldClusterRegistrations =
+ NetconfTopologyManager.class.getDeclaredField("clusterRegistrations");
+ fieldClusterRegistrations.setAccessible(true);
@SuppressWarnings("unchecked")
- final Map<InstanceIdentifier<Node>, NetconfTopologyContext> contexts =
+ final Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration> clusterRegistrations =
+ (Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration>)
+ fieldClusterRegistrations.get(netconfTopologyManager);
+
+ final InstanceIdentifier<Node> instanceIdentifier = NetconfTopologyUtils.createTopologyNodeListPath(
+ new NodeKey(new NodeId("node-id-1")), "topology-1");
+
+
+ final NetconfTopologyContext context = mock(NetconfTopologyContext.class);
+ final ClusterSingletonServiceRegistration clusterRegistration =
+ mock(ClusterSingletonServiceRegistration.class);
+ contexts.put(instanceIdentifier, context);
+ clusterRegistrations.put(instanceIdentifier, clusterRegistration);
+
+ doNothing().when(context).closeFinal();
+ doNothing().when(clusterRegistration).close();
+
+ netconfTopologyManager.close();
+ verify(context, times(1)).closeFinal();
+ verify(clusterRegistration, times(1)).close();
+
+ assertTrue(contexts.isEmpty());
+ assertTrue(clusterRegistrations.isEmpty());
+
+ }
+
+ private void writeConfiguration(final boolean fail) throws Exception {
+
+ final ClusterSingletonServiceRegistration clusterRegistration = mock(ClusterSingletonServiceRegistration.class);
+
+ final Field fieldContexts = NetconfTopologyManager.class.getDeclaredField("contexts");
+ fieldContexts.setAccessible(true);
+ @SuppressWarnings("unchecked") final Map<InstanceIdentifier<Node>, NetconfTopologyContext> contexts =
(Map<InstanceIdentifier<Node>, NetconfTopologyContext>) fieldContexts.get(netconfTopologyManager);
- final Field fieldClusterRegistrations = NetconfTopologyManager.class.getDeclaredField("clusterRegistrations");
+ final Field fieldClusterRegistrations =
+ NetconfTopologyManager.class.getDeclaredField("clusterRegistrations");
fieldClusterRegistrations.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration> clusterRegistrations =
final Collection<DataTreeModification<Node>> changes = new ArrayList<>();
final InstanceIdentifier<Node> instanceIdentifier = NetconfTopologyUtils.createTopologyNodeListPath(
- new NodeKey(new NodeId("node-id-1")),"topology-1");
+ new NodeKey(new NodeId("node-id-1")), "topology-1");
final InstanceIdentifier<Node> instanceIdentifierDiferent = NetconfTopologyUtils.createTopologyNodeListPath(
- new NodeKey(new NodeId("node-id-2")),"topology-2");
+ new NodeKey(new NodeId("node-id-2")), "topology-2");
final DataTreeIdentifier<Node> rootIdentifier =
new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, instanceIdentifier);
final DataTreeIdentifier<Node> rootIdentifierDifferent =
new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, instanceIdentifierDiferent);
- @SuppressWarnings("unchecked")
- final DataObjectModification<Node> objectModification = mock(DataObjectModification.class);
+ @SuppressWarnings("unchecked") final DataObjectModification<Node> objectModification =
+ mock(DataObjectModification.class);
final NetconfNode netconfNode = new NetconfNodeBuilder()
.setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
final Identifier key = new NodeKey(new NodeId("node-id"));
- @SuppressWarnings("unchecked")
- final InstanceIdentifier.IdentifiableItem<Node, NodeKey> pathArgument =
+ @SuppressWarnings("unchecked") final InstanceIdentifier.IdentifiableItem<Node, NodeKey> pathArgument =
new InstanceIdentifier.IdentifiableItem(Node.class, key);
// testing WRITE on two identical rootIdentifiers and one different
-
- changes.add(new CustomTreeModification(rootIdentifier, objectModification));
- changes.add(new CustomTreeModification(rootIdentifier, objectModification));
- changes.add(new CustomTreeModification(rootIdentifierDifferent, objectModification));
-
+ if (fail) {
+ changes.add(new CustomTreeModification(rootIdentifier, objectModification));
+ } else {
+ changes.add(new CustomTreeModification(rootIdentifier, objectModification));
+ changes.add(new CustomTreeModification(rootIdentifier, objectModification));
+ changes.add(new CustomTreeModification(rootIdentifierDifferent, objectModification));
+ }
doReturn(WRITE).when(objectModification).getModificationType();
doReturn(node).when(objectModification).getDataAfter();
doReturn(pathArgument).when(objectModification).getIdentifier();
- doReturn(clusterRegistration).when(clusterSingletonServiceProvider).registerClusterSingletonService(any());
-
- netconfTopologyManager.onDataTreeChanged(changes);
-
- verify(clusterSingletonServiceProvider, times(2)).registerClusterSingletonService(any());
-
- // only two created contexts
- assertEquals(2, contexts.size());
- assertTrue(contexts.containsKey(rootIdentifier.getRootIdentifier()));
- assertTrue(contexts.containsKey(rootIdentifierDifferent.getRootIdentifier()));
-
- // only two created cluster registrations
- assertEquals(2, contexts.size());
- assertTrue(clusterRegistrations.containsKey(rootIdentifier.getRootIdentifier()));
- assertTrue(clusterRegistrations.containsKey(rootIdentifierDifferent.getRootIdentifier()));
-
- // after delete there should be no context and clustered registrations
- doReturn(DELETE).when(objectModification).getModificationType();
-
- doNothing().when(clusterRegistration).close();
+ if (fail) {
+ doThrow(new RuntimeException("error")).when(clusterSingletonServiceProvider)
+ .registerClusterSingletonService(any());
+ } else {
+ doReturn(clusterRegistration).when(clusterSingletonServiceProvider).registerClusterSingletonService(any());
+ }
netconfTopologyManager.onDataTreeChanged(changes);
- verify(clusterRegistration, times(2)).close();
-
- // empty map of contexts
- assertTrue(contexts.isEmpty());
- assertFalse(contexts.containsKey(rootIdentifier.getRootIdentifier()));
- assertFalse(contexts.containsKey(rootIdentifierDifferent.getRootIdentifier()));
-
- // empty map of clustered registrations
- assertTrue(clusterRegistrations.isEmpty());
- assertFalse(clusterRegistrations.containsKey(rootIdentifier.getRootIdentifier()));
- assertFalse(clusterRegistrations.containsKey(rootIdentifierDifferent.getRootIdentifier()));
-
- }
-
- @Test
- public void testRegisterDataTreeChangeListener() {
+ if (fail) {
+ verify(clusterSingletonServiceProvider, times(3))
+ .registerClusterSingletonService(any());
+ assertTrue(contexts.isEmpty());
+ assertTrue(clusterRegistrations.isEmpty());
+ } else {
+ verify(clusterSingletonServiceProvider, times(2))
+ .registerClusterSingletonService(any());
- final WriteTransaction wtx = mock(WriteTransaction.class);
+ // only two created contexts
+ assertEquals(2, contexts.size());
+ assertTrue(contexts.containsKey(rootIdentifier.getRootIdentifier()));
+ assertTrue(contexts.containsKey(rootIdentifierDifferent.getRootIdentifier()));
- doReturn(wtx).when(dataBroker).newWriteOnlyTransaction();
- doNothing().when(wtx).merge(any(), any(), any());
- doReturn(Futures.immediateCheckedFuture(null)).when(wtx).submit();
- doReturn(null).when(dataBroker).registerDataChangeListener(any(), any(), any(), any());
+ // only two created cluster registrations
+ assertEquals(2, clusterRegistrations.size());
+ assertTrue(clusterRegistrations.containsKey(rootIdentifier.getRootIdentifier()));
+ assertTrue(clusterRegistrations.containsKey(rootIdentifierDifferent.getRootIdentifier()));
- netconfTopologyManager.init();
+ // after delete there should be no context and clustered registrations
+ doReturn(DELETE).when(objectModification).getModificationType();
- // verify if listener is called with right parameters = registered on right path
+ doNothing().when(clusterRegistration).close();
- verify(dataBroker, times(1)).registerDataTreeChangeListener(
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, NetconfTopologyUtils
- .createTopologyListPath(topologyId).child(Node.class)), netconfTopologyManager);
+ netconfTopologyManager.onDataTreeChanged(changes);
- }
+ verify(clusterRegistration, times(2)).close();
- @Test
- public void testClose() throws Exception {
-
- final Field fieldContexts = NetconfTopologyManager.class.getDeclaredField("contexts");
- fieldContexts.setAccessible(true);
- @SuppressWarnings("unchecked")
- final Map<InstanceIdentifier<Node>, NetconfTopologyContext> contexts =
- (Map<InstanceIdentifier<Node>, NetconfTopologyContext>) fieldContexts.get(netconfTopologyManager);
-
- final Field fieldClusterRegistrations = NetconfTopologyManager.class.getDeclaredField("clusterRegistrations");
- fieldClusterRegistrations.setAccessible(true);
- @SuppressWarnings("unchecked")
- final Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration> clusterRegistrations =
- (Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration>)
- fieldClusterRegistrations.get(netconfTopologyManager);
-
- final InstanceIdentifier<Node> instanceIdentifier = NetconfTopologyUtils.createTopologyNodeListPath(
- new NodeKey(new NodeId("node-id-1")),"topology-1");
-
-
- final NetconfTopologyContext context = mock(NetconfTopologyContext.class);
- final ClusterSingletonServiceRegistration clusterRegistration =
- mock(ClusterSingletonServiceRegistration.class);
- contexts.put(instanceIdentifier, context);
- clusterRegistrations.put(instanceIdentifier, clusterRegistration);
-
- doNothing().when(context).closeFinal();
- doNothing().when(clusterRegistration).close();
-
- netconfTopologyManager.close();
- verify(context, times(1)).closeFinal();
- verify(clusterRegistration, times(1)).close();
-
- assertTrue(contexts.isEmpty());
- assertTrue(clusterRegistrations.isEmpty());
+ // empty map of contexts
+ assertTrue(contexts.isEmpty());
+ assertFalse(contexts.containsKey(rootIdentifier.getRootIdentifier()));
+ assertFalse(contexts.containsKey(rootIdentifierDifferent.getRootIdentifier()));
+ // empty map of clustered registrations
+ assertTrue(clusterRegistrations.isEmpty());
+ assertFalse(clusterRegistrations.containsKey(rootIdentifier.getRootIdentifier()));
+ assertFalse(clusterRegistrations.containsKey(rootIdentifierDifferent.getRootIdentifier()));
+ }
}
private class CustomTreeModification implements DataTreeModification<Node> {
builder.setNode(node);
- final NetconfDeviceCommunicator communicator = mock (NetconfDeviceCommunicator.class);
+ final NetconfDeviceCommunicator communicator = mock(NetconfDeviceCommunicator.class);
final RemoteDeviceHandler salFacade = mock(RemoteDeviceHandler.class);
final TestingRemoteDeviceConnectorImpl remoteDeviceConnection =
public class ReadTransactionActorTest {
- private static final YangInstanceIdentifier path = YangInstanceIdentifier.EMPTY;
- private static final LogicalDatastoreType store = LogicalDatastoreType.CONFIGURATION;
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.EMPTY;
+ private static final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
@Mock
private DOMDataReadOnlyTransaction deviceReadTx;
final ContainerNode node = Builders.containerBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
.build();
- when(deviceReadTx.read(store, path)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
- actorRef.tell(new ReadRequest(store, path), probe.ref());
- verify(deviceReadTx).read(store, path);
+ when(deviceReadTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
+ actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+ verify(deviceReadTx).read(STORE, PATH);
probe.expectMsgClass(NormalizedNodeMessage.class);
}
@Test
public void testReadEmpty() throws Exception {
- when(deviceReadTx.read(store, path)).thenReturn(Futures.immediateCheckedFuture(Optional.absent()));
- actorRef.tell(new ReadRequest(store, path), probe.ref());
- verify(deviceReadTx).read(store, path);
+ when(deviceReadTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.absent()));
+ actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+ verify(deviceReadTx).read(STORE, PATH);
probe.expectMsgClass(EmptyReadResponse.class);
}
@Test
public void testReadFailure() throws Exception {
final ReadFailedException cause = new ReadFailedException("fail");
- when(deviceReadTx.read(store, path)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
- actorRef.tell(new ReadRequest(store, path), probe.ref());
- verify(deviceReadTx).read(store, path);
+ when(deviceReadTx.read(STORE, PATH)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+ actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+ verify(deviceReadTx).read(STORE, PATH);
probe.expectMsg(cause);
}
@Test
public void testExists() throws Exception {
- when(deviceReadTx.exists(store, path)).thenReturn(Futures.immediateCheckedFuture(true));
- actorRef.tell(new ExistsRequest(store, path), probe.ref());
- verify(deviceReadTx).exists(store, path);
+ when(deviceReadTx.exists(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(true));
+ actorRef.tell(new ExistsRequest(STORE, PATH), probe.ref());
+ verify(deviceReadTx).exists(STORE, PATH);
probe.expectMsg(true);
}
@Test
public void testExistsFailure() throws Exception {
final ReadFailedException cause = new ReadFailedException("fail");
- when(deviceReadTx.exists(store, path)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
- actorRef.tell(new ExistsRequest(store, path), probe.ref());
- verify(deviceReadTx).exists(store, path);
+ when(deviceReadTx.exists(STORE, PATH)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+ actorRef.tell(new ExistsRequest(STORE, PATH), probe.ref());
+ verify(deviceReadTx).exists(STORE, PATH);
probe.expectMsg(cause);
}
}
\ No newline at end of file
@Test
public void testSubmitWithOperation() throws Exception {
- final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx =
+ Futures.immediateCheckedFuture(null);
doReturn(resultSubmitTx).when(readWriteTx).submit();
// With Tx
final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
@Test
public void testSubmitWithOperation() throws Exception {
- final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
+ final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx =
+ Futures.immediateCheckedFuture(null);
doReturn(resultSubmitTx).when(writeTx).submit();
// With Tx
final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
assertEquals("nodeId", listPath.firstKeyOf(Node.class).getNodeId().getValue());
assertEquals("topologyId", listPath.firstKeyOf(Topology.class).getTopologyId().getValue());
- assertEquals("topologyId", NetconfTopologyUtils.createTopologyNodePath("topologyId").
- firstKeyOf(Topology.class).getTopologyId().getValue());
+ assertEquals("topologyId", NetconfTopologyUtils.createTopologyNodePath("topologyId")
+ .firstKeyOf(Topology.class).getTopologyId().getValue());
}
}
<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);
}
<tag>HEAD</tag>
<url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
</scm>
+
+ <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>
import org.slf4j.LoggerFactory;
/**
- * Instead of using loopback (controller-config mount point) to create your netconf-connector, you should use the network-topology capability.
+ * Instead of using loopback (controller-config mount point) to create your netconf-connector,
+ * you should use the network-topology capability.
+ *
* <p>
- * Follow instructions provided in this <a href="https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf#Spawning_netconf_connectors_via_topology_configuration">wiki</a>.
+ * Follow instructions provided in this
+ * <a href="https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf#Spawning_netconf_connectors_via_topology_configuration">wiki</a>.
+ *
* <p>
* Deprecation notice in Carbon, removal planned for Nitrogen.
*/
@Deprecated
-public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule implements BindingAwareConsumer {
+public final class NetconfConnectorModule
+ extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
+ implements BindingAwareConsumer {
private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
private static final InstanceIdentifier<Topology> TOPOLOGY_PATH = InstanceIdentifier.create(NetworkTopology.class)
private InstanceIdentifier<Node> nodePath;
private DataBroker dataBroker;
- public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+ public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
instanceName = identifier.getInstanceName();
}
- public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
+ public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+ final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
instanceName = identifier.getInstanceName();
}
@Override
protected void customValidation() {
checkNotNull(getAddress(), addressJmxAttribute);
- checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
+ checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(),
+ addressJmxAttribute);
checkNotNull(getPort(), portJmxAttribute);
checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
}
private static boolean isHostAddressPresent(final Host address) {
- return address.getDomainName() != null ||
- address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
+ return address.getDomainName() != null || address.getIpAddress() != null
+ && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
}
@Override
}
@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);
}
});
}
}
@Override
- public void onFailure(final Throwable t) {
- LOG.error("Node {} deletion failed: {}", instanceName, t);
+ public void onFailure(final Throwable throwable) {
+ LOG.error("Node {} deletion failed: {}", instanceName, throwable);
}
});
}
NonModuleCapabilities nonModuleCapabilities = null;
- if(getNonModuleCapabilities() != null) {
+ if (getNonModuleCapabilities() != null) {
nonModuleCapabilities = new NonModuleCapabilitiesBuilder()
.setOverride(getNonModuleCapabilities().getOverride())
.setCapability(getNonModuleCapabilities().getCapability())
@Override
public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
- old, bundleContext);
+ final NetconfConnectorModule module =
+ (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, old, bundleContext);
return module;
}
@Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
- bundleContext);
+ public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
+ final NetconfConnectorModule module =
+ (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, bundleContext);
return module;
}
}
import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
/**
- * Factory for netconf device schemas
+ * Factory for netconf device schemas.
*/
public interface NetconfDeviceSchemasResolver {
- NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id);
+ NetconfDeviceSchemas resolve(
+ NetconfDeviceRpc deviceRpc, NetconfSessionPreferences remoteSessionCapabilities, RemoteDeviceId id);
}
package org.opendaylight.netconf.sal.connect.api;
/**
- *
+ * Remote device.
*/
public interface RemoteDevice<PREF, M, LISTENER extends RemoteDeviceCommunicator<M>> {
/**
* Holds URLs with YANG schema resources for all yang modules reported in
- * ietf-netconf-yang-library/modules-state/modules node
+ * ietf-netconf-yang-library/modules-state/modules node.
*/
public class LibraryModulesSchemas implements NetconfDeviceSchemas {
static {
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- moduleInfoBackedContext.registerModuleInfo(
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.
- $YangModuleInfoImpl.getInstance());
+ moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
+ .library.rev160409.$YangModuleInfoImpl.getInstance());
LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
}
final Map<SourceIdentifier, URL> result = Maps.newHashMap();
for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
final SourceIdentifier sId = RevisionSourceIdentifier
- .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
+ .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
result.put(sId, entry.getValue());
}
final URL urlConnection = new URL(url);
final URLConnection connection = urlConnection.openConnection();
- if(connection instanceof HttpURLConnection) {
+ if (connection instanceof HttpURLConnection) {
connection.setRequestProperty("Accept", "application/xml");
final String userpass = username + ":" + password;
final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
throw new RuntimeException(deviceId + ": Interrupted while waiting for response to "
+ MODULES_STATE_MODULE_LIST, e);
} catch (final ExecutionException e) {
- LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId, MODULES_STATE_MODULE_LIST, e);
+ LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
+ MODULES_STATE_MODULE_LIST, e);
return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
}
- if(moduleListNodeResult.getErrors().isEmpty() == false) {
+ if (moduleListNodeResult.getErrors().isEmpty() == false) {
LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
findModulesStateNode(moduleListNodeResult.getResult());
- if(modulesStateNode.isPresent()) {
+ if (modulesStateNode.isPresent()) {
Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
"Expecting container containing schemas, but was %s", modulesStateNode.get());
return create(((ContainerNode) modulesStateNode.get()));
}
}
- private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
- if(result == null) {
- return Optional.absent();
- }
- final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
- if(dataNode.isPresent() == false) {
- return Optional.absent();
- }
-
- return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
- }
-
private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
return new LibraryModulesSchemas(schemasMapping.build());
}
+ /**
+ * Resolves URLs with YANG schema resources from modules-state.
+ * @param url URL pointing to yang library
+ * @return Resolved URLs with YANG schema resources for all yang modules from yang library
+ */
+ public static LibraryModulesSchemas create(final String url) {
+ Preconditions.checkNotNull(url);
+ try {
+ final URL urlConnection = new URL(url);
+ final URLConnection connection = urlConnection.openConnection();
+
+ if (connection instanceof HttpURLConnection) {
+ connection.setRequestProperty("Accept", "application/xml");
+ }
+
+ return createFromURLConnection(connection);
+
+ } catch (final IOException e) {
+ LOG.warn("Unable to download yang library from {}", url, e);
+ return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+ }
+ }
+
+ private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
+ if (result == null) {
+ return Optional.absent();
+ }
+ final Optional<DataContainerChild<?, ?>> dataNode =
+ ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+ if (dataNode.isPresent() == false) {
+ return Optional.absent();
+ }
+
+ return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
+ }
+
private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
String contentType = connection.getContentType();
Preconditions.checkNotNull(contentType, "Content type unknown");
Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
"Only XML and JSON types are supported.");
- try (final InputStream in = connection.getInputStream()) {
+ try (InputStream in = connection.getInputStream()) {
final Optional<NormalizedNode<?, ?>> optionalModulesStateNode =
contentType.equals("application/json") ? readJson(in) : readXml(in);
}
}
- /**
- * Resolves URLs with YANG schema resources from modules-state
- * @param url URL pointing to yang library
- * @return Resolved URLs with YANG schema resources for all yang modules from yang library
- */
- public static LibraryModulesSchemas create(final String url) {
- Preconditions.checkNotNull(url);
- try {
- final URL urlConnection = new URL(url);
- final URLConnection connection = urlConnection.openConnection();
-
- if(connection instanceof HttpURLConnection) {
- connection.setRequestProperty("Accept", "application/xml");
- }
-
- return createFromURLConnection(connection);
-
- } catch (final IOException e) {
- LOG.warn("Unable to download yang library from {}", url, e);
- return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
- }
- }
-
private static boolean guessJsonFromFileName(final String fileName) {
String extension = "";
final int i = fileName.lastIndexOf(46);
- if(i != -1) {
+ if (i != -1) {
extension = fileName.substring(i).toLowerCase();
}
jsonParser.parse(reader);
- return resultHolder.isFinished() ?
- Optional.of(resultHolder.getResult()) :
- Optional.<NormalizedNode<?, ?>>absent();
+ return resultHolder.isFinished()
+ ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
}
private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
parserFactory.getContainerNodeParser().parse(Collections.singleton(XmlUtil.readXmlToElement(in)),
(ContainerSchemaNode) LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME));
return Optional.of(parsed);
- } catch (IOException|SAXException e) {
+ } catch (IOException | SAXException e) {
LOG.warn("Unable to parse yang library xml content", e);
}
childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
- if(revision.isPresent()) {
- if(!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
+ if (revision.isPresent()) {
+ if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
return Optional.<Map.Entry<QName, URL>>absent();
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
+import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.slf4j.LoggerFactory;
/**
- * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
+ * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
*/
-public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
+public class NetconfDevice
+ implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION =
- input -> RevisionSourceIdentifier.create(input.getLocalName(),
- Optional.fromNullable(input.getFormattedRevision()));
+ input -> RevisionSourceIdentifier.create(input.getLocalName(),
+ Optional.fromNullable(input.getFormattedRevision()));
protected final RemoteDeviceId id;
private final boolean reconnectOnSchemasChange;
protected final SchemaRepository schemaRepository;
private final NetconfDeviceSchemasResolver stateSchemasResolver;
private final NotificationHandler notificationHandler;
- protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
+ protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
+ Lists.newArrayList();
+ @GuardedBy("this")
+ private boolean connected = false;
// Message transformer is constructed once the schemas are available
private MessageTransformer<NetconfMessage> messageTransformer;
/**
- * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
+ * Create rpc implementation capable of handling RPC for monitoring and notifications
+ * even before the schemas of remote device are downloaded.
*/
- static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
- final BaseSchema baseSchema = notificationSupport ?
- BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
- BaseSchema.BASE_NETCONF_CTX;
-
- return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
+ static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
+ final boolean notificationSupport) {
+ final BaseSchema baseSchema = notificationSupport
+ ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS
+ : BaseSchema.BASE_NETCONF_CTX;
+
+ return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
+ new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
}
- public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
+ public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
+ final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
this.id = id;
this.reconnectOnSchemasChange = reconnectOnSchemasChange;
// Yang models are being downloaded in this method and it would cause a
// deadlock if we used the netty thread
// http://netty.io/wiki/thread-model.html
+ setConnected(true);
LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
- final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
- final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
+ final NetconfDeviceRpc initRpc =
+ getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
+ final DeviceSourcesResolver task =
+ new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
- handleSalInitializationFailure(t, listener);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("{}: Unexpected error resolving device sources: {}", id, throwable);
+ handleSalInitializationFailure(throwable, listener);
}
};
Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
}
- private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
- // TODO check whether the model describing create subscription is present in schema
- // Perhaps add a default schema context to support create-subscription if the model was not provided (same as what we do for base netconf operations in transformer)
+ private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
+ final NetconfDeviceCommunicator listener) {
+ // TODO check whether the model describing create subscription is present in schema
+ // Perhaps add a default schema context to support create-subscription if the model was not provided
+ // (same as what we do for base netconf operations in transformer)
final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
- NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
- NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
+ NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
+ NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
@Override
public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
if (isCapabilityChanged(notification)) {
LOG.info("{}: Schemas change detected, reconnecting", id);
- // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
+ // Only disconnect is enough,
+ // the reconnecting nature of the connector will take care of reconnecting
listener.disconnect();
return Optional.absent();
}
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
+ throwable);
}
});
}
return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
}
- void handleSalInitializationSuccess(final SchemaContext result,
+ private synchronized void handleSalInitializationSuccess(final SchemaContext result,
final NetconfSessionPreferences remoteSessionCapabilities,
final DOMRpcService deviceRpc) {
- final BaseSchema baseSchema =
- remoteSessionCapabilities.isNotificationsSupported() ?
- BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
- BaseSchema.BASE_NETCONF_CTX;
- messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
-
- updateTransformer(messageTransformer);
- // salFacade.onDeviceConnected has to be called before the notification handler is initialized
- salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
- notificationHandler.onRemoteSchemaUp(messageTransformer);
-
- LOG.info("{}: Netconf connector initialized successfully", id);
+ //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
+ //since salFacade.onDeviceDisconnected was already called.
+ if (connected) {
+ final BaseSchema baseSchema =
+ remoteSessionCapabilities.isNotificationsSupported()
+ ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
+ messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
+
+ updateTransformer(messageTransformer);
+ // salFacade.onDeviceConnected has to be called before the notification handler is initialized
+ salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
+ notificationHandler.onRemoteSchemaUp(messageTransformer);
+
+ LOG.info("{}: Netconf connector initialized successfully", id);
+ } else {
+ LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
+ }
}
- void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
- LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
+ private void handleSalInitializationFailure(final Throwable throwable,
+ final RemoteDeviceCommunicator<NetconfMessage> listener) {
+ LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
listener.close();
onRemoteSessionDown();
resetMessageTransformer();
}
/**
- * Set the transformer to null as is in initial state
+ * Set the transformer to null as is in initial state.
*/
private void resetMessageTransformer() {
updateTransformer(null);
messageTransformer = transformer;
}
+ private synchronized void setConnected(final boolean connected) {
+ this.connected = connected;
+ }
+
private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
- PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
+ PotentialSchemaSource.create(
+ sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
}
}
@Override
public void onRemoteSessionDown() {
+ setConnected(false);
notificationHandler.onRemoteSchemaDown();
salFacade.onDeviceDisconnected();
- for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
+ for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
+ : sourceRegistrations) {
sourceRegistration.close();
}
resetMessageTransformer();
@Override
public void onRemoteSessionFailed(final Throwable throwable) {
+ setConnected(false);
salFacade.onDeviceFailed(throwable);
}
private final RemoteDeviceId id;
private final NetconfDeviceSchemasResolver stateSchemasResolver;
- DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
- final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
+ DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
+ final NetconfSessionPreferences remoteSessionCapabilities,
+ final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
this.deviceRpc = deviceRpc;
this.remoteSessionCapabilities = remoteSessionCapabilities;
this.id = id;
this.stateSchemasResolver = stateSchemasResolver;
}
- public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
+ DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
+ final NetconfDeviceSchemasResolver stateSchemasResolver,
+ final NetconfDeviceRpc rpcForMonitoring) {
this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
}
@Override
public DeviceSources call() throws Exception {
- final NetconfDeviceSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
- LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
+ final NetconfDeviceSchemas availableSchemas =
+ stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
+ LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
+ availableSchemas.getAvailableYangSchemasQNames());
final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
if (!requiredSourcesNotProvided.isEmpty()) {
- LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
- id, requiredSourcesNotProvided);
+ LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
+ + " required but not provided: {}", id, requiredSourcesNotProvided);
LOG.warn("{}: Attempting to build schema context from required sources", id);
}
// Here all the sources reported in netconf monitoring are merged with those reported in hello.
// It is necessary to perform this since submodules are not mentioned in hello but still required.
- // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
- // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
+ // This clashes with the option of a user to specify supported yang models manually in configuration
+ // for netconf-connector and as a result one is not able to fully override yang models of a device.
+ // It is only possible to add additional models.
final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
if (!providedSourcesNotRequired.isEmpty()) {
- LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
- id, providedSourcesNotRequired);
+ LOG.warn("{}: Netconf device provides additional yang models not reported in "
+ + "hello message capabilities: {}", id, providedSourcesNotRequired);
LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
requiredSources.addAll(providedSourcesNotRequired);
}
final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- if(availableSchemas instanceof LibraryModulesSchemas) {
+ if (availableSchemas instanceof LibraryModulesSchemas) {
sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
((LibraryModulesSchemas) availableSchemas).getAvailableModels());
} else {
private final Set<QName> providedSources;
private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
- public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
+ DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
this.requiredSources = requiredSources;
this.providedSources = providedSources;
private final RemoteDeviceCommunicator<NetconfMessage> listener;
private final NetconfDeviceCapabilities capabilities;
- public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
+ SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
+ final RemoteDeviceCommunicator<NetconfMessage> listener) {
this.deviceSources = deviceSources;
this.remoteSessionCapabilities = remoteSessionCapabilities;
this.listener = listener;
private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
return requiredSources.parallelStream().filter(sourceIdentifier -> {
- boolean remove = false;
- try {
- schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
- } catch (SchemaSourceException e) {
- remove = true;
- }
- return remove;
- }).collect(Collectors.toList());
+ boolean remove = false;
+ try {
+ schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
+ } catch (SchemaSourceException e) {
+ remove = true;
+ }
+ return remove;
+ }).collect(Collectors.toList());
}
/**
- * Build schema context, in case of success or final failure notify device
+ * Build schema context, in case of success or final failure notify device.
*/
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
while (!requiredSources.isEmpty()) {
LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
try {
- final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
+ final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture =
+ schemaContextFactory.createSchemaContext(requiredSources);
final SchemaContext result = schemaBuilderFuture.checkedGet();
LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
- final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
+ final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
+ capabilities.getUnresolvedCapabilites().keySet());
capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
- .setCapability(entry.toString()).setCapabilityOrigin(remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
+ .setCapability(entry.toString()).setCapabilityOrigin(
+ remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
.collect(Collectors.toList()));
- capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
- .setCapability(entry).setCapabilityOrigin(remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
+ capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
+ .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
+ .setCapability(entry).setCapabilityOrigin(
+ remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
.collect(Collectors.toList()));
handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
return;
} catch (final Throwable t) {
- if (t instanceof MissingSchemaSourceException){
- requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
+ if (t instanceof MissingSchemaSourceException) {
+ requiredSources =
+ handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
} else if (t instanceof SchemaResolutionException) {
// schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
// that might be wrapping a MissingSchemaSourceException so we need to look
// at the cause of the exception to make sure we don't misinterpret it.
if (t.getCause() instanceof MissingSchemaSourceException) {
- requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
+ requiredSources = handleMissingSchemaSourceException(
+ requiredSources, (MissingSchemaSourceException) t.getCause());
continue;
}
- requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
+ requiredSources =
+ handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
} else {
// unknown error, fail
handleSalInitializationFailure(t, listener);
salFacade.onDeviceFailed(cause);
}
- private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
+ private Collection<SourceIdentifier> handleMissingSchemaSourceException(
+ final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
// In case source missing, try without it
- final SourceIdentifier missingSource = t.getSourceId();
- LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
- LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
- final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
+ final SourceIdentifier missingSource = exception.getSourceId();
+ LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id,
+ missingSource);
+ LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
+ exception);
+ final Collection<QName> qNameOfMissingSource =
+ getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
if (!qNameOfMissingSource.isEmpty()) {
- capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
+ capabilities.addUnresolvedCapabilities(
+ qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
}
return stripUnavailableSource(requiredSources, missingSource);
}
- private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
+ private Collection<SourceIdentifier> handleSchemaResolutionException(
+ final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
// In case resolution error, try only with resolved sources
// There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
// FIXME Do we really have assurance that these two cases cannot happen at once?
if (resolutionException.getFailedSource() != null) {
// flawed model - exclude it
final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
- LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId);
- LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException);
- capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
- UnavailableCapability.FailureReason.UnableToResolve);
+ LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
+ id, failedSourceId);
+ LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
+ id, resolutionException);
+ capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(
+ Collections.singleton(failedSourceId)), UnavailableCapability.FailureReason.UnableToResolve);
return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
}
// unsatisfied imports
final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
- capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
- LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
- LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
+ capabilities.addUnresolvedCapabilities(
+ getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
+ LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
+ id, resolutionException.getUnsatisfiedImports());
+ LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
+ resolutionException);
return resolutionException.getResolvedSources();
}
return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
}
- private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
+ private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
+ final SourceIdentifier sourceIdToRemove) {
final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
- final boolean removed = sourceIdentifiers.remove(sIdToRemove);
- Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
+ final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
+ Preconditions.checkState(
+ removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources);
return sourceIdentifiers;
}
final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
if (qNames.isEmpty()) {
- LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
+ LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
+ identifiers);
}
return Collections2.filter(qNames, Predicates.notNull());
}
return qname;
}
}
- LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
- // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability
+ LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
+ deviceSources.getRequiredSourcesQName());
+ // return null since we cannot find the QName,
+ // this capability will be removed from required sources and not reported as unresolved-capability
return null;
}
import org.slf4j.LoggerFactory;
/**
- * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas
+ * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
*/
public final class NetconfStateSchemas implements NetconfDeviceSchemas {
YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
private static final ContainerNode GET_SCHEMAS_RPC;
+
static {
final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
@Override
public Set<QName> getAvailableYangSchemasQNames() {
- return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), new Function<RemoteYangSchema, QName>() {
- @Override
- public QName apply(final RemoteYangSchema input) {
- return input.getQName();
- }
- }));
+ return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(),
+ new Function<RemoteYangSchema, QName>() {
+ @Override
+ public QName apply(final RemoteYangSchema input) {
+ return input.getQName();
+ }
+ }));
}
/**
- * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas
+ * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
*/
- static NetconfStateSchemas create(final DOMRpcService deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
- if(remoteSessionCapabilities.isMonitoringSupported() == false) {
+ static NetconfStateSchemas create(final DOMRpcService deviceRpc,
+ final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+ if (remoteSessionCapabilities.isMonitoringSupported() == false) {
// TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
// issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
- throw new RuntimeException(id + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
+ throw new RuntimeException(id
+ + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
} catch (final ExecutionException e) {
LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
return EMPTY;
}
- if(schemasNodeResult.getErrors().isEmpty() == false) {
- LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
+ if (schemasNodeResult.getErrors().isEmpty() == false) {
+ LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
+ id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
return EMPTY;
}
final Optional<? extends NormalizedNode<?, ?>> schemasNode = findSchemasNode(schemasNodeResult.getResult());
- if(schemasNode.isPresent()) {
+ if (schemasNode.isPresent()) {
Preconditions.checkState(schemasNode.get() instanceof ContainerNode,
"Expecting container containing schemas, but was %s", schemasNode.get());
return create(id, (ContainerNode) schemasNode.get());
}
}
- private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
- if(result == null) {
- return Optional.absent();
- }
- final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
- if(dataNode.isPresent() == false) {
- return Optional.absent();
- }
-
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
- ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
- if(nStateNode.isPresent() == false) {
- return Optional.absent();
- }
-
- return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
- }
-
/**
- * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas
+ * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
*/
@VisibleForTesting
protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemasNode.getChild(toId(Schema.QNAME));
- Preconditions.checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
- Preconditions.checkState(child.get() instanceof MapNode, "Unexpected structure for container: %s in response: %s. Expecting a list", Schema.QNAME.withoutRevision(), schemasNode);
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ schemasNode.getChild(toId(Schema.QNAME));
+ Preconditions.checkState(child.isPresent(),
+ "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
+ Preconditions.checkState(child.get() instanceof MapNode,
+ "Unexpected structure for container: %s in response: %s. Expecting a list",
+ Schema.QNAME.withoutRevision(), schemasNode);
for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
- final Optional<RemoteYangSchema> fromCompositeNode = RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
- if(fromCompositeNode.isPresent()) {
+ final Optional<RemoteYangSchema> fromCompositeNode =
+ RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
+ if (fromCompositeNode.isPresent()) {
availableYangSchemas.add(fromCompositeNode.get());
}
}
return new NetconfStateSchemas(availableYangSchemas);
}
- public final static class RemoteYangSchema {
+ private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
+ if (result == null) {
+ return Optional.absent();
+ }
+ final Optional<DataContainerChild<?, ?>> dataNode =
+ ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+ if (dataNode.isPresent() == false) {
+ return Optional.absent();
+ }
+
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
+ ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
+ if (nStateNode.isPresent() == false) {
+ return Optional.absent();
+ }
+
+ return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
+ }
+
+ public static final class RemoteYangSchema {
private final QName qname;
RemoteYangSchema(final QName qname) {
return qname;
}
- static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id, final MapEntryNode schemaNode) {
- Preconditions.checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
+ static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
+ final MapEntryNode schemaNode) {
+ Preconditions.checkArgument(
+ schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
- if(formatAsString.equals(Yang.QNAME.toString()) == false) {
+ if (formatAsString.equals(Yang.QNAME.toString()) == false) {
LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
return Optional.absent();
}
childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
- if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
+ if (locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
return Optional.absent();
}
}
/**
- * Extracts all values of a leaf-list node as a set of strings
+ * Extracts all values of a leaf-list node as a set of strings.
*/
- private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode, final QName childNodeQName) {
+ private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
+ final QName childNodeQName) {
final Set<String> extractedValues = Sets.newHashSet();
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemaNode.getChild(toId(childNodeQName));
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ schemaNode.getChild(toId(childNodeQName));
Preconditions.checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
- Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
+ Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>,
+ "Child nodes %s not present", childNodeQName);
for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
extractedValues.add(getValueOfSimpleNode(childNode).get());
}
return extractedValues;
}
- private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode, final QName childNode) {
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node = schemaNode.getChild(toId(childNode));
+ private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
+ final QName childNode) {
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
+ schemaNode.getChild(toId(childNode));
if (node.isPresent()) {
return getValueOfSimpleNode(node.get());
} else {
}
}
- private static Optional<String> getValueOfSimpleNode(final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
+ private static Optional<String> getValueOfSimpleNode(
+ final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
final Object value = node.getValue();
- return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.<String>absent() : Optional.of(value.toString().trim());
+ return value == null || Strings.isNullOrEmpty(value.toString())
+ ? Optional.<String>absent() : Optional.of(value.toString().trim());
}
@Override
- public boolean equals(final Object o) {
- if (this == o) {
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (o == null || getClass() != o.getClass()) {
+ if (obj == null || getClass() != obj.getClass()) {
return false;
}
- final RemoteYangSchema that = (RemoteYangSchema) o;
+ final RemoteYangSchema that = (RemoteYangSchema) obj;
if (!qname.equals(that.qname)) {
return false;
import org.opendaylight.yangtools.yang.common.QName;
/**
- * Default implementation resolving schemas QNames from netconf-state or from modules-state
+ * Default implementation resolving schemas QNames from netconf-state or from modules-state.
*/
public final class NetconfStateSchemasResolverImpl implements NetconfDeviceSchemasResolver {
@Override
- public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+ public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc,
+ final NetconfSessionPreferences remoteSessionCapabilities,
+ final RemoteDeviceId id) {
if (remoteSessionCapabilities.isMonitoringSupported()) {
return NetconfStateSchemas.create(deviceRpc, remoteSessionCapabilities, id);
- } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME, "ietf-yang-library"))) {
+ } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME,
+ "ietf-yang-library"))) {
return LibraryModulesSchemas.create(deviceRpc, id);
}
return NetconfStateSchemas.EMPTY;
}
synchronized void handleNotification(final NetconfMessage notification) {
- if(passNotifications) {
+ if (passNotifications) {
passNotification(transformNotification(notification));
} else {
queueNotification(notification);
/**
* Forward all cached notifications and pass all notifications from this point directly to sal facade.
- * @param messageTransformer
+ * @param messageTransformer Message transformer
*/
synchronized void onRemoteSchemaUp(final MessageTransformer<NetconfMessage> messageTransformer) {
this.messageTransformer = Preconditions.checkNotNull(messageTransformer);
private DOMNotification transformNotification(final NetconfMessage cachedNotification) {
final DOMNotification parsedNotification = messageTransformer.toNotification(cachedNotification);
- Preconditions.checkNotNull(parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification);
+ Preconditions.checkNotNull(
+ parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification);
return parsedNotification;
}
Preconditions.checkState(passNotifications == false);
LOG.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
}
private synchronized void passNotification(final DOMNotification parsedNotification) {
LOG.debug("{}: Forwarding notification {}", id, parsedNotification);
- if(filter == null || filter.filterNotification(parsedNotification).isPresent()) {
+ if (filter == null || filter.filterNotification(parsedNotification).isPresent()) {
salFacade.onNotification(parsedNotification);
}
}
messageTransformer = null;
}
- static interface NotificationFilter {
+ interface NotificationFilter {
Optional<DOMNotification> filterNotification(DOMNotification notification);
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
+public class NetconfDeviceCommunicator
+ implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
return isSessionClosing.get();
}
- public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
- final UserPreferences NetconfSessionPreferences, final int rpcMessageLimit) {
- this(id, remoteDevice, Optional.of(NetconfSessionPreferences), rpcMessageLimit);
+ public NetconfDeviceCommunicator(
+ final RemoteDeviceId id,
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+ final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) {
+ this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit);
}
- public NetconfDeviceCommunicator(final RemoteDeviceId id,
- final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
- final int rpcMessageLimit) {
+ public NetconfDeviceCommunicator(
+ final RemoteDeviceId id,
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+ final int rpcMessageLimit) {
this(id, remoteDevice, Optional.<UserPreferences>absent(), rpcMessageLimit);
}
- private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
- final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
+ private NetconfDeviceCommunicator(
+ final RemoteDeviceId id,
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+ final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
this.concurentRpcMsgs = rpcMessageLimit;
this.id = id;
this.remoteDevice = remoteDevice;
if (!firstConnectionFuture.isDone()) {
firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
}
- }
- finally {
+ } finally {
sessionLock.unlock();
}
}
/**
+ * Initialize remote connection.
*
- * @param dispatcher
- * @param config
+ * @param dispatcher {@code NetconfCLientDispatcher}
+ * @param config {@code NetconfClientConfiguration}
* @return future that returns succes on first succesfull connection and failure when the underlying
- * reconnecting strategy runs out of reconnection attempts
+ * reconnecting strategy runs out of reconnection attempts
*/
- public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
- if(config instanceof NetconfReconnectingClientConfiguration) {
+ public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(
+ final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
+ if (config instanceof NetconfReconnectingClientConfiguration) {
initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
} else {
initFuture = dispatcher.createClient(config);
public void disconnect() {
// If session is already in closing, no need to close it again
- if(session != null && isSessionClosing.compareAndSet(false, true)) {
+ if (session != null && isSessionClosing.compareAndSet(false, true)) {
session.close();
}
}
final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
sessionLock.lock();
try {
- if( session != null ) {
+ if (session != null) {
session = null;
-
/*
* Walk all requests, check if they have been executing
* or cancelled and remove them from the queue.
while (it.hasNext()) {
final Request r = it.next();
if (r.future.isUncancellable()) {
- futuresToCancel.add( r.future );
+ futuresToCancel.add(r.future);
it.remove();
} else if (r.future.isCancelled()) {
// This just does some house-cleaning
remoteDevice.onRemoteSessionDown();
}
- }
- finally {
+ } finally {
sessionLock.unlock();
}
// Notify pending request futures outside of the sessionLock to avoid unnecessarily
// blocking the caller.
for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
- if( Strings.isNullOrEmpty( reason ) ) {
- future.set( createSessionDownRpcResult() );
+ if (Strings.isNullOrEmpty(reason)) {
+ future.set(createSessionDownRpcResult());
} else {
- future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
+ future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, reason));
}
}
}
private RpcResult<NetconfMessage> createSessionDownRpcResult() {
- return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
- String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
+ return createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
+ String.format("The netconf session to %1$s is disconnected", id.getName()));
}
private static RpcResult<NetconfMessage> createErrorRpcResult(final RpcError.ErrorType errorType,
final String message) {
return RpcResultBuilder.<NetconfMessage>failed()
- .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
+ .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
}
@Override
- public void onSessionDown(final NetconfClientSession session, final Exception e) {
+ public void onSessionDown(final NetconfClientSession session, final Exception exception) {
// If session is already in closing, no need to call tearDown again.
if (isSessionClosing.compareAndSet(false, true)) {
- LOG.warn("{}: Session went down", id, e);
- tearDown( null );
+ LOG.warn("{}: Session went down", id, exception);
+ tearDown(null);
}
}
public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
// onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
LOG.warn("{}: Session terminated {}", id, reason);
- tearDown( reason.getErrorMessage() );
+ tearDown(reason.getErrorMessage());
}
@Override
public void close() {
// Cancel reconnect if in progress
- if(initFuture != null) {
+ if (initFuture != null) {
initFuture.cancel(false);
}
// Disconnect from device
requests.poll();
// we have just removed one request from the queue
// we can also release one permit
- if(semaphore != null) {
+ if (semaphore != null) {
semaphore.release();
}
} else {
LOG.warn("{}: Ignoring unsolicited message {}", id,
msgToS(message));
}
- }
- finally {
+ } finally {
sessionLock.unlock();
}
- if( request != null ) {
+ if (request != null) {
LOG.debug("{}: Message received {}", id, message);
- if(LOG.isTraceEnabled()) {
- LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
}
try {
- NetconfMessageTransformUtil.checkValidReply( request.request, message );
+ NetconfMessageTransformUtil.checkValidReply(request.request, message);
} catch (final NetconfDocumentedException e) {
LOG.warn(
- "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
+ "{}: Invalid request-reply match,"
+ + "reply message contains different message-id, request: {}, response: {}",
id, msgToS(request.request), msgToS(message), e);
- request.future.set( RpcResultBuilder.<NetconfMessage>failed()
- .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
+ request.future.set(RpcResultBuilder.<NetconfMessage>failed()
+ .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
//recursively processing message to eventually find matching request
processMessage(message);
try {
NetconfMessageTransformUtil.checkSuccessReply(message);
- } catch(final NetconfDocumentedException e) {
+ } catch (final NetconfDocumentedException e) {
LOG.warn(
"{}: Error reply from remote device, request: {}, response: {}",
id, msgToS(request.request), msgToS(message), e);
- request.future.set( RpcResultBuilder.<NetconfMessage>failed()
- .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
+ request.future.set(RpcResultBuilder.<NetconfMessage>failed()
+ .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
return;
}
- request.future.set( RpcResultBuilder.success( message ).build() );
+ request.future.set(RpcResultBuilder.success(message).build());
}
}
sessionLock.lock();
if (semaphore != null && !semaphore.tryAcquire()) {
- LOG.warn("Limit of concurrent rpc messages was reached (limit :" +
- concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
+ LOG.warn("Limit of concurrent rpc messages was reached (limit :"
+ + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id"
+ + id.getName());
sessionLock.unlock();
- return Futures.immediateFailedFuture(new NetconfDocumentedException("Limit of rpc messages was reached (Limit :" +
- concurentRpcMsgs + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
+ return Futures.immediateFailedFuture(new NetconfDocumentedException(
+ "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
+ + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
}
try {
}
}
- private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
- final NetconfMessage message, final QName rpc) {
- if(LOG.isTraceEnabled()) {
+ private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
+ final QName rpc) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("{}: Sending message {}", id, msgToS(message));
}
if (session == null) {
LOG.warn("{}: Session is disconnected, failing RPC request {}",
id, message);
- return Futures.immediateFuture( createSessionDownRpcResult() );
+ return Futures.immediateFuture(createSessionDownRpcResult());
}
final Request req = new Request(new UncancellableFuture<>(true), message);
requests.add(req);
session.sendMessage(req.request).addListener(future -> {
- if( !future.isSuccess() ) {
+ if (!future.isSuccess()) {
// We expect that a session down will occur at this point
LOG.debug("{}: Failed to send request {}", id,
XmlUtil.toString(req.request.getDocument()),
future.cause());
- if( future.cause() != null ) {
- req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
- future.cause().getLocalizedMessage() ) );
+ if (future.cause() != null) {
+ req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
+ future.cause().getLocalizedMessage()));
} else {
- req.future.set( createSessionDownRpcResult() ); // assume session is down
+ req.future.set(createSessionDownRpcResult()); // assume session is down
}
- req.future.setException( future.cause() );
- }
- else {
+ req.future.setException(future.cause());
+ } else {
LOG.trace("Finished sending request {}", req.request);
}
});
}
private void processNotification(final NetconfMessage notification) {
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("{}: Notification received: {}", id, notification);
}
private final Map<QName, CapabilityOrigin> moduleBasedCaps;
private final Map<String, CapabilityOrigin> nonModuleCaps;
- NetconfSessionPreferences(final Map<String, CapabilityOrigin> nonModuleCaps, final Map<QName, CapabilityOrigin> moduleBasedCaps) {
+ NetconfSessionPreferences(final Map<String, CapabilityOrigin> nonModuleCaps,
+ final Map<QName, CapabilityOrigin> moduleBasedCaps) {
this.nonModuleCaps = Preconditions.checkNotNull(nonModuleCaps);
this.moduleBasedCaps = Preconditions.checkNotNull(moduleBasedCaps);
}
// allows partial matches - assuming parameters are in the same order
public boolean containsPartialNonModuleCapability(final String capability) {
final Iterator<String> iterator = getNonModuleCaps().iterator();
- while(iterator.hasNext()) {
+ while (iterator.hasNext()) {
if (iterator.next().startsWith(capability)) {
LOG.trace("capability {} partially matches {}", capability, nonModuleCaps);
return true;
public boolean isMonitoringSupported() {
return containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
- || containsPartialNonModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+ || containsPartialNonModuleCapability(
+ NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
}
/**
- * Merge module-based list of capabilities with current list of module-based capabilities
+ * Merge module-based list of capabilities with current list of module-based capabilities.
*
* @param netconfSessionModuleCapabilities capabilities to merge into this
*
* @return new instance of preferences with merged module-based capabilities
*/
public NetconfSessionPreferences addModuleCaps(final NetconfSessionPreferences netconfSessionModuleCapabilities) {
- final Map<QName, CapabilityOrigin> mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size() + netconfSessionModuleCapabilities.getModuleBasedCaps().size());
+ final Map<QName, CapabilityOrigin> mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size()
+ + netconfSessionModuleCapabilities.getModuleBasedCaps().size());
mergedCaps.putAll(moduleBasedCaps);
mergedCaps.putAll(netconfSessionModuleCapabilities.getModuleBasedCapsOrigin());
return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), mergedCaps);
}
/**
- * Override current list of module-based capabilities
+ * Override current list of module-based capabilities.
*
* @param netconfSessionPreferences capabilities to override in this
*
* @return new instance of preferences with replaced module-based capabilities
*/
public NetconfSessionPreferences replaceModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) {
- return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin());
+ return new NetconfSessionPreferences(
+ getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin());
}
public NetconfSessionPreferences replaceModuleCaps(final Map<QName, CapabilityOrigin> newModuleBasedCaps) {
/**
- * Merge list of non-module based capabilities with current list of non-module based capabilities
+ * Merge list of non-module based capabilities with current list of non-module based capabilities.
*
* @param netconfSessionNonModuleCapabilities capabilities to merge into this
*
}
/**
- * Override current list of non-module based capabilities
+ * Override current list of non-module based capabilities.
*
* @param netconfSessionPreferences capabilities to override in this
*
* @return new instance of preferences with replaced non-module based capabilities
*/
public NetconfSessionPreferences replaceNonModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) {
- return new NetconfSessionPreferences(netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin());
+ return new NetconfSessionPreferences(
+ netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin());
}
public static NetconfSessionPreferences fromNetconfSession(final NetconfClientSession session) {
return fromStrings(capabilities, CapabilityOrigin.DeviceAdvertised);
}
- public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities, final CapabilityOrigin capabilityOrigin) {
+ public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities,
+ final CapabilityOrigin capabilityOrigin) {
final Map<QName, CapabilityOrigin> moduleBasedCaps = new HashMap<>();
final Map<String, CapabilityOrigin> nonModuleCaps = new HashMap<>();
String revision = REVISION_PARAM.from(queryParams);
if (!Strings.isNullOrEmpty(revision)) {
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName),
+ capabilityOrigin);
continue;
}
revision = BROKEN_REVISON_PARAM.from(queryParams);
if (Strings.isNullOrEmpty(revision)) {
LOG.warn("Netconf device returned revision incorrectly escaped for {}, ignoring it", capability);
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+ cachedQName(namespace, moduleName), capabilityOrigin);
} else {
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+ cachedQName(namespace, revision, moduleName), capabilityOrigin);
}
continue;
}
// Fallback, no revision provided for module
- addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin);
+ addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+ cachedQName(namespace, moduleName), capabilityOrigin);
}
return new NetconfSessionPreferences(ImmutableMap.copyOf(nonModuleCaps), ImmutableMap.copyOf(moduleBasedCaps));
}
- private static void addModuleQName(final Map<QName, CapabilityOrigin> moduleBasedCaps, final Map<String, CapabilityOrigin> nonModuleCaps, final String capability, final QName qName, final CapabilityOrigin capabilityOrigin) {
- moduleBasedCaps.put(qName, capabilityOrigin);
+ private static void addModuleQName(final Map<QName, CapabilityOrigin> moduleBasedCaps,
+ final Map<String, CapabilityOrigin> nonModuleCaps, final String capability,
+ final QName qualifiedName, final CapabilityOrigin capabilityOrigin) {
+ moduleBasedCaps.put(qualifiedName, capabilityOrigin);
nonModuleCaps.remove(capability);
}
@GuardedBy("this")
private boolean uncancellable = false;
- public UncancellableFuture(final boolean uncancellable) {
+ UncancellableFuture(final boolean uncancellable) {
this.uncancellable = uncancellable;
}
import javax.annotation.Nonnull;
/**
- * DTO with user capabilities to override or merge with device specific capabilities
+ * DTO with user capabilities to override or merge with device specific capabilities.
*/
public class UserPreferences {
private volatile DOMRpcService currentDeviceRpc;
public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
- final ScheduledExecutorService executor, final long keepaliveDelaySeconds, final long defaultRequestTimeoutMillis) {
+ final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
+ final long defaultRequestTimeoutMillis) {
this.id = id;
this.salFacade = salFacade;
this.executor = executor;
}
/**
- * Set the netconf session listener whenever ready
+ * Set the netconf session listener whenever ready.
*
* @param listener netconf session listener
*/
* Just cancel current keepalive task.
* If its already started, let it finish ... not such a big deal.
*
+ * <p>
* Then schedule next keepalive.
*/
private void resetKeepalive() {
LOG.trace("{}: Resetting netconf keepalive timer", id);
- if(currentKeepalive != null) {
+ if (currentKeepalive != null) {
currentKeepalive.cancel(false);
}
scheduleKeepalive();
}
/**
- * Cancel current keepalive and also reset current deviceRpc
+ * Cancel current keepalive and also reset current deviceRpc.
*/
private void stopKeepalives() {
- if(currentKeepalive != null) {
+ if (currentKeepalive != null) {
currentKeepalive.cancel(false);
}
currentDeviceRpc = null;
}
@Override
- public void onDeviceConnected(final SchemaContext remoteSchemaContext, final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
+ public void onDeviceConnected(final SchemaContext remoteSchemaContext,
+ final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
this.currentDeviceRpc = deviceRpc;
- final DOMRpcService deviceRpc1 = new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
+ final DOMRpcService deviceRpc1 =
+ new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
LOG.debug("{}: Netconf session initiated, starting keepalives", id);
// Keepalive RPC static resources
private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
- private static final ContainerNode KEEPALIVE_PAYLOAD =
- NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
+ private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
+ getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
/**
* Invoke keepalive RPC and check the response. In case of any received response the keepalive
private final ScheduledFuture<?> previousKeepalive;
- public Keepalive(final ScheduledFuture<?> previousKeepalive) {
+ Keepalive(final ScheduledFuture<?> previousKeepalive) {
this.previousKeepalive = previousKeepalive;
}
LOG.trace("{}: Invoking keepalive RPC", id);
try {
- if(previousKeepalive != null && !previousKeepalive.isDone()) {
+ if (previousKeepalive != null && !previousKeepalive.isDone()) {
onFailure(new IllegalStateException("Previous keepalive timed out"));
} else {
Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this);
}
@Override
- public void onFailure(@Nonnull final Throwable t) {
- LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, t);
+ public void onFailure(@Nonnull final Throwable throwable) {
+ LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
reconnect();
}
}
/**
- * Reset keepalive after each RPC response received
+ * Reset keepalive after each RPC response received.
*/
private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
@Override
public void onSuccess(@Nullable final DOMRpcResult result) {
- // No matter what response we got, rpc-reply or rpc-error, we got it from device so the netconf session is OK
+ // No matter what response we got,
+ // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
resetKeepalive();
}
@Override
- public void onFailure(@Nonnull final Throwable t) {
- // User/Application RPC failed (The RPC did not reach the remote device or .. TODO what other reasons could cause this ?)
+ public void onFailure(@Nonnull final Throwable throwable) {
+ // User/Application RPC failed (The RPC did not reach the remote device or ..
+ // TODO what other reasons could cause this ?)
// There is no point in keeping this session. Reconnect.
- LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, t);
+ LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
reconnect();
}
}
private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
- public RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
+ RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
this.rpcResultFuture = rpcResultFuture;
}
private final long defaultRequestTimeoutMillis;
private final ScheduledExecutorService executor;
- public KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
+ KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
this.deviceRpc = deviceRpc;
this.resetKeepaliveTask = resetKeepaliveTask;
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, final NormalizedNode<?, ?> input) {
- final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture = deviceRpc.invokeRpc(type, input);
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+ final NormalizedNode<?, ?> input) {
+ final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
+ deviceRpc.invokeRpc(type, input);
Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask);
final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
}
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
// There is no real communication with the device (yet), no reset here
return deviceRpc.registerRpcListener(listener);
}
private final boolean candidateSupported;
private final boolean runningWritable;
- public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext, final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) {
+ public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext,
+ final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) {
this.id = id;
this.netconfOps = new NetconfBaseOps(rpc, schemaContext);
// get specific attributes from netconf preferences and get rid of it
runningWritable = netconfSessionPreferences.isRunningWritable();
rollbackSupport = netconfSessionPreferences.isRollbackSupported();
Preconditions.checkArgument(candidateSupported || runningWritable,
- "Device %s has advertised neither :writable-running nor :candidate capability. At least one of these should be advertised. Failed to establish a session.", id.getName());
+ "Device %s has advertised neither :writable-running nor :candidate capability."
+ + "At least one of these should be advertised. Failed to establish a session.", id.getName());
}
@Override
@Override
public DOMDataWriteTransaction newWriteOnlyTransaction() {
- if(candidateSupported) {
- if(runningWritable) {
+ if (candidateSupported) {
+ if (runningWritable) {
return new WriteCandidateRunningTx(id, netconfOps, rollbackSupport);
} else {
return new WriteCandidateTx(id, netconfOps, rollbackSupport);
}
@Override
- public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener, final DataChangeScope triggeringScope) {
+ public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(
+ final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener,
+ final DataChangeScope triggeringScope) {
throw new UnsupportedOperationException(id + ": Data change listeners not supported for netconf mount point");
}
// Notification publish is very simple and hijacks the thread of the caller
// TODO shouldnt we reuse the implementation for notification router from sal-broker-impl ?
+ @SuppressWarnings("checkstyle:IllegalCatch")
public synchronized void publishNotification(final DOMNotification notification) {
for (final DOMNotificationListener domNotificationListener : listeners.get(notification.getType())) {
try {
}
@Override
- public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(@Nonnull final T listener, @Nonnull final Collection<SchemaPath> types) {
+ public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+ @Nonnull final T listener, @Nonnull final Collection<SchemaPath> types) {
for (final SchemaPath type : types) {
listeners.put(type, listener);
}
}
@Override
- public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(@Nonnull final T listener, final SchemaPath... types) {
+ public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+ @Nonnull final T listener, final SchemaPath... types) {
return registerNotificationListener(listener, Lists.newArrayList(types));
}
}
*/
public final class NetconfDeviceRpc implements DOMRpcService {
- private static final Function<RpcDefinition, DOMRpcIdentifier> RPC_TO_RPC_IDENTIFIER = new Function<RpcDefinition, DOMRpcIdentifier>() {
- @Override
- public DOMRpcIdentifier apply(final RpcDefinition input) {
- return DOMRpcIdentifier.create(input.getPath());
- }
- };
+ private static final Function<RpcDefinition, DOMRpcIdentifier> RPC_TO_RPC_IDENTIFIER =
+ new Function<RpcDefinition, DOMRpcIdentifier>() {
+ @Override
+ public DOMRpcIdentifier apply(final RpcDefinition input) {
+ return DOMRpcIdentifier.create(input.getPath());
+ }
+ };
private final RemoteDeviceCommunicator<NetconfMessage> listener;
private final MessageTransformer<NetconfMessage> transformer;
private final Collection<DOMRpcIdentifier> availableRpcs;
- public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener, final MessageTransformer<NetconfMessage> transformer) {
+ public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener,
+ final MessageTransformer<NetconfMessage> transformer) {
this.listener = listener;
this.transformer = transformer;
@Nonnull
@Override
- public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+ public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+ @Nullable final NormalizedNode<?, ?> input) {
final NetconfMessage message = transformer.toRpcRequest(type, input);
- final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener.sendRequest(message, type.getLastComponent());
+ final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult =
+ listener.sendRequest(message, type.getLastComponent());
- final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
- @Override
- public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
- if (input.isSuccessful()) {
- return transformer.toRpcResult(input.getResult(), type);
- } else {
- return new DefaultDOMRpcResult(input.getErrors());
+ final ListenableFuture<DOMRpcResult> transformed =
+ Futures.transform(delegateFutureWithPureResult, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
+ @Override
+ public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
+ if (input.isSuccessful()) {
+ return transformer.toRpcResult(input.getResult(), type);
+ } else {
+ return new DefaultDOMRpcResult(input.getErrors());
+ }
}
- }
- });
+ });
return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
@Nullable
@Override
- public DOMRpcException apply(@Nullable final Exception e) {
- return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type);
+ public DOMRpcException apply(@Nullable final Exception exception) {
+ return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type);
}
});
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
listener.onRpcAvailable(availableRpcs);
@Override
public synchronized void onDeviceConnected(final SchemaContext schemaContext,
- final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
+ final NetconfSessionPreferences netconfSessionPreferences,
+ final DOMRpcService deviceRpc) {
- final DOMDataBroker domBroker = new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences);
+ final DOMDataBroker domBroker =
+ new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences);
final NetconfDeviceNotificationService notificationService = new NetconfDeviceNotificationService();
- salProvider.getMountInstance().onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService);
- salProvider.getTopologyDatastoreAdapter().updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
+ salProvider.getMountInstance()
+ .onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService);
+ salProvider.getTopologyDatastoreAdapter()
+ .updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
}
@Override
closeGracefully(salProvider);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void closeGracefully(final AutoCloseable resource) {
if (resource != null) {
try {
public class NetconfDeviceSalProvider implements AutoCloseable {
- private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
private final RemoteDeviceId id;
private final MountInstance mountInstance;
private final TransactionChainListener transactionChainListener = new TransactionChainListener() {
@Override
- public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
- logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
+ public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
+ final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+ LOG.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
chain.close();
resetTransactionChainForAdapaters();
throw new IllegalStateException(id + " TransactionChain(" + chain + ") not committed correctly", cause);
@Override
public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
- logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
+ LOG.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
}
};
topologyDatastoreAdapter.setTxChain(txChain);
- logger.trace("{}: Resetting TransactionChain {}", id, txChain);
+ LOG.trace("{}: Resetting TransactionChain {}", id, txChain);
}
Preconditions.checkNotNull(mountService, "Closed");
Preconditions.checkState(topologyRegistration == null, "Already initialized");
- final DOMMountPointService.DOMMountPointBuilder mountBuilder = mountService.createMountPoint(id.getTopologyPath());
+ final DOMMountPointService.DOMMountPointBuilder mountBuilder =
+ mountService.createMountPoint(id.getTopologyPath());
mountBuilder.addInitialSchemaContext(initialCtx);
mountBuilder.addService(DOMDataBroker.class, broker);
this.notificationService = notificationService;
topologyRegistration = mountBuilder.register();
- logger.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
+ LOG.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public synchronized void onTopologyDeviceDisconnected() {
- if(topologyRegistration == null) {
- logger.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
+ if (topologyRegistration == null) {
+ LOG.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
return;
}
topologyRegistration.close();
} catch (final Exception e) {
// Only log and ignore
- logger.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e);
+ LOG.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e);
} finally {
- logger.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration);
+ LOG.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration);
topologyRegistration = null;
}
}
}
public synchronized void publish(final DOMNotification domNotification) {
- Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}", domNotification);
+ Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}",
+ domNotification);
notificationService.publishNotification(domNotification);
}
}
public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
- public static final Function<Entry<QName, FailureReason>, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = input -> new UnavailableCapabilityBuilder()
- .setCapability(input.getKey().toString())
- .setFailureReason(input.getValue()).build();
+ public static final Function<Entry<QName, FailureReason>, UnavailableCapability>
+ UNAVAILABLE_CAPABILITY_TRANSFORMER =
+ input -> new UnavailableCapabilityBuilder()
+ .setCapability(input.getKey().toString()).setFailureReason(input.getValue()).build();
private final RemoteDeviceId id;
private BindingTransactionChain txChain;
this.txChain = Preconditions.checkNotNull(txChain);
this.networkTopologyPath = InstanceIdentifier.builder(NetworkTopology.class).build();
- this.topologyListPath = networkTopologyPath.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
+ this.topologyListPath = networkTopologyPath
+ .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
initDeviceData();
}
createNetworkTopologyIfNotPresent(writeTx);
final InstanceIdentifier<Node> path = id.getTopologyBindingPath();
- NodeBuilder nodeBuilder = getNodeIdBuilder(id);
+ final NodeBuilder nodeBuilder = getNodeIdBuilder(id);
NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder();
netconfNodeBuilder.setConnectionStatus(ConnectionStatus.Connecting);
netconfNodeBuilder.setHost(id.getHost());
LOG.trace(
"{}: Update device state transaction {} merging operational data started.",
id, writeTx.getIdentifier());
- writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+ writeTx.put(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
LOG.trace(
"{}: Update device state transaction {} merging operational data ended.",
id, writeTx.getIdentifier());
commitTransaction(writeTx, "update");
}
- public void updateClusteredDeviceData(final boolean up, final String masterAddress, final NetconfDeviceCapabilities capabilities) {
+ public void updateClusteredDeviceData(final boolean up, final String masterAddress,
+ final NetconfDeviceCapabilities capabilities) {
final NetconfNode data = buildDataForNetconfClusteredNode(up, masterAddress, capabilities);
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
LOG.trace(
"{}: Update device state transaction {} merging operational data started.",
id, writeTx.getIdentifier());
- writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+ writeTx.put(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
LOG.trace(
"{}: Update device state transaction {} merging operational data ended.",
id, writeTx.getIdentifier());
public void setDeviceAsFailed(final Throwable throwable) {
String reason = (throwable != null && throwable.getMessage() != null) ? throwable.getMessage() : UNKNOWN_REASON;
- final NetconfNode data = new NetconfNodeBuilder().setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
+ final NetconfNode data = new NetconfNodeBuilder()
+ .setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
LOG.trace(
"{}: Setting device state as failed {} putting operational data started.",
id, writeTx.getIdentifier());
- writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+ writeTx.put(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
LOG.trace(
"{}: Setting device state as failed {} putting operational data ended.",
id, writeTx.getIdentifier());
final AvailableCapabilitiesBuilder avCapabalitiesBuilder = new AvailableCapabilitiesBuilder();
avCapabalitiesBuilder.setAvailableCapability(capabilityList);
- final UnavailableCapabilities unavailableCapabilities =
- new UnavailableCapabilitiesBuilder().setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
+ final UnavailableCapabilities unavailableCapabilities = new UnavailableCapabilitiesBuilder()
+ .setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
.transform(UNAVAILABLE_CAPABILITY_TRANSFORMER).toList()).build();
final NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder()
return netconfNodeBuilder.build();
}
- private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress, final NetconfDeviceCapabilities capabilities) {
+ private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress,
+ final NetconfDeviceCapabilities capabilities) {
List<AvailableCapability> capabilityList = new ArrayList<>();
capabilityList.addAll(capabilities.getNonModuleBasedCapabilities());
capabilityList.addAll(capabilities.getResolvedCapabilities());
NetworkTopology.QNAME, writeTx.getIdentifier());
writeTx.merge(LogicalDatastoreType.OPERATIONAL, networkTopologyPath, networkTopology);
- final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
+ final Topology topology =
+ new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
LOG.trace("{}: Merging {} container to ensure its presence", id,
Topology.QNAME, writeTx.getIdentifier());
writeTx.merge(LogicalDatastoreType.OPERATIONAL, topologyListPath, topology);
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
LOG.error("{}: Transaction({}) {} FAILED!", id, txType,
- transaction.getIdentifier(), t);
- throw new IllegalStateException(id + " Transaction(" + txType + ") not committed correctly", t);
+ transaction.getIdentifier(), throwable);
+ throw new IllegalStateException(
+ id + " Transaction(" + txType + ") not committed correctly", throwable);
}
});
private final SchemalessMessageTransformer schemalessTransformer;
private final RemoteDeviceId deviceId;
- public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId, final RemoteDeviceCommunicator<NetconfMessage> listener,
+ public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId,
+ final RemoteDeviceCommunicator<NetconfMessage> listener,
final BaseRpcSchemalessTransformer baseRpcTransformer,
final SchemalessMessageTransformer messageTransformer) {
this.deviceId = deviceId;
} else if (isBaseRpc(type)) {
transformer = baseRpcTransformer;
} else {
- return Futures.immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type));
+ return Futures.immediateFailedCheckedFuture(
+ new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type));
}
return handleRpc(type, input, transformer);
}
- private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(@Nonnull final SchemaPath type,
- @Nullable final NormalizedNode<?, ?> input,
- final MessageTransformer<NetconfMessage> transformer) {
+ private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(
+ @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input,
+ final MessageTransformer<NetconfMessage> transformer) {
final NetconfMessage netconfMessage = transformer.toRpcRequest(type, input);
- final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture = listener.sendRequest(netconfMessage, type.getLastComponent());
+ final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture =
+ listener.sendRequest(netconfMessage, type.getLastComponent());
- final ListenableFuture<DOMRpcResult> transformed = Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
- if (input1.isSuccessful()) {
- return transformer.toRpcResult(input1.getResult(), type);
- } else {
- return new DefaultDOMRpcResult(input1.getErrors());
- }
- });
+ final ListenableFuture<DOMRpcResult> transformed =
+ Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
+ if (input1.isSuccessful()) {
+ return transformer.toRpcResult(input1.getResult(), type);
+ } else {
+ return new DefaultDOMRpcResult(input1.getErrors());
+ }
+ });
return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
@Nullable
@Override
- public DOMRpcException apply(@Nullable final Exception e) {
- return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s on device %s", type, deviceId);
+ public DOMRpcException apply(@Nullable final Exception exception) {
+ return new DOMRpcImplementationNotAvailableException(
+ exception, "Unable to invoke rpc %s on device %s", type, deviceId);
}
});
}
@Nonnull
@Override
- public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+ public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+ @Nonnull final T listener) {
throw new UnsupportedOperationException("Not available for netconf 1.0");
}
@Override
public synchronized boolean cancel() {
- if(isFinished()) {
+ if (isFinished()) {
return false;
}
listeners.forEach(listener -> listener.onTransactionCancelled(this));
}
@Override
- public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
checkEditable(store);
- // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
- if(containsOnlyNonVisibleData(path, data)) {
+ // Trying to write only mixin nodes (not visible when serialized).
+ // Ignoring. Some devices cannot handle empty edit-config rpc
+ if (containsOnlyNonVisibleData(path, data)) {
LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
return;
}
- final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.of(ModifyAction.REPLACE), path);
+ final DataContainerChild<?, ?> editStructure =
+ netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+ Optional.of(ModifyAction.REPLACE), path);
editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
}
@Override
- public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
checkEditable(store);
- // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
+ // Trying to write only mixin nodes (not visible when serialized).
+ // Ignoring. Some devices cannot handle empty edit-config rpc
if (containsOnlyNonVisibleData(path, data)) {
LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
return;
}
- final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.<ModifyAction>absent(), path);
+ final DataContainerChild<?, ?> editStructure =
+ netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+ Optional.<ModifyAction>absent(), path);
editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
}
/**
- * Check whether the data to be written consists only from mixins
+ * Check whether the data to be written consists only from mixins.
*/
- private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
// There's only one such case:top level list (pathArguments == 1 && data is Mixin)
// any other mixin nodes are contained by a "regular" node thus visible when serialized
return path.getPathArguments().size() == 1 && data instanceof MixinNode;
@Override
public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
checkEditable(store);
- final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(), Optional.of(ModifyAction.DELETE), path);
- editConfig(path, Optional.<NormalizedNode<?, ?>>absent(), editStructure, Optional.of(ModifyAction.NONE), "delete");
+ final DataContainerChild<?, ?> editStructure =
+ netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
+ Optional.of(ModifyAction.DELETE), path);
+ editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
+ editStructure, Optional.of(ModifyAction.NONE), "delete");
}
@Override
if (result != null && result.isSuccessful()) {
listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
} else {
- final TransactionCommitFailedException cause = new TransactionCommitFailedException("Transaction failed", result.getErrors().toArray(new RpcError[result.getErrors().size()]));
+ final TransactionCommitFailedException cause =
+ new TransactionCommitFailedException("Transaction failed",
+ result.getErrors().toArray(new RpcError[result.getErrors().size()]));
listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
}
}
@Override
- public void onFailure(final Throwable t) {
- listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, t));
+ public void onFailure(final Throwable throwable) {
+ listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
}
});
return result;
private void checkEditable(final LogicalDatastoreType store) {
checkNotFinished();
- Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store);
+ Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
+ "Can edit only configuration data, not %s", store);
}
- protected abstract void editConfig(final YangInstanceIdentifier path, final Optional<NormalizedNode<?, ?>> data, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final String operation);
+ protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
+ DataContainerChild<?, ?> editStructure,
+ Optional<ModifyAction> defaultOperation, String operation);
protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
@Override
public void onSuccess(final List<DOMRpcResult> domRpcResults) {
domRpcResults.forEach(domRpcResult -> {
- if(!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
+ if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
final NetconfDocumentedException exception =
new NetconfDocumentedException(id + ":RPC during tx failed",
DocumentedException.ErrorType.APPLICATION,
}
});
- if(!transformed.isDone()) {
+ if (!transformed.isDone()) {
transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
}
}
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
final LogicalDatastoreType store, final YangInstanceIdentifier path) {
switch (store) {
- case CONFIGURATION: {
- return readConfigurationData(path);
- }
- case OPERATIONAL: {
- return readOperationalData(path);
- }
+ case CONFIGURATION: {
+ return readConfigurationData(path);
+ }
+ case OPERATIONAL: {
+ return readOperationalData(path);
+ }
+ default: {
+ LOG.info("Unknown datastore type: {}.", store);
+ }
}
- throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
+ throw new IllegalArgumentException(String.format(
+ "%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
}
@Override
- public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+ public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+ final YangInstanceIdentifier path) {
final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> data = read(store, path);
final ListenableFuture<Boolean> result =
- Futures.transform(data, (Optional<NormalizedNode<?, ?>> a) -> a != null && a.isPresent());
+ Futures.transform(data, (Optional<NormalizedNode<?, ?>> optionalNode) ->
+ optionalNode != null && optionalNode.isPresent());
return MappingCheckedFuture.create(result, ReadFailedException.MAPPER);
}
}
@Override
- public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
delegateWriteTx.put(store, path, data);
}
@Override
- public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+ public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+ final NormalizedNode<?, ?> data) {
delegateWriteTx.merge(store, path, data);
}
currentTransaction = null;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
private void removePendingTx(final AbstractWriteTx transaction) {
try {
pendingTransactions.remove(transaction).close();
import org.slf4j.LoggerFactory;
/**
- * Tx implementation for netconf devices that support only candidate datastore and writable running
+ * Tx implementation for netconf devices that support only candidate datastore and writable running.
* The sequence goes exactly as with only candidate supported, with one addition:
* <ul>
* <li>Running datastore is locked as the first thing and this lock has to succeed</li>
private static final Logger LOG = LoggerFactory.getLogger(WriteCandidateRunningTx.class);
- public WriteCandidateRunningTx(final RemoteDeviceId id, final NetconfBaseOps netOps, final boolean rollbackSupport) {
+ public WriteCandidateRunningTx(final RemoteDeviceId id, final NetconfBaseOps netOps,
+ final boolean rollbackSupport) {
super(id, netOps, rollbackSupport);
}
}
/**
- * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+ * This has to be non blocking since it is called from a callback on commit
+ * and its netty threadpool that is really sensitive to blocking calls.
*/
private void unlockRunning() {
netOps.unlockRunning(new NetconfRpcFutureCallback("Unlock running", id));
import org.slf4j.LoggerFactory;
/**
- * Tx implementation for netconf devices that support only candidate datastore and no writable running
+ * Tx implementation for netconf devices that support only candidate datastore and no writable running.
* The sequence goes as:
* <ol>
* <li>Lock candidate datastore on tx construction
* </li>
* <li>Edit-config in candidate N times
* <ul>
- * <li>If any issue occurs during edit, datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async</li>
+ * <li>If any issue occurs during edit,
+ * datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async</li>
* </ul>
* </li>
* <li>Commit and Unlock candidate datastore async</li>
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Lock candidate operation failed. {}", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Lock candidate operation failed. {}", throwable);
discardChanges();
}
};
@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
- final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
- @Override
- public Void apply(final RpcResult<TransactionStatus> input) {
- Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(), "Submit failed with errors: %s", input.getErrors());
- return null;
- }
- });
+ final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
+ new Function<RpcResult<TransactionStatus>, Void>() {
+ @Override
+ public Void apply(final RpcResult<TransactionStatus> input) {
+ Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
+ "Submit failed with errors: %s", input.getErrors());
+ return null;
+ }
+ });
return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
@Override
public TransactionCommitFailedException apply(final Exception input) {
- return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
+ return new TransactionCommitFailedException(
+ "Submit of transaction " + getIdentifier() + " failed", input);
}
});
}
/**
- * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+ * This has to be non blocking since it is called from a callback on commit
+ * and its netty threadpool that is really sensitive to blocking calls.
*/
private void discardChanges() {
netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
}
@Override
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable throwable) {
// TODO If lock is cause of this failure cleanup will issue warning log
// cleanup is trying to do unlock, but this will fail
cleanup();
}
/**
- * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+ * This has to be non blocking since it is called from a callback on commit
+ * and its netty threadpool that is really sensitive to blocking calls.
*/
private void unlock() {
netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
import org.slf4j.LoggerFactory;
/**
- * Tx implementation for netconf devices that support only writable-running with no candidate
+ * Tx implementation for netconf devices that support only writable-running with no candidate.
* The sequence goes as:
* <ol>
* <li>Lock running datastore on tx construction
@Override
public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
- final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
- @Override
- public Void apply(final RpcResult<TransactionStatus> input) {
- return null;
- }
- });
+ final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(),
+ new Function<RpcResult<TransactionStatus>, Void>() {
+ @Override
+ public Void apply(final RpcResult<TransactionStatus> input) {
+ return null;
+ }
+ });
return Futures.makeChecked(commmitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
@Override
public TransactionCommitFailedException apply(final Exception input) {
- return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
+ return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
+ input);
}
});
}
final boolean rollbackSupport) {
final NetconfRpcFutureCallback editConfigCallback = new NetconfRpcFutureCallback("Edit running", id);
if (defaultOperation.isPresent()) {
- return netOps.editConfigRunning(editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport);
+ return netOps.editConfigRunning(
+ editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport);
} else {
return netOps.editConfigRunning(editConfigCallback, editStructure, rollbackSupport);
}
private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
"schemaDownload", SchemaSourceException.class) {
@Override
- protected SchemaSourceException newWithCause(final String s, final Throwable throwable) {
- return new SchemaSourceException(s, throwable);
+ protected SchemaSourceException newWithCause(final String message, final Throwable throwable) {
+ return new SchemaSourceException(message, throwable);
}
};
this.rpc = Preconditions.checkNotNull(rpc);
}
- private static final NodeIdentifier FORMAT_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format").intern());
- private static final NodeIdentifier GET_SCHEMA_PATHARG = new NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME);
- private static final NodeIdentifier IDENTIFIER_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier").intern());
- private static final NodeIdentifier VERSION_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version").intern());
+ private static final NodeIdentifier FORMAT_PATHARG =
+ new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format").intern());
+ private static final NodeIdentifier GET_SCHEMA_PATHARG =
+ new NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME);
+ private static final NodeIdentifier IDENTIFIER_PATHARG =
+ new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier").intern());
+ private static final NodeIdentifier VERSION_PATHARG =
+ new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version").intern());
- private static final LeafNode<?> FORMAT_LEAF = Builders.leafBuilder().withNodeIdentifier(FORMAT_PATHARG).withValue(Yang.QNAME).build();
+ private static final LeafNode<?> FORMAT_LEAF =
+ Builders.leafBuilder().withNodeIdentifier(FORMAT_PATHARG).withValue(Yang.QNAME).build();
- private static final QName NETCONF_DATA = QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()).intern();
+ private static final QName NETCONF_DATA =
+ QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()).intern();
private static final NodeIdentifier NETCONF_DATA_PATHARG = toId(NETCONF_DATA);
public static ContainerNode createGetSchemaRequest(final String moduleName, final Optional<String> revision) {
- final LeafNode<?> identifier = Builders.leafBuilder().withNodeIdentifier(IDENTIFIER_PATHARG).withValue(moduleName).build();
+ final LeafNode<?> identifier =
+ Builders.leafBuilder().withNodeIdentifier(IDENTIFIER_PATHARG).withValue(moduleName).build();
final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = Builders.containerBuilder()
.withNodeIdentifier(GET_SCHEMA_PATHARG).withChild(identifier).withChild(FORMAT_LEAF);
if (revision.isPresent()) {
- builder.withChild(Builders.leafBuilder().withNodeIdentifier(VERSION_PATHARG).withValue(revision.get()).build());
+ builder.withChild(Builders.leafBuilder()
+ .withNodeIdentifier(VERSION_PATHARG).withValue(revision.get()).build());
}
return builder.build();
return Optional.absent();
}
- final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
+ final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+ ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
Preconditions.checkState(child.isPresent() && child.get() instanceof AnyXmlNode,
"%s Unexpected response to get-schema, expected response with one child %s, but was %s", id,
}
@Override
- public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
+ public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
+ final SourceIdentifier sourceIdentifier) {
final String moduleName = sourceIdentifier.getName();
// If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));
- final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER);
+ final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked =
+ Futures.makeChecked(transformed, MAPPER);
return checked;
}
/**
- * Transform composite node to string schema representation and then to ASTSchemaSource
+ * Transform composite node to string schema representation and then to ASTSchemaSource.
*/
private static final class ResultToYangSourceTransformer implements
Function<DOMRpcResult, YangTextSchemaSource> {
private final String moduleName;
private final Optional<String> revision;
- public ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
+ ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
final String moduleName, final Optional<String> revision) {
this.id = id;
this.sourceIdentifier = sourceIdentifier;
final Optional<String> schemaString = getSchemaFromRpc(id, input.getResult());
Preconditions.checkState(schemaString.isPresent(),
- "%s: Unexpected response to get-schema, schema not present in message for: %s", id, sourceIdentifier);
+ "%s: Unexpected response to get-schema, schema not present in message for: %s",
+ id, sourceIdentifier);
LOG.debug("{}: YANG Schema successfully retrieved for {}:{}",
id, moduleName, revision);
private final RemoteDeviceId id;
private final Optional<String> schemaString;
- public NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sId, final Optional<String> schemaString) {
- super(sId);
+ NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
+ final Optional<String> schemaString) {
+ super(sourceIdentifier);
this.id = id;
this.schemaString = schemaString;
}
import org.slf4j.LoggerFactory;
/**
- * Provides YANG schema sources from yang library
+ * Provides YANG schema sources from yang library.
*/
public final class YangLibrarySchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
return download(sourceIdentifier);
}
- private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(final SourceIdentifier sId) {
- final URL url = availableSources.get(sId);
- try(final InputStream in = url.openStream()) {
+ private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(
+ final SourceIdentifier sourceIdentifier) {
+ final URL url = availableSources.get(sourceIdentifier);
+ try (InputStream in = url.openStream()) {
final String schemaContent = new String(ByteStreams.toByteArray(in));
final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource =
- new NetconfRemoteSchemaYangSourceProvider.
- NetconfYangTextSchemaSource(id, sId, Optional.of(schemaContent));
- LOG.debug("Source {} downloaded from a yang library's url {}", sId, url);
+ new NetconfRemoteSchemaYangSourceProvider
+ .NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
+ LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url);
return Futures.immediateCheckedFuture(yangSource);
} catch (IOException e) {
- LOG.warn("Unable to download source {} from a yang library's url {}", sId, url, e);
+ LOG.warn("Unable to download source {} from a yang library's url {}", sourceIdentifier, url, e);
return Futures.immediateFailedCheckedFuture(
- new SchemaSourceException("Unable to download remote schema for " + sId + " from " + url, e));
+ new SchemaSourceException(
+ "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));
}
}
}
import org.w3c.dom.Element;
/**
- * Transforms base netconf rpcs
+ * Transforms base netconf RPCs.
*/
public class BaseRpcSchemalessTransformer implements MessageTransformer<NetconfMessage> {
- private static final Map<QName, RpcDefinition> mappedRpcs = BaseSchema.BASE_NETCONF_CTX.getMappedRpcs();
- private static final SchemaContext schemaContext = BaseSchema.BASE_NETCONF_CTX.getSchemaContext();
+ private static final Map<QName, RpcDefinition> MAPPED_RPCS = BaseSchema.BASE_NETCONF_CTX.getMappedRpcs();
+ private static final SchemaContext SCHEMA_CONTEXT = BaseSchema.BASE_NETCONF_CTX.getSchemaContext();
private final MessageCounter counter;
// In case no input for rpc is defined, we can simply construct the payload here
final QName rpcQName = rpc.getLastComponent();
- Preconditions.checkNotNull(mappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, mappedRpcs.keySet());
+ Preconditions.checkNotNull(MAPPED_RPCS.get(rpcQName), "Unknown rpc %s, available rpcs: %s",
+ rpcQName, MAPPED_RPCS.keySet());
final DOMResult domResult = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
- if (mappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
+ if (MAPPED_RPCS.get(rpcQName).getInput().getChildNodes().isEmpty()) {
return new NetconfMessage(domResult.getNode().getOwnerDocument());
}
final DOMResult result = domResult;
try {
- NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, inputPath, schemaContext);
+ NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result,
+ inputPath, SCHEMA_CONTEXT);
} catch (final XMLStreamException | IOException | IllegalStateException e) {
throw new IllegalStateException("Unable to serialize " + inputPath, e);
}
final Document data = XmlUtil.newDocument();
data.appendChild(data.importNode(xmlData, true));
AnyXmlNode xmlDataNode = Builders.anyXmlBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
.withValue(new DOMSource(data))
.build();
normalizedNode = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
.withChild(xmlDataNode).build();
} else {
//other base rpcs don't have any output, we can simply construct the payload here
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+@SuppressWarnings("checkstyle:IllegalCatch")
public enum BaseSchema {
BASE_NETCONF_CTX(
Lists.newArrayList(
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+ .base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+ .monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
)
),
BASE_NETCONF_CTX_WITH_NOTIFICATIONS(
Lists.newArrayList(
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+ .monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+ .notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+ .base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+ .notifications.rev120206.$YangModuleInfoImpl.getInstance()
)
);
private static final Function<SchemaNode, QName> QNAME_FUNCTION = rpcDefinition -> rpcDefinition.getQName();
- private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
+ private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION =
+ notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
private final SchemaContext schemaContext;
private final BaseSchema baseSchema;
this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
}
- public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
+ public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
+ final BaseSchema baseSchema) {
this.counter = new MessageCounter();
this.schemaContext = schemaContext;
- parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
+ parserFactory = DomToNormalizedNodeParserFactory
+ .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
this.baseSchema = baseSchema;
final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
final QName notificationNoRev;
try {
- notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
+ notificationNoRev = QName.create(
+ stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
} catch (final MissingNameSpaceException e) {
- throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
+ throw new IllegalArgumentException(
+ "Unable to parse notification " + message + ", cannot find namespace", e);
}
final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
Preconditions.checkArgument(notificationDefinitions.size() > 0,
- "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
+ "Unable to parse notification %s, unknown notification. Available notifications: %s",
+ notificationDefinitions, mappedNotifications.keySet());
final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
- final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
+ final ContainerSchemaNode notificationAsContainerSchemaNode =
+ NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
final Element element = stripped.getValue().getDomElement();
final ContainerNode content;
return new NetconfDeviceNotification(content, stripped.getKey());
}
- private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
- Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
+ private static NotificationDefinition getMostRecentNotification(
+ final Collection<NotificationDefinition> notificationDefinitions) {
+ Comparator<NotificationDefinition> cmp = (o1, o2) ->
+ o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
return Collections.max(notificationDefinitions, cmp);
}
final QName rpcQName = rpc.getLastComponent();
Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
- // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
+ // Determine whether a base netconf operation is being invoked
+ // and also check if the device exposed model for base netconf.
// If no, use pre built base netconf operations model
final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
- if(needToUseBaseCtx) {
+ if (needToUseBaseCtx) {
currentMappedRpcs = baseSchema.getMappedRpcs();
}
- Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
- if(currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
- return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
+ Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
+ "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
+ if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
+ return new NetconfMessage(NetconfMessageTransformUtil
+ .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
}
Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
try {
- // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
+ // If the schema context for netconf device does not contain model for base netconf operations,
+ // use default pre build context with just the base model
// This way operations like lock/unlock are supported even if the source for base model was not provided
SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
}
private static boolean isBaseOrNotificationRpc(final QName rpc) {
- return rpc.getNamespace().equals(NETCONF_URI) ||
- rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
- rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
+ return rpc.getNamespace().equals(NETCONF_URI)
+ || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
+ || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
}
final QName rpcQName = rpc.getLastComponent();
if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
- final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
+ final ContainerSchemaNode schemaForDataRead =
+ NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
final ContainerNode dataNode;
try {
- dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
+ dataNode =
+ parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
}
- normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+ normalizedNode = Builders.containerBuilder()
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
.withChild(dataNode).build();
} else {
Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
- // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
+ // Determine whether a base netconf operation is being invoked
+ // and also check if the device exposed model for base netconf.
// If no, use pre built base netconf operations model
final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
- if(needToUseBaseCtx) {
+ if (needToUseBaseCtx) {
currentMappedRpcs = baseSchema.getMappedRpcs();
}
final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
- Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
+ Preconditions.checkArgument(rpcDefinition != null,
+ "Unable to parse response of %s, the rpc is unknown", rpcQName);
// In case no input for rpc is defined, we can simply construct the payload here
if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
notificationNoRev =
QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
} catch (final MissingNameSpaceException e) {
- throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
+ throw new IllegalArgumentException("Unable to parse notification "
+ + message + ", cannot find namespace", e);
}
final AnyXmlNode notificationPayload = Builders.anyXmlBuilder()
}
/**
- * Transforms reply message to anyXml node. In case, that rpc-reply doesn't contain data and contains only <ok/>
- * element, returns null.
+ * Transforms reply message to anyXml node.
+ * In case, that rpc-reply doesn't contain data and contains only <ok/> element, returns null.
* @param rpcReply reply message
* @return anyxml
*/
public DOMRpcResult toRpcResult(final NetconfMessage rpcReply, final SchemaPath rpc) {
final Document document = rpcReply.getDocument();
final AnyXmlNode result;
- if(BaseRpcSchemalessTransformer.isOkPresent(document)) {
+ if (BaseRpcSchemalessTransformer.isOkPresent(document)) {
result = null;
} else {
result = Builders.anyXmlBuilder()
private void wrapPayload(final Document doc) {
final Element payload = doc.getDocumentElement();
doc.removeChild(payload);
- final Element rpcNS = doc.createElementNS(NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getNamespace().toString(),
+ final Element rpcNS =
+ doc.createElementNS(NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getNamespace().toString(),
NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getLocalName());
// set msg id
- rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(NetconfMessageTransformUtil.MESSAGE_ID_PREFIX));
+ rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR,
+ counter.getNewMessageId(NetconfMessageTransformUtil.MESSAGE_ID_PREFIX));
rpcNS.appendChild(payload);
doc.appendChild(rpcNS);
}
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(datastore));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(datastore));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> lockCandidate(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_CANDIDATE_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_CANDIDATE_QNAME));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> lockRunning(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_RUNNING_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_RUNNING_QNAME));
Futures.addCallback(future, callback);
return future;
}
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(datastore));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(datastore));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> unlockRunning(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_RUNNING_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_RUNNING_QNAME));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> unlockCandidate(final FutureCallback<DOMRpcResult> callback) {
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_CANDIDATE_QNAME));
+ final ListenableFuture<DOMRpcResult> future =
+ rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_CANDIDATE_QNAME));
Futures.addCallback(future, callback);
return future;
}
public ListenableFuture<DOMRpcResult> commit(final FutureCallback<DOMRpcResult> callback) {
Preconditions.checkNotNull(callback);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+ toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
Futures.addCallback(future, callback);
return future;
}
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME), getValidateContent(datastore));
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+ toPath(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME), getValidateContent(datastore));
Futures.addCallback(future, callback);
return future;
}
return validate(callback, NETCONF_RUNNING_QNAME);
}
- public ListenableFuture<DOMRpcResult> copyConfig(final FutureCallback<DOMRpcResult> callback, final QName source, final QName target) {
+ public ListenableFuture<DOMRpcResult> copyConfig(final FutureCallback<DOMRpcResult> callback,
+ final QName source, final QName target) {
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(source);
Preconditions.checkNotNull(target);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME), getCopyConfigContent(source, target));
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+ toPath(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME), getCopyConfigContent(source, target));
Futures.addCallback(future, callback);
return future;
}
return copyConfig(callback, NETCONF_RUNNING_QNAME, NETCONF_CANDIDATE_QNAME);
}
- public ListenableFuture<DOMRpcResult> getConfig(final FutureCallback<DOMRpcResult> callback, final QName datastore, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> getConfig(final FutureCallback<DOMRpcResult> callback, final QName datastore,
+ final Optional<YangInstanceIdentifier> filterPath) {
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
return future;
}
- public ListenableFuture<Optional<NormalizedNode<?, ?>>> getConfigRunningData(final FutureCallback<DOMRpcResult> callback,
- final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<Optional<NormalizedNode<?, ?>>> getConfigRunningData(
+ final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
final ListenableFuture<DOMRpcResult> configRunning = getConfigRunning(callback, filterPath);
return extractData(filterPath, configRunning);
}
return extractData(filterPath, configRunning);
}
- private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(final Optional<YangInstanceIdentifier> path,
- final ListenableFuture<DOMRpcResult> configRunning) {
+ private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(
+ final Optional<YangInstanceIdentifier> path, final ListenableFuture<DOMRpcResult> configRunning) {
return Futures.transform(configRunning, (Function<DOMRpcResult, Optional<NormalizedNode<?, ?>>>) result -> {
- Preconditions.checkArgument(result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
+ Preconditions.checkArgument(
+ result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataNode =
- ((ContainerNode) result.getResult()).getChild(NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
+ ((ContainerNode) result.getResult()).getChild(
+ NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
return transformer.selectFromDataStructure(dataNode, path.get());
});
}
- public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback,
+ final Optional<YangInstanceIdentifier> filterPath) {
return getConfig(callback, NETCONF_RUNNING_QNAME, filterPath);
}
- public ListenableFuture<DOMRpcResult> getConfigCandidate(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> getConfigCandidate(final FutureCallback<DOMRpcResult> callback,
+ final Optional<YangInstanceIdentifier> filterPath) {
return getConfig(callback, NETCONF_CANDIDATE_QNAME, filterPath);
}
- public ListenableFuture<DOMRpcResult> get(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+ public ListenableFuture<DOMRpcResult> get(final FutureCallback<DOMRpcResult> callback,
+ final Optional<YangInstanceIdentifier> filterPath) {
Preconditions.checkNotNull(callback);
final ListenableFuture<DOMRpcResult> future;
- future = isFilterPresent(filterPath) ?
- rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext))) :
- rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
+ future = isFilterPresent(filterPath)
+ ? rpc.invokeRpc(toPath(NETCONF_GET_QNAME),
+ NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext)))
+ : rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
Futures.addCallback(future, callback);
return future;
return filterPath.isPresent() && !filterPath.get().isEmpty();
}
- public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final ModifyAction modifyAction, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final ModifyAction modifyAction, final boolean rollback) {
return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.of(modifyAction), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final boolean rollback) {
return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final ModifyAction modifyAction, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final ModifyAction modifyAction, final boolean rollback) {
return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.of(modifyAction), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
+ final DataContainerChild<?, ?> editStructure,
+ final boolean rollback) {
return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
}
- public ListenableFuture<DOMRpcResult> editConfig(final FutureCallback<? super DOMRpcResult> callback, final QName datastore, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> modifyAction, final boolean rollback) {
+ public ListenableFuture<DOMRpcResult> editConfig(
+ final FutureCallback<? super DOMRpcResult> callback, final QName datastore,
+ final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> modifyAction,
+ final boolean rollback) {
Preconditions.checkNotNull(editStructure);
Preconditions.checkNotNull(callback);
Preconditions.checkNotNull(datastore);
- final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_EDIT_CONFIG_QNAME), getEditConfigContent(datastore, editStructure, modifyAction, rollback));
+ final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_EDIT_CONFIG_QNAME),
+ getEditConfigContent(datastore, editStructure, modifyAction, rollback));
Futures.addCallback(future, callback);
return future;
}
- public DataContainerChild<?, ?> createEditConfigStrcture(final Optional<NormalizedNode<?, ?>> lastChild, final Optional<ModifyAction> operation, final YangInstanceIdentifier dataPath) {
+ public DataContainerChild<?, ?> createEditConfigStrcture(final Optional<NormalizedNode<?, ?>> lastChild,
+ final Optional<ModifyAction> operation,
+ final YangInstanceIdentifier dataPath) {
final AnyXmlNode configContent = transformer.createEditConfigStructure(lastChild, dataPath, operation);
return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(configContent).build();
}
- private static ContainerNode getEditConfigContent(final QName datastore,
- final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final boolean rollback) {
+ private static ContainerNode getEditConfigContent(
+ final QName datastore, final DataContainerChild<?, ?> editStructure,
+ final Optional<ModifyAction> defaultOperation, final boolean rollback) {
final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> editBuilder =
Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_EDIT_CONFIG_QNAME));
editBuilder.withChild(getTargetNode(datastore));
// Default operation
- if(defaultOperation.isPresent()) {
+ if (defaultOperation.isPresent()) {
final String opString = defaultOperation.get().name().toLowerCase();
- editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME)).withValue(opString).build());
+ editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME))
+ .withValue(opString).build());
}
// Error option
- if(rollback) {
- editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_ERROR_OPTION_QNAME)).withValue(ROLLBACK_ON_ERROR_OPTION).build());
+ if (rollback) {
+ editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_ERROR_OPTION_QNAME))
+ .withValue(ROLLBACK_ON_ERROR_OPTION).build());
}
// Edit content
public static final String MESSAGE_ID_PREFIX = "m";
public static final String MESSAGE_ID_ATTR = "message-id";
- public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
+ public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
+ QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
private static final String SUBTREE = "subtree";
// Blank document used for creation of new DOM nodes
private NetconfMessageTransformUtil() {}
- public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
+ public static final QName IETF_NETCONF_MONITORING =
+ QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version").intern();
- public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
-
- public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
-
- public static final QName NETCONF_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
+ QName.create(IETF_NETCONF_MONITORING, "format").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
+ QName.create(IETF_NETCONF_MONITORING, "location").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
+ QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
+ QName.create(IETF_NETCONF_MONITORING, "version").intern();
+ public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
+ QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
+
+ public static final QName IETF_NETCONF_NOTIFICATIONS =
+ QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
+
+ public static final QName NETCONF_QNAME =
+ QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
- public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
+ public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
+ QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
public static final DataContainerChild<?, ?> EMPTY_FILTER;
static {
- final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+ final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+ Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
- final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
- element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
+ final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
+ Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+ element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
+ NETCONF_TYPE_QNAME.getLocalName(), "subtree");
anyXmlBuilder.withValue(new DOMSource(element));
EMPTY_FILTER = anyXmlBuilder.build();
}
- public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
- final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+ public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
+ final SchemaContext ctx) {
+ final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+ Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
- final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
- element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
+ final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
+ Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+ element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
+ "subtree");
try {
NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
- if(inputMsgId.equals(outputMsgId) == false) {
- final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
- .put( "actual-message-id", outputMsgId )
- .put( "expected-message-id", inputMsgId )
+ if (inputMsgId.equals(outputMsgId) == false) {
+ final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
+ .put("actual-message-id", outputMsgId)
+ .put("expected-message-id", inputMsgId)
.build();
- throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
+ throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
null, NetconfDocumentedException.ErrorType.PROTOCOL,
NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
}
public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
- if(NetconfMessageUtil.isErrorMessage(output)) {
+ if (NetconfMessageUtil.isErrorMessage(output)) {
throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
}
}
- public static RpcError toRpcError( final NetconfDocumentedException ex ) {
+ public static RpcError toRpcError(final NetconfDocumentedException ex) {
final StringBuilder infoBuilder = new StringBuilder();
final Map<String, String> errorInfo = ex.getErrorInfo();
- if(errorInfo != null) {
- for( final Entry<String,String> e: errorInfo.entrySet() ) {
- infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
- .append( "</" ).append( e.getKey() ).append( '>' );
+ if (errorInfo != null) {
+ for (final Entry<String, String> e : errorInfo.entrySet()) {
+ infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
+ .append("</").append(e.getKey()).append('>');
}
}
- final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
- return severity == ErrorSeverity.ERROR ?
- RpcResultBuilder.newError(
- toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
- ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
- RpcResultBuilder.newWarning(
- toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
- ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
+ final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
+ return severity == ErrorSeverity.ERROR
+ ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
+ ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
+ : RpcResultBuilder.newWarning(
+ toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
+ ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
}
- private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
+ private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
switch (severity) {
case WARNING:
return RpcError.ErrorSeverity.WARNING;
private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
switch (type) {
case PROTOCOL:
- return RpcError.ErrorType.PROTOCOL;
+ return RpcError.ErrorType.PROTOCOL;
case RPC:
- return RpcError.ErrorType.RPC;
+ return RpcError.ErrorType.RPC;
case TRANSPORT:
- return RpcError.ErrorType.TRANSPORT;
- default:
- return RpcError.ErrorType.APPLICATION;
+ return RpcError.ErrorType.TRANSPORT;
+ default:
+ return RpcError.ErrorType.APPLICATION;
}
}
return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
}
- public static AnyXmlNode createEditConfigAnyxml(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
- final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+ public static AnyXmlNode createEditConfigAnyxml(
+ final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+ final Optional<NormalizedNode<?, ?>> lastChildOverride) {
final NormalizedNode<?, ?> configContent;
if (dataPath.isEmpty()) {
- Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
+ Preconditions.checkArgument(lastChildOverride.isPresent(),
+ "Data has to be present when creating structure for top level element");
Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
- "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
+ "Data has to be either container or a list node when creating structure for top level element, "
+ + "but was: %s", lastChildOverride.get());
configContent = lastChildOverride.get();
} else {
- final Entry<QName, ModifyAction> modifyOperation =
- operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
- configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
+ final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
+ ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
+ configContent = ImmutableNodes
+ .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
}
- final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
+ final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
+ Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
try {
NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
} catch (IOException | XMLStreamException e) {
return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
}
- public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
- final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+ public static DataContainerChild<?, ?> createEditConfigStructure(
+ final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+ final Optional<NormalizedNode<?, ?>> lastChildOverride) {
return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
.withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
}
public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
final List<XmlElement> childElements = xmlElement.getChildElements();
- Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format.\nExpected 2 childElements," +
- " actual childElements size is %s", message, childElements.size());
+ Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
+ + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
final XmlElement eventTimeElement;
final XmlElement notificationElement;
if (childElements.get(0).getName().equals(EVENT_TIME)) {
eventTimeElement = childElements.get(0);
notificationElement = childElements.get(1);
- }
- else if(childElements.get(1).getName().equals(EVENT_TIME)) {
+ } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
eventTimeElement = childElements.get(1);
notificationElement = childElements.get(0);
} else {
} catch (final DocumentedException e) {
throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
} catch (final DateTimeParseException e) {
- LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
+ LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
+ NetconfNotification.UNKNOWN_EVENT_TIME, e);
return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
}
}
return new DOMResult(elementNS);
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
- final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
+ final SchemaPath schemaPath,
+ final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
try {
- try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
+ try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
- try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
+ try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
normalizedNodeWriter.write(value);
try {
writer.close();
} catch (final Exception e) {
- LOG.warn("Unable to close resource properly", e);
+ LOG.warn("Unable to close resource properly", e);
}
}
}
import org.slf4j.LoggerFactory;
/**
- * Simple Netconf rpc logging callback
+ * Simple Netconf RPC logging callback.
*/
public class NetconfRpcFutureCallback implements FutureCallback<DOMRpcResult> {
private static final Logger LOG = LoggerFactory.getLogger(NetconfRpcFutureCallback.class);
@Override
public void onSuccess(final DOMRpcResult result) {
- if(result.getErrors().isEmpty()) {
+ if (result.getErrors().isEmpty()) {
LOG.trace("{}: {} invoked successfully", id, type);
} else {
onUnsuccess(result);
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("{}: {} failed.", id, type, t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("{}: {} failed.", id, type, throwable);
}
}
}
@Override
- public Optional<NormalizedNode<?, ?>> selectFromDataStructure(final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
- final YangInstanceIdentifier path) {
+ public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
+ final YangInstanceIdentifier path) {
return NormalizedNodes.findNode(data, path.getPathArguments());
}
@Override
public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
- final YangInstanceIdentifier dataPath, Optional<ModifyAction> operation) {
+ final YangInstanceIdentifier dataPath,
+ Optional<ModifyAction> operation) {
return NetconfMessageTransformUtil.createEditConfigAnyxml(schemaContext, dataPath, operation, data);
}
import org.opendaylight.yangtools.yang.model.api.UsesNode;
/**
- * Simple proxy for container like schema nodes, where user provides a collection of children schema nodes
+ * Simple proxy for container like schema nodes, where user provides a collection of children schema nodes.
*/
public final class NodeContainerProxy implements ContainerSchemaNode {
private final Map<QName, DataSchemaNode> childNodes;
- private final QName qName;
+ private final QName qualifiedName;
private final Set<AugmentationSchema> availableAugmentations;
- public NodeContainerProxy(final QName qName, final Map<QName, DataSchemaNode> childNodes, final Set<AugmentationSchema> availableAugmentations) {
+ public NodeContainerProxy(final QName qualifiedName, final Map<QName, DataSchemaNode> childNodes,
+ final Set<AugmentationSchema> availableAugmentations) {
this.availableAugmentations = availableAugmentations;
this.childNodes = Preconditions.checkNotNull(childNodes, "childNodes");
- this.qName = qName;
+ this.qualifiedName = qualifiedName;
}
- public NodeContainerProxy(final QName qName, final Collection<DataSchemaNode> childNodes) {
- this(qName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
+ public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes) {
+ this(qualifiedName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
}
- public NodeContainerProxy(final QName qName, final Collection<DataSchemaNode> childNodes, final Set<AugmentationSchema> availableAugmentations) {
- this(qName, asMap(childNodes), availableAugmentations);
+ public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes,
+ final Set<AugmentationSchema> availableAugmentations) {
+ this(qualifiedName, asMap(childNodes), availableAugmentations);
}
private static Map<QName, DataSchemaNode> asMap(final Collection<DataSchemaNode> childNodes) {
}
@Override
- public DataSchemaNode getDataChildByName(final QName qName) {
- return childNodes.get(qName);
+ public DataSchemaNode getDataChildByName(final QName qualifiedName) {
+ return childNodes.get(qualifiedName);
}
@Override
@Override
public QName getQName() {
- return qName;
+ return qualifiedName;
}
@Override
* @param path path to select
* @return selected data
*/
- Optional<NormalizedNode<?, ?>> selectFromDataStructure(DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
- YangInstanceIdentifier path);
+ Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+ DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data, YangInstanceIdentifier path);
}
* @return selected data
*/
@Override
- public Optional<NormalizedNode<?, ?>> selectFromDataStructure(final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
- final YangInstanceIdentifier path) {
+ public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+ final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
+ final YangInstanceIdentifier path) {
Preconditions.checkArgument(data instanceof AnyXmlNode);
final List<XmlElement> xmlElements = selectMatchingNodes(getSourceElement(((AnyXmlNode)data).getValue()), path);
final Document result = XmlUtil.newDocument();
final QName dataQName = NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
- final Element dataElement = result.createElementNS(dataQName.getNamespace().toString(), dataQName.getLocalName());
+ final Element dataElement =
+ result.createElementNS(dataQName.getNamespace().toString(), dataQName.getLocalName());
result.appendChild(dataElement);
for (XmlElement xmlElement : xmlElements) {
dataElement.appendChild(result.importNode(xmlElement.getDomElement(), true));
*/
@Override
public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
- final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation) {
+ final YangInstanceIdentifier dataPath,
+ final Optional<ModifyAction> operation) {
Preconditions.checkArgument(data.isPresent());
Preconditions.checkArgument(data.get() instanceof AnyXmlNode);
} else {
final List<YangInstanceIdentifier.PathArgument> pathArguments = dataPath.getPathArguments();
//last will be appended later
- final List<YangInstanceIdentifier.PathArgument> pathWithoutLast = pathArguments.subList(0, pathArguments.size() - 1);
+ final List<YangInstanceIdentifier.PathArgument> pathWithoutLast =
+ pathArguments.subList(0, pathArguments.size() - 1);
parentXmlStructure = instanceIdToXmlStructure(pathWithoutLast, configElement);
}
if (operation.isPresent()) {
public DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier path) {
final Document document = XmlUtil.newDocument();
final QName filterQname = NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
- final Element filter = document.createElementNS(filterQname.getNamespace().toString(), filterQname.getLocalName());
+ final Element filter =
+ document.createElementNS(filterQname.getNamespace().toString(), filterQname.getLocalName());
final Attr a = document.createAttributeNS(filterQname.getNamespace().toString(), "type");
a.setTextContent("subtree");
filter.setAttributeNode(a);
final XmlElement dataElement = XmlElement.fromDomElement(dataNode);
final YangInstanceIdentifier.PathArgument lastPathArgument = dataPath.getLastPathArgument();
final QName nodeType = lastPathArgument.getNodeType();
- if (!nodeType.getNamespace().toString().equals(dataNode.getNamespaceURI()) ||
- !nodeType.getLocalName().equals(dataElement.getName())) {
+ if (!nodeType.getNamespace().toString().equals(dataNode.getNamespaceURI())
+ || !nodeType.getLocalName().equals(dataElement.getName())) {
throw new IllegalStateException(
String.format("Can't write data '%s' to path %s", dataNode.getTagName(), dataPath));
}
final YangInstanceIdentifier.NodeIdentifierWithPredicates keyedId =
(YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument;
final Map<QName, Object> keyValues = keyedId.getKeyValues();
- for (QName qName : keyValues.keySet()) {
+ for (QName qualifiedName : keyValues.keySet()) {
final List<XmlElement> key =
- dataElement.getChildElementsWithinNamespace(qName.getLocalName(), qName.getNamespace().toString());
+ dataElement.getChildElementsWithinNamespace(qualifiedName.getLocalName(),
+ qualifiedName.getNamespace().toString());
if (key.isEmpty()) {
throw new IllegalStateException("No key present in xml");
}
} catch (DocumentedException e) {
throw new IllegalStateException("Key value not present in key element");
}
- if (!keyValues.get(qName).equals(textContent)) {
+ if (!keyValues.get(qualifiedName).equals(textContent)) {
throw new IllegalStateException("Key value in path not equal to key value in xml");
}
}
parent.appendChild(element);
//if path argument is list id, add also keys to resulting xml
if (pathArgument instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
- YangInstanceIdentifier.NodeIdentifierWithPredicates listNode = (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
+ YangInstanceIdentifier.NodeIdentifierWithPredicates listNode =
+ (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
for (Map.Entry<QName, Object> key : listNode.getKeyValues().entrySet()) {
- final Element keyElement = doc.createElementNS(key.getKey().getNamespace().toString(), key.getKey().getLocalName());
+ final Element keyElement =
+ doc.createElementNS(key.getKey().getNamespace().toString(), key.getKey().getLocalName());
keyElement.setTextContent(key.getValue().toString());
element.appendChild(keyElement);
}
public class MessageCounter {
final AtomicInteger messageId = new AtomicInteger(0);
- private static final String messageIdBlueprint = "%s-%s";
+ private static final String MESSAGE_ID_BLUEPRINT = "%s-%s";
public String getNewMessageId(final String prefix) {
Preconditions.checkArgument(Strings.isNullOrEmpty(prefix) == false, "Null or empty prefix");
- return String.format(messageIdBlueprint, prefix, getNewMessageId());
+ return String.format(MESSAGE_ID_BLUEPRINT, prefix, getNewMessageId());
}
public String getNewMessageId() {
private final InstanceIdentifier<Node> bindingPath;
private final NodeKey key;
private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier topologyPath;
- private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
+ private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
private InetSocketAddress address;
private Host host;
private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPath(final String name) {
final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
- builder.node(Nodes.QNAME).node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
+ builder.node(Nodes.QNAME).node(Node.QNAME)
+ .nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
return builder.build();
}
- private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
- final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.builder(NetworkTopology.class).build();
- final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
+ private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network
+ .topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
+ final InstanceIdentifier<NetworkTopology> networkTopology =
+ InstanceIdentifier.builder(NetworkTopology.class).build();
+ final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology
+ .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
return topology
- .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class,
- new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey(
- new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId(key.getId().getValue())));
+ .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.class,
+ new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network
+ .topology.topology.NodeKey(new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.NodeId(key.getId().getValue())));
}
- private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(final String name) {
+ private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(
+ final String name) {
final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
builder
.node(NetworkTopology.QNAME)
.node(Topology.QNAME)
- .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME.getLocalName())
- .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME)
- .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME,
- QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
+ .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"),
+ TopologyNetconf.QNAME.getLocalName())
+ .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.QNAME)
+ .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.QNAME,
+ QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
return builder.build();
}
return key;
}
- public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
+ public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+ .network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
return topologyBindingPath;
}
@Override
public String toString() {
- return "RemoteDevice{" + name +'}';
+ return "RemoteDevice{" + name + '}';
}
@Override
- public boolean equals(final Object o) {
- if (this == o) {
+ public boolean equals(final Object obj) {
+ if (this == obj) {
return true;
}
- if (!(o instanceof RemoteDeviceId)) {
+ if (!(obj instanceof RemoteDeviceId)) {
return false;
}
- final RemoteDeviceId that = (RemoteDeviceId) o;
+ final RemoteDeviceId that = (RemoteDeviceId) obj;
if (!name.equals(that.name)) {
return false;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyCollectionOf;
import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.SettableFuture;
+import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
+import org.xml.sax.SAXException;
+@SuppressWarnings("checkstyle:IllegalCatch")
public class NetconfDeviceTest {
- private static final NetconfMessage notification;
+ private static final NetconfMessage NOTIFICATION;
- private static final ContainerNode compositeNode;
+ private static final ContainerNode COMPOSITE_NODE;
static {
try {
- compositeNode = mockClass(ContainerNode.class);
+ COMPOSITE_NODE = mockClass(ContainerNode.class);
} catch (final Exception e) {
throw new RuntimeException(e);
}
try {
- notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
- } catch (Exception e) {
+ NOTIFICATION = new NetconfMessage(XmlUtil
+ .readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
+ } catch (SAXException | IOException e) {
throw new ExceptionInInitializerError(e);
}
}
- private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
+ private static final DOMRpcResult RPC_RESULT = new DefaultDOMRpcResult(COMPOSITE_NODE);
public static final String TEST_NAMESPACE = "test:namespace";
public static final String TEST_MODULE = "test-module";
public static final String TEST_REVISION = "2013-07-22";
public static final SourceIdentifier TEST_SID =
RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
- public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
+ public static final String TEST_CAPABILITY =
+ TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
public static final SourceIdentifier TEST_SID2 =
RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
- public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
+ public static final String TEST_CAPABILITY2 =
+ TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
- private static final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
+ private static final NetconfDeviceSchemasResolver STATE_SCHEMAS_RESOLVER =
+ (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
@Test
public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
final Module first = Iterables.getFirst(schema.getModules(), null);
final QName qName = QName.create(first.getQNameModule(), first.getName());
final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
- final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
+ final NetconfStateSchemas.RemoteYangSchema source2 =
+ new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
};
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+ .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSalFacade(facade)
.build();
// Monitoring supported
- final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
+ final NetconfSessionPreferences sessionCaps =
+ getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
}
schemaResolutionException))
.when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+ .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
final SchemaRepository schemaRepository = getSchemaRepository();
// Make fallback attempt to fail due to empty resolved sources
- final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
- doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
+ final MissingSchemaSourceException schemaResolutionException =
+ new MissingSchemaSourceException("fail first", TEST_SID);
+ doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException))
+ .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
doAnswer(invocation -> {
if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
return Futures.immediateFailedCheckedFuture(schemaResolutionException);
final Module first = Iterables.getFirst(schema.getModules(), null);
final QName qName = QName.create(first.getQNameModule(), first.getName());
final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
- final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
+ final NetconfStateSchemas.RemoteYangSchema source2 =
+ new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
};
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+ .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSalFacade(facade)
.build();
// Monitoring supported
- final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
+ final NetconfSessionPreferences sessionCaps =
+ getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
device.onRemoteSessionUp(sessionCaps, listener);
- Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
}
final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
doNothing().when(mockReg).close();
- doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
+ doReturn(mockReg).when(mock).registerSchemaSource(
+ any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class),
+ any(PotentialSchemaSource.class));
return mock;
}
private static SchemaRepository getSchemaRepository() {
final SchemaRepository mock = mock(SchemaRepository.class);
final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
- doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
+ doReturn(Futures.immediateCheckedFuture(mockRep))
+ .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
return mock;
}
public void testNotificationBeforeSchema() throws Exception {
final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
final NetconfDeviceCommunicator listener = getListener();
-
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
+ final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class);
+ final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
+ doReturn(Futures.makeChecked(schemaFuture, e -> new SchemaResolutionException("fail")))
+ .when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
+ new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
+ schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
.setSalFacade(facade)
.build();
- device.onNotification(notification);
- device.onNotification(notification);
-
- verify(facade, times(0)).onNotification(any(DOMNotification.class));
-
final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
Lists.newArrayList(TEST_CAPABILITY));
+ device.onRemoteSessionUp(sessionCaps, listener);
- final DOMRpcService deviceRpc = mock(DOMRpcService.class);
-
- device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
+ device.onNotification(NOTIFICATION);
+ device.onNotification(NOTIFICATION);
+ verify(facade, times(0)).onNotification(any(DOMNotification.class));
+ verify(facade, times(0)).onNotification(any(DOMNotification.class));
+ schemaFuture.set(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false));
verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
- device.onNotification(notification);
+ device.onNotification(NOTIFICATION);
verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
}
final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+ getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
device.onRemoteSessionUp(sessionCaps, listener);
verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
- verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ verify(facade, timeout(5000)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
device.onRemoteSessionDown();
verify(facade, timeout(5000)).onDeviceDisconnected();
device.onRemoteSessionUp(sessionCaps, listener);
verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
- verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ verify(facade, timeout(5000).times(2)).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ }
+
+ @Test
+ public void testNetconfDeviceDisconnectListenerCallCancellation() throws Exception {
+ final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
+ final NetconfDeviceCommunicator listener = getListener();
+ final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class);
+ final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
+ doReturn(Futures.makeChecked(schemaFuture, e -> new SchemaResolutionException("fail")))
+ .when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
+ = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
+ schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
+ final NetconfDevice device = new NetconfDeviceBuilder()
+ .setReconnectOnSchemasChange(true)
+ .setSchemaResourcesDTO(schemaResourcesDTO)
+ .setGlobalProcessingExecutor(getExecutor())
+ .setId(getId())
+ .setSalFacade(facade)
+ .build();
+ final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
+ Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
+ //session up, start schema resolution
+ device.onRemoteSessionUp(sessionCaps, listener);
+ //session closed
+ device.onRemoteSessionDown();
+ verify(facade, timeout(5000)).onDeviceDisconnected();
+ //complete schema setup
+ schemaFuture.set(getSchema());
+ //facade.onDeviceDisconnected() was called, so facade.onDeviceConnected() shouldn't be called anymore
+ verify(facade, after(1000).never()).onDeviceConnected(any(), any(), any());
}
@Test
final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
+ final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+ getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
final NetconfDevice device = new NetconfDeviceBuilder()
.setReconnectOnSchemasChange(true)
.setSchemaResourcesDTO(schemaResourcesDTO)
.setId(getId())
.setSalFacade(facade)
.build();
- NetconfDevice netconfSpy = Mockito.spy(device);
+ final NetconfDevice netconfSpy = Mockito.spy(device);
final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION));
- Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
+ final Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
- moduleBasedCaps.put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
+ moduleBasedCaps
+ .put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
- ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
- verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
- NetconfDeviceCapabilities netconfDeviceCaps = ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
+ final ArgumentCaptor<NetconfSessionPreferences> argument =
+ ArgumentCaptor.forClass(NetconfSessionPreferences.class);
+ verify(facade, timeout(5000))
+ .onDeviceConnected(any(SchemaContext.class), argument.capture(), any(DOMRpcService.class));
+ final NetconfDeviceCapabilities netconfDeviceCaps = argument.getValue().getNetconfDeviceCapabilities();
- netconfDeviceCaps.getResolvedCapabilities().forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
- moduleBasedCaps.get(QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
+ netconfDeviceCaps.getResolvedCapabilities()
+ .forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
+ moduleBasedCaps.get(
+ QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
}
private static SchemaContextFactory getSchemaFactory() throws Exception {
final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
- doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
+ doReturn(Futures.immediateCheckedFuture(getSchema()))
+ .when(schemaFactory).createSchemaContext(any(Collection.class));
return schemaFactory;
}
}
private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
- final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
- doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
+ mockCloseableClass(RemoteDeviceHandler.class);
+ doNothing().when(remoteDeviceHandler).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
return remoteDeviceHandler;
public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
- doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
- doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
- doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
+ doReturn(NOTIFICATION).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
+ doReturn(RPC_RESULT).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
+ doReturn(COMPOSITE_NODE).when(messageTransformer).toNotification(any(NetconfMessage.class));
return messageTransformer;
}
- public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
+ public NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
+ final Collection<String> additionalCapabilities) {
final ArrayList<String> capabilities = Lists.newArrayList(
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
- if(addMonitor) {
+ if (addMonitor) {
capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
}
public NetconfDeviceCommunicator getListener() throws Exception {
final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
-// doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
+// doReturn(Futures.immediateFuture(rpcResult))
+// .when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
return remoteDeviceCommunicator;
}
}
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class NetconfStateSchemasTest {
- private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04"));
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemasTest.class);
+
+ private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton(
+ "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04"));
private final RemoteDeviceId deviceId = new RemoteDeviceId("device", new InetSocketAddress(99));
+ private final int numberOfSchemas = 73;
+ private final int numberOfLegalSchemas = numberOfSchemas - 3;
private ContainerNode compositeNodeSchemas;
- private final int NUMBER_OF_SCHEMAS = 73;
- private final int NUMBER_OF_LEGAL_SCHEMAS = NUMBER_OF_SCHEMAS - 3;
@Mock
private DOMRpcService rpc;
final DataSchemaNode schemasNode =
((ContainerSchemaNode) schemaContext
.getDataChildByName(NetconfState.QNAME)).getDataChildByName(Schemas.QNAME);
- final Document schemasXml = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
- final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
- compositeNodeSchemas = containerNodeParser.parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
+ final Document schemasXml =
+ XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
+ final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser =
+ DomToNormalizedNodeParserFactory
+ .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
+ compositeNodeSchemas = containerNodeParser
+ .parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
}
final NetconfStateSchemas schemas = NetconfStateSchemas.create(deviceId, compositeNodeSchemas);
final Set<QName> availableYangSchemasQNames = schemas.getAvailableYangSchemasQNames();
- assertEquals(NUMBER_OF_LEGAL_SCHEMAS, availableYangSchemasQNames.size());
+ assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
assertThat(availableYangSchemasQNames,
hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
.withChild(compositeNodeSchemas)
.build();
final ContainerNode data = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
.withChild(netconfState)
.build();
final ContainerNode rpcReply = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier
+ .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
.withChild(data)
.build();
- when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
+ when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
+ .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
- assertEquals(NUMBER_OF_LEGAL_SCHEMAS, availableYangSchemasQNames.size());
+ assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
assertThat(availableYangSchemasQNames,
hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
@Test
public void testCreateRpcError() throws Exception {
final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, "fail", "fail");
- when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
+ when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
+ .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
Assert.assertTrue(availableYangSchemasQNames.isEmpty());
}
+ @SuppressWarnings("checkstyle:IllegalThrows")
@Test(expected = RuntimeException.class)
public void testCreateInterrupted() throws Throwable {
//NetconfStateSchemas.create calls Thread.currentThread().interrupt(), so it must run in its own thread
when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(checkedFuture);
NetconfStateSchemas.create(rpc, CAPS, deviceId);
} catch (final InterruptedException | ExecutionException e) {
- e.printStackTrace();
+ LOG.info("Operation failed.", e);
}
});
@Test
public void testRemoteYangSchemaEquals() throws Exception {
- final NetconfStateSchemas.RemoteYangSchema schema1 = new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
- final NetconfStateSchemas.RemoteYangSchema schema2 = new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
- final NetconfStateSchemas.RemoteYangSchema schema3 = new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
+ final NetconfStateSchemas.RemoteYangSchema schema1 =
+ new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
+ final NetconfStateSchemas.RemoteYangSchema schema2 =
+ new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
+ final NetconfStateSchemas.RemoteYangSchema schema3 =
+ new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
Assert.assertEquals(schema1, schema2);
Assert.assertEquals(schema2, schema1);
Assert.assertNotEquals(schema1, schema3);
userNotification = new NetconfMessage(doc);
}
- static SchemaContext getNotificationSchemaContext(final Class<?> loadClass, final boolean getExceptionTest) throws Exception {
+ static SchemaContext getNotificationSchemaContext(final Class<?> loadClass,
+ final boolean getExceptionTest) throws Exception {
final List<InputStream> modelsToParse = new ArrayList<>();
if (getExceptionTest) {
public class NetconfToRpcRequestTest {
- private final static String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
- private final static String REVISION = "2014-07-14";
- private final static QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
- private final static QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
- private final static QName SUBSCRIBE_RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
-
- private final static String CONFIG_TEST_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:config:defs";
- private final static String CONFIG_TEST_REVISION = "2014-07-21";
- private final static QName EDIT_CONFIG_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "edit-config");
- private final static QName GET_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get");
- private final static QName GET_CONFIG_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get-config");
+ private static final String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
+ private static final String REVISION = "2014-07-14";
+ private static final QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
+ private static final QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
+ private static final QName SUBSCRIBE_RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
+
+ private static final String CONFIG_TEST_NAMESPACE =
+ "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:config:defs";
+ private static final String CONFIG_TEST_REVISION = "2014-07-21";
+ private static final QName EDIT_CONFIG_QNAME =
+ QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "edit-config");
+ private static final QName GET_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get");
+ private static final QName GET_CONFIG_QNAME =
+ QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get-config");
static SchemaContext cfgCtx;
static NetconfMessageTransformer messageTransformer;
@BeforeClass
public static void setup() throws Exception {
- List<InputStream> modelsToParse = Collections
- .singletonList(NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
+ List<InputStream> modelsToParse = Collections.singletonList(
+ NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
final Set<Module> notifModules = YangParserTestUtils.parseYangStreams(modelsToParse).getModules();
assertTrue(!notifModules.isEmpty());
@Test
public void testUserDefinedRpcCall() throws Exception {
- final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> rootBuilder = Builders.containerBuilder();
+ final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> rootBuilder =
+ Builders.containerBuilder();
rootBuilder.withNodeIdentifier(toId(SUBSCRIBE_RPC_NAME));
rootBuilder.withChild(buildLeaf(STREAM_NAME, "NETCONF"));
@Test(expected = IllegalArgumentException.class)
public void testRpcResponse() throws Exception {
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
- "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-5\">\n" +
- "<data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">" +
- "module schema" +
- "</data>\n" +
- "</rpc-reply>\n"
+ "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-5\">\n"
+ + "<data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">"
+ + "module schema"
+ + "</data>\n"
+ + "</rpc-reply>\n"
));
messageTransformer.toRpcResult(response, toPath(EDIT_CONFIG_QNAME));
final NetconfMessage netconfMessage = mock(NetconfMessage.class);
device.onRemoteSessionUp(sessionCaps, listener);
- verify(facade).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ verify(facade).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
device.onNotification(netconfMessage);
verify(facade).onNotification(any(DOMNotification.class));
@SuppressWarnings("unchecked")
private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
- final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
- doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+ final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
+ mockCloseableClass(RemoteDeviceHandler.class);
+ doNothing().when(remoteDeviceHandler).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
return remoteDeviceHandler;
}
- private static <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
+ private static <T extends AutoCloseable> T mockCloseableClass(
+ final Class<T> remoteDeviceHandlerClass) throws Exception {
final T mock = mockClass(remoteDeviceHandlerClass);
doNothing().when(mock).close();
return mock;
return mock;
}
- private static NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
+ private static NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
+ final Collection<String> additionalCapabilities) {
final ArrayList<String> capabilities = Lists.newArrayList(
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
- if(addMonitor) {
+ if (addMonitor) {
capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
}
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class NetconfDeviceCommunicatorTest {
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicatorTest.class);
+
@Mock
NetconfClientSession mockSession;
@Before
public void setUp() throws Exception {
- MockitoAnnotations.initMocks( this );
+ MockitoAnnotations.initMocks(this);
- communicator = new NetconfDeviceCommunicator( new RemoteDeviceId( "test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
+ communicator = new NetconfDeviceCommunicator(
+ new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
}
void setupSession() {
}
private ListenableFuture<RpcResult<NetconfMessage>> sendRequest() throws Exception {
- return sendRequest( UUID.randomUUID().toString(), true );
+ return sendRequest(UUID.randomUUID().toString(), true);
}
@SuppressWarnings("unchecked")
- private ListenableFuture<RpcResult<NetconfMessage>> sendRequest( final String messageID, final boolean doLastTest ) throws Exception {
+ private ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final String messageID,
+ final boolean doLastTest) throws Exception {
Document doc = UntrustedXML.newDocumentBuilder().newDocument();
- Element element = doc.createElement( "request" );
- element.setAttribute( "message-id", messageID );
- doc.appendChild( element );
- NetconfMessage message = new NetconfMessage( doc );
+ Element element = doc.createElement("request");
+ element.setAttribute("message-id", messageID);
+ doc.appendChild(element);
+ NetconfMessage message = new NetconfMessage(doc);
- ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
- doReturn( mockChannelFuture ).when( mockChannelFuture )
- .addListener( any( (GenericFutureListener.class ) ) );
- doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+ ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+ doReturn(mockChannelFuture).when(mockChannelFuture)
+ .addListener(any((GenericFutureListener.class)));
+ doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
ListenableFuture<RpcResult<NetconfMessage>> resultFuture =
- communicator.sendRequest( message, QName.create( "mock rpc" ) );
- if(doLastTest) {
+ communicator.sendRequest(message, QName.create("mock rpc"));
+ if (doLastTest) {
assertNotNull("ListenableFuture is null", resultFuture);
}
return resultFuture;
public void testOnSessionUp() {
String testCapability = "urn:opendaylight:params:xml:ns:test?module=test-module&revision=2014-06-02";
Collection<String> serverCapabilities =
- Sets.newHashSet( NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
- NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
- testCapability );
- doReturn( serverCapabilities ).when( mockSession ).getServerCapabilities();
-
- ArgumentCaptor<NetconfSessionPreferences> NetconfSessionPreferences =
- ArgumentCaptor.forClass( NetconfSessionPreferences.class );
- doNothing().when( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
-
- communicator.onSessionUp( mockSession );
-
- verify( mockSession ).getServerCapabilities();
- verify( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
-
- NetconfSessionPreferences actualCapabilites = NetconfSessionPreferences.getValue();
- assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
- NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
- assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
- assertEquals( "getModuleBasedCaps", Sets.newHashSet(
- QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
- actualCapabilites.getModuleBasedCaps());
- assertEquals( "isRollbackSupported", true, actualCapabilites.isRollbackSupported() );
- assertEquals( "isMonitoringSupported", true, actualCapabilites.isMonitoringSupported() );
+ Sets.newHashSet(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
+ NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
+ testCapability);
+ doReturn(serverCapabilities).when(mockSession).getServerCapabilities();
+
+ ArgumentCaptor<NetconfSessionPreferences> netconfSessionPreferences =
+ ArgumentCaptor.forClass(NetconfSessionPreferences.class);
+ doNothing().when(mockDevice).onRemoteSessionUp(netconfSessionPreferences.capture(), eq(communicator));
+
+ communicator.onSessionUp(mockSession);
+
+ verify(mockSession).getServerCapabilities();
+ verify(mockDevice).onRemoteSessionUp(netconfSessionPreferences.capture(), eq(communicator));
+
+ NetconfSessionPreferences actualCapabilites = netconfSessionPreferences.getValue();
+ assertEquals("containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
+ NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()));
+ assertEquals("containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability));
+ assertEquals("getModuleBasedCaps", Sets.newHashSet(
+ QName.create("urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module")),
+ actualCapabilites.getModuleBasedCaps());
+ assertEquals("isRollbackSupported", true, actualCapabilites.isRollbackSupported());
+ assertEquals("isMonitoringSupported", true, actualCapabilites.isMonitoringSupported());
}
@SuppressWarnings("unchecked")
- @Test(timeout=5000)
+ @Test(timeout = 5000)
public void testOnSessionDown() throws Exception {
setupSession();
ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
+ final ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
- doNothing().when( mockDevice ).onRemoteSessionDown();
+ doNothing().when(mockDevice).onRemoteSessionDown();
- communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
+ communicator.onSessionDown(mockSession, new Exception("mock ex"));
- verifyErrorRpcResult( resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
- verifyErrorRpcResult( resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
+ verifyErrorRpcResult(resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed");
+ verifyErrorRpcResult(resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed");
- verify( mockDevice ).onRemoteSessionDown();
+ verify(mockDevice).onRemoteSessionDown();
- reset( mockDevice );
+ reset(mockDevice);
- communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
+ communicator.onSessionDown(mockSession, new Exception("mock ex"));
- verify( mockDevice, never() ).onRemoteSessionDown();
+ verify(mockDevice, never()).onRemoteSessionDown();
}
@Test
ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest();
- doNothing().when( mockDevice ).onRemoteSessionDown();
+ doNothing().when(mockDevice).onRemoteSessionDown();
String reasonText = "testing terminate";
- NetconfTerminationReason reason = new NetconfTerminationReason( reasonText );
- communicator.onSessionTerminated( mockSession, reason );
+ NetconfTerminationReason reason = new NetconfTerminationReason(reasonText);
+ communicator.onSessionTerminated(mockSession, reason);
- RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.TRANSPORT,
- "operation-failed" );
- assertEquals( "RpcError message", reasonText, rpcError.getMessage() );
+ RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.TRANSPORT,
+ "operation-failed");
+ assertEquals("RpcError message", reasonText, rpcError.getMessage());
- verify( mockDevice ).onRemoteSessionDown();
+ verify(mockDevice).onRemoteSessionDown();
}
@Test
public void testClose() throws Exception {
communicator.close();
- verify( mockDevice, never() ).onRemoteSessionDown();
+ verify(mockDevice, never()).onRemoteSessionDown();
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ @SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testSendRequest() throws Exception {
setupSession();
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create( "mock rpc" );
+ QName rpc = QName.create("mock rpc");
ArgumentCaptor<GenericFutureListener> futureListener =
- ArgumentCaptor.forClass( GenericFutureListener.class );
+ ArgumentCaptor.forClass(GenericFutureListener.class);
- ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
- doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
- doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+ ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+ doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
+ doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
- verify( mockSession ).sendMessage( same( message ) );
+ verify(mockSession).sendMessage(same(message));
- assertNotNull( "ListenableFuture is null", resultFuture );
+ assertNotNull("ListenableFuture is null", resultFuture);
- verify( mockChannelFuture ).addListener( futureListener.capture() );
- Future<Void> operationFuture = mock( Future.class );
- doReturn( true ).when( operationFuture ).isSuccess();
- doReturn( true ).when( operationFuture ).isDone();
- futureListener.getValue().operationComplete( operationFuture );
+ verify(mockChannelFuture).addListener(futureListener.capture());
+ Future<Void> operationFuture = mock(Future.class);
+ doReturn(true).when(operationFuture).isSuccess();
+ doReturn(true).when(operationFuture).isDone();
+ futureListener.getValue().operationComplete(operationFuture);
try {
- resultFuture.get( 1, TimeUnit.MILLISECONDS ); // verify it's not cancelled or has an error set
- }
- catch( TimeoutException e ) {} // expected
+ resultFuture.get(1, TimeUnit.MILLISECONDS); // verify it's not cancelled or has an error set
+ } catch (TimeoutException e) {
+ LOG.info("Operation failed due timeout.");
+ } // expected
}
@Test
public void testSendRequestWithNoSession() throws Exception {
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create( "mock rpc" );
+ QName rpc = QName.create("mock rpc");
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
- assertNotNull( "ListenableFuture is null", resultFuture );
+ assertNotNull("ListenableFuture is null", resultFuture);
// Should have an immediate result
- RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
+ RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
+
+ verifyErrorRpcResult(rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed");
+ }
- verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
+ private static NetconfMessage createSuccessResponseMessage(final String messageID)
+ throws ParserConfigurationException {
+ Document doc = UntrustedXML.newDocumentBuilder().newDocument();
+ Element rpcReply =
+ doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
+ rpcReply.setAttribute("message-id", messageID);
+ Element element = doc.createElementNS("ns", "data");
+ element.setTextContent(messageID);
+ rpcReply.appendChild(element);
+ doc.appendChild(rpcReply);
+
+ return new NetconfMessage(doc);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
setupSession();
NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
- QName rpc = QName.create( "mock rpc" );
+ QName rpc = QName.create("mock rpc");
ArgumentCaptor<GenericFutureListener> futureListener =
- ArgumentCaptor.forClass( GenericFutureListener.class );
+ ArgumentCaptor.forClass(GenericFutureListener.class);
- ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
- doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
- doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+ ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+ doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
+ doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
- assertNotNull( "ListenableFuture is null", resultFuture );
+ assertNotNull("ListenableFuture is null", resultFuture);
- verify( mockChannelFuture ).addListener( futureListener.capture() );
+ verify(mockChannelFuture).addListener(futureListener.capture());
- Future<Void> operationFuture = mock( Future.class );
- doReturn( false ).when( operationFuture ).isSuccess();
- doReturn( true ).when( operationFuture ).isDone();
- doReturn( new Exception( "mock error" ) ).when( operationFuture ).cause();
- futureListener.getValue().operationComplete( operationFuture );
+ Future<Void> operationFuture = mock(Future.class);
+ doReturn(false).when(operationFuture).isSuccess();
+ doReturn(true).when(operationFuture).isDone();
+ doReturn(new Exception("mock error")).when(operationFuture).cause();
+ futureListener.getValue().operationComplete(operationFuture);
// Should have an immediate result
- RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
-
- RpcError rpcError = verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
- assertEquals( "RpcError message contains \"mock error\"", true,
- rpcError.getMessage().contains( "mock error" ) );
- }
+ RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
- private static NetconfMessage createSuccessResponseMessage( final String messageID ) throws ParserConfigurationException {
- Document doc = UntrustedXML.newDocumentBuilder().newDocument();
- Element rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
- rpcReply.setAttribute( "message-id", messageID );
- Element element = doc.createElementNS( "ns", "data" );
- element.setTextContent( messageID );
- rpcReply.appendChild( element );
- doc.appendChild( rpcReply );
-
- return new NetconfMessage( doc );
+ RpcError rpcError = verifyErrorRpcResult(rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed");
+ assertEquals("RpcError message contains \"mock error\"", true,
+ rpcError.getMessage().contains("mock error"));
}
//Test scenario verifying whether missing message is handled
setupSession();
String messageID1 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest(messageID1, true);
String messageID2 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest(messageID2, true);
String messageID3 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest( messageID3, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest(messageID3, true);
//response messages 1,2 are omitted
- communicator.onMessage( mockSession, createSuccessResponseMessage( messageID3 ) );
+ communicator.onMessage(mockSession, createSuccessResponseMessage(messageID3));
- verifyResponseMessage( resultFuture3.get(), messageID3 );
+ verifyResponseMessage(resultFuture3.get(), messageID3);
}
@Test
setupSession();
String messageID1 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest(messageID1, true);
String messageID2 = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
+ final ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest(messageID2, true);
- communicator.onMessage( mockSession, createSuccessResponseMessage( messageID1 ) );
- communicator.onMessage( mockSession, createSuccessResponseMessage( messageID2 ) );
+ communicator.onMessage(mockSession, createSuccessResponseMessage(messageID1));
+ communicator.onMessage(mockSession, createSuccessResponseMessage(messageID2));
- verifyResponseMessage( resultFuture1.get(), messageID1 );
- verifyResponseMessage( resultFuture2.get(), messageID2 );
+ verifyResponseMessage(resultFuture1.get(), messageID1);
+ verifyResponseMessage(resultFuture2.get(), messageID2);
}
@Test
setupSession();
String messageID = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID, true);
- communicator.onMessage( mockSession, createErrorResponseMessage( messageID ) );
+ communicator.onMessage(mockSession, createErrorResponseMessage(messageID));
- RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.RPC,
- "missing-attribute" );
- assertEquals( "RpcError message", "Missing attribute", rpcError.getMessage() );
+ RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.RPC,
+ "missing-attribute");
+ assertEquals("RpcError message", "Missing attribute", rpcError.getMessage());
String errorInfo = rpcError.getInfo();
- assertNotNull( "RpcError info is null", errorInfo );
- assertEquals( "Error info contains \"foo\"", true,
- errorInfo.contains( "<bad-attribute>foo</bad-attribute>" ) );
- assertEquals( "Error info contains \"bar\"", true,
- errorInfo.contains( "<bad-element>bar</bad-element>" ) );
+ assertNotNull("RpcError info is null", errorInfo);
+ assertEquals("Error info contains \"foo\"", true,
+ errorInfo.contains("<bad-attribute>foo</bad-attribute>"));
+ assertEquals("Error info contains \"bar\"", true,
+ errorInfo.contains("<bad-element>bar</bad-element>"));
}
/**
- * Test whether reconnect is scheduled properly
+ * Test whether reconnect is scheduled properly.
*/
@Test
public void testNetconfDeviceReconnectInCommunicator() throws Exception {
- final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(RemoteDevice.class);
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device =
+ mock(RemoteDevice.class);
- final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
+ final TimedReconnectStrategy timedReconnectStrategy =
+ new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
@Override
public int getConnectTimeout() throws Exception {
final EventLoopGroup group = new NioEventLoopGroup();
final Timer time = new HashedWheelTimer();
try {
- final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
+ final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(
+ new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
.withAddress(new InetSocketAddress("localhost", 65000))
.withReconnectStrategy(reconnectStrategy)
listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);
- verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
+ verify(reconnectStrategy,
+ timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
} finally {
time.stop();
group.shutdownGracefully();
setupSession();
String messageID = UUID.randomUUID().toString();
- ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
+ ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID, true);
- communicator.onMessage( mockSession, createSuccessResponseMessage( UUID.randomUUID().toString() ) );
+ communicator.onMessage(mockSession, createSuccessResponseMessage(UUID.randomUUID().toString()));
- RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.PROTOCOL,
- "bad-attribute" );
- assertEquals( "RpcError message non-empty", true,
- !Strings.isNullOrEmpty( rpcError.getMessage() ) );
+ RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.PROTOCOL,
+ "bad-attribute");
+ assertEquals("RpcError message non-empty", true,
+ !Strings.isNullOrEmpty(rpcError.getMessage()));
String errorInfo = rpcError.getInfo();
- assertNotNull( "RpcError info is null", errorInfo );
- assertEquals( "Error info contains \"actual-message-id\"", true,
- errorInfo.contains( "actual-message-id" ) );
- assertEquals( "Error info contains \"expected-message-id\"", true,
- errorInfo.contains( "expected-message-id" ) );
+ assertNotNull("RpcError info is null", errorInfo);
+ assertEquals("Error info contains \"actual-message-id\"", true,
+ errorInfo.contains("actual-message-id"));
+ assertEquals("Error info contains \"expected-message-id\"", true,
+ errorInfo.contains("expected-message-id"));
}
@Test
assertNotNull("ListenableFuture is null", resultFuture);
}
- private static NetconfMessage createErrorResponseMessage( final String messageID ) throws Exception {
- String xmlStr =
- "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" +
- " message-id=\"" + messageID + "\">" +
- " <rpc-error>" +
- " <error-type>rpc</error-type>" +
- " <error-tag>missing-attribute</error-tag>" +
- " <error-severity>error</error-severity>" +
- " <error-message>Missing attribute</error-message>" +
- " <error-info>" +
- " <bad-attribute>foo</bad-attribute>" +
- " <bad-element>bar</bad-element>" +
- " </error-info>" +
- " </rpc-error>" +
- "</rpc-reply>";
-
- ByteArrayInputStream bis = new ByteArrayInputStream( xmlStr.getBytes() );
+ private static NetconfMessage createErrorResponseMessage(final String messageID) throws Exception {
+ String xmlStr = "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""
+ + " message-id=\"" + messageID + "\">"
+ + " <rpc-error>"
+ + " <error-type>rpc</error-type>"
+ + " <error-tag>missing-attribute</error-tag>"
+ + " <error-severity>error</error-severity>"
+ + " <error-message>Missing attribute</error-message>"
+ + " <error-info>"
+ + " <bad-attribute>foo</bad-attribute>"
+ + " <bad-element>bar</bad-element>"
+ + " </error-info>"
+ + " </rpc-error>"
+ + "</rpc-reply>";
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(xmlStr.getBytes());
Document doc = UntrustedXML.newDocumentBuilder().parse(bis);
- return new NetconfMessage( doc );
+ return new NetconfMessage(doc);
}
- private static void verifyResponseMessage( final RpcResult<NetconfMessage> rpcResult, final String dataText ) {
- assertNotNull( "RpcResult is null", rpcResult );
- assertEquals( "isSuccessful", true, rpcResult.isSuccessful() );
+ private static void verifyResponseMessage(final RpcResult<NetconfMessage> rpcResult, final String dataText) {
+ assertNotNull("RpcResult is null", rpcResult);
+ assertEquals("isSuccessful", true, rpcResult.isSuccessful());
NetconfMessage messageResult = rpcResult.getResult();
- assertNotNull( "getResult", messageResult );
+ assertNotNull("getResult", messageResult);
// List<SimpleNode<?>> nodes = messageResult.getSimpleNodesByName(
// QName.create( URI.create( "ns" ), null, "data" ) );
// assertNotNull( "getSimpleNodesByName", nodes );
// assertEquals( "SimpleNode value", dataText, nodes.iterator().next().getValue() );
}
- private static RpcError verifyErrorRpcResult( final RpcResult<NetconfMessage> rpcResult,
- final RpcError.ErrorType expErrorType, final String expErrorTag ) {
- assertNotNull( "RpcResult is null", rpcResult );
- assertEquals( "isSuccessful", false, rpcResult.isSuccessful() );
- assertNotNull( "RpcResult errors is null", rpcResult.getErrors() );
- assertEquals( "Errors size", 1, rpcResult.getErrors().size() );
+ private static RpcError verifyErrorRpcResult(final RpcResult<NetconfMessage> rpcResult,
+ final RpcError.ErrorType expErrorType, final String expErrorTag) {
+ assertNotNull("RpcResult is null", rpcResult);
+ assertEquals("isSuccessful", false, rpcResult.isSuccessful());
+ assertNotNull("RpcResult errors is null", rpcResult.getErrors());
+ assertEquals("Errors size", 1, rpcResult.getErrors().size());
RpcError rpcError = rpcResult.getErrors().iterator().next();
- assertEquals( "getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity() );
- assertEquals( "getErrorType", expErrorType, rpcError.getErrorType() );
- assertEquals( "getErrorTag", expErrorTag, rpcError.getTag() );
+ assertEquals("getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity());
+ assertEquals("getErrorType", expErrorType, rpcError.getErrorType());
+ assertEquals("getErrorTag", expErrorTag, rpcError.getTag());
final String msg = rpcError.getMessage();
assertNotNull("getMessage is null", msg);
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0"
);
final NetconfSessionPreferences merged = sessionCaps1.addModuleCaps(sessionCaps2);
assertCaps(merged, 2, 2 + 1 /*Preserved monitoring*/ + 2 /*already present*/);
- for (final QName qName : sessionCaps2.getModuleBasedCaps()) {
- assertThat(merged.getModuleBasedCaps(), hasItem(qName));
+ for (final QName qualifiedName : sessionCaps2.getModuleBasedCaps()) {
+ assertThat(merged.getModuleBasedCaps(), hasItem(qualifiedName));
}
assertThat(merged.getModuleBasedCaps(), hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0"
);
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0"
final NetconfSessionPreferences merged = sessionCaps1.addNonModuleCaps(sessionCaps2);
- assertCaps(merged, 3+2, 3);
+ assertCaps(merged, 3 + 2, 3);
for (final String capability : sessionCaps2.getNonModuleCaps()) {
assertThat(merged.getNonModuleCaps(), hasItem(capability));
}
final List<String> caps1 = Lists.newArrayList(
"namespace:1?module=module1&revision=2012-12-12",
"namespace:2?module=module2&revision=2012-12-12",
- "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
+ "urn:ietf:params:xml:ns:yang:"
+ + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04",
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:rollback-on-error:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0"
public class KeepaliveSalFacadeTest {
- private static final RemoteDeviceId REMOTE_DEVICE_ID = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
+ private static final RemoteDeviceId REMOTE_DEVICE_ID =
+ new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
@Mock
private RemoteDeviceHandler<NetconfSessionPreferences> underlyingSalFacade;
invocationOnMock.callRealMethod();
return currentKeepalive;
}
- }).when(executorServiceSpy).schedule(Mockito.<Runnable> any(),
- Mockito.anyLong(), Matchers.<TimeUnit> any());
+ }).when(executorServiceSpy).schedule(Mockito.<Runnable>any(),
+ Mockito.anyLong(), Matchers.<TimeUnit>any());
Mockito.when(currentKeepalive.isDone()).thenReturn(true);
}
final DOMRpcResult result = new DefaultDOMRpcResult(Builders.containerBuilder().withNodeIdentifier(
new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME)).build());
- doReturn(Futures.immediateCheckedFuture(result)).when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
+ doReturn(Futures.immediateCheckedFuture(result))
+ .when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
final KeepaliveSalFacade keepaliveSalFacade =
new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 1L, 1L);
proxyRpc = (DOMRpcService) invocationOnMock.getArguments()[2];
return null;
}
- }).when(underlyingSalFacade).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+ }).when(underlyingSalFacade).onDeviceConnected(
+ any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state")))
.when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class MountInstanceTest {
+ private static final Logger LOG = LoggerFactory.getLogger(MountInstanceTest.class);
+
private static SchemaContext SCHEMA_CONTEXT;
@Mock
private NetconfDeviceSalProvider.MountInstance mountInstance;
@BeforeClass
- public static void suiteSetUp() throws Exception{
+ public static void suiteSetUp() throws Exception {
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- moduleInfoBackedContext.addModuleInfos(
- Lists.newArrayList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
+ moduleInfoBackedContext.addModuleInfos(Lists.newArrayList(org.opendaylight.yang.gen
+ .v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
SCHEMA_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
}
when(service.createMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountPointBuilder);
when(mountPointBuilder.register()).thenReturn(registration);
- mountInstance = new NetconfDeviceSalProvider.MountInstance(service, new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830)));
+ mountInstance = new NetconfDeviceSalProvider.MountInstance(
+ service, new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830)));
}
try {
mountInstance.onTopologyDeviceConnected(SCHEMA_CONTEXT, broker, rpcService, notificationService);
} catch (final IllegalStateException e) {
- e.printStackTrace();
+ LOG.warn("Operation failed.", e);
Assert.fail("Topology registration still present after disconnect ");
}
}
MockitoAnnotations.initMocks(this);
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
moduleInfoBackedContext.addModuleInfos(
- Lists.newArrayList(
- $YangModuleInfoImpl.getInstance(),
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
+ Lists.newArrayList($YangModuleInfoImpl.getInstance(),
+ org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
+ .netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get();
DOMRpcResult result = new DefaultDOMRpcResult();
- when(rpcService.invokeRpc(any(SchemaPath.class), any(NormalizedNode.class))).thenReturn(Futures.immediateCheckedFuture(result));
+ when(rpcService.invokeRpc(any(SchemaPath.class), any(NormalizedNode.class)))
+ .thenReturn(Futures.immediateCheckedFuture(result));
dataBroker = getDataBroker(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
@Test
public void testWritableRunningCandidateWriteTransaction() throws Exception {
- testWriteTransaction(WriteCandidateRunningTx.class, NetconfMessageTransformUtil.NETCONF_RUNNING_WRITABLE_URI.toString(),
+ testWriteTransaction(
+ WriteCandidateRunningTx.class, NetconfMessageTransformUtil.NETCONF_RUNNING_WRITABLE_URI.toString(),
NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
private NetconfDeviceDataBroker getDataBroker(String... caps) {
NetconfSessionPreferences prefs = NetconfSessionPreferences.fromStrings(Arrays.asList(caps));
- final RemoteDeviceId id = new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
+ final RemoteDeviceId id =
+ new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
return new NetconfDeviceDataBroker(id, schemaContext, rpcService, prefs);
}
schema = getSchema();
NetconfMessageTransformer transformer = new NetconfMessageTransformer(schema, true);
final NetconfMessage reply = new NetconfMessage(XmlUtil.readXmlToDocument(
- "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
- "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n" +
- "<data>\n" +
- "</data>\n" +
- "</rpc-reply>"));
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
+ + "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n"
+ + "<data>\n"
+ + "</data>\n"
+ + "</rpc-reply>"));
RpcResult<NetconfMessage> result = RpcResultBuilder.success(reply).build();
- doReturn(Futures.immediateFuture(result)).when(communicator).sendRequest(any(NetconfMessage.class), any(QName.class));
+ doReturn(Futures.immediateFuture(result))
+ .when(communicator).sendRequest(any(NetconfMessage.class), any(QName.class));
rpc = new NetconfDeviceRpc(schema, communicator, transformer);
- path = SchemaPath.create(true, QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config"));
+ path = SchemaPath
+ .create(true, QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config"));
expectedReply = transformer.toRpcResult(reply, path);
}
}
private static ContainerNode createNode(String namespace, String date, String localName) {
- return Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, date, localName))).build();
+ return Builders.containerBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, date, localName))).build();
}
private static SchemaContext getSchema() {
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class, NetconfSessionPreferences.class})
+@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class,
+ NetconfSessionPreferences.class})
public class NetconfDeviceSalFacadeTest {
private NetconfDeviceSalFacade deviceFacade;
private NetconfDeviceSalProvider salProvider;
@Before
- public void setUp() throws Exception{
+ public void setUp() throws Exception {
initMocks(this);
final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("test", address);
mountInstance = PowerMockito.mock(NetconfDeviceSalProvider.MountInstance.class);
doReturn(netconfDeviceTopologyAdapter).when(salProvider).getTopologyDatastoreAdapter();
- doNothing().when(netconfDeviceTopologyAdapter).updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
+ doNothing().when(netconfDeviceTopologyAdapter)
+ .updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
doReturn(mountInstance).when(salProvider).getMountInstance();
doNothing().when(mountInstance).onTopologyDeviceDisconnected();
public void testOnDeviceConnected() {
final SchemaContext schemaContext = mock(SchemaContext.class);
- final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(getCapabilities());
+ final NetconfSessionPreferences netconfSessionPreferences =
+ NetconfSessionPreferences.fromStrings(getCapabilities());
final DOMRpcService deviceRpc = mock(DOMRpcService.class);
deviceFacade.onDeviceConnected(schemaContext, netconfSessionPreferences, deviceRpc);
- verify(mountInstance, times(1)).onTopologyDeviceConnected(eq(schemaContext), any(DOMDataBroker.class), eq(deviceRpc), any(NetconfDeviceNotificationService.class));
- verify(netconfDeviceTopologyAdapter, times(1)).updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
+ verify(mountInstance, times(1)).onTopologyDeviceConnected(eq(schemaContext),
+ any(DOMDataBroker.class), eq(deviceRpc), any(NetconfDeviceNotificationService.class));
+ verify(netconfDeviceTopologyAdapter,
+ times(1)).updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
}
@Test
verify(mountInstance).publish(domNotification);
}
- private static List<String> getCapabilities() {
+ private static List<String> getCapabilities() {
return Arrays.asList(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
}
}
private DataBroker dataBroker;
- private ConcurrentDOMDataBroker cDOMDataBroker;
+ private ConcurrentDOMDataBroker concurrentDOMDataBroker;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doReturn(txChain).when(broker).createTransactionChain(any(TransactionChainListener.class));
doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
- doNothing().when(writeTx).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
- doNothing().when(writeTx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ doNothing().when(writeTx)
+ .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ doNothing().when(writeTx)
+ .merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
doReturn(txIdent).when(writeTx).getIdentifier();
ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
16, 16, "CommitFutures");
- cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
+ concurrentDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
final ClassPool pool = ClassPool.getDefault();
final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
+ codecRegistry.onBindingRuntimeContextUpdated(
+ BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
- final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
+ final BindingToNormalizedNodeCodec bindingToNormalized =
+ new BindingToNormalizedNodeCodec(loading, codecRegistry);
bindingToNormalized.onGlobalContextUpdated(schemaContext);
- dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
+ dataBroker = new BindingDOMDataBrokerAdapter(concurrentDOMDataBroker, bindingToNormalized);
transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() {
@Override
- public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction, Throwable cause) {
+ public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction,
+ Throwable cause) {
}
adapter.setDeviceAsFailed(null);
verify(txChain, times(2)).newWriteOnlyTransaction();
- verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ verify(writeTx, times(1))
+ .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
adapter.close();
adapter = new NetconfDeviceTopologyAdapter(id, transactionChain); //not a mock
adapter.setDeviceAsFailed(null);
- Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
+ Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL,
+ id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
assertEquals("Netconf node should be presented.", true, netconfNode.isPresent());
- assertEquals("Connection status should be failed.", NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(), netconfNode.get().getConnectionStatus().getName());
+ assertEquals("Connection status should be failed.",
+ NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(),
+ netconfNode.get().getConnectionStatus().getName());
}
adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
verify(txChain, times(2)).newWriteOnlyTransaction();
- verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+ verify(writeTx, times(1))
+ .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class));
}
NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, transactionChain);
- QName nTestLeafQname = QName.create("urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
+ QName netconfTestLeafQname = QName.create(
+ "urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
- YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME).
- node(Topology.QNAME).nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf").
- node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test").node(nTestLeafQname).build();
+ YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME)
+ .node(Topology.QNAME)
+ .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf")
+ .node(Node.QNAME)
+ .nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test")
+ .node(netconfTestLeafQname).build();
- NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId).withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(nTestLeafQname)).build();
+ NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId)
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(netconfTestLeafQname)).build();
- DOMDataWriteTransaction writeTx = cDOMDataBroker.newWriteOnlyTransaction();
+ DOMDataWriteTransaction writeTx = concurrentDOMDataBroker.newWriteOnlyTransaction();
writeTx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode);
writeTx.submit();
adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
- Optional<NormalizedNode<?, ?>> testNode = cDOMDataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
+ Optional<NormalizedNode<?, ?>> testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
+ .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
assertEquals("Augmented node data should be still present after device update.", true, testNode.isPresent());
assertEquals("Augmented data should be the same as before update node.", dataTestId, testNode.get().getValue());
adapter.setDeviceAsFailed(null);
- testNode = cDOMDataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
+ testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
+ .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
assertEquals("Augmented node data should be still present after device failed.", true, testNode.isPresent());
- assertEquals("Augmented data should be the same as before failed device.", dataTestId, testNode.get().getValue());
+ assertEquals("Augmented data should be the same as before failed device.",
+ dataTestId, testNode.get().getValue());
}
private List<InputStream> getYangSchemas() {
final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
- "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang",
- "/schemas/network-topology-augment-test@2016-08-08.yang");
+ "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
+ "/schemas/netconf-node-topology.yang", "/schemas/network-topology-augment-test@2016-08-08.yang");
final List<InputStream> schemas = new ArrayList<>();
for (String schemaPath : schemaPaths) {
}
@Override
- public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
+ public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+ final SchemaContextListener listener) {
listener.onGlobalContextUpdated(getGlobalContext());
return new ListenerRegistration<SchemaContextListener>() {
@Override
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SchemalessNetconfDeviceRpcTest {
+ private static final Logger LOG = LoggerFactory.getLogger(SchemalessNetconfDeviceRpcTest.class);
+
@Mock
private RemoteDeviceCommunicator<NetconfMessage> listener;
public void testInvokeRpc() throws Exception {
final QName qName = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config");
SchemaPath type = SchemaPath.create(true, qName);
- DOMSource src = new DOMSource(XmlUtil.readXmlToDocument("<get-config xmlns=\"dd\">\n" +
- " <source>\n" +
- " <running/>\n" +
- " </source>\n" +
- " <filter type=\"subtree\">\n" +
- " <mainroot xmlns=\"urn:dummy:mod-0\">\n" +
- " <maincontent/>\n" +
- "<choiceList></choiceList>\n" +
- " </mainroot>\n" +
- " </filter>\n" +
- " </get-config>"));
+ DOMSource src = new DOMSource(XmlUtil.readXmlToDocument("<get-config xmlns=\"dd\">\n"
+ + " <source>\n"
+ + " <running/>\n"
+ + " </source>\n"
+ + " <filter type=\"subtree\">\n"
+ + " <mainroot xmlns=\"urn:dummy:mod-0\">\n"
+ + " <maincontent/>\n"
+ + "<choiceList></choiceList>\n"
+ + " </mainroot>\n"
+ + " </filter>\n"
+ + " </get-config>"));
NormalizedNode<?, ?> input = Builders.anyXmlBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(qName))
.withValue(src)
deviceRpc.invokeRpc(type, input);
ArgumentCaptor<NetconfMessage> msgCaptor = ArgumentCaptor.forClass(NetconfMessage.class);
- ArgumentCaptor<QName> qNameCaptor = ArgumentCaptor.forClass(QName.class);
- verify(listener).sendRequest(msgCaptor.capture(), qNameCaptor.capture());
- System.out.println(XmlUtil.toString(msgCaptor.getValue().getDocument()));
+ ArgumentCaptor<QName> qnameCaptor = ArgumentCaptor.forClass(QName.class);
+ verify(listener).sendRequest(msgCaptor.capture(), qnameCaptor.capture());
+ LOG.info(XmlUtil.toString(msgCaptor.getValue().getDocument()));
}
}
final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, mock(SchemaContext.class)),
false);
final MapNode emptyList = ImmutableNodes.mapNodeBuilder(NETCONF_FILTER_QNAME).build();
- tx.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
- tx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
+ tx.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier
+ .create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
+ tx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier
+ .create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
verify(rpc, atMost(1)).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
}
} catch (final TransactionCommitFailedException e) {
// verify discard changes was sent
final InOrder inOrder = inOrder(rpc);
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), NetconfBaseOps.getLockContent(NETCONF_CANDIDATE_QNAME));
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
- inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)), any(NormalizedNode.class));
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME), NetconfBaseOps.getUnLockContent(NETCONF_CANDIDATE_QNAME));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME),
+ NetconfBaseOps.getLockContent(NETCONF_CANDIDATE_QNAME));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+ NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)),
+ any(NormalizedNode.class));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME),
+ NetconfBaseOps.getUnLockContent(NETCONF_CANDIDATE_QNAME));
return;
}
@Test
public void testFailedCommit() throws Exception {
- final CheckedFuture<DefaultDOMRpcResult, Exception> rpcErrorFuture =
- Futures.immediateCheckedFuture(new DefaultDOMRpcResult(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "a", "m")));
+ final CheckedFuture<DefaultDOMRpcResult, Exception> rpcErrorFuture = Futures.immediateCheckedFuture(
+ new DefaultDOMRpcResult(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "a", "m")));
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(((NormalizedNode<?, ?>) null))))
.doReturn(rpcErrorFuture).when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
.doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("Failed tx")))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteRunningTx tx = new WriteRunningTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()),
- false);
+ final WriteRunningTx tx = new WriteRunningTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()), false);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
tx.submit();
// verify discard changes was sent
final InOrder inOrder = inOrder(rpc);
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), NetconfBaseOps.getLockContent(NETCONF_RUNNING_QNAME));
- inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any(NormalizedNode.class));
- inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME), NetconfBaseOps.getUnLockContent(NETCONF_RUNNING_QNAME));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME),
+ NetconfBaseOps.getLockContent(NETCONF_RUNNING_QNAME));
+ inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)),
+ any(NormalizedNode.class));
+ inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME),
+ NetconfBaseOps.getUnLockContent(NETCONF_RUNNING_QNAME));
}
@Test
public void testListenerSuccess() throws Exception {
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult((NormalizedNode<?, ?>) null)))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+ final WriteCandidateTx tx = new WriteCandidateTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
final TxListener listener = mock(TxListener.class);
tx.addListener(listener);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
public void testListenerCancellation() throws Exception {
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult((NormalizedNode<?, ?>) null)))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+ final WriteCandidateTx tx = new WriteCandidateTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
final TxListener listener = mock(TxListener.class);
tx.addListener(listener);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
final IllegalStateException cause = new IllegalStateException("Failed tx");
doReturn(Futures.immediateFailedCheckedFuture(cause))
.when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+ final WriteCandidateTx tx = new WriteCandidateTx(
+ id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
final TxListener listener = mock(TxListener.class);
tx.addListener(listener);
tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
public class ReadOnlyTxTest {
- private static final YangInstanceIdentifier path = YangInstanceIdentifier.create();
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.create();
@Mock
private DOMRpcService rpc;
public void testRead() throws Exception {
final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
- final ReadOnlyTx readOnlyTx = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx readOnlyTx =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
readOnlyTx.read(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create());
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
- readOnlyTx.read(LogicalDatastoreType.OPERATIONAL, path);
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
+ readOnlyTx.read(LogicalDatastoreType.OPERATIONAL, PATH);
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
}
@Test
public void testExists() throws Exception {
final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
- final ReadOnlyTx readOnlyTx = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx readOnlyTx =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
readOnlyTx.exists(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create());
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
- readOnlyTx.exists(LogicalDatastoreType.OPERATIONAL, path);
- verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
+ readOnlyTx.exists(LogicalDatastoreType.OPERATIONAL, PATH);
+ verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+ NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
}
@Test
public void testIdentifier() throws Exception {
final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
- final ReadOnlyTx tx1 = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
- final ReadOnlyTx tx2 = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx tx1 =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+ final ReadOnlyTx tx2 =
+ new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
Assert.assertNotEquals(tx1.getIdentifier(), tx2.getIdentifier());
}
}
\ No newline at end of file
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(broker.newReadOnlyTransaction()).thenReturn(readOnlyTx);
- when(broker.newWriteOnlyTransaction()).thenReturn(writeOnlyTx1).thenReturn(writeOnlyTx2).thenReturn(writeOnlyTx3);
+ when(broker.newWriteOnlyTransaction()).thenReturn(writeOnlyTx1)
+ .thenReturn(writeOnlyTx2).thenReturn(writeOnlyTx3);
when(writeOnlyTx1.addListener(any())).thenReturn(registration1);
when(writeOnlyTx2.addListener(any())).thenReturn(registration2);
when(writeOnlyTx3.addListener(any())).thenReturn(registration3);
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+ final SchemaContext schemaContext =
+ YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any());
netconfOps = new NetconfBaseOps(rpc, schemaContext);
id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830));
public void testSubmit() throws Exception {
final WriteCandidateRunningTx tx = new WriteCandidateRunningTx(id, netconfOps, true);
//check, if lock is called
- final ContainerNode candidateLock = getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
- final ContainerNode runningLock = getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
+ final ContainerNode candidateLock =
+ getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
+ final ContainerNode runningLock =
+ getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), runningLock);
verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), candidateLock);
tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
//check, if both edits are called
- verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, times(2)).invokeRpc(
+ eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
tx.submit().get();
//check, if unlock is called
- verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
- final ContainerNode candidateUnlock = getLockContent(NETCONF_UNLOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
- final ContainerNode runningUnlock = getLockContent(NETCONF_UNLOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
+ verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+ NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ final ContainerNode candidateUnlock = getLockContent(NETCONF_UNLOCK_QNAME,
+ NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
+ final ContainerNode runningUnlock = getLockContent(NETCONF_UNLOCK_QNAME,
+ NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
verify(rpc).invokeRpc(SchemaPath.create(true, NETCONF_UNLOCK_QNAME), candidateUnlock);
verify(rpc).invokeRpc(SchemaPath.create(true, NETCONF_UNLOCK_QNAME), runningUnlock);
}
tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
//check, if both edits are called
- verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, times(2))
+ .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
tx.submit().get();
//check, if unlock is called
- verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+ verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+ NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
verify(rpc).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)), any());
}
tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
//check, if no edit-config is called before submit
- verify(rpc, never()).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, never())
+ .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
tx.submit().get();
//check, if both edits are called
- verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+ verify(rpc, times(2))
+ .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
//check, if unlock is called
verify(rpc).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)), any());
}
CheckedFuture<DOMRpcResult, DOMRpcException> response = Futures.immediateCheckedFuture(value);
doReturn(response).when(service).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
- provider = new NetconfRemoteSchemaYangSourceProvider(new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)), service);
+ provider = new NetconfRemoteSchemaYangSourceProvider(
+ new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)), service);
}
@Test
Assert.assertEquals(identifier, source.getIdentifier());
verify(service).invokeRpc(
SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME),
- NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest(identifier.getName(), Optional.of(identifier.getRevision()))
+ NetconfRemoteSchemaYangSourceProvider
+ .createGetSchemaRequest(identifier.getName(), Optional.of(identifier.getRevision()))
);
}
Element root = xmlDoc.createElement("data");
root.setTextContent("module test {}");
final DOMSource v = new DOMSource(root);
- DataContainerChild<?, ?> child = ImmutableAnyXmlNodeBuilder.create().withNodeIdentifier(childId).withValue(v).build();
+ DataContainerChild<?, ?> child =
+ ImmutableAnyXmlNodeBuilder.create().withNodeIdentifier(childId).withValue(v).build();
return ImmutableContainerNodeBuilder.create().withNodeIdentifier(id).withChild(child).build();
}
XMLUnit.setIgnoreAttributeOrder(true);
}
- private static final String EXP_RPC = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- " <edit-config>\n" +
- " <target>\n" +
- " <candidate/>\n" +
- " </target>\n" +
- " <config>\n" +
- " <top xmlns=\"http://example.com/schema/1.2/config\">\n" +
- " <users xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:operation=\"replace\">\n" +
- " <user>\n" +
- " <name>fred</name>\n" +
- " </user>\n" +
- " </users>\n" +
- " </top>\n" +
- " </config>\n" +
- " </edit-config>\n" +
- "</rpc>\n";
+ private static final String EXP_RPC = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + " <edit-config>\n"
+ + " <target>\n"
+ + " <candidate/>\n"
+ + " </target>\n"
+ + " <config>\n"
+ + " <top xmlns=\"http://example.com/schema/1.2/config\">\n"
+ + " <users xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:operation=\"replace\">\n"
+ + " <user>\n"
+ + " <name>fred</name>\n"
+ + " </user>\n"
+ + " </users>\n"
+ + " </top>\n"
+ + " </config>\n"
+ + " </edit-config>\n"
+ + "</rpc>\n";
BaseRpcSchemalessTransformer transformer;
@Test(expected = UnsupportedOperationException.class)
public void toNotification() throws Exception {
- transformer.toNotification(new NetconfMessage(XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"))));
+ transformer.toNotification(new NetconfMessage(
+ XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"))));
}
@Test
public void toRpcRequest() throws Exception {
- final Document doc = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/edit-config/container.xml"));
+ final Document doc =
+ XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/edit-config/container.xml"));
final AnyXmlNode xml = Builders.anyXmlBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME))
+ .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(
+ NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME))
.withValue(new DOMSource(doc.getDocumentElement()))
.build();
final ChoiceNode editContent = Builders.choiceBuilder()
.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(EditContent.QNAME))
.withChild(xml)
.build();
- final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
- .withChild(Builders.leafBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
+ final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
+ .withChild(Builders.leafBuilder().withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
.build();
final DataContainerChild<?, ?> target = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_TARGET_QNAME))
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_TARGET_QNAME))
.withChild(candidate)
.build();
final ContainerNode editConfig = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME))
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME))
.withChild(editContent)
.withChild(target)
.build();
- final NetconfMessage msg = transformer.toRpcRequest(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), editConfig);
+ final NetconfMessage msg = transformer.toRpcRequest(
+ SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), editConfig);
final Diff diff = XMLUnit.compareXML(EXP_RPC, XmlUtil.toString(msg.getDocument()));
Assert.assertTrue(diff.toString(), diff.similar());
}
@Test
public void toRpcResult() throws Exception {
- final Document doc = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
+ final Document doc = XmlUtil.readXmlToDocument(
+ "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
final InputStream stream = getClass().getResourceAsStream("/schemaless/get-config/container.xml");
final Element dataElement = XmlUtil.readXmlToElement(stream);
final Element element = (Element) doc.importNode(dataElement, true);
doc.getDocumentElement().appendChild(element);
final NetconfMessage msg = new NetconfMessage(doc);
- final DOMRpcResult result = transformer.toRpcResult(msg, SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME));
+ final DOMRpcResult result = transformer.toRpcResult(msg,
+ SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME));
Assert.assertNotNull(result.getResult());
final ContainerNode rpcReply = (ContainerNode) result.getResult();
Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME, rpcReply.getNodeType());
- final Optional dataOpt = rpcReply.getChild(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
+ final Optional dataOpt = rpcReply.getChild(
+ new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
Assert.assertTrue(dataOpt.isPresent());
final AnyXmlNode data = (AnyXmlNode) dataOpt.get();
final Diff diff = XMLUnit.compareXML(dataElement.getOwnerDocument(), (Document) data.getValue().getNode());
@Test
public void testDiscardChangesRequest() throws Exception {
- final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_DISCARD_CHANGES_QNAME), null);
+ final NetconfMessage netconfMessage =
+ netconfMessageTransformer.toRpcRequest(toPath(NETCONF_DISCARD_CHANGES_QNAME), null);
assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("<discard"));
assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("<rpc"));
assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("message-id"));
public void tesGetSchemaRequest() throws Exception {
final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(GET_SCHEMA_QNAME),
NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")));
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<format>yang</format>\n" +
- "<identifier>module</identifier>\n" +
- "<version>2012-12-12</version>\n" +
- "</get-schema>\n" +
- "</rpc>");
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<format>yang</format>\n"
+ + "<identifier>module</identifier>\n"
+ + "<version>2012-12-12</version>\n"
+ + "</get-schema>\n"
+ + "</rpc>");
}
@Test
public void tesGetSchemaResponse() throws Exception {
final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
- "<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<data\n" +
- "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
- "Random YANG SCHEMA\n" +
- "</xs:schema>\n" +
- "</data>\n" +
- "</rpc-reply>"
+ "<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<data\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n"
+ + "Random YANG SCHEMA\n"
+ + "</xs:schema>\n"
+ + "</data>\n"
+ + "</rpc-reply>"
));
- final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
+ final DOMRpcResult compositeNodeRpcResult =
+ netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNotNull(compositeNodeRpcResult.getResult());
- final DOMSource schemaContent = ((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
- assertThat(((Element) schemaContent.getNode()).getTextContent(), CoreMatchers.containsString("Random YANG SCHEMA"));
+ final DOMSource schemaContent =
+ ((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
+ assertThat(((Element) schemaContent.getNode()).getTextContent(),
+ CoreMatchers.containsString("Random YANG SCHEMA"));
}
@Test
public void testGetConfigResponse() throws Exception {
- final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<data>\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<schemas>\n" +
- "<schema>\n" +
- "<identifier>module</identifier>\n" +
- "<version>2012-12-12</version>\n" +
- "<format xmlns:x=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">x:yang</format>\n" +
- "</schema>\n" +
- "</schemas>\n" +
- "</netconf-state>\n" +
- "</data>\n" +
- "</rpc-reply>"));
+ final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<data>\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<schemas>\n"
+ + "<schema>\n"
+ + "<identifier>module</identifier>\n"
+ + "<version>2012-12-12</version>\n"
+ + "<format xmlns:x=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">x:yang</format>\n"
+ + "</schema>\n"
+ + "</schemas>\n"
+ + "</netconf-state>\n"
+ + "</data>\n"
+ + "</rpc-reply>"));
final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
- final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
+ final DOMRpcResult compositeNodeRpcResult =
+ netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNotNull(compositeNodeRpcResult.getResult());
final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> values = Lists.newArrayList(
- NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
+ NetconfRemoteSchemaYangSourceProvider
+ .createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
final Map<QName, Object> keys = Maps.newHashMap();
for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> value : values) {
keys.put(value.getNodeType(), value.getValue());
}
- final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
- final MapEntryNode schemaNode = Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates =
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
+ final MapEntryNode schemaNode =
+ Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
- final ContainerNode data = (ContainerNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getChild(toId(NETCONF_DATA_QNAME)).get();
+ final ContainerNode data = (ContainerNode) ((ContainerNode) compositeNodeRpcResult
+ .getResult()).getChild(toId(NETCONF_DATA_QNAME)).get();
final ContainerNode state = (ContainerNode) data.getChild(toId(NetconfState.QNAME)).get();
final ContainerNode schemas = (ContainerNode) state.getChild(toId(Schemas.QNAME)).get();
final MapNode schemaParent = (MapNode) schemas.getChild(toId(Schema.QNAME)).get();
final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_GET_CONFIG_QNAME),
NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, source, filter));
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<schemas/>\n" +
- "</netconf-state>" +
- "</filter>\n" +
- "<source>\n" +
- "<running/>\n" +
- "</source>\n" +
- "</get-config>" +
- "</rpc>");
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<schemas/>\n"
+ + "</netconf-state>"
+ + "</filter>\n"
+ + "<source>\n"
+ + "<running/>\n"
+ + "</source>\n"
+ + "</get-config>"
+ + "</rpc>");
}
@Test
public void testEditConfigRequest() throws Exception {
final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> values = Lists.newArrayList(
- NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
+ NetconfRemoteSchemaYangSourceProvider
+ .createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
final Map<QName, Object> keys = Maps.newHashMap();
for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> value : values) {
keys.put(value.getNodeType(), value.getValue());
}
- final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
- final MapEntryNode schemaNode = Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
+ final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates =
+ new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
+ final MapEntryNode schemaNode =
+ Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
- final YangInstanceIdentifier id = YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).node(Schema.QNAME).nodeWithKey(Schema.QNAME, keys).build();
- final DataContainerChild<?, ?> editConfigStructure = createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id, Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
+ final YangInstanceIdentifier id = YangInstanceIdentifier.builder()
+ .node(NetconfState.QNAME).node(Schemas.QNAME).node(Schema.QNAME)
+ .nodeWithKey(Schema.QNAME, keys).build();
+ final DataContainerChild<?, ?> editConfigStructure =
+ createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id,
+ Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
final DataContainerChild<?, ?> target = NetconfBaseOps.getTargetNode(NETCONF_CANDIDATE_QNAME);
- final ContainerNode wrap = NetconfMessageTransformUtil.wrap(NETCONF_EDIT_CONFIG_QNAME, editConfigStructure, target);
- final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_EDIT_CONFIG_QNAME), wrap);
-
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<edit-config>\n" +
- "<target>\n" +
- "<candidate/>\n" +
- "</target>\n" +
- "<config>\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<schemas>\n" +
- "<schema>\n" +
- "<identifier>module</identifier>\n" +
- "<version>2012-12-12</version>\n" +
- "<format>yang</format>\n" +
- "</schema>\n" +
- "</schemas>\n" +
- "</netconf-state>\n" +
- "</config>\n" +
- "</edit-config>\n" +
- "</rpc>");
+ final ContainerNode wrap =
+ NetconfMessageTransformUtil.wrap(NETCONF_EDIT_CONFIG_QNAME, editConfigStructure, target);
+ final NetconfMessage netconfMessage =
+ netconfMessageTransformer.toRpcRequest(toPath(NETCONF_EDIT_CONFIG_QNAME), wrap);
+
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<edit-config>\n"
+ + "<target>\n"
+ + "<candidate/>\n"
+ + "</target>\n"
+ + "<config>\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<schemas>\n"
+ + "<schema>\n"
+ + "<identifier>module</identifier>\n"
+ + "<version>2012-12-12</version>\n"
+ + "<format>yang</format>\n"
+ + "</schema>\n"
+ + "</schemas>\n"
+ + "</netconf-state>\n"
+ + "</config>\n"
+ + "</edit-config>\n"
+ + "</rpc>");
}
private static void assertSimilarXml(final NetconfMessage netconfMessage, final String xmlContent)
final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_GET_QNAME),
NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, filter));
- assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
- "<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n" +
- "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
- "<capabilities>\n" +
- "<capability>a:b:c</capability>\n" +
- "</capabilities>\n" +
- "</netconf-state>" +
- "</filter>\n" +
- "</get>" +
- "</rpc>");
+ assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
+ + "<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
+ + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+ + "<capabilities>\n"
+ + "<capability>a:b:c</capability>\n"
+ + "</capabilities>\n"
+ + "</netconf-state>"
+ + "</filter>\n"
+ + "</get>"
+ + "</rpc>");
}
private static NetconfMessageTransformer getTransformer(final SchemaContext schema) {
final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
"<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><ok/></rpc-reply>"
));
- final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_COMMIT_QNAME));
+ final DOMRpcResult compositeNodeRpcResult =
+ netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_COMMIT_QNAME));
assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
assertNull(compositeNodeRpcResult.getResult());
}
public SchemaContext getSchema(final boolean addBase) {
final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
- if(addBase) {
+ if (addBase) {
moduleInfoBackedContext.addModuleInfos(Collections.singleton($YangModuleInfoImpl.getInstance()));
}
- moduleInfoBackedContext.addModuleInfos(Collections.singleton(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.$YangModuleInfoImpl.getInstance()));
+ moduleInfoBackedContext
+ .addModuleInfos(Collections.singleton(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
+ .netconf.monitoring.rev101004.$YangModuleInfoImpl.getInstance()));
return moduleInfoBackedContext.tryToCreateSchemaContext().get();
}
}
XMLUnit.setIgnoreWhitespace(true);
}
- private static final String EXP_REQUEST = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<test-rpc xmlns=\"test-ns\">\n" +
- "<input>aaa</input>\n" +
- "</test-rpc>\n" +
- "</rpc>";
- private static final String EXP_REPLY = "<rpc-reply message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<output xmlns=\"test-ns\">aaa</output>\n" +
- "</rpc-reply>";
- private static final String OK_REPLY = "<rpc-reply message-id=\"101\"\n" +
- "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<ok/>\n" +
- "</rpc-reply>\n";
+ private static final String EXP_REQUEST =
+ "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<test-rpc xmlns=\"test-ns\">\n"
+ + "<input>aaa</input>\n"
+ + "</test-rpc>\n"
+ + "</rpc>";
+ private static final String EXP_REPLY =
+ "<rpc-reply message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<output xmlns=\"test-ns\">aaa</output>\n"
+ + "</rpc-reply>";
+ private static final String OK_REPLY = "<rpc-reply message-id=\"101\"\n"
+ + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "<ok/>\n"
+ + "</rpc-reply>\n";
private SchemalessMessageTransformer transformer;
private static final QName TEST_RPC = QName.create("test-ns", "2016-10-13", "test-rpc");
final Document payload = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"));
final NetconfMessage netconfMessage = new NetconfMessage(payload);
final DOMNotification domNotification = transformer.toNotification(netconfMessage);
- Assert.assertEquals(domNotification.getType().getLastComponent(), SchemalessMessageTransformer.SCHEMALESS_NOTIFICATION_PAYLOAD.getNodeType());
- final QName qName = QName.create("org:opendaylight:notification:test:ns:yang:user-notification", "user-visited-page");
+ Assert.assertEquals(domNotification.getType().getLastComponent(),
+ SchemalessMessageTransformer.SCHEMALESS_NOTIFICATION_PAYLOAD.getNodeType());
+ final QName qName =
+ QName.create("org:opendaylight:notification:test:ns:yang:user-notification", "user-visited-page");
final AnyXmlNode dataContainerChild =
(AnyXmlNode) domNotification.getBody().getChild(new YangInstanceIdentifier.NodeIdentifier(qName)).get();
final Diff diff = XMLUnit.compareXML(payload, dataContainerChild.getValue().getNode().getOwnerDocument());
@Test
public void toEmptyRpcResult() throws Exception {
final Document doc = XmlUtil.readXmlToDocument(OK_REPLY);
- final DOMRpcResult result = transformer.toRpcResult(new NetconfMessage(doc), SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME));
+ final DOMRpcResult result = transformer.toRpcResult(
+ new NetconfMessage(doc), SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME));
Assert.assertNull(result.getResult());
}
private final SchemalessRpcStructureTransformer adapter = new SchemalessRpcStructureTransformer();
private final String testDataset;
- public SchemalessRpcStructureTransformerTest(YangInstanceIdentifier path, String testDataset, Class<? extends Exception> expectedException) throws IOException, SAXException, URISyntaxException {
+ public SchemalessRpcStructureTransformerTest(
+ YangInstanceIdentifier path, String testDataset,
+ Class<? extends Exception> expectedException) throws IOException, SAXException, URISyntaxException {
this.path = path;
this.testDataset = testDataset;
this.expectedException = expectedException;
- this.source = new DOMSource(XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/data/" + testDataset)).getDocumentElement());
- this.expectedConfig = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/edit-config/" + testDataset).toURI())));
- this.expectedFilter = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/filter/" + testDataset).toURI())));
- this.getConfigData = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/get-config/" + testDataset).toURI())));
+ this.source = new DOMSource(XmlUtil.readXmlToDocument(getClass()
+ .getResourceAsStream("/schemaless/data/" + testDataset)).getDocumentElement());
+ this.expectedConfig = new String(Files.readAllBytes(
+ Paths.get(getClass().getResource("/schemaless/edit-config/" + testDataset).toURI())));
+ this.expectedFilter = new String(Files.readAllBytes(
+ Paths.get(getClass().getResource("/schemaless/filter/" + testDataset).toURI())));
+ this.getConfigData = new String(Files.readAllBytes(
+ Paths.get(getClass().getResource("/schemaless/get-config/" + testDataset).toURI())));
}
@Parameterized.Parameters
{YangInstanceIdentifier.builder()
.node(createNodeId("top"))
.node(createNodeId("users"))
- .node(createListNodeId("user", ImmutableMap.of(QName.create(NAMESPACE, "key1"), "k1", QName.create(NAMESPACE, "key2"), "k2")))
+ .node(createListNodeId("user", ImmutableMap.of(QName.create(NAMESPACE, "key1"), "k1",
+ QName.create(NAMESPACE, "key2"), "k2")))
.build(), "keyed-list-compound-key.xml", null},
{YangInstanceIdentifier.builder()
.node(createNodeId("top"))
@Test
public void testCreateEditConfigStructure() throws Exception {
- if(expectedException != null) {
+ if (expectedException != null) {
thrown.expect(expectedException);
}
AnyXmlNode data = Builders.anyXmlBuilder()
.withNodeIdentifier(createNodeId(path.getLastPathArgument().getNodeType().getLocalName()))
.withValue(source)
.build();
- final AnyXmlNode anyXmlNode = adapter.createEditConfigStructure(Optional.of(data), path, Optional.of(ModifyAction.REPLACE));
+ final AnyXmlNode anyXmlNode =
+ adapter.createEditConfigStructure(Optional.of(data), path, Optional.of(ModifyAction.REPLACE));
final String s = XmlUtil.toString((Element) anyXmlNode.getValue().getNode());
Diff diff = new Diff(expectedConfig, s);
Assert.assertTrue(String.format("Input %s: %s", testDataset, diff.toString()), diff.similar());
return new YangInstanceIdentifier.NodeIdentifier(QName.create(NAMESPACE, name));
}
- private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(String nodeName, String keyName, String id) {
- return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), QName.create(NAMESPACE, keyName), id);
+ private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(
+ String nodeName, String keyName, String id) {
+ return new YangInstanceIdentifier
+ .NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), QName.create(NAMESPACE, keyName), id);
}
- private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(String nodeName, Map<QName, Object> keys) {
+ private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(
+ String nodeName, Map<QName, Object> keys) {
return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), keys);
}
}
public class YanglibModule extends org.opendaylight.controller.config.yang.yanglib.impl.AbstractYanglibModule {
private static final Logger LOG = LoggerFactory.getLogger(YanglibModule.class);
- public YanglibModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+ public YanglibModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
- public YanglibModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.yanglib.impl.YanglibModule oldModule, java.lang.AutoCloseable oldInstance) {
+ public YanglibModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+ org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+ org.opendaylight.controller.config.yang.yanglib.impl.YanglibModule oldModule,
+ java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
* Do not modify this file unless it is present under src/main directory
*/
package org.opendaylight.controller.config.yang.yanglib.impl;
-public class YanglibModuleFactory extends org.opendaylight.controller.config.yang.yanglib.impl.AbstractYanglibModuleFactory {
+public class YanglibModuleFactory
+ extends org.opendaylight.controller.config.yang.yanglib.impl.AbstractYanglibModuleFactory {
}
/**
* Get {@link YangLibServiceImpl} via service.
- * @return
+ * @return YangLibServiceImpl
*/
YangLibServiceImpl getYangLibService();
}
public interface YangLibService {
/**
- * Get module's source for each module from yang library
+ * Get module's source for each module from yang library.
* @param name Module's name
* @param revision Module's revision
* @return Module's source
* along with source identifier to
* ietf-netconf-yang-library/modules-state/module list.
*/
-public class YangLibProvider implements BindingAwareProvider, AutoCloseable, SchemaSourceListener{
+public class YangLibProvider implements BindingAwareProvider, AutoCloseable, SchemaSourceListener {
private static final Logger LOG = LoggerFactory.getLogger(YangLibProvider.class);
private static final OptionalRevision NO_REVISION = new OptionalRevision("");
private static final Predicate<PotentialSchemaSource<?>> YANG_SCHEMA_SOURCE =
- input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
+ input -> YangTextSchemaSource.class.isAssignableFrom(input.getRepresentation());
protected DataBroker dataBroker;
protected SchemaListenerRegistration schemaListenerRegistration;
public void schemaSourceRegistered(final Iterable<PotentialSchemaSource<?>> sources) {
final List<Module> newModules = new ArrayList<>();
- for(PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
+ for (PotentialSchemaSource<?> potentialYangSource : Iterables.filter(sources, YANG_SCHEMA_SOURCE)) {
final YangIdentifier moduleName = new YangIdentifier(potentialYangSource.getSourceIdentifier().getName());
final OptionalRevision moduleRevision = getRevisionForModule(potentialYangSource.getSourceIdentifier());
newModules.add(newModule);
}
- if(newModules.isEmpty()) {
+ if (newModules.isEmpty()) {
// If no new yang modules then do nothing
return;
}
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Unable to update modules state", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Unable to update modules state", throwable);
}
});
}
@Override
public void schemaSourceUnregistered(final PotentialSchemaSource<?> source) {
- if(!YANG_SCHEMA_SOURCE.apply(source)) {
+ if (!YANG_SCHEMA_SOURCE.apply(source)) {
// if representation of potential schema source is not yang text schema source do nothing
// we do not want to delete this module entry from module list
return;
}
@Override
- public void onFailure(final Throwable t) {
- LOG.warn("Unable to update modules state", t);
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Unable to update modules state", throwable);
}
});
}
import org.slf4j.LoggerFactory;
/**
- * Provides schema sources from yang library
+ * Provides schema sources from yang library.
*/
public class YangLibServiceImpl implements YangLibService {
private static final Logger LOG = LoggerFactory.getLogger(YangLibServiceImpl.class);
try {
final YangTextSchemaSource source = sourceFuture.checkedGet();
return new String(ByteStreams.toByteArray(source.openStream()));
- } catch (SchemaSourceException|IOException e) {
+ } catch (SchemaSourceException | IOException e) {
throw new IllegalStateException("Unable to get schema" + sourceId, e);
}
}
private static class TestingYangLibProvider extends YangLibProvider {
- public TestingYangLibProvider(SharedSchemaRepository schemaRepository, String bindingAddress, long bindingPort) {
+ TestingYangLibProvider(
+ SharedSchemaRepository schemaRepository, String bindingAddress, long bindingPort) {
super(schemaRepository, bindingAddress, bindingPort);
}
assertTrue(singleton.contains(yangLibRestApp.getYangLibService()));
- then(bundleContext).should(times(1)).registerService(eq(YangLibRestAppService.class.getName()), eq(yangLibRestApp), eq(null));
+ then(bundleContext).should(times(1))
+ .registerService(eq(YangLibRestAppService.class.getName()), eq(yangLibRestApp), eq(null));
}
}
public class YangLibServiceImplTest {
- private final static String TEST_OUTPUT_STRING = "hello world";
+ private static final String TEST_OUTPUT_STRING = "hello world";
@Test
public void testSchema() throws SchemaSourceException {
package org.opendaylight.controller.config.yang.md.sal.rest.connector;
import org.opendaylight.controller.config.api.DependencyResolver;
+import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
import org.osgi.framework.BundleContext;
-public class RestConnectorModuleFactory extends org.opendaylight.controller.config.yang.md.sal.rest.connector.AbstractRestConnectorModuleFactory {
+public class RestConnectorModuleFactory
+ extends org.opendaylight.controller.config.yang.md.sal.rest.connector.AbstractRestConnectorModuleFactory {
@Override
- public RestConnectorModule instantiateModule(String instanceName, DependencyResolver dependencyResolver,
- BundleContext bundleContext) {
+ public RestConnectorModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final BundleContext bundleContext) {
final RestConnectorModule restConnectorModule = super.instantiateModule(instanceName,
dependencyResolver, bundleContext);
restConnectorModule.setBundleContext(bundleContext);
}
@Override
- public RestConnectorModule instantiateModule(String instanceName, DependencyResolver dependencyResolver,
- RestConnectorModule oldModule, AutoCloseable oldInstance, BundleContext bundleContext) {
+ public RestConnectorModule instantiateModule(final String instanceName, final DependencyResolver dependencyResolver,
+ final RestConnectorModule oldModule, final AutoCloseable oldInstance,
+ final BundleContext bundleContext) {
final RestConnectorModule restConnectorModule = super.instantiateModule(instanceName,
dependencyResolver, oldModule, oldInstance, bundleContext);
restConnectorModule.setBundleContext(bundleContext);
return restConnectorModule;
}
+
+ @Override
+ public RestConnectorModule handleChangedClass(final DependencyResolver dependencyResolver,
+ final DynamicMBeanWithInstance old, final BundleContext bundleContext)
+ throws Exception {
+ //close old restconf instance
+ old.getModule().getInstance().close();
+ final RestConnectorModule restconfModule = super.handleChangedClass(dependencyResolver, old, bundleContext);
+ restconfModule.setBundleContext(bundleContext);
+ return restconfModule;
+ }
}