<classifier>features</classifier>
<type>xml</type>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-netconf</artifactId>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-config</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-file-xml-adapter</artifactId>
+ <artifactId>config-manager-facade-xml</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-impl</artifactId>
+ <artifactId>config-util</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>config-persister-feature-adapter</artifactId>
+ <artifactId>config-persister-file-xml-adapter</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-util</artifactId>
+ <artifactId>config-persister-impl</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-mapping-api</artifactId>
+ <artifactId>config-persister-feature-adapter</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
<repository>mvn:org.opendaylight.yangtools/features-yangtools/${yangtools.version}/xml/features</repository>
- <repository>mvn:org.opendaylight.controller/features-netconf/${netconf.version}/xml/features</repository>
<repository>mvn:org.opendaylight.controller/features-config/${config.version}/xml/features</repository>
<feature name='odl-config-persister-all' version='${project.version}' description="OpenDaylight :: Config Persister:: All">
<feature version='${project.version}'>odl-config-persister</feature>
<feature version='${project.version}'>odl-config-startup</feature>
</feature>
<feature name='odl-config-persister' version='${project.version}' description="OpenDaylight :: Config Persister ">
- <feature version='${netconf.version}'>odl-netconf-api</feature>
<feature version='${project.version}'>odl-config-api</feature>
+ <feature version='${project.version}'>odl-config-core</feature>
+ <feature version='${project.version}'>odl-config-manager</feature>
<feature version='${yangtools.version}'>odl-yangtools-binding-generator</feature>
+ <bundle>mvn:org.opendaylight.controller/yang-jmx-generator/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/config-persister-api/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/config-util/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/config-manager-facade-xml/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/config-persister-file-xml-adapter/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/config-persister-impl/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/config-persister-feature-adapter/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/netconf-util/${netconf.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/netconf-mapping-api/${netconf.version}</bundle>
<bundle>mvn:com.google.guava/guava/${guava.version}</bundle>
<bundle>mvn:commons-io/commons-io/${commons.io.version}</bundle>
<bundle>mvn:org.eclipse.persistence/org.eclipse.persistence.moxy/${eclipse.persistence.version}</bundle>
</feature>
<feature name='odl-config-startup' version='${project.version}' description="OpenDaylight :: Config Persister:: Config Startup">
- <feature version='${project.version}'>odl-config-netconf-connector</feature>
<feature version='${project.version}'>odl-config-persister</feature>
- <feature version='${project.version}'>odl-netconf-impl</feature>
+ </feature>
+ <feature name='odl-config-manager-facade-xml' version='${project.version}' description="Opendaylight :: Config Persister:: Mapping for Config Subsystem">
+ <feature version='${project.version}'>odl-config-core</feature>
+ <bundle>mvn:org.opendaylight.controller/config-manager-facade-xml/${project.version}</bundle>
</feature>
</features>
<bundle>mvn:io.netty/netty-transport/${netty.version}</bundle>
<bundle>mvn:io.netty/netty-common/${netty.version}</bundle>
<bundle>mvn:io.netty/netty-buffer/${netty.version}</bundle>
+ <bundle>mvn:io.netty/netty-codec/${netty.version}</bundle>
+ <bundle>mvn:io.netty/netty-handler/${netty.version}</bundle>
</feature>
<feature name='odl-config-core' version='${project.version}' description="OpenDaylight :: Config :: Core">
<feature version='${yangtools.version}'>odl-yangtools-binding</feature>
<feature version='${yangtools.version}'>odl-yangtools-binding-generator</feature>
<feature version='${project.version}'>odl-config-api</feature>
+ <bundle>mvn:org.opendaylight.yangtools/yang-model-api/${yangtools.version}</bundle>
<bundle>mvn:org.opendaylight.controller/config-util/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/yang-jmx-generator/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/shutdown-api/${project.version}</bundle>
<classifier>features</classifier>
<type>xml</type>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-netconf</artifactId>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-config-persister</artifactId>
<artifactId>sal-distributed-datastore</artifactId>
</dependency>
+ <!-- message-bus -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-inmemory-datastore</artifactId>
+ <artifactId>messagebus-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>messagebus-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>messagebus-config</artifactId>
+ <version>${mdsal.version}</version>
+ <type>xml</type>
+ <classifier>config</classifier>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>mdsal-netconf-connector</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>mdsal-netconf-monitoring</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-mdsal-config</artifactId>
- <version>${netconf.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-netconf-connector</artifactId>
+ <artifactId>sal-inmemory-datastore</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-rest-docgen</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-config-dispatcher</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-connector-config</artifactId>
- <version>${netconf.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-ssh</artifactId>
- </dependency>
-
<dependency>
<groupId>org.opendaylight.controller.model</groupId>
<artifactId>model-inventory</artifactId>
<repository>mvn:org.opendaylight.controller/features-config/${config.version}/xml/features</repository>
<repository>mvn:org.opendaylight.controller/features-config-persister/${config.version}/xml/features</repository>
<repository>mvn:org.opendaylight.controller/features-config-netty/${config.version}/xml/features</repository>
- <repository>mvn:org.opendaylight.controller/features-netconf/${netconf.version}/xml/features</repository>
<repository>mvn:org.opendaylight.controller/features-akka/${commons.opendaylight.version}/xml/features</repository>
<feature name='odl-mdsal-all' version='${project.version}' description="OpenDaylight :: MDSAL :: All">
<feature version='${project.version}'>odl-mdsal-broker</feature>
<bundle>mvn:org.opendaylight.controller/sal-common-util/${mdsal.version}</bundle>
</feature>
- <!-- TODO move to netconf features, however there are some weird dependencies on features-config-persister all over that cause cyclic dependencies-->
- <feature name='odl-netconf-mdsal' version='${project.version}' description="OpenDaylight :: Netconf :: Mdsal">
- <feature version='${config.version}'>odl-config-all</feature>
- <feature version='${netconf.version}'>odl-netconf-all</feature>
- <feature version='${config.version}'>odl-config-netty</feature>
- <bundle>mvn:org.opendaylight.controller/netconf-tcp/${netconf.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/netconf-ssh/${netconf.version}</bundle>
- <feature version='${mdsal.version}'>odl-mdsal-broker</feature>
- <bundle>mvn:org.opendaylight.controller/mdsal-netconf-connector/${netconf.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/mdsal-netconf-monitoring/${netconf.version}</bundle>
- <!-- TODO 01-netconf.xml file requires netconf-config-dispatcher to be present and its part of netconf-connector features. Clean Up-->
- <bundle>mvn:org.opendaylight.controller/netconf-config-dispatcher/${config.version}</bundle>
- <configfile finalname='${config.configfile.directory}/${config.netconf.client.configfile}'>mvn:org.opendaylight.controller/netconf-config/${netconf.version}/xml/config</configfile>
- <configfile finalname='${config.configfile.directory}/${config.netconf.mdsal.configfile}'>mvn:org.opendaylight.controller/netconf-mdsal-config/${netconf.version}/xml/config</configfile>
- </feature>
-
<feature name='odl-mdsal-broker-local' version='${project.version}' description="OpenDaylight :: MDSAL :: Broker">
<feature version='${yangtools.version}'>odl-yangtools-common</feature>
<feature version='${yangtools.version}'>odl-yangtools-binding</feature>
<bundle>mvn:org.opendaylight.controller.samples/clustering-it-provider/${project.version}</bundle>
<configfile finalname="${config.configfile.directory}/20-clustering-test-app.xml">mvn:org.opendaylight.controller.samples/clustering-it-config/${project.version}/xml/config</configfile>
</feature>
+
+ <!-- FIXME decouple messagebus code into messagebus and messagebus netconf -->
+ <feature name='odl-message-bus' version='${project.version}'>
+ <!--<feature version='${project.version}'>odl-netconf-connector</feature>-->
+ <bundle>mvn:org.opendaylight.controller.model/model-inventory/${mdsal.version}</bundle>
+ <feature version='${project.version}'>odl-mdsal-broker</feature>
+ <bundle>mvn:org.opendaylight.controller/messagebus-api/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/messagebus-spi/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/messagebus-impl/${project.version}</bundle>
+ <configfile finalname="${config.configfile.directory}/05-message-bus.xml">mvn:org.opendaylight.controller/messagebus-config/${project.version}/xml/config</configfile>
+ </feature>
</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
--->
-<features name="odl-controller-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
- <!--
- Necessary TODO: Please read the features guidelines:
- https://wiki.opendaylight.org/view/Runtime:Karaf_Features_Guidelines#Feature_Best_Practices
- -->
- <!--
- Necessary TODO: Add repo entries for the repositories of features you refer to
- in this feature file but do not define here.
- Examples:
- <repository>mvn:org.opendaylight.yangtools/features-yangtools/0.8.0-SNAPSHOT/xml/features</repository>
- <repository>mvn:org.opendaylight.controller/features-mdsal/1.3.0-SNAPSHOT/xml/features</repository>
- <repository>mvn:org.opendaylight.openflowplugin/features-openflowplugin/0.2.0-SNAPSHOT/xml/features</repository>
- -->
- <repository>mvn:org.opendaylight.controller/features-mdsal/${mdsal.version}/xml/features</repository>
- <repository>mvn:org.opendaylight.yangtools/features-yangtools/${yangtools.version}/xml/features</repository>
- <repository>mvn:org.opendaylight.controller/features-netconf/${netconf.version}/xml/features</repository>
- <!-- FIXME: This introduces cycle between projects, which makes version updates
- harder. Should be moved to different.
- -->
- <repository>mvn:org.opendaylight.aaa/features-aaa/${aaa.version}/xml/features</repository>
- <feature name='odl-netconf-connector-all' version='${project.version}' description='OpenDaylight :: Netconf Connector :: All'>
- <!--
- Necessary TODO:
- List all of the user consumable features you define in this feature file here.
- Generally you would *not* list individual bundles here, but only features defined in *this* file.
- It is useful to list them in the same order they occur in the file.
-
- Examples:
- <feature version='${project.version}'>odl-controller-provider</feature>
- <feature version='${project.version}'>odl-controller-model</feature>
- -->
- <feature version='${project.version}'>odl-netconf-connector</feature>
- <feature version='${project.version}'>odl-netconf-connector-ssh</feature>
-
-
- </feature>
- <!--
- Necessary TODO: Define your features. It is useful to list then in order of dependency. So if A depends on B, list A first.
- When naming your features please be mindful of the guidelines:
- https://wiki.opendaylight.org/view/Runtime:Karaf_Features_Guidelines
- Particularly:
- a) Prefixing names with 'odl-': https://wiki.opendaylight.org/view/Runtime:Karaf_Features_Guidelines#Feature_Naming
- b) Descriptions: https://wiki.opendaylight.org/view/Runtime:Karaf_Features_Guidelines#Description
- c) Avoid start-levels: https://wiki.opendaylight.org/view/Runtime:Karaf_Features_Guidelines#Avoid_start-levels
-
- It's also nice to list inside a feature, first the features it needs, then the bundles it needs, then the configfiles.
- Examples:
-
- * Basic MD-SAL Provider
- <feature name='odl-controller-provider' version='${project.version}' description='OpenDaylight :: controller :: Provider '>
- <feature version='1.3.0-SNAPSHOT'>odl-mdsal-broker</feature>
- <feature version='${project.version}'>odl-controller-model</feature>
- <bundle>mvn:org.opendaylight.controller/controller-provider/${project.version}</bundle>
- ... whatever other bundles you need
- </feature>
-
- * Basic MD-SAL Model feature
- <feature name='odl-controller-model' version='${project.version}' description='OpenDaylight :: controller :: Model'>
- <feature version='0.8.0-SNAPSHOT'>odl-yangtools-binding</feature>
- <feature version='0.8.0-SNAPSHOT'>odl-yangtools-models</feature>
- <bundle>mvn:org.opendaylight.controller/controller-model/${project.version}</bundle>
- ... whatever other bundles you need
- </feature>
-
- * Config Subsystem example - the config file is your config subsystem configuration
- <feature name='odl-controller-provider' version='${project.version}' description='OpenDaylight :: controller :: Provider'>
- <feature version='1.3.0-SNAPSHOT'>odl-mdsal-broker</feature>
- <bundle>mvn:org.opendaylight.controller/controller-provider/${project.version}</bundle>
- <configfile finalname="etc/opendaylight/karaf/80-controller.xml">mvn:org.opendaylight.controller/controller-config/${project.version}/xml/config</configfile>
- ... whatever other bundles you need
- </feature>
-
- * Basic MD-SAL Provider that uses openflowplugin-flow-services (which brings along odl-mdsal-broker)
- <feature name='odl-controller-provider' version='${project.version}' description='OpenDaylight :: controller :: Provider'>
- <feature version='0.2.0-SNAPSHOT'>odl-openflowplugin-flow-services</feature>
- <bundle>mvn:org.opendaylight.controller/controller-provider/${project.version}</bundle>
- ... whatever other bundles you need
- </feature>
-
- -->
- <feature name='odl-netconf-connector' version='${project.version}' description="OpenDaylight :: Netconf Connector :: Netconf Connector">
- <feature version='${project.version}'>odl-mdsal-broker</feature>
- <feature version='${netconf.version}'>odl-netconf-client</feature>
- <feature version='${yangtools.version}'>odl-yangtools-models</feature>
- <bundle>mvn:org.opendaylight.controller/sal-netconf-connector/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.controller.model/model-inventory/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/netconf-config-dispatcher/${config.version}</bundle>
- <configfile finalname='${config.configfile.directory}/${config.netconf.client.configfile}'>mvn:org.opendaylight.controller/netconf-config/${netconf.version}/xml/config</configfile>
- </feature>
- <feature name='odl-netconf-connector-ssh' version='${project.version}' description="OpenDaylight :: Netconf Connector :: Netconf Connector + Netconf SSH Server + loopback connection configuration">
- <feature version='${netconf.version}'>odl-netconf-ssh</feature>
- <feature version='${project.version}'>odl-netconf-connector</feature>
- <configfile finalname="${config.configfile.directory}/${config.netconf.connector.configfile}">mvn:org.opendaylight.controller/netconf-connector-config/${netconf.version}/xml/config</configfile>
- </feature>
- <feature name='odl-netconf-ssh' version='${netconf.version}' description="OpenDaylight :: Netconf Connector :: SSH">
- <feature version='${netconf.version}'>odl-netconf-tcp</feature>
- <feature version='${config.version}'>odl-config-netty</feature>
- <!-- FIXME: This introduces cycle between projects, which makes version updates
- harder. Should be moved to different.
- -->
- <feature version='${aaa.version}'>odl-aaa-netconf-plugin</feature>
- <bundle>mvn:org.opendaylight.controller/netconf-ssh/${netconf.version}</bundle>
- </feature>
- <feature name='odl-netconf-tcp' version='${netconf.version}' description="OpenDaylight :: Netconf Connector :: TCP">
- <feature version='${netconf.version}'>odl-netconf-impl</feature>
- <feature version='${config.version}'>odl-config-netty</feature>
- <bundle>mvn:org.opendaylight.controller/netconf-tcp/${netconf.version}</bundle>
- </feature>
-
- <feature name='odl-message-bus' version='${project.version}'>
- <feature version='${project.version}'>odl-netconf-connector</feature>
- <feature version='${project.version}'>odl-mdsal-broker</feature>
- <bundle>mvn:org.opendaylight.controller/messagebus-api/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/messagebus-spi/${project.version}</bundle>
- <bundle>mvn:org.opendaylight.controller/messagebus-impl/${project.version}</bundle>
- <configfile finalname="${config.configfile.directory}/05-message-bus.xml">mvn:org.opendaylight.controller/messagebus-config/${project.version}/xml/config</configfile>
- </feature>
- <!-- Optional TODO: Remove TODO Comments -->
-
-</features>
<module>config-persister</module>
<module>config-netty</module>
<module>mdsal</module>
- <module>netconf</module>
<module>protocol-framework</module>
<module>akka</module>
- <module>netconf-connector</module>
<module>restconf</module>
<module>extras</module>
</modules>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Export-Package>org.opendaylight.controller.config.api,
- org.opendaylight.controller.config.api.annotations,
- org.opendaylight.controller.config.spi,
- org.opendaylight.controller.config.api.jmx,
- org.opendaylight.controller.config.api.jmx.constants,
- org.opendaylight.controller.config.api.runtime,
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.rpc.context.rev130617.*,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.*,</Export-Package>
- </instructions>
- </configuration>
</plugin>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
* ConfigRegisry is registered.
*/
public static final ObjectName OBJECT_NAME = ConfigRegistryConstants.OBJECT_NAME;
+ public static final ObjectName OBJECT_NAME_NO_NOTIFICATIONS = ConfigRegistryConstants.OBJECT_NAME_NO_NOTIFICATIONS;
/**
* Opens new configuration transaction.
*/
Set<String> getAvailableModuleNames();
-
}
public static final String TYPE_CONFIG_REGISTRY = "ConfigRegistry";
+ public static final String TYPE_CONFIG_REGISTRY_NO_NOTIFICATIONS = "ConfigRegistryNoNotifications";
+
public static final String ON_DOMAIN = "org.opendaylight.controller";
public static final String TYPE_KEY = "type";
public static final ObjectName OBJECT_NAME = createONWithDomainAndType(TYPE_CONFIG_REGISTRY);
+ public static final ObjectName OBJECT_NAME_NO_NOTIFICATIONS = createONWithDomainAndType(TYPE_CONFIG_REGISTRY_NO_NOTIFICATIONS);
+
public static final String GET_AVAILABLE_MODULE_NAMES_ATTRIBUT_NAME = "AvailableModuleNames";
public static ObjectName createONWithDomainAndType(String type) {
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.api.jmx.notifications;
+
+import javax.management.NotificationBroadcasterSupport;
+
+public class CommitJMXNotification extends ConfigJMXNotification {
+
+ private static final String AFTER_COMMIT_MESSAGE_TEMPLATE = "Commit successful: %s";
+
+ CommitJMXNotification(NotificationBroadcasterSupport source, String message) {
+ super(ConfigJMXNotification.NotificationType.COMMIT, source, String.format(AFTER_COMMIT_MESSAGE_TEMPLATE, message));
+ }
+
+ @Override
+ public String toString() {
+ final StringBuffer sb = new StringBuffer("CommitJMXNotification{");
+ sb.append('}');
+ return sb.toString();
+ }
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -8587623362011695514L;
+
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.api.jmx;
+package org.opendaylight.controller.config.api.jmx.notifications;
-import java.util.Set;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
-import org.w3c.dom.Element;
+import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-public abstract class NetconfJMXNotification extends Notification {
+public abstract class ConfigJMXNotification extends Notification {
/**
*
private static long sequenceNumber = 1;
- private final TransactionProviderJMXNotificationType type;
+ public static String TYPE_NAME = "configfNotificationProvider";
+ public static ObjectName OBJECT_NAME = ObjectNameUtil.createONWithDomainAndType(TYPE_NAME);
- protected NetconfJMXNotification(TransactionProviderJMXNotificationType type,
- NotificationBroadcasterSupport source, String message) {
+ private final NotificationType type;
+
+ protected ConfigJMXNotification(NotificationType type,
+ NotificationBroadcasterSupport source, String message) {
super(type.toString(), source, sequenceNumber++, System.nanoTime(), message);
this.type = type;
}
* @param transactionName
* @param cfgSnapshot
*/
- public static CommitJMXNotification afterCommit(NotificationBroadcasterSupport source, String message,
- Element cfgSnapshot, Set<String> capabilities) {
- return new CommitJMXNotification(source, message, cfgSnapshot, capabilities);
+ public static CommitJMXNotification afterCommit(NotificationBroadcasterSupport source, String messages) {
+ return new CommitJMXNotification(source, messages);
}
- static enum TransactionProviderJMXNotificationType {
- commit;
+ enum NotificationType {
+ COMMIT;
}
}
<artifactId>config-plugin-parent</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-persister-impl</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-util</artifactId>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <artifactId>config-subsystem</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <version>0.4.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <name>${project.artifactId}</name>
+ <packaging>bundle</packaging>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>yang-jmx-generator</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>binding-generator-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Activator>org.opendaylight.controller.config.facade.xml.osgi.YangStoreActivator</Bundle-Activator>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
\ No newline at end of file
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig;
+package org.opendaylight.controller.config.facade.xml;
import java.util.Set;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
public class CandidateDatastoreQueryStrategy implements DatastoreQueryStrategy {
--- /dev/null
+
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml;
+
+import com.google.common.collect.Multimap;
+import java.util.Map;
+import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+
+public class ConfigExecution {
+
+ private final TestOption testOption;
+ private final EditStrategyType defaultEditStrategyType;
+ private final Services services;
+ private final Config configResolver;
+ private final XmlElement configElement;
+
+ public ConfigExecution(Config configResolver, XmlElement configElement, TestOption testOption, EditStrategyType defaultStrategy) throws DocumentedException {
+ Config.checkUnrecognisedChildren(configElement);
+ this.configResolver = configResolver;
+ this.configElement = configElement;
+ this.services = configResolver.fromXmlServices(configElement);
+ this.testOption = testOption;
+ this.defaultEditStrategyType = defaultStrategy;
+ }
+
+ public boolean shouldTest() {
+ return testOption == TestOption.testOnly || testOption == TestOption.testThenSet;
+ }
+
+ public boolean shouldSet() {
+ return testOption == TestOption.set || testOption == TestOption.testThenSet;
+ }
+
+ public Map<String, Multimap<String, ModuleElementResolved>> getResolvedXmlElements(ServiceReferenceReadableRegistry serviceRegistry) throws DocumentedException {
+ return configResolver.fromXmlModulesResolved(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
+ }
+
+ public ServiceRegistryWrapper getServiceRegistryWrapper(ServiceReferenceReadableRegistry serviceRegistry) {
+ // TODO cache service registry
+ return new ServiceRegistryWrapper(serviceRegistry);
+ }
+
+ public Map<String, Multimap<String,ModuleElementDefinition>> getModulesDefinition(ServiceReferenceReadableRegistry serviceRegistry) throws DocumentedException {
+ return configResolver.fromXmlModulesMap(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
+ }
+
+ public EditStrategyType getDefaultStrategy() {
+ return defaultEditStrategyType;
+ }
+
+ public Services getServices() {
+ return services;
+ }
+
+ public XmlElement getConfigElement() {
+ return configElement;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
+import java.io.Closeable;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.api.jmx.CommitStatus;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfig;
+import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfigElementResolved;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreContext;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.facade.xml.runtime.InstanceRuntime;
+import org.opendaylight.controller.config.facade.xml.runtime.ModuleRuntime;
+import org.opendaylight.controller.config.facade.xml.runtime.Runtime;
+import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
+import org.opendaylight.controller.config.util.BeanReader;
+import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Config subsystem facade for xml format
+ * <p/>
+ * TODO extract generic interface for config subsystem facades
+ */
+public class ConfigSubsystemFacade implements Closeable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigSubsystemFacade.class);
+ private final YangStoreService yangStoreService;
+ private final TransactionProvider transactionProvider;
+ private final ConfigRegistryClient configRegistryClient;
+ private final ConfigRegistryClient configRegistryClientNoNotifications;
+ private final RpcFacade rpcFacade;
+
+ public ConfigSubsystemFacade(ConfigRegistryClient configRegistryClient, ConfigRegistryClient configRegistryClientNoNotifications, YangStoreService yangStoreService, String id) {
+ this.configRegistryClient = configRegistryClient;
+ this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
+ this.yangStoreService = yangStoreService;
+ this.transactionProvider = new TransactionProvider(configRegistryClient, id);
+ rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
+ }
+
+ public ConfigSubsystemFacade(ConfigRegistryClient configRegistryClient, ConfigRegistryClient configRegistryClientNoNotifications, YangStoreService yangStoreService, TransactionProvider txProvider) {
+ this.configRegistryClient = configRegistryClient;
+ this.configRegistryClientNoNotifications = configRegistryClientNoNotifications;
+ this.yangStoreService = yangStoreService;
+ this.transactionProvider = txProvider;
+ rpcFacade = new RpcFacade(yangStoreService, configRegistryClient);
+ }
+
+ public Element getConfiguration(final Document document, final Datastore source, final Optional<String> maybeNamespace) {
+
+ final ConfigTransactionClient registryClient;
+ // Read current state from a transaction, if running is source, then start new transaction just for reading
+ // in case of candidate, get current transaction representing candidate
+ if (source == Datastore.running) {
+ final ObjectName readTx = transactionProvider.getOrCreateReadTransaction();
+ registryClient = configRegistryClient.getConfigTransactionClient(readTx);
+ } else {
+ registryClient = configRegistryClient.getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
+ }
+
+ try {
+ Element dataElement = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
+ final Set<ObjectName> instances = Datastore.getInstanceQueryStrategy(source, this.transactionProvider)
+ .queryInstances(configRegistryClient);
+
+ final Config configMapping =
+ new Config(transformMbeToModuleConfigs(yangStoreService.getModuleMXBeanEntryMap()), yangStoreService.getEnumResolver());
+
+ ServiceRegistryWrapper serviceTracker = new ServiceRegistryWrapper(registryClient);
+ dataElement = configMapping.toXml(instances, maybeNamespace, document, dataElement, serviceTracker);
+
+ return dataElement;
+ } finally {
+ if (source == Datastore.running) {
+ transactionProvider.closeReadTransaction();
+ }
+ }
+ }
+
+ public void executeConfigExecution(ConfigExecution configExecution) throws DocumentedException, ValidationException {
+ if (configExecution.shouldTest()) {
+ executeTests(configExecution);
+ }
+
+ if (configExecution.shouldSet()) {
+ executeSet(configExecution);
+ }
+ }
+
+ public CommitStatus commitTransaction() throws DocumentedException, ValidationException, ConflictingVersionException {
+ final CommitStatus status = this.transactionProvider.commitTransaction();
+ LOG.trace("Transaction committed successfully: {}", status);
+ return status;
+ }
+
+ public CommitStatus commitSilentTransaction() throws DocumentedException, ValidationException, ConflictingVersionException {
+ final CommitStatus status = this.transactionProvider.commitTransaction(configRegistryClientNoNotifications);
+ LOG.trace("Transaction committed successfully: {}", status);
+ return status;
+ }
+
+ private void executeSet(ConfigExecution configExecution) throws DocumentedException {
+ set(configExecution);
+ LOG.debug("Set phase for {} operation successful, element: ", configExecution.getDefaultStrategy(), configExecution.getConfigElement());
+ }
+
+ private void executeTests(ConfigExecution configExecution) throws DocumentedException, ValidationException {
+ test(configExecution, configExecution.getDefaultStrategy());
+ LOG.debug("Test phase for {} operation successful, element: ", configExecution.getDefaultStrategy(), configExecution.getConfigElement());
+ }
+
+ private void test(ConfigExecution execution, EditStrategyType editStrategyType) throws ValidationException, DocumentedException {
+ ObjectName taON = transactionProvider.getTestTransaction();
+ try {
+ // default strategy = replace wipes config
+ if (editStrategyType == EditStrategyType.replace) {
+ transactionProvider.wipeTestTransaction(taON);
+ }
+
+ ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
+
+ handleMisssingInstancesOnTransaction(ta, execution);
+ setServicesOnTransaction(ta, execution);
+ setOnTransaction(ta, execution);
+ transactionProvider.validateTestTransaction(taON);
+ } finally {
+ transactionProvider.abortTestTransaction(taON);
+ }
+ }
+
+ private void set(ConfigExecution ConfigExecution) throws DocumentedException {
+ ObjectName taON = transactionProvider.getOrCreateTransaction();
+
+ // default strategy = replace wipes config
+ if (ConfigExecution.getDefaultStrategy() == EditStrategyType.replace) {
+ transactionProvider.wipeTransaction();
+ }
+
+ ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
+
+ handleMisssingInstancesOnTransaction(ta, ConfigExecution);
+ setServicesOnTransaction(ta, ConfigExecution);
+ setOnTransaction(ta, ConfigExecution);
+ }
+
+ private void setServicesOnTransaction(ConfigTransactionClient ta, ConfigExecution execution) throws DocumentedException {
+
+ Services services = execution.getServices();
+
+ Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = services
+ .getNamespaceToServiceNameToRefNameToInstance();
+
+ for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance.entrySet()) {
+ for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry : namespaceToServiceToRefEntry.getValue().entrySet()) {
+
+ String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
+ Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
+
+ for (Map.Entry<String, Services.ServiceInstance> refNameToServiceEntry : refNameToInstance.entrySet()) {
+ ObjectName on = refNameToServiceEntry.getValue().getObjectName(ta.getTransactionName());
+ try {
+ if (Services.ServiceInstance.EMPTY_SERVICE_INSTANCE == refNameToServiceEntry.getValue()) {
+ ta.removeServiceReference(qnameOfService, refNameToServiceEntry.getKey());
+ LOG.debug("Removing service {} with name {}", qnameOfService, refNameToServiceEntry.getKey());
+ } else {
+ ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(), on);
+ LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
+ on, refNameToServiceEntry.getKey(), saved);
+ }
+ } catch (InstanceNotFoundException e) {
+ throw new DocumentedException(String.format("Unable to edit ref name " + refNameToServiceEntry.getKey() + " for instance " + on, e),
+ ErrorType.application,
+ ErrorTag.operation_failed,
+ ErrorSeverity.error);
+ }
+ }
+ }
+ }
+ }
+
+ private String getQname(ConfigTransactionClient ta, String namespace, String serviceName) {
+ return ta.getServiceInterfaceName(namespace, serviceName);
+ }
+
+ private void setOnTransaction(ConfigTransactionClient ta, ConfigExecution execution) throws DocumentedException {
+
+ for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta).values()) {
+
+ for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
+ String moduleName = moduleToResolved.getKey();
+
+ ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
+ String instanceName = moduleElementResolved.getInstanceName();
+
+ InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
+ EditConfigStrategy strategy = ice.getEditStrategy();
+ strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta, execution.getServiceRegistryWrapper(ta));
+ }
+ }
+ }
+
+ private void handleMisssingInstancesOnTransaction(ConfigTransactionClient ta,
+ ConfigExecution execution) throws DocumentedException {
+
+ for (Multimap<String, ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta).values()) {
+ for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
+ String moduleName = moduleToResolved.getKey();
+
+ ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
+
+ EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
+ strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta, execution.getServiceRegistryWrapper(ta));
+ }
+ }
+ }
+
+ public Config getConfigMapping() {
+ final YangStoreContext snapshot = yangStoreService.getCurrentSnapshot();
+ Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(snapshot.getModuleMXBeanEntryMap());
+ Map<String, Map<Date, IdentityMapping>> identitiesMap = transformIdentities(snapshot.getModules());
+ return new Config(factories, identitiesMap, snapshot.getEnumResolver());
+ }
+
+ private static Map<String, Map<Date, IdentityMapping>> transformIdentities(Set<Module> modules) {
+ Map<String, Map<Date, IdentityMapping>> mappedIds = Maps.newHashMap();
+ for (Module module : modules) {
+ String namespace = module.getNamespace().toString();
+ Map<Date, IdentityMapping> revisionsByNamespace = mappedIds.get(namespace);
+ if (revisionsByNamespace == null) {
+ revisionsByNamespace = Maps.newHashMap();
+ mappedIds.put(namespace, revisionsByNamespace);
+ }
+
+ Date revision = module.getRevision();
+
+ IdentityMapping identityMapping = revisionsByNamespace.get(revision);
+ if (identityMapping == null) {
+ identityMapping = new IdentityMapping();
+ revisionsByNamespace.put(revision, identityMapping);
+ }
+
+ for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
+ identityMapping.addIdSchemaNode(identitySchemaNode);
+ }
+
+ }
+
+ return mappedIds;
+ }
+
+ public Map<String/* Namespace from yang file */,
+ Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs(
+ Map<String/* Namespace from yang file */,
+ Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
+ return transformMbeToModuleConfigs(configRegistryClient, mBeanEntries);
+ }
+
+ public Map<String/* Namespace from yang file */,
+ Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs(BeanReader reader,
+ Map<String/* Namespace from yang file */,
+ Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
+
+ Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = Maps.newHashMap();
+
+ for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mBeanEntries.entrySet()) {
+ for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
+ String moduleName = moduleNameToMbe.getKey();
+ ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
+
+ ModuleConfig moduleConfig = new ModuleConfig(moduleName,
+ new InstanceConfig(reader, moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
+
+ Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig.get(namespaceToModuleToMbe.getKey());
+ if (moduleNameToModuleConfig == null) {
+ moduleNameToModuleConfig = Maps.newHashMap();
+ namespaceToModuleNameToModuleConfig.put(namespaceToModuleToMbe.getKey(), moduleNameToModuleConfig);
+ }
+
+ moduleNameToModuleConfig.put(moduleName, moduleConfig);
+ }
+ }
+
+ return namespaceToModuleNameToModuleConfig;
+ }
+
+ public ConfigExecution getConfigExecution(final Config configMapping, final Element xmlToBePersisted) throws DocumentedException {
+ return new ConfigExecution(configMapping, XmlElement.fromDomElement(xmlToBePersisted), TestOption.testThenSet, EditStrategyType.getDefaultStrategy());
+ }
+
+ private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(ConfigRegistryClient configRegistryClient,
+ Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries) {
+ Map<String, Map<String, ModuleRuntime>> retVal = Maps.newHashMap();
+
+ for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mBeanEntries.entrySet()) {
+
+ Map<String, ModuleRuntime> innerMap = Maps.newHashMap();
+ Map<String, ModuleMXBeanEntry> entriesFromNamespace = namespaceToModuleEntry.getValue();
+ for (Map.Entry<String, ModuleMXBeanEntry> moduleToMXEntry : entriesFromNamespace.entrySet()) {
+
+ ModuleMXBeanEntry mbe = moduleToMXEntry.getValue();
+
+ Map<RuntimeBeanEntry, InstanceConfig> cache = Maps.newHashMap();
+ RuntimeBeanEntry root = null;
+ for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
+ cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap(), mbe.getNullableDummyContainerName()));
+ if (rbe.isRoot()) {
+ root = rbe;
+ }
+ }
+
+ if (root == null) {
+ continue;
+ }
+
+ InstanceRuntime rootInstanceRuntime = createInstanceRuntime(root, cache);
+ ModuleRuntime moduleRuntime = new ModuleRuntime(rootInstanceRuntime);
+ innerMap.put(moduleToMXEntry.getKey(), moduleRuntime);
+ }
+
+ retVal.put(namespaceToModuleEntry.getKey(), innerMap);
+ }
+ return retVal;
+ }
+
+ private InstanceRuntime createInstanceRuntime(RuntimeBeanEntry root, Map<RuntimeBeanEntry, InstanceConfig> cache) {
+ Map<String, InstanceRuntime> children = Maps.newHashMap();
+ for (RuntimeBeanEntry child : root.getChildren()) {
+ children.put(child.getJavaNamePrefix(), createInstanceRuntime(child, cache));
+ }
+
+ return new InstanceRuntime(cache.get(root), children, createJmxToYangMap(root.getChildren()));
+ }
+
+ private Map<String, String> createJmxToYangMap(List<RuntimeBeanEntry> children) {
+ Map<String, String> jmxToYangNamesForChildRbe = Maps.newHashMap();
+ for (RuntimeBeanEntry rbe : children) {
+ jmxToYangNamesForChildRbe.put(rbe.getJavaNamePrefix(), rbe.getYangName());
+ }
+ return jmxToYangNamesForChildRbe;
+ }
+
+ public Element get(Document document) throws DocumentedException {
+ final ObjectName testTransaction = transactionProvider.getOrCreateReadTransaction();
+ final ConfigTransactionClient txClient = configRegistryClient.getConfigTransactionClient(testTransaction);
+
+ try {
+ // Runtime beans are not parts of transactions and have to be queried against the central registry
+ final Set<ObjectName> runtimeBeans = configRegistryClient.lookupRuntimeBeans();
+
+ final Set<ObjectName> configBeans = Datastore.getInstanceQueryStrategy(Datastore.running, transactionProvider)
+ .queryInstances(configRegistryClient);
+
+ final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(configRegistryClient,
+ yangStoreService.getModuleMXBeanEntryMap());
+
+ final YangStoreContext yangStoreSnapshot = yangStoreService.getCurrentSnapshot();
+ final Map<String, Map<String, ModuleConfig>> moduleConfigs = transformMbeToModuleConfigs(txClient,
+ yangStoreSnapshot.getModuleMXBeanEntryMap());
+
+ final org.opendaylight.controller.config.facade.xml.runtime.Runtime runtime = new Runtime(moduleRuntimes, moduleConfigs);
+
+ return runtime.toXml(runtimeBeans, configBeans, document, yangStoreSnapshot.getEnumResolver());
+ } finally {
+ transactionProvider.closeReadTransaction();
+ }
+ }
+
+ public void abortConfiguration() {
+ if (transactionProvider.getTransaction().isPresent()) {
+ this.transactionProvider.abortTransaction();
+ }
+ }
+
+ public void validateConfiguration() throws ValidationException {
+ transactionProvider.validateTransaction();
+ }
+
+ @Override
+ public void close() {
+ transactionProvider.close();
+ }
+
+ public RpcFacade getRpcFacade() {
+ return rpcFacade;
+ }
+
+}
+
--- /dev/null
+package org.opendaylight.controller.config.facade.xml;
+
+import com.google.common.collect.Sets;
+import java.util.Set;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.capability.YangModuleCapability;
+import org.opendaylight.yangtools.yang.model.api.Module;
+
+public class ConfigSubsystemFacadeFactory {
+
+ private ConfigRegistryClient cfgRegClient;
+ private ConfigRegistryJMXClient cfgRegClientNoNotifications;
+ private YangStoreService yangStoreService;
+
+ public ConfigSubsystemFacadeFactory(final ConfigRegistryClient cfgRegClient, final ConfigRegistryJMXClient jmxClientNoNotifications, final YangStoreService yangStoreService) {
+ this.cfgRegClient = cfgRegClient;
+ this.cfgRegClientNoNotifications = jmxClientNoNotifications;
+ this.yangStoreService = yangStoreService;
+ }
+
+ /**
+ * Create new instance of ConfigSubsystemFacade. Each instance works with a dedicated transaction provider, making
+ * the instances suitable for facade-per-client use.
+ */
+ public ConfigSubsystemFacade createFacade(final String id) {
+ return new ConfigSubsystemFacade(cfgRegClient, cfgRegClientNoNotifications, yangStoreService, id);
+ }
+
+ public YangStoreService getYangStoreService() {
+ return yangStoreService;
+ }
+
+ public Set<Capability> getCurrentCapabilities() {
+ Set<Module> modules = yangStoreService.getModules();
+ final Set<Capability> capabilities = Sets.newHashSet();
+ for (Module module : modules) {
+ capabilities.add(new YangModuleCapability(module, yangStoreService.getModuleSource(module)));
+ }
+
+ return capabilities;
+ }
+
+
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations;
+package org.opendaylight.controller.config.facade.xml;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.CandidateDatastoreQueryStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.DatastoreQueryStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.RunningDatastoreQueryStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
+import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
public enum Datastore {
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig;
+package org.opendaylight.controller.config.facade.xml;
import java.util.Set;
import javax.management.ObjectName;
--- /dev/null
+package org.opendaylight.controller.config.facade.xml;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import javax.management.ObjectName;
+import javax.management.openmbean.OpenType;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.AttributeMappingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectMapper;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.ObjectXmlWriter;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.facade.xml.rpc.InstanceRuntimeRpc;
+import org.opendaylight.controller.config.facade.xml.rpc.ModuleRpcs;
+import org.opendaylight.controller.config.facade.xml.rpc.Rpcs;
+import org.opendaylight.controller.config.facade.xml.rpc.RuntimeRpcElementResolved;
+import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
+import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
+import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+public class RpcFacade {
+
+ public static final String CONTEXT_INSTANCE = "context-instance";
+ private YangStoreService yangStoreService;
+ private ConfigRegistryClient configRegistryClient;
+
+ public RpcFacade(final YangStoreService yangStoreService, final ConfigRegistryClient configRegistryClient) {
+ this.yangStoreService = yangStoreService;
+ this.configRegistryClient = configRegistryClient;
+ }
+
+ public Rpcs mapRpcs() {
+
+ final Map<String, Map<String, ModuleRpcs>> map = Maps.newHashMap();
+
+ for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : yangStoreService.getModuleMXBeanEntryMap().entrySet()) {
+
+ Map<String, ModuleRpcs> namespaceToModules = map.get(namespaceToModuleEntry.getKey());
+ if (namespaceToModules == null) {
+ namespaceToModules = Maps.newHashMap();
+ map.put(namespaceToModuleEntry.getKey(), namespaceToModules);
+ }
+
+ for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue().entrySet()) {
+
+ ModuleRpcs rpcMapping = namespaceToModules.get(moduleEntry.getKey());
+ if (rpcMapping == null) {
+ rpcMapping = new ModuleRpcs(yangStoreService.getEnumResolver());
+ namespaceToModules.put(moduleEntry.getKey(), rpcMapping);
+ }
+
+ final ModuleMXBeanEntry entry = moduleEntry.getValue();
+
+ for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
+ rpcMapping.addNameMapping(runtimeEntry);
+ for (final RuntimeBeanEntry.Rpc rpc : runtimeEntry.getRpcs()) {
+ rpcMapping.addRpc(runtimeEntry, rpc);
+ }
+ }
+ }
+ }
+
+ return new Rpcs(map);
+ }
+
+
+ public OperationExecution fromXml(final XmlElement xml) throws DocumentedException {
+ final String namespace;
+ namespace = xml.getNamespace();
+
+ final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
+ final String operationName = xml.getName();
+
+ final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(
+ contextInstanceElement.getTextContent(), operationName, namespace);
+
+ final Rpcs rpcs = mapRpcs();
+
+ final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
+ final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(), operationName);
+
+ // TODO move to Rpcs after xpath attribute is redesigned
+
+ final ObjectName on = id.getObjectName(rpcMapping);
+ Map<String, AttributeConfigElement> attributes = instanceRuntimeRpc.fromXml(xml);
+ attributes = sortAttributes(attributes, xml);
+
+ return new OperationExecution(on, instanceRuntimeRpc.getName(), attributes,
+ instanceRuntimeRpc.getReturnType(), namespace);
+ }
+
+ private Map<String, AttributeConfigElement> sortAttributes(
+ final Map<String, AttributeConfigElement> attributes, final XmlElement xml) {
+ final Map<String, AttributeConfigElement> sorted = Maps.newLinkedHashMap();
+
+ for (XmlElement xmlElement : xml.getChildElements()) {
+ final String name = xmlElement.getName();
+ if (!CONTEXT_INSTANCE.equals(name)) { // skip context
+ // instance child node
+ // because it
+ // specifies
+ // ObjectName
+ final AttributeConfigElement value = attributes.get(name);
+ if (value == null) {
+ throw new IllegalArgumentException("Cannot find yang mapping for node " + xmlElement);
+ }
+ sorted.put(name, value);
+ }
+ }
+
+ return sorted;
+ }
+
+ public Object executeOperation(final OperationExecution execution) {
+ final Object[] params = new Object[execution.attributes.size()];
+ final String[] signature = new String[execution.attributes.size()];
+
+ int i = 0;
+ for (final AttributeConfigElement attribute : execution.attributes.values()) {
+ final Optional<?> resolvedValueOpt = attribute.getResolvedValue();
+
+ params[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
+ signature[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName() : attribute
+ .getResolvedDefaultValue().getClass().getName();
+ i++;
+ }
+
+ return configRegistryClient.invokeMethod(execution.on, execution.operationName, params, signature);
+ }
+
+ public Element toXml(Document doc, Object result, OperationExecution execution) throws DocumentedException {
+ AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper().prepareStrategy(execution.getReturnType());
+ Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
+ Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, execution.getReturnType().getOpenType());
+
+ // FIXME: multiple return values defined as leaf-list and list in yang should not be wrapped in output xml element,
+ // they need to be appended directly under rpc-reply element
+ //
+ // Either allow List of Elements to be returned from NetconfOperation or
+ // pass reference to parent output xml element for netconf operations to
+ // append result(s) on their own
+ Element tempParent = XmlUtil.createElement(doc, "output", Optional.of(XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ new ObjectXmlWriter().prepareWritingStrategy(execution.getReturnType().getAttributeYangName(),
+ execution.getReturnType(), doc).writeElement(tempParent, execution.getNamespace(), mappedAttributeOpt.get());
+
+ XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
+ return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
+ }
+
+ public class OperationExecution {
+
+ private final ObjectName on;
+ private final String operationName;
+ private final Map<String, AttributeConfigElement> attributes;
+ private final AttributeIfc returnType;
+ private final String namespace;
+
+ public OperationExecution(final ObjectName on, final String name,
+ final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType, final String namespace) {
+ this.on = on;
+ this.operationName = name;
+ this.attributes = attributes;
+ this.returnType = returnType;
+ this.namespace = namespace;
+ }
+
+ public boolean isVoid() {
+ return returnType == VoidAttribute.getInstance();
+ }
+
+ public ObjectName getOn() {
+ return on;
+ }
+
+ public String getOperationName() {
+ return operationName;
+ }
+
+ public Map<String, AttributeConfigElement> getAttributes() {
+ return attributes;
+ }
+
+ public AttributeIfc getReturnType() {
+ return returnType;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+ }
+
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig;
+package org.opendaylight.controller.config.facade.xml;
import java.util.Set;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
public class RunningDatastoreQueryStrategy implements DatastoreQueryStrategy {
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml;
+
+import java.util.Arrays;
+
+public enum TestOption {
+ testOnly, set, testThenSet;
+
+ public static TestOption getFromXmlName(String testOptionXmlName) {
+ switch (testOptionXmlName) {
+ case "test-only":
+ return testOnly;
+ case "test-then-set":
+ return testThenSet;
+ case "set":
+ return set;
+ default:
+ throw new IllegalArgumentException("Unsupported test option " + testOptionXmlName + " supported: "
+ + Arrays.toString(TestOption.values()));
+ }
+ }
+
+ public static TestOption getDefault() {
+ return testThenSet;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.config.facade.xml.exception;
+
+import java.util.Collections;
+import java.util.Map;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+
+public class ConfigHandlingException extends DocumentedException {
+ private static final long serialVersionUID = 1L;
+
+ public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
+ }
+
+ public ConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ super(message,errorType,errorTag,errorSeverity,errorInfo);
+ }
+}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.exception;
+package org.opendaylight.controller.config.facade.xml.exception;
import java.util.Collections;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
-public class NoTransactionFoundException extends NetconfDocumentedException {
+public class NoTransactionFoundException extends DocumentedException {
private static final long serialVersionUID = 1L;
public NoTransactionFoundException(final String message, final ErrorType errorType, final ErrorTag errorTag,
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.exception;
+package org.opendaylight.controller.config.facade.xml.exception;
import java.util.Collections;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
-public class OperationNotPermittedException extends NetconfDocumentedException {
+public class OperationNotPermittedException extends DocumentedException {
private static final long serialVersionUID = 1L;
public OperationNotPermittedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml.mapping;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
+
+public class IdentityMapping {
+ private final Map<String, IdentitySchemaNode> identityNameToSchemaNode;
+
+ public IdentityMapping() {
+ this.identityNameToSchemaNode = Maps.newHashMap();
+ }
+
+ public void addIdSchemaNode(IdentitySchemaNode node) {
+ String name = node.getQName().getLocalName();
+ Preconditions.checkState(!identityNameToSchemaNode.containsKey(name));
+ identityNameToSchemaNode.put(name, node);
+ }
+
+ public boolean containsIdName(String idName) {
+ return identityNameToSchemaNode.containsKey(idName);
+ }
+
+}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeType;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import java.util.List;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
public abstract class AbstractAttributeReadingStrategy implements AttributeReadingStrategy {
}
@Override
- public AttributeConfigElement readElement(List<XmlElement> configNodes) throws NetconfDocumentedException {
+ public AttributeConfigElement readElement(List<XmlElement> configNodes) throws DocumentedException {
if (configNodes.size() == 0){
return AttributeConfigElement.createNullValue(postprocessNullableDefault(nullableDefault));
}
return readElementHook(configNodes);
}
- abstract AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException;
+ abstract AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException;
protected Object postprocessNullableDefault(String nullableDefault) {
return nullableDefault;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.collect.Lists;
import java.util.List;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
public class ArrayAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException {
List<Object> innerList = Lists.newArrayList();
EditStrategyType innerEditStrategy= null;
for (XmlElement configNode : configNodes) {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.base.Optional;
import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.AttributeResolvingStrategy;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
/**
* Parsed xml element containing configuration for one attribute of an instance
}
public void resolveValue(AttributeResolvingStrategy<?, ? extends OpenType<?>> attributeResolvingStrategy,
- String attrName) throws NetconfDocumentedException {
+ String attrName) throws DocumentedException {
resolvedValue = attributeResolvingStrategy.parseAttribute(attrName, value);
Optional<?> resolvedDefault = attributeResolvingStrategy.parseAttribute(attrName, defaultValue);
resolvedDefaultValue = resolvedDefault.isPresent() ? resolvedDefault.get() : null;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import java.util.List;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
public interface AttributeReadingStrategy {
- public abstract AttributeConfigElement readElement(List<XmlElement> element) throws NetconfDocumentedException;
+ public abstract AttributeConfigElement readElement(List<XmlElement> element) throws DocumentedException;
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
public class CompositeAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException {
Preconditions.checkState(configNodes.size() == 1, "This element should be present only once %s", configNodes);
complexElement.checkUnrecognisedElements(recognisedChildren);
- String perInstanceEditStrategy = complexElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ String perInstanceEditStrategy = complexElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return Strings.isNullOrEmpty(perInstanceEditStrategy) ? AttributeConfigElement.create(getNullableDefault(), innerMap) :
AttributeConfigElement.create(getNullableDefault(), innerMap, EditStrategyType.valueOf(perInstanceEditStrategy));
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
public class ObjectNameAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException {
XmlElement firstChild = configNodes.get(0);
Preconditions.checkState(configNodes.size() == 1, "This element should be present only once " + firstChild
return AttributeConfigElement.create(getNullableDefault(), resolve(firstChild));
}
- private ObjectNameAttributeMappingStrategy.MappedDependency resolve(XmlElement firstChild) throws NetconfDocumentedException{
- XmlElement typeElement = firstChild.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
+ private ObjectNameAttributeMappingStrategy.MappedDependency resolve(XmlElement firstChild) throws DocumentedException{
+ XmlElement typeElement = firstChild.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
Map.Entry<String, String> prefixNamespace = typeElement.findNamespaceOfTextContent();
String serviceName = checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
- XmlElement nameElement = firstChild.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
+ XmlElement nameElement = firstChild.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY);
String dependencyName = nameElement.getTextContent();
return new ObjectNameAttributeMappingStrategy.MappedDependency(prefixNamespace.getValue(), serviceName,
dependencyName);
}
- public static String checkPrefixAndExtractServiceName(XmlElement typeElement, Map.Entry<String, String> prefixNamespace) throws NetconfDocumentedException {
+ public static String checkPrefixAndExtractServiceName(XmlElement typeElement, Map.Entry<String, String> prefixNamespace) throws DocumentedException {
String serviceName = typeElement.getTextContent();
Preconditions.checkNotNull(prefixNamespace.getKey(), "Service %s value cannot be linked to namespace",
- XmlNetconfConstants.TYPE_KEY);
+ XmlMappingConstants.TYPE_KEY);
if(prefixNamespace.getKey().isEmpty()) {
return serviceName;
} else {
String prefix = prefixNamespace.getKey() + PREFIX_SEPARATOR;
Preconditions.checkState(serviceName.startsWith(prefix),
- "Service %s not correctly prefixed, expected %s, but was %s", XmlNetconfConstants.TYPE_KEY, prefix,
+ "Service %s not correctly prefixed, expected %s, but was %s", XmlMappingConstants.TYPE_KEY, prefix,
serviceName);
serviceName = serviceName.substring(prefix.length());
return serviceName;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
public class ObjectXmlReader extends AttributeIfcSwitchStatement<AttributeReadingStrategy> {
private String key;
- private Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap;
+ private Map<String, Map<Date, IdentityMapping>> identityMap;
- public Map<String, AttributeReadingStrategy> prepareReading(Map<String, AttributeIfc> yangToAttrConfig, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) {
+ public Map<String, AttributeReadingStrategy> prepareReading(Map<String, AttributeIfc> yangToAttrConfig, Map<String, Map<Date, IdentityMapping>> identityMap) {
Map<String, AttributeReadingStrategy> strategies = Maps.newHashMap();
this.identityMap = identityMap;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
import java.util.List;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
public class SimpleAttributeReadingStrategy extends AbstractAttributeReadingStrategy {
public SimpleAttributeReadingStrategy(String nullableDefault) {
}
@Override
- AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws NetconfDocumentedException {
+ AttributeConfigElement readElementHook(List<XmlElement> configNodes) throws DocumentedException {
XmlElement xmlElement = configNodes.get(0);
Preconditions.checkState(configNodes.size() == 1, "This element should be present only once " + xmlElement
+ " but was " + configNodes.size());
postprocessParsedValue(textContent));
}
- protected String readElementContent(XmlElement xmlElement) throws NetconfDocumentedException {
+ protected String readElementContent(XmlElement xmlElement) throws DocumentedException {
return xmlElement.getTextContent();
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.collect.Lists;
import com.google.common.io.BaseEncoding;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.collect.Maps;
import java.util.HashMap;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.yangtools.yang.common.QName;
public class SimpleIdentityRefAttributeReadingStrategy extends SimpleAttributeReadingStrategy {
private final String key;
- private final Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap;
+ private final Map<String, Map<Date, IdentityMapping>> identityMap;
- public SimpleIdentityRefAttributeReadingStrategy(String nullableDefault, String key, Map<String, Map<Date,EditConfig.IdentityMapping>> identityMap) {
+ public SimpleIdentityRefAttributeReadingStrategy(String nullableDefault, String key, Map<String, Map<Date, IdentityMapping>> identityMap) {
super(nullableDefault);
this.key = key;
this.identityMap = identityMap;
}
@Override
- protected String readElementContent(XmlElement xmlElement) throws NetconfDocumentedException {
+ protected String readElementContent(XmlElement xmlElement) throws DocumentedException {
Map.Entry<String, String> namespaceOfTextContent = xmlElement.findNamespaceOfTextContent();
String content = xmlElement.getTextContent();
}
Date revision = null;
- Map<Date, EditConfig.IdentityMapping> revisions = identityMap.get(namespace);
+ Map<Date, IdentityMapping> revisions = identityMap.get(namespace);
if(revisions.keySet().size() > 1) {
- for (Map.Entry<Date, EditConfig.IdentityMapping> revisionToIdentityEntry : revisions.entrySet()) {
+ for (Map.Entry<Date, IdentityMapping> revisionToIdentityEntry : revisions.entrySet()) {
if(revisionToIdentityEntry.getValue().containsIdName(localName)) {
Preconditions.checkState(revision == null, "Duplicate identity %s, in namespace %s, with revisions: %s, %s detected. Cannot map attribute",
localName, namespace, revision, revisionToIdentityEntry.getKey());
} else {
revision = revisions.keySet().iterator().next();
}
-
return QName.create(URI.create(namespace), revision, localName).toString();
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import javax.management.openmbean.OpenType;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import javax.management.openmbean.OpenType;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
public class CompositeAttributeMappingStrategy extends
AbstractAttributeMappingStrategy<Map<String, Object>, CompositeType> {
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import javax.management.openmbean.CompositeType;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
public class EnumAttributeMappingStrategy extends AbstractAttributeMappingStrategy<String, CompositeType> {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
public class ObjectMapper extends AttributeIfcSwitchStatement<AttributeMappingStrategy<?, ? extends OpenType<?>>> {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import javax.management.ObjectName;
import javax.management.openmbean.SimpleType;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
import org.opendaylight.yangtools.yang.common.QName;
public class ObjectNameAttributeMappingStrategy extends
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Date;
import java.util.Map;
import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
public class SimpleAttributeMappingStrategy extends AbstractAttributeMappingStrategy<String, SimpleType<?>> {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping;
import com.google.common.base.Optional;
import java.util.Map;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import javax.management.openmbean.OpenType;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Optional;
import java.lang.reflect.Array;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
@Override
- public Optional<Object> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
+ public Optional<Object> parseAttribute(String attrName, Object value) throws DocumentedException {
if (value == null) {
return Optional.absent();
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Optional;
import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
/**
* Create real object from String or Map that corresponds to given opentype.
public interface AttributeResolvingStrategy<T, O extends OpenType<?>> {
O getOpenType();
- Optional<T> parseAttribute(String attrName, Object value) throws NetconfDocumentedException;
+ Optional<T> parseAttribute(String attrName, Object value) throws DocumentedException;
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
@Override
- public Optional<CompositeDataSupport> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
+ public Optional<CompositeDataSupport> parseAttribute(String attrName, Object value) throws DocumentedException {
if (value == null) {
return Optional.absent();
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Map;
import javax.management.openmbean.CompositeType;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
@Override
- public Optional<Object> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
+ public Optional<Object> parseAttribute(String attrName, Object value) throws DocumentedException {
if (value == null) {
return Optional.absent();
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Optional;
import javax.management.ObjectName;
import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.facade.xml.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.AttributeIfcSwitchStatement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
public class ObjectResolver extends AttributeIfcSwitchStatement<AttributeResolvingStrategy<?, ? extends OpenType<?>>> {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import java.util.Date;
import java.util.Map;
import javax.management.openmbean.SimpleType;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
@Override
- public Optional<Object> parseAttribute(String attrName, Object value) throws NetconfDocumentedException {
+ public Optional<Object> parseAttribute(String attrName, Object value) throws DocumentedException {
if (value == null) {
return Optional.absent();
}
}
static interface Resolver {
- Object resolveObject(Class<?> type, String attrName, String value) throws NetconfDocumentedException;
+ Object resolveObject(Class<?> type, String attrName, String value) throws DocumentedException;
}
static class DefaultResolver implements Resolver {
@Override
- public Object resolveObject(Class<?> type, String attrName, String value) throws NetconfDocumentedException {
+ public Object resolveObject(Class<?> type, String attrName, String value) throws DocumentedException {
try {
return parseObject(type, value);
} catch (Exception e) {
- throw new NetconfDocumentedException("Unable to resolve attribute " + attrName + " from " + value,
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Unable to resolve attribute " + attrName + " from " + value,
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
- protected Object parseObject(Class<?> type, String value) throws NetconfDocumentedException {
+ protected Object parseObject(Class<?> type, String value) throws DocumentedException {
Method method = null;
try {
method = type.getMethod("valueOf", String.class);
return method.invoke(null, value);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
LOG.trace("Error parsing object ",e);
- throw new NetconfDocumentedException("Error parsing object.",
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Error parsing object.",
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
}
static class DateResolver extends DefaultResolver {
@Override
- protected Object parseObject(Class<?> type, String value) throws NetconfDocumentedException {
+ protected Object parseObject(Class<?> type, String value) throws DocumentedException {
try {
return Util.readDate(value);
} catch (ParseException e) {
LOG.trace("Unable parse value {} due to ",value, e);
- throw new NetconfDocumentedException("Unable to parse value "+value+" as date.",
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Unable to parse value "+value+" as date.",
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import java.util.List;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
import org.w3c.dom.Element;
public class ArrayAttributeWritingStrategy implements AttributeWritingStrategy {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import org.w3c.dom.Element;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Optional;
import java.util.Map;
import java.util.Map.Entry;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectNameAttributeMappingStrategy;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
String refName = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getRefName();
String namespaceForType = ((ObjectNameAttributeMappingStrategy.MappedDependency) value).getNamespace();
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlNetconfConstants.TYPE_KEY, XmlNetconfConstants.PREFIX,
+ Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY, XmlMappingConstants.PREFIX,
namespaceForType, moduleName);
innerNode.appendChild(typeElement);
- final Element nameElement = XmlUtil.createTextElement(document, XmlNetconfConstants.NAME_KEY, refName, Optional.<String>absent());
+ final Element nameElement = XmlUtil.createTextElement(document, XmlMappingConstants.NAME_KEY, refName, Optional.<String>absent());
innerNode.appendChild(nameElement);
parentElement.appendChild(innerNode);
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.AttributeIfcSwitchStatement;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.AttributeIfcSwitchStatement;
import org.w3c.dom.Document;
public class ObjectXmlWriter extends AttributeIfcSwitchStatement<AttributeWritingStrategy> {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Optional;
import java.util.Map;
import java.util.Map.Entry;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
super(document, key, innerStrats);
}
- /*
- * (non-Javadoc)
- *
- * @see org.opendaylight.controller.config.netconf.mapping.attributes.toxml.
- * AttributeWritingStrategy#writeElement(org.w3c.dom.Element,
- * java.lang.Object)
- */
@Override
public void writeElement(Element parentElement, String namespace, Object value) {
Util.checkType(value, Map.class);
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Preconditions;
import com.google.common.io.BaseEncoding;
import java.util.List;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
import org.w3c.dom.Document;
public class SimpleBinaryAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Preconditions;
import java.util.Map;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
import org.w3c.dom.Document;
public class SimpleCompositeAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Map;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.common.QName;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml;
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.Map;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
import org.w3c.dom.Document;
public class SimpleUnionAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
import static com.google.common.base.Preconditions.checkState;
import java.util.Set;
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
private final Map<String/* Namespace from yang file */,
Map<String /* Name of module entry from yang file */, ModuleConfig>> moduleConfigs;
- private final Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap;
+ private final Map<String, Map<Date, IdentityMapping>> identityMap;
private final EnumResolver enumResolver;
public Config(Map<String, Map<String, ModuleConfig>> moduleConfigs, final EnumResolver enumResolver) {
- this(moduleConfigs, Collections.<String, Map<Date, EditConfig.IdentityMapping>>emptyMap(), enumResolver);
+ this(moduleConfigs, Collections.<String, Map<Date, IdentityMapping>>emptyMap(), enumResolver);
}
- public Config(Map<String, Map<String, ModuleConfig>> moduleConfigs, Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap, final EnumResolver enumResolver) {
+ public Config(Map<String, Map<String, ModuleConfig>> moduleConfigs, Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) {
this.moduleConfigs = moduleConfigs;
this.identityMap = identityMap;
this.enumResolver = enumResolver;
dataElement.setAttributeNS(maybeNamespace.get(), dataElement.getNodeName(), "xmlns");
}
- Element modulesElement = XmlUtil.createElement(document, XmlNetconfConstants.MODULES_KEY, Optional.of(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
+ Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
dataElement.appendChild(modulesElement);
for (Entry<String, Map<String, Collection<ObjectName>>> moduleToInstanceEntry : moduleToInstances.entrySet()) {
for (Entry<String, Collection<ObjectName>> moduleMappingEntry : moduleToInstanceEntry.getValue()
// TODO refactor, replace Map->Multimap with e.g. ConfigElementResolved
// class
- public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(XmlElement xml, EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws NetconfDocumentedException {
+ public Map<String, Multimap<String, ModuleElementResolved>> fromXmlModulesResolved(XmlElement xml, EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws DocumentedException {
Optional<XmlElement> modulesElement = getModulesElement(xml);
List<XmlElement> moduleElements = getModulesElementList(modulesElement);
for (XmlElement moduleElement : moduleElements) {
ResolvingStrategy<ModuleElementResolved> resolvingStrategy = new ResolvingStrategy<ModuleElementResolved>() {
@Override
- public ModuleElementResolved resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker, String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws NetconfDocumentedException {
+ public ModuleElementResolved resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker, String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws DocumentedException {
return moduleMapping.fromXml(moduleElement, serviceTracker,
instanceName, moduleNamespace, defaultStrategy, identityMap, enumResolver);
}
* return a map containing namespace -> moduleName -> instanceName map. Attribute parsing is omitted.
*/
public Map<String, Multimap<String, ModuleElementDefinition>> fromXmlModulesMap(XmlElement xml,
- EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws NetconfDocumentedException {
+ EditStrategyType defaultEditStrategyType, ServiceRegistryWrapper serviceTracker) throws DocumentedException {
Optional<XmlElement> modulesElement = getModulesElement(xml);
List<XmlElement> moduleElements = getModulesElementList(modulesElement);
EditStrategyType defaultStrategy) {
// TODO: add check for conflicts between global and local
// edit strategy
- String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ String perInstanceEditStrategy = moduleElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return new ModuleElementDefinition(instanceName, perInstanceEditStrategy, defaultStrategy);
}
};
}
private static Optional<XmlElement> getModulesElement(XmlElement xml) {
- return xml.getOnlyChildElementOptionally(XmlNetconfConstants.MODULES_KEY,
- XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ return xml.getOnlyChildElementOptionally(XmlMappingConstants.MODULES_KEY,
+ XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
- private List<XmlElement> getModulesElementList(Optional<XmlElement> modulesElement) throws NetconfDocumentedException {
+ private List<XmlElement> getModulesElementList(Optional<XmlElement> modulesElement) throws DocumentedException {
List<XmlElement> moduleElements;
if (modulesElement.isPresent()) {
- moduleElements = modulesElement.get().getChildElementsWithSameNamespace(XmlNetconfConstants.MODULE_KEY);
+ moduleElements = modulesElement.get().getChildElementsWithSameNamespace(XmlMappingConstants.MODULE_KEY);
modulesElement.get().checkUnrecognisedElements(moduleElements);
} else {
moduleElements = Lists.newArrayList();
}
private <T> void resolveModule(Map<String, Multimap<String, T>> retVal, ServiceRegistryWrapper serviceTracker,
- XmlElement moduleElement, EditStrategyType defaultStrategy, ResolvingStrategy<T> resolvingStrategy) throws NetconfDocumentedException {
+ XmlElement moduleElement, EditStrategyType defaultStrategy, ResolvingStrategy<T> resolvingStrategy) throws DocumentedException {
XmlElement typeElement = null;
- typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
+ typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
Entry<String, String> prefixToNamespace = typeElement.findNamespaceOfTextContent();
String moduleNamespace = prefixToNamespace.getValue();
XmlElement nameElement = null;
- nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
+ nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY);
String instanceName = nameElement.getTextContent();
String factoryNameWithPrefix = typeElement.getTextContent();
String prefixOrEmptyString = prefixToNamespace.getKey();
innerMap.put(factoryName, resolvedElement);
}
- public Services fromXmlServices(XmlElement xml) throws NetconfDocumentedException {
+ public Services fromXmlServices(XmlElement xml) throws DocumentedException {
Optional<XmlElement> servicesElement = getServicesElement(xml);
Services services;
}
private static Optional<XmlElement> getServicesElement(XmlElement xml) {
- return xml.getOnlyChildElementOptionally(XmlNetconfConstants.SERVICES_KEY,
- XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ return xml.getOnlyChildElementOptionally(XmlMappingConstants.SERVICES_KEY,
+ XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
- public static void checkUnrecognisedChildren(XmlElement parent) throws NetconfDocumentedException {
+ public static void checkUnrecognisedChildren(XmlElement parent) throws DocumentedException {
Optional<XmlElement> servicesOpt = getServicesElement(parent);
Optional<XmlElement> modulesOpt = getModulesElement(parent);
private interface ResolvingStrategy<T> {
public T resolveElement(ModuleConfig moduleMapping, XmlElement moduleElement, ServiceRegistryWrapper serviceTracker,
- String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws NetconfDocumentedException;
+ String instanceName, String moduleNamespace, EditStrategyType defaultStrategy) throws DocumentedException;
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import java.util.Map.Entry;
import javax.management.ObjectName;
import javax.management.openmbean.OpenType;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeReadingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.ObjectXmlReader;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.AttributeMappingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.mapping.ObjectMapper;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.AttributeResolvingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.ObjectResolver;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.AttributeWritingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.toxml.ObjectXmlWriter;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
import org.opendaylight.controller.config.util.BeanReader;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.ObjectResolver;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.AttributeWritingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
public InstanceConfigElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper services, String moduleNamespace,
EditStrategyType defaultStrategy,
- Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap, final EnumResolver enumResolver) throws NetconfDocumentedException {
+ Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) throws DocumentedException {
Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig, identityMap);
List<XmlElement> recognisedChildren = Lists.newArrayList();
- XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.TYPE_KEY);
- XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.NAME_KEY);
+ XmlElement typeElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.TYPE_KEY);
+ XmlElement nameElement = moduleElement.getOnlyChildElementWithSameNamespace(XmlMappingConstants.NAME_KEY);
List<XmlElement> typeAndNameElements = Lists.newArrayList(typeElement, nameElement);
// if dummy container was defined in yang, set moduleElement to its content
int size = moduleElement.getChildElements().size();
int expectedChildNodes = 1 + typeAndNameElements.size();
if (size > expectedChildNodes) {
- throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
+ throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
nameElement.getTextContent() + " - Expected " + expectedChildNodes +" child nodes, " +
"one of them with name " + nullableDummyContainerName +
", got " + size + " elements.");
if (size == expectedChildNodes) {
try {
moduleElement = moduleElement.getOnlyChildElement(nullableDummyContainerName, moduleNamespace);
- } catch (NetconfDocumentedException e) {
- throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
+ } catch (DocumentedException e) {
+ throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
nameElement.getTextContent() + " - Expected child node with name " + nullableDummyContainerName +
"." + e.getMessage());
}
recognisedChildren.addAll(typeAndNameElements);
try {
moduleElement.checkUnrecognisedElements(recognisedChildren);
- } catch (NetconfDocumentedException e) {
- throw new NetconfDocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
+ } catch (DocumentedException e) {
+ throw new DocumentedException("Error reading module " + typeElement.getTextContent() + " : " +
nameElement.getTextContent() + " - " +
e.getMessage(), e.getErrorType(), e.getErrorTag(),e.getErrorSeverity(),e.getErrorInfo());
}
// TODO: add check for conflicts between global and local edit strategy
- String perInstanceEditStrategy = moduleElement.getAttribute(XmlNetconfConstants.OPERATION_ATTR_KEY,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+ String perInstanceEditStrategy = moduleElement.getAttribute(XmlMappingConstants.OPERATION_ATTR_KEY,
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
InstanceConfigElementResolved instanceConfigElementResolved = perInstanceEditStrategy.equals("") ? new InstanceConfigElementResolved(
retVal, defaultStrategy) : new InstanceConfigElementResolved(perInstanceEditStrategy, retVal, defaultStrategy);
}
private List<XmlElement> getConfigNodes(XmlElement moduleElement, String moduleNamespace, String name,
- List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws NetconfDocumentedException {
+ List<XmlElement> recognisedChildren, List<XmlElement> typeAndName) throws DocumentedException {
List<XmlElement> foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name, moduleNamespace);
if (foundConfigNodes.isEmpty()) {
LOG.debug("No config nodes {}:{} found in {}", moduleNamespace, name, moduleElement);
LOG.debug("Trying lookup of config nodes without specified namespace");
foundConfigNodes = moduleElement.getChildElementsWithinNamespace(name,
- XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
// In case module type or name element is not present in config it
// would be matched with config type or name
// We need to remove config type and name from available module
moduleElement);
} else {
List<XmlElement> foundWithoutNamespaceNodes = moduleElement.getChildElementsWithinNamespace(name,
- XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
foundWithoutNamespaceNodes.removeAll(typeAndName);
if (!foundWithoutNamespaceNodes.isEmpty()){
- throw new NetconfDocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
+ throw new DocumentedException(String.format("Element %s present multiple times with different namespaces: %s, %s", name, foundConfigNodes,
foundWithoutNamespaceNodes),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.OperationNotPermittedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
+import org.opendaylight.controller.config.facade.xml.exception.OperationNotPermittedException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
/**
* Parsed xml element containing whole configuration for an instance of some
public InstanceConfigElementResolved(String currentStrategy, Map<String, AttributeConfigElement> configuration,
EditStrategyType defaultStrategy)
- throws NetconfDocumentedException {
+ throws DocumentedException {
this.editStrategy = parseStrategy(currentStrategy, defaultStrategy);
this.configuration = configuration;
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
import com.google.common.base.Optional;
import java.util.Date;
import java.util.Map;
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
public Element toXml(ObjectName instanceON, Document document, String namespace, final EnumResolver enumResolver) {
- Element root = XmlUtil.createElement(document, XmlNetconfConstants.MODULE_KEY, Optional.<String>absent());
+ Element root = XmlUtil.createElement(document, XmlMappingConstants.MODULE_KEY, Optional.<String>absent());
// type belongs to config.yang namespace, but needs to be <type prefix:moduleNS>prefix:moduleName</type>
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlNetconfConstants.TYPE_KEY,
- XmlNetconfConstants.PREFIX, namespace, moduleName);
+ Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY,
+ XmlMappingConstants.PREFIX, namespace, moduleName);
root.appendChild(typeElement);
// name belongs to config.yang namespace
String instanceName = ObjectNameUtil.getInstanceName(instanceON);
- Element nameElement = XmlUtil.createTextElement(document, XmlNetconfConstants.NAME_KEY, instanceName, Optional.<String>absent());
+ Element nameElement = XmlUtil.createTextElement(document, XmlMappingConstants.NAME_KEY, instanceName, Optional.<String>absent());
root.appendChild(nameElement);
}
public ModuleElementResolved fromXml(XmlElement moduleElement, ServiceRegistryWrapper depTracker, String instanceName,
- String moduleNamespace, EditStrategyType defaultStrategy, Map<String, Map<Date, EditConfig.IdentityMapping>> identityMap, final EnumResolver enumResolver) throws NetconfDocumentedException {
+ String moduleNamespace, EditStrategyType defaultStrategy, Map<String, Map<Date, IdentityMapping>> identityMap, final EnumResolver enumResolver) throws DocumentedException {
InstanceConfigElementResolved ice = instanceConfig.fromXml(moduleElement, depTracker, moduleNamespace, defaultStrategy, identityMap, enumResolver);
return new ModuleElementResolved(instanceName, ice);
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.OperationNotPermittedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditStrategyType;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.MissingInstanceHandlingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.NoneEditConfigStrategy;
+import org.opendaylight.controller.config.facade.xml.exception.OperationNotPermittedException;
+import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.facade.xml.strategy.MissingInstanceHandlingStrategy;
+import org.opendaylight.controller.config.facade.xml.strategy.NoneEditConfigStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
public class ModuleElementResolved {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+
+package org.opendaylight.controller.config.facade.xml.mapping.config;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.config;
+package org.opendaylight.controller.config.facade.xml.mapping.config;
+
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.regex.Pattern;
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.ObjectNameAttributeReadingStrategy;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
// TODO support edit strategies on services
- public static Services fromXml(XmlElement xml) throws NetconfDocumentedException {
+ public static Services fromXml(XmlElement xml) throws DocumentedException {
Map<String, Map<String, Map<String, String>>> retVal = Maps.newHashMap();
List<XmlElement> services = xml.getChildElements(SERVICE_KEY);
retVal.put(prefixNamespace.getValue(), namespaceToServices);
}
- String serviceName = ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
+ String serviceName = ObjectNameAttributeReadingStrategy
+ .checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
Map<String, String> innerMap = namespaceToServices.get(serviceName);
if (innerMap == null) {
namespaceToServices.put(serviceName, innerMap);
}
- List<XmlElement> instances = service.getChildElements(XmlNetconfConstants.INSTANCE_KEY);
+ List<XmlElement> instances = service.getChildElements(XmlMappingConstants.INSTANCE_KEY);
service.checkUnrecognisedElements(instances, typeElement);
for (XmlElement instance : instances) {
if (!ModifyAction.DELETE.toString().toLowerCase().equals(
instance.getAttribute(
- XmlNetconfConstants.OPERATION_ATTR_KEY,
- XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)))
+ XmlMappingConstants.OPERATION_ATTR_KEY,
+ XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)))
{
XmlElement providerElement = instance.getOnlyChildElement(PROVIDER_KEY);
String providerName = providerElement.getTextContent();
}
public static Element toXml(ServiceRegistryWrapper serviceRegistryWrapper, Document document) {
- Element root = XmlUtil.createElement(document, XmlNetconfConstants.SERVICES_KEY, Optional.of(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
+ Element root = XmlUtil.createElement(document, XmlMappingConstants.SERVICES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
Map<String, Map<String, Map<String, String>>> mappedServices = serviceRegistryWrapper.getMappedServices();
for (Entry<String, Map<String, Map<String, String>>> namespaceToRefEntry : mappedServices.entrySet()) {
// type belongs to config.yang namespace
String serviceType = serviceEntry.getKey();
- Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlNetconfConstants.TYPE_KEY,
- XmlNetconfConstants.PREFIX, namespaceToRefEntry.getKey(), serviceType);
+ Element typeElement = XmlUtil.createTextElementWithNamespacedContent(document, XmlMappingConstants.TYPE_KEY,
+ XmlMappingConstants.PREFIX, namespaceToRefEntry.getKey(), serviceType);
serviceElement.appendChild(typeElement);
for (Entry<String, String> instanceEntry : serviceEntry.getValue().entrySet()) {
- Element instanceElement = XmlUtil.createElement(document, XmlNetconfConstants.INSTANCE_KEY, Optional.<String>absent());
+ Element instanceElement = XmlUtil.createElement(document, XmlMappingConstants.INSTANCE_KEY, Optional.<String>absent());
serviceElement.appendChild(instanceElement);
Element nameElement = XmlUtil.createTextElement(document, NAME_KEY, instanceEntry.getKey(), Optional.<String>absent());
}
private static final String blueprint = "/"
- + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "["
- + XmlNetconfConstants.TYPE_KEY + "='%s']["
- + XmlNetconfConstants.NAME_KEY + "='%s']";
+ + XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "["
+ + XmlMappingConstants.TYPE_KEY + "='%s']["
+ + XmlMappingConstants.NAME_KEY + "='%s']";
// TODO unify with xpath in RuntimeRpc
// Previous version of xpath, needs to be supported for backwards compatibility (persisted configs by config-persister)
- private static final String blueprintRDeprecated = "/" + XmlNetconfConstants.CONFIG_KEY + "/"
- + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "\\["
- + XmlNetconfConstants.NAME_KEY + "='%s'\\]/" + XmlNetconfConstants.INSTANCE_KEY + "\\["
- + XmlNetconfConstants.NAME_KEY + "='%s'\\]";
+ private static final String blueprintRDeprecated = "/" + XmlMappingConstants.CONFIG_KEY + "/"
+ + XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "\\["
+ + XmlMappingConstants.NAME_KEY + "='%s'\\]/" + XmlMappingConstants.INSTANCE_KEY + "\\["
+ + XmlMappingConstants.NAME_KEY + "='%s'\\]";
private static final String blueprintR = "/"
- + XmlNetconfConstants.MODULES_KEY + "/" + XmlNetconfConstants.MODULE_KEY + "\\["
- + XmlNetconfConstants.TYPE_KEY + "='%s'\\]\\["
- + XmlNetconfConstants.NAME_KEY + "='%s'\\]";
+ + XmlMappingConstants.MODULES_KEY + "/" + XmlMappingConstants.MODULE_KEY + "\\["
+ + XmlMappingConstants.TYPE_KEY + "='%s'\\]\\["
+ + XmlMappingConstants.NAME_KEY + "='%s'\\]";
private static final Pattern pDeprecated = Pattern.compile(String.format(blueprintRDeprecated, "(.+)", "(.+)"));
private static final Pattern p = Pattern.compile(String.format(blueprintR, "(.+)", "(.+)"));
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
+package org.opendaylight.controller.config.facade.xml.osgi;
public interface EnumResolver {
--- /dev/null
+ /*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml.osgi;
+
+import java.lang.management.ManagementFactory;
+import java.util.Hashtable;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.management.MBeanServer;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Start yang store service and the XML config manager facade
+ */
+public class YangStoreActivator implements BundleActivator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(YangStoreActivator.class);
+
+ private final MBeanServer configMBeanServer = ManagementFactory.getPlatformMBeanServer();
+
+ private ServiceRegistration<YangStoreService> yangStoreServiceServiceRegistration;
+ private ConfigRegistryLookupThread configRegistryLookup = null;
+ private BundleContext context;
+ private ServiceRegistration<ConfigSubsystemFacadeFactory> osgiRegistrayion;
+
+ @Override
+ public void start(final BundleContext context) throws Exception {
+ LOG.debug("ConfigPersister starting");
+ this.context = context;
+
+ ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<SchemaContextProvider, YangStoreService>() {
+
+ private final AtomicBoolean alreadyStarted = new AtomicBoolean(false);
+
+ @Override
+ public YangStoreService addingService(ServiceReference<SchemaContextProvider> reference) {
+ LOG.debug("Got addingService(SchemaContextProvider) event");
+
+ // Yang store service should not be registered multiple times
+ if(!alreadyStarted.compareAndSet(false, true)) {
+ LOG.warn("Starting yang store service multiple times. Received new service {}", reference);
+ throw new RuntimeException("Starting yang store service multiple times");
+ }
+ SchemaContextProvider schemaContextProvider = reference.getBundle().getBundleContext().getService(reference);
+ final YangStoreService yangStoreService = new YangStoreService(schemaContextProvider);
+ yangStoreServiceServiceRegistration = context.registerService(YangStoreService.class, yangStoreService, new Hashtable<String, Object>());
+ configRegistryLookup = new ConfigRegistryLookupThread(yangStoreService);
+ configRegistryLookup.start();
+ return yangStoreService;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<SchemaContextProvider> reference, YangStoreService service) {
+ LOG.debug("Got modifiedService(SchemaContextProvider) event");
+ final BindingRuntimeContext runtimeContext = (BindingRuntimeContext) reference.getProperty(BindingRuntimeContext.class.getName());
+ LOG.debug("BindingRuntimeContext retrieved as {}", runtimeContext);
+ service.refresh(runtimeContext);
+ }
+
+ @Override
+ public void removedService(ServiceReference<SchemaContextProvider> reference, YangStoreService service) {
+ LOG.debug("Got removedService(SchemaContextProvider) event");
+ alreadyStarted.set(false);
+ configRegistryLookup.interrupt();
+ yangStoreServiceServiceRegistration.unregister();
+ yangStoreServiceServiceRegistration = null;
+ }
+ };
+
+ ServiceTracker<SchemaContextProvider, YangStoreService> schemaContextProviderServiceTracker =
+ new ServiceTracker<>(context, SchemaContextProvider.class, schemaServiceTrackerCustomizer);
+ schemaContextProviderServiceTracker.open();
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ if(configRegistryLookup != null) {
+ configRegistryLookup.interrupt();
+ }
+ if(osgiRegistrayion != null) {
+ osgiRegistrayion.unregister();
+ }
+ if (yangStoreServiceServiceRegistration != null) {
+ yangStoreServiceServiceRegistration.unregister();
+ yangStoreServiceServiceRegistration = null;
+ }
+ }
+
+ /**
+ * Find ConfigRegistry from config manager in JMX
+ */
+ private class ConfigRegistryLookupThread extends Thread {
+ public static final int ATTEMPT_TIMEOUT_MS = 1000;
+ private static final int SILENT_ATTEMPTS = 30;
+
+ private final YangStoreService yangStoreService;
+
+ private ConfigRegistryLookupThread(YangStoreService yangStoreService) {
+ super("config-registry-lookup");
+ this.yangStoreService = yangStoreService;
+ }
+
+ @Override
+ public void run() {
+
+ ConfigRegistryJMXClient configRegistryJMXClient;
+ ConfigRegistryJMXClient configRegistryJMXClientNoNotifications;
+ int i = 0;
+ // Config registry might not be present yet, but will be eventually
+ while(true) {
+
+ try {
+ configRegistryJMXClient = new ConfigRegistryJMXClient(configMBeanServer);
+ configRegistryJMXClientNoNotifications = ConfigRegistryJMXClient.createWithoutNotifications(configMBeanServer);
+ break;
+ } catch (IllegalStateException e) {
+ ++i;
+ if (i > SILENT_ATTEMPTS) {
+ LOG.info("JMX client not created after {} attempts, still trying", i, e);
+ } else {
+ LOG.debug("JMX client could not be created, reattempting, try {}", i, e);
+ }
+ try {
+ Thread.sleep(ATTEMPT_TIMEOUT_MS);
+ } catch (InterruptedException e1) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted while reattempting connection", e1);
+ }
+ }
+ }
+
+ final ConfigRegistryJMXClient jmxClient = configRegistryJMXClient;
+ final ConfigRegistryJMXClient jmxClientNoNotifications = configRegistryJMXClientNoNotifications;
+ if (i > SILENT_ATTEMPTS) {
+ LOG.info("Created JMX client after {} attempts", i);
+ } else {
+ LOG.debug("Created JMX client after {} attempts", i);
+ }
+
+ final ConfigSubsystemFacadeFactory configSubsystemFacade =
+ new ConfigSubsystemFacadeFactory(jmxClient, jmxClientNoNotifications, yangStoreService);
+ osgiRegistrayion = context.registerService(ConfigSubsystemFacadeFactory.class, configSubsystemFacade, new Hashtable<String, Object>());
+ }
+ }
+}
+
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
+package org.opendaylight.controller.config.facade.xml.osgi;
import java.util.Map;
import java.util.Set;
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml.osgi;
+
+import com.google.common.collect.Sets;
+import java.lang.ref.SoftReference;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicReference;
+import org.opendaylight.controller.config.util.capability.ModuleListener;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class YangStoreService implements YangStoreContext {
+
+ private static final Logger LOG = LoggerFactory.getLogger(YangStoreService.class);
+
+ /**
+ * This is a rather interesting locking model. We need to guard against both the
+ * cache expiring from GC and being invalidated by schema context change. The
+ * context can change while we are doing processing, so we do not want to block
+ * it, so no synchronization can happen on the methods.
+ *
+ * So what we are doing is the following:
+ *
+ * We synchronize with GC as usual, using a SoftReference.
+ *
+ * The atomic reference is used to synchronize with {@link #refresh(org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext)}, e.g. when
+ * refresh happens, it will push a SoftReference(null), e.g. simulate the GC. Now
+ * that may happen while the getter is already busy acting on the old schema context,
+ * so it needs to understand that a refresh has happened and retry. To do that, it
+ * attempts a CAS operation -- if it fails, in knows that the SoftReference has
+ * been replaced and thus it needs to retry.
+ *
+ * Note that {@link #getYangStoreSnapshot()} will still use synchronize() internally
+ * to stop multiple threads doing the same work.
+ */
+ private final AtomicReference<SoftReference<YangStoreSnapshot>> ref =
+ new AtomicReference<>(new SoftReference<YangStoreSnapshot>(null));
+
+ private final AtomicReference<SoftReference<BindingRuntimeContext>> refBindingContext =
+ new AtomicReference<>(new SoftReference<BindingRuntimeContext>(null));
+
+ private final SchemaContextProvider schemaContextProvider;
+
+ private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ @Override
+ public Thread newThread(final Runnable r) {
+ return new Thread(r, "yangstore-capability-notifications");
+ }
+ });
+
+ private final Set<ModuleListener> listeners = Collections.synchronizedSet(new HashSet<ModuleListener>());
+
+ public YangStoreService(final SchemaContextProvider schemaContextProvider) {
+ this.schemaContextProvider = schemaContextProvider;
+ }
+
+ private synchronized YangStoreContext getYangStoreSnapshot() {
+ SoftReference<YangStoreSnapshot> r = ref.get();
+ YangStoreSnapshot ret = r.get();
+
+ while (ret == null) {
+ // We need to be compute a new value
+ ret = new YangStoreSnapshot(schemaContextProvider.getSchemaContext(), refBindingContext.get().get());
+
+ if (!ref.compareAndSet(r, new SoftReference<>(ret))) {
+ LOG.debug("Concurrent refresh detected, recomputing snapshot");
+ r = ref.get();
+ ret = null;
+ }
+ }
+
+ return ret;
+ }
+
+ public YangStoreContext getCurrentSnapshot() {
+ return getYangStoreSnapshot();
+ }
+
+ @Override
+ public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
+ return getYangStoreSnapshot().getModuleMXBeanEntryMap();
+ }
+
+ @Override
+ public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
+ return getYangStoreSnapshot().getQNamesToIdentitiesToModuleMXBeanEntries();
+ }
+
+ @Override
+ public Set<Module> getModules() {
+ return getYangStoreSnapshot().getModules();
+ }
+
+ @Override
+ public String getModuleSource(final ModuleIdentifier moduleIdentifier) {
+ return getYangStoreSnapshot().getModuleSource(moduleIdentifier);
+ }
+
+ @Override
+ public EnumResolver getEnumResolver() {
+ return getYangStoreSnapshot().getEnumResolver();
+ }
+
+ public void refresh(final BindingRuntimeContext runtimeContext) {
+ final YangStoreSnapshot previous = ref.get().get();
+ ref.set(new SoftReference<YangStoreSnapshot>(null));
+ refBindingContext.set(new SoftReference<>(runtimeContext));
+ notificationExecutor.submit(new CapabilityChangeNotifier(previous));
+ }
+
+ public AutoCloseable registerModuleListener(final ModuleListener listener) {
+ YangStoreContext context = ref.get().get();
+
+ if (context == null) {
+ context = getYangStoreSnapshot();
+ }
+
+ this.listeners.add(listener);
+ listener.onCapabilitiesChanged(context.getModules(), Collections.<Module>emptySet());
+
+ return new AutoCloseable() {
+ @Override
+ public void close() throws Exception {
+ YangStoreService.this.listeners.remove(listener);
+ }
+ };
+ }
+
+ private final class CapabilityChangeNotifier implements Runnable {
+
+ private final YangStoreSnapshot previous;
+
+ public CapabilityChangeNotifier(final YangStoreSnapshot previous) {
+ this.previous = previous;
+ }
+
+ @Override
+ public void run() {
+ final YangStoreContext current = getYangStoreSnapshot();
+
+ if(!current.equals(previous)) {
+ final Set<Module> removed = Sets.difference(previous.getModules(), current.getModules());
+ final Set<Module> added = Sets.difference(current.getModules(), previous.getModules());
+
+ for (final ModuleListener listener : listeners) {
+ listener.onCapabilitiesChanged(added, removed);
+ }
+ }
+ }
+ }
+}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
+package org.opendaylight.controller.config.facade.xml.osgi;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc;
+package org.opendaylight.controller.config.facade.xml.rpc;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import javax.management.openmbean.OpenType;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeReadingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.ObjectXmlReader;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.AttributeResolvingStrategy;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.resolving.ObjectResolver;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeReadingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.ObjectXmlReader;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.AttributeResolvingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.resolving.ObjectResolver;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
public final class InstanceRuntimeRpc {
}
}
- public Map<String, AttributeConfigElement> fromXml(XmlElement configRootNode) throws NetconfDocumentedException {
+ public Map<String, AttributeConfigElement> fromXml(XmlElement configRootNode) throws DocumentedException {
Map<String, AttributeConfigElement> retVal = Maps.newHashMap();
// FIXME add identity map to runtime data
Map<String, AttributeReadingStrategy> strats = new ObjectXmlReader().prepareReading(yangToAttrConfig,
- Collections.<String, Map<Date, EditConfig.IdentityMapping>> emptyMap());
+ Collections.<String, Map<Date, IdentityMapping>> emptyMap());
for (Entry<String, AttributeReadingStrategy> readStratEntry : strats.entrySet()) {
List<XmlElement> configNodes = configRootNode.getChildElements(readStratEntry.getKey());
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc;
+package org.opendaylight.controller.config.facade.xml.rpc;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.util.Map;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
public final class ModuleRpcs {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc;
+package org.opendaylight.controller.config.facade.xml.rpc;
import com.google.common.base.Preconditions;
import java.util.Map;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpcElementResolved;
public class Rpcs {
private final Map<String, Map<String, ModuleRpcs>> mappedRpcs;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
+package org.opendaylight.controller.config.facade.xml.rpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.util.regex.Pattern;
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.ModuleRpcs;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.Modules;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.rev130405.modules.Module;
private final Map<String, String> additionalAttributes;
private RuntimeRpcElementResolved(String namespace, String moduleName, String instanceName, String runtimeBeanName,
- Map<String, String> additionalAttributes) {
+ Map<String, String> additionalAttributes) {
this.moduleName = Preconditions.checkNotNull(moduleName, "Module name");
this.instanceName = Preconditions.checkNotNull(instanceName, "Instance name");
this.additionalAttributes = additionalAttributes;
"/" + getRegExForPrefixedName(Modules.QNAME.getLocalName())+ "/" + getRegExForPrefixedName(Module.QNAME.getLocalName())
+ "\\["
- + "(?<key1>" + getRegExForPrefixedName(XmlNetconfConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlNetconfConstants.NAME_KEY) + ")"
+ + "(?<key1>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")"
+ "=('|\")?(?<value1>[^'\"\\]]+)('|\")?"
+ "( and |\\]\\[)"
- + "(?<key2>" + getRegExForPrefixedName(XmlNetconfConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlNetconfConstants.NAME_KEY) + ")"
+ + "(?<key2>" + getRegExForPrefixedName(XmlMappingConstants.TYPE_KEY) + "|" + getRegExForPrefixedName(XmlMappingConstants.NAME_KEY) + ")"
+ "=('|\")?(?<value2>[^'\"\\]]+)('|\")?"
+ "\\]"
Matcher matcher = xpathPattern.matcher(xpath);
Preconditions.checkState(matcher.matches(),
"Node %s with value '%s' not in required form on rpc element %s, required format is %s",
- RuntimeRpc.CONTEXT_INSTANCE, xpath, elementName, xpathPatternBlueprint);
+ //TODO refactor this string, and/or unify with RPR.CONTEXT_INSTANCE from netconf
+ "context-instance", xpath, elementName, xpathPatternBlueprint);
PatternGroupResolver groups = new PatternGroupResolver(matcher.group("key1"), matcher.group("value1"),
matcher.group("value2"), matcher.group("additional"));
}
String getModuleName() {
- return key1.contains(XmlNetconfConstants.TYPE_KEY) ? value1 : value2;
+ return key1.contains(XmlMappingConstants.TYPE_KEY) ? value1 : value2;
}
String getInstanceName() {
- return key1.contains(XmlNetconfConstants.NAME_KEY) ? value1 : value2;
+ return key1.contains(XmlMappingConstants.NAME_KEY) ? value1 : value2;
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime;
+package org.opendaylight.controller.config.facade.xml.runtime;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.Map.Entry;
import java.util.Set;
import javax.management.ObjectName;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfig;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime;
+package org.opendaylight.controller.config.facade.xml.runtime;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
import javax.management.ObjectName;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime;
+package org.opendaylight.controller.config.facade.xml.runtime;
import com.google.common.base.Optional;
import com.google.common.collect.HashMultimap;
import java.util.Set;
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleConfig;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
public Element toXml(Set<ObjectName> instancesToMap, Set<ObjectName> configBeans, Document document, final EnumResolver enumResolver) {
- Element root = XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
+ Element root = XmlUtil.createElement(document, XmlMappingConstants.DATA_KEY, Optional.<String>absent());
- Element modulesElement = XmlUtil.createElement(document, XmlNetconfConstants.MODULES_KEY, Optional.of(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
+ Element modulesElement = XmlUtil.createElement(document, XmlMappingConstants.MODULES_KEY, Optional.of(XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
root.appendChild(modulesElement);
Map<String, Multimap<String, ObjectName>> moduleToRuntimeInstance = mapInstancesToModules(instancesToMap);
- Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config.getMappedInstances(
- configBeans, moduleConfigs);
+ Map<String, Map<String, Collection<ObjectName>>> moduleToConfigInstance = Config
+ .getMappedInstances(configBeans, moduleConfigs);
for (String localNamespace : moduleConfigs.keySet()) {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.Map;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
public void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ ConfigTransactionClient ta, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
try {
ObjectName on = ta.lookupConfigBean(module, instance);
// edit configs should not handle missing
abstract void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException;
+ String module, String instance, ServiceRegistryWrapper services) throws
+ ConfigHandlingException;
abstract void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- ObjectName objectName, ServiceRegistryWrapper services) throws NetconfConfigHandlingException;
+ ObjectName objectName, ServiceRegistryWrapper services) throws
+ ConfigHandlingException;
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml.strategy;
+
+import java.util.Map;
+import javax.management.InstanceNotFoundException;
+import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.util.ConfigTransactionClient;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class DeleteEditConfigStrategy extends AbstractEditConfigStrategy {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DeleteEditConfigStrategy.class);
+
+
+ @Override
+ void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
+ String module, String instance, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
+ throw new ConfigHandlingException(String.format("Unable to delete %s : %s , ServiceInstance not found", module, instance),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
+ }
+
+ @Override
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
+ try {
+ ta.destroyModule(on);
+ LOG.debug("ServiceInstance {} deleted successfully", on);
+ } catch (InstanceNotFoundException e) {
+ throw new ConfigHandlingException(
+ String.format("Unable to delete %s because of exception %s" + on, e.getMessage()),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
+ }
+ }
+}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.Map;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
public interface EditConfigStrategy {
void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws NetconfConfigHandlingException;
+ ConfigTransactionClient ta, ServiceRegistryWrapper services) throws
+ ConfigHandlingException;
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.EnumSet;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.OperationNotPermittedException;
+import org.opendaylight.controller.config.facade.xml.exception.OperationNotPermittedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
public enum EditStrategyType {
// can be default
if (parsedStrategy != defaultStrategy){
throw new OperationNotPermittedException(String.format("With "
+ defaultStrategy
- + " as "
- + EditConfigXmlParser.DEFAULT_OPERATION_KEY
- + " operations on module elements are not permitted since the default option is restrictive"),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ + " as default-operation operations on module elements are not permitted since the default option is restrictive"),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import static java.util.Arrays.asList;
import java.util.Map.Entry;
import javax.management.Attribute;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
- throw new NetconfConfigHandlingException(
+ String module, String instance, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
+ throw new ConfigHandlingException(
String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
module,
instance),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
try {
LOG.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), toBeMergedIn, on);
} catch (Exception e) {
LOG.error("Error while merging objectnames of {}", on, e);
- throw new NetconfConfigHandlingException(String.format("Unable to set attributes for %s, Error with attribute %s : %s ",
+ throw new ConfigHandlingException(String.format("Unable to set attributes for %s, Error with attribute %s : %s ",
on,
configAttributeEntry.getKey(),
configAttributeEntry.getValue()),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.Map;
import javax.management.InstanceAlreadyExistsException;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ String module, String instance, ServiceRegistryWrapper services) throws ConfigHandlingException {
try {
ObjectName on = ta.createModule(module, instance);
LOG.trace("New instance for {} {} created under name {}", module, instance, on);
} catch (InstanceAlreadyExistsException e1) {
- throw new NetconfConfigHandlingException(String.format("Unable to create instance for %s : %s.", module, instance),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new ConfigHandlingException(String.format("Unable to create instance for %s : %s.", module, instance),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.Collections;
import java.util.Map;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
public void executeConfiguration(String module, String instance, Map<String, AttributeConfigElement> configuration,
- ConfigTransactionClient ta, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ ConfigTransactionClient ta, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
if(configuration != null && !configuration.isEmpty()) {
for (Map.Entry<String, AttributeConfigElement> attrEntry : configuration.entrySet()) {
if(attrEntry.getValue().getEditStrategy().isPresent()) {
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.Map;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+package org.opendaylight.controller.config.facade.xml.strategy;
import java.util.Map;
import java.util.Map.Entry;
import javax.management.Attribute;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.facade.xml.exception.ConfigHandlingException;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
- throw new NetconfConfigHandlingException(
+ String module, String instance, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
+ throw new ConfigHandlingException(
String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
module,
instance),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
@Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+ void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws
+ ConfigHandlingException {
for (Entry<String, AttributeConfigElement> configAttributeEntry : configuration.entrySet()) {
try {
AttributeConfigElement ace = configAttributeEntry.getValue();
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.transactions;
+package org.opendaylight.controller.config.facade.xml.transactions;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
+import org.opendaylight.controller.config.facade.xml.exception.NoTransactionFoundException;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NoTransactionFoundException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final ConfigRegistryClient configRegistryClient;
- private final String netconfSessionIdForReporting;
+ private final String sessionIdForReporting;
private ObjectName candidateTx;
private ObjectName readTx;
private final List<ObjectName> allOpenedTransactions = new ArrayList<>();
- private static final String NO_TRANSACTION_FOUND_FOR_SESSION = "No transaction found for session ";
+ private static final String NO_TRANSACTION_FOUND_FOR_SESSION = "No transaction found for session ";
- public TransactionProvider(ConfigRegistryClient configRegistryClient, String netconfSessionIdForReporting) {
+ public TransactionProvider(ConfigRegistryClient configRegistryClient, String sessionIdForReporting) {
this.configRegistryClient = configRegistryClient;
- this.netconfSessionIdForReporting = netconfSessionIdForReporting;
+ this.sessionIdForReporting = sessionIdForReporting;
}
@Override
// Transaction was already closed somehow
if (!isStillOpenTransaction(candidateTx)) {
- LOG.warn("Fixing illegal state: transaction {} was closed in {}", candidateTx,
- netconfSessionIdForReporting);
+ LOG.warn("Fixing illegal state: transaction {} was closed in {}", candidateTx, sessionIdForReporting);
candidateTx = null;
return Optional.absent();
}
// Transaction was already closed somehow
if (!isStillOpenTransaction(readTx)) {
- LOG.warn("Fixing illegal state: transaction {} was closed in {}", readTx,
- netconfSessionIdForReporting);
+ LOG.warn("Fixing illegal state: transaction {} was closed in {}", readTx, sessionIdForReporting);
readTx = null;
return Optional.absent();
}
/**
* Commit and notification send must be atomic
*/
- public synchronized CommitStatus commitTransaction() throws ValidationException, ConflictingVersionException, NoTransactionFoundException {
+ public CommitStatus commitTransaction() throws ValidationException, ConflictingVersionException,
+ NoTransactionFoundException {
+ return commitTransaction(configRegistryClient);
+ }
+
+ /**
+ * Commit and notification send must be atomic
+ * @param configRegistryClient
+ */
+ public synchronized CommitStatus commitTransaction(final ConfigRegistryClient configRegistryClient) throws ValidationException, ConflictingVersionException, NoTransactionFoundException {
if (!getTransaction().isPresent()){
- throw new NoTransactionFoundException("No transaction found for session " + netconfSessionIdForReporting,
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new NoTransactionFoundException("No transaction found for session " + sessionIdForReporting,
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
final Optional<ObjectName> maybeTaON = getTransaction();
ObjectName taON = maybeTaON.get();
public synchronized void abortTransaction() {
LOG.debug("Aborting current transaction");
Optional<ObjectName> taON = getTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
+ Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
transactionClient.abortConfig();
public synchronized void closeReadTransaction() {
LOG.debug("Closing read transaction");
Optional<ObjectName> taON = getReadTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
+ Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
transactionClient.abortConfig();
public void validateTransaction() throws ValidationException {
Optional<ObjectName> taON = getTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
+ Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
ConfigTransactionClient transactionClient = configRegistryClient.getConfigTransactionClient(taON.get());
transactionClient.validateConfig();
public void wipeTransaction() {
Optional<ObjectName> taON = getTransaction();
- Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting);
+ Preconditions.checkState(taON.isPresent(), NO_TRANSACTION_FOUND_FOR_SESSION + sessionIdForReporting);
wipeInternal(taON.get(), false);
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.util;
+package org.opendaylight.controller.config.facade.xml.util;
import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml;
+package org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.Map;
import org.junit.Test;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.facade.xml.mapping.IdentityMapping;
+import org.opendaylight.controller.config.util.xml.XmlElement;
public class SimpleIdentityRefAttributeReadingStrategyTest {
@Test
public void testReadIdRef() throws Exception {
- final Map<String, Map<Date, EditConfig.IdentityMapping>> identityMapping = Maps.newHashMap();
- final EditConfig.IdentityMapping value = new EditConfig.IdentityMapping();
+ final Map<String, Map<Date, IdentityMapping>> identityMapping = Maps.newHashMap();
+ final IdentityMapping value = new IdentityMapping();
final Date rev = new Date();
identityMapping.put("namespace", Collections.singletonMap(rev, value));
identityMapping.put("inner", Collections.singletonMap(rev, value));
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.facade.xml.rpc;
+
+import static org.junit.Assert.assertEquals;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+@RunWith(Parameterized.class)
+public class RuntimeRpcElementResolvedTest {
+
+ private static final String MODULE_TYPE = "moduleType";
+ private static final String INSTANCE_NAME = "instanceName";
+ @Parameterized.Parameter(0)
+ public String xpath;
+ @Parameterized.Parameter(1)
+ public Map<String, String> additional;
+
+ @Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][]{
+ // With namespaces
+ {"/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
+ new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1"))},
+ {"/a:modules/a:module[a:name='instanceName'][a:type='moduleType']",
+ null},
+
+ // Without namespaces
+ {"/modules/module[name=instanceName][type=moduleType]", null},
+ {"/modules/module[type=moduleType][name='instanceName']", null},
+ {"/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null},
+ {"/modules/module[type=moduleType and name=instanceName]", null},
+ {"/modules/module[name=\"instanceName\" and type=moduleType]", null},
+ {"/modules/module[type=\"moduleType\" and name=instanceName]", null},
+ {"/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null},
+
+ // With inner beans
+ {"/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")},
+ {"/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")},
+ {"/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")},
+ {"/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")},
+
+ {"/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
+ new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b"))
+ },
+ });
+ }
+
+ @Test
+ public void testFromXpath() throws Exception {
+ final RuntimeRpcElementResolved resolved = RuntimeRpcElementResolved.fromXpath(xpath, "element", "namespace");
+ assertEquals(MODULE_TYPE, resolved.getModuleName());
+ assertEquals(INSTANCE_NAME, resolved.getInstanceName());
+ if (additional != null) {
+ assertEquals(additional, resolved.getAdditionalAttributes());
+ }
+ }
+}
+++ /dev/null
-target
-.classpath
-.settings
ConfigRegistryMXBean.OBJECT_NAME);
}
+ public AutoCloseable registerToJMXNoNotifications(ConfigRegistryImplMXBean configRegistry)
+ throws InstanceAlreadyExistsException {
+ return internalJMXRegistrator.registerMBean(configRegistry,
+ ConfigRegistryMXBean.OBJECT_NAME_NO_NOTIFICATIONS);
+ }
+
@Override
public void close() {
internalJMXRegistrator.close();
--- /dev/null
+package org.opendaylight.controller.config.manager.impl.jmx;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.InstanceNotFoundException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MBeanServer;
+import javax.management.NotCompliantMBeanException;
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.api.jmx.CommitStatus;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
+import org.opendaylight.controller.config.manager.impl.ConfigRegistryImplMXBean;
+
+/**
+ * Thin wrapper over ConfigRegistry emitting JMX notifications
+ */
+public class JMXNotifierConfigRegistry implements ConfigRegistryImplMXBean, AutoCloseable {
+
+ private final ConfigRegistryImplMXBean delegate;
+ private final NotifierMXBeanImpl notifier;
+ private final MBeanServer mBeanServer;
+
+ public JMXNotifierConfigRegistry(final ConfigRegistryImplMXBean delegate, final MBeanServer mBeanServer) {
+ this.delegate = delegate;
+ notifier = new NotifierMXBeanImpl();
+ this.mBeanServer = mBeanServer;
+ registerMBean(notifier, this.mBeanServer, ConfigJMXNotification.OBJECT_NAME);
+ }
+
+ private static void registerMBean(final Object instance, final MBeanServer mbs, final ObjectName on) {
+ try {
+ mbs.registerMBean(instance, on);
+ } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
+ throw new IllegalStateException("Unable to register " + instance + " as " + on, e);
+ }
+ }
+
+ @Override
+ public long getVersion() {
+ return delegate.getVersion();
+ }
+
+ @Override
+ public ObjectName beginConfig() {
+ return delegate.beginConfig();
+ }
+
+ @Override
+ public CommitStatus commitConfig(final ObjectName transactionControllerON) throws ConflictingVersionException, ValidationException {
+ final CommitStatus commitStatus = delegate.commitConfig(transactionControllerON);
+ notifier.notifyCommit(ObjectNameUtil.getTransactionName(transactionControllerON));
+ return commitStatus;
+ }
+
+ @Override
+ public List<ObjectName> getOpenConfigs() {
+ return delegate.getOpenConfigs();
+ }
+
+ @Override
+ public boolean isHealthy() {
+ return delegate.isHealthy();
+ }
+
+ @Override
+ public Set<String> getAvailableModuleNames() {
+ return delegate.getAvailableModuleNames();
+ }
+
+ @Override
+ public Set<ObjectName> lookupConfigBeans() {
+ return delegate.lookupConfigBeans();
+ }
+
+ @Override
+ public Set<ObjectName> lookupConfigBeans(final String moduleName) {
+ return delegate.lookupConfigBeans(moduleName);
+ }
+
+ @Override
+ public Set<ObjectName> lookupConfigBeans(final String moduleName, final String instanceName) {
+ return delegate.lookupConfigBeans(moduleName, instanceName);
+ }
+
+ @Override
+ public ObjectName lookupConfigBean(final String moduleName, final String instanceName) throws InstanceNotFoundException {
+ return delegate.lookupConfigBean(moduleName, instanceName);
+ }
+
+ @Override
+ public void checkConfigBeanExists(final ObjectName objectName) throws InstanceNotFoundException {
+ delegate.checkConfigBeanExists(objectName);
+ }
+
+ @Override
+ public Set<String> getAvailableModuleFactoryQNames() {
+ return delegate.getAvailableModuleFactoryQNames();
+ }
+
+ @Override
+ public Set<ObjectName> lookupRuntimeBeans() {
+ return delegate.lookupRuntimeBeans();
+ }
+
+ @Override
+ public Set<ObjectName> lookupRuntimeBeans(final String moduleName, final String instanceName) {
+ return delegate.lookupRuntimeBeans(moduleName, instanceName);
+ }
+
+ @Override
+ public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
+ return delegate.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
+ }
+
+ @Override
+ public Map<String, Map<String, ObjectName>> getServiceMapping() {
+ return delegate.getServiceMapping();
+ }
+
+ @Override
+ public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
+ return delegate.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
+ }
+
+ @Override
+ public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
+ return delegate.lookupServiceInterfaceNames(objectName);
+ }
+
+ @Override
+ public String getServiceInterfaceName(final String namespace, final String localName) {
+ return delegate.getServiceInterfaceName(namespace, localName);
+ }
+
+ @Override
+ public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
+ return delegate.getServiceReference(serviceInterfaceQName, refName);
+ }
+
+ @Override
+ public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
+ delegate.checkServiceReferenceExists(objectName);
+ }
+
+ @Override
+ public void close() {
+ try {
+ mBeanServer.unregisterMBean(ConfigJMXNotification.OBJECT_NAME);
+ } catch (InstanceNotFoundException | MBeanRegistrationException e) {
+ throw new IllegalStateException("Notifier: " + ConfigJMXNotification.OBJECT_NAME + " not found in JMX when closing");
+ }
+ }
+
+ public interface NotifierMXBean {}
+
+ public static class NotifierMXBeanImpl extends NotificationBroadcasterSupport implements NotifierMXBean {
+
+ private void notifyCommit(final String transactionName) {
+ sendNotification(ConfigJMXNotification.afterCommit(this, "commit success " + transactionName));
+ }
+ }
+}
import java.util.List;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
+import org.opendaylight.controller.config.api.ConfigRegistry;
import org.opendaylight.controller.config.manager.impl.ConfigRegistryImpl;
import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
+import org.opendaylight.controller.config.manager.impl.jmx.JMXNotifierConfigRegistry;
import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
import org.opendaylight.controller.config.manager.impl.osgi.mapping.ModuleInfoBundleTracker;
import org.opendaylight.controller.config.manager.impl.osgi.mapping.RefreshingSCPModuleInfoRegistry;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ConfigManagerActivator implements BundleActivator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigManagerActivator.class);
+
private final MBeanServer configMBeanServer = ManagementFactory.getPlatformMBeanServer();
private AutoCloseable autoCloseable;
@Override
public void start(final BundleContext context) {
-
- ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();// the inner strategy is backed by thread context cl?
-
- BindingContextProvider bindingContextProvider = new BindingContextProvider();
-
- RefreshingSCPModuleInfoRegistry moduleInfoRegistryWrapper = new RefreshingSCPModuleInfoRegistry(
- moduleInfoBackedContext, moduleInfoBackedContext, moduleInfoBackedContext, bindingContextProvider, context);
-
- ModuleInfoBundleTracker moduleInfoBundleTracker = new ModuleInfoBundleTracker(moduleInfoRegistryWrapper);
-
-
- // start config registry
- BundleContextBackedModuleFactoriesResolver bundleContextBackedModuleFactoriesResolver = new BundleContextBackedModuleFactoriesResolver(
- context);
- ConfigRegistryImpl configRegistry = new ConfigRegistryImpl(bundleContextBackedModuleFactoriesResolver, configMBeanServer,
- bindingContextProvider);
-
- // track bundles containing factories
- BlankTransactionServiceTracker blankTransactionServiceTracker = new BlankTransactionServiceTracker(
- configRegistry);
- ModuleFactoryBundleTracker primaryModuleFactoryBundleTracker = new ModuleFactoryBundleTracker(
- blankTransactionServiceTracker);
-
- // start extensible tracker
- ExtensibleBundleTracker<?> bundleTracker = new ExtensibleBundleTracker<>(context,
- primaryModuleFactoryBundleTracker, moduleInfoBundleTracker);
- bundleTracker.open();
-
- // register config registry to OSGi
- AutoCloseable clsReg = registerService(context, moduleInfoBackedContext, GeneratedClassLoadingStrategy.class);
- AutoCloseable configRegReg = registerService(context, configRegistry, ConfigRegistryImpl.class);
-
- // register config registry to jmx
- ConfigRegistryJMXRegistrator configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(configMBeanServer);
try {
- configRegistryJMXRegistrator.registerToJMX(configRegistry);
- } catch (InstanceAlreadyExistsException e) {
- throw new IllegalStateException("Config Registry was already registered to JMX", e);
+ ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();// the inner strategy is backed by thread context cl?
+
+ BindingContextProvider bindingContextProvider = new BindingContextProvider();
+
+ RefreshingSCPModuleInfoRegistry moduleInfoRegistryWrapper = new RefreshingSCPModuleInfoRegistry(
+ moduleInfoBackedContext, moduleInfoBackedContext, moduleInfoBackedContext, bindingContextProvider, context);
+
+ ModuleInfoBundleTracker moduleInfoBundleTracker = new ModuleInfoBundleTracker(moduleInfoRegistryWrapper);
+
+ // start config registry
+ BundleContextBackedModuleFactoriesResolver bundleContextBackedModuleFactoriesResolver = new BundleContextBackedModuleFactoriesResolver(
+ context);
+ ConfigRegistryImpl configRegistry = new ConfigRegistryImpl(bundleContextBackedModuleFactoriesResolver, configMBeanServer,
+ bindingContextProvider);
+
+ // track bundles containing factories
+ BlankTransactionServiceTracker blankTransactionServiceTracker = new BlankTransactionServiceTracker(
+ configRegistry);
+ ModuleFactoryBundleTracker primaryModuleFactoryBundleTracker = new ModuleFactoryBundleTracker(
+ blankTransactionServiceTracker);
+
+ // start extensible tracker
+ ExtensibleBundleTracker<?> bundleTracker = new ExtensibleBundleTracker<>(context,
+ primaryModuleFactoryBundleTracker, moduleInfoBundleTracker);
+ bundleTracker.open();
+
+ // Wrap config registry with JMX notification publishing adapter
+ final JMXNotifierConfigRegistry notifyingConfigRegistry =
+ new JMXNotifierConfigRegistry(configRegistry, configMBeanServer);
+
+ // register config registry to OSGi
+ AutoCloseable clsReg = registerService(context, moduleInfoBackedContext, GeneratedClassLoadingStrategy.class);
+ AutoCloseable configRegReg = registerService(context, notifyingConfigRegistry, ConfigRegistry.class);
+
+ // register config registry to jmx
+ ConfigRegistryJMXRegistrator configRegistryJMXRegistrator = new ConfigRegistryJMXRegistrator(configMBeanServer);
+ try {
+ configRegistryJMXRegistrator.registerToJMXNoNotifications(configRegistry);
+ } catch (InstanceAlreadyExistsException e) {
+ throw new IllegalStateException("Config Registry was already registered to JMX", e);
+ }
+
+ // register config registry to jmx
+ final ConfigRegistryJMXRegistrator configRegistryJMXRegistratorWithNotifications = new ConfigRegistryJMXRegistrator(configMBeanServer);
+ try {
+ configRegistryJMXRegistrator.registerToJMX(notifyingConfigRegistry);
+ } catch (InstanceAlreadyExistsException e) {
+ throw new IllegalStateException("Config Registry was already registered to JMX", e);
+ }
+
+ // TODO wire directly via moduleInfoBundleTracker
+ ServiceTracker<ModuleFactory, Object> serviceTracker = new ServiceTracker<>(context, ModuleFactory.class,
+ blankTransactionServiceTracker);
+ serviceTracker.open();
+
+ List<AutoCloseable> list = Arrays.asList(bindingContextProvider, clsReg, configRegistry, wrap(bundleTracker),
+ configRegReg, configRegistryJMXRegistrator, configRegistryJMXRegistratorWithNotifications, wrap(serviceTracker), moduleInfoRegistryWrapper, notifyingConfigRegistry);
+ autoCloseable = OsgiRegistrationUtil.aggregate(list);
+ } catch(Exception e) {
+ LOG.warn("Error starting config manager", e);
}
-
- // TODO wire directly via moduleInfoBundleTracker
- ServiceTracker<ModuleFactory, Object> serviceTracker = new ServiceTracker<>(context, ModuleFactory.class,
- blankTransactionServiceTracker);
- serviceTracker.open();
-
- List<AutoCloseable> list = Arrays.asList(
- bindingContextProvider, clsReg,configRegistry, wrap(bundleTracker), configRegReg, configRegistryJMXRegistrator, wrap(serviceTracker));
- autoCloseable = OsgiRegistrationUtil.aggregate(list);
}
@Override
}
public synchronized BindingRuntimeContext getBindingContext() {
- Preconditions.checkState(current != null, "Binding context not yet initialized");
+ Preconditions.checkState(this.current != null, "Binding context not yet initialized");
return this.current;
}
@Override
public synchronized void close() throws Exception {
- current = null;
+ this.current = null;
}
}
osgiReg.unregister();
}
-
private class ObjectRegistrationWrapper implements ObjectRegistration<YangModuleInfo> {
private final ObjectRegistration<YangModuleInfo> inner;
updateService();// send modify event when a bundle disappears
}
-
@Override
public String toString() {
return inner.toString();
import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
import org.opendaylight.controller.config.manager.impl.jmx.ConfigRegistryJMXRegistrator;
import org.opendaylight.controller.config.manager.impl.jmx.InternalJMXRegistrator;
+import org.opendaylight.controller.config.manager.impl.jmx.JMXNotifierConfigRegistry;
import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolImpl;
import org.opendaylight.controller.config.manager.testingservices.threadpool.TestingFixedThreadPool;
AbstractLockedPlatformMBeanServerTest {
protected ConfigRegistryJMXRegistrator configRegistryJMXRegistrator;
protected ConfigRegistryImpl configRegistry;
+ private JMXNotifierConfigRegistry notifyingConfigRegistry;
protected ConfigRegistryJMXClient configRegistryClient;
protected BaseJMXRegistrator baseJmxRegistrator;
protected InternalJMXRegistrator internalJmxRegistrator;
return getBindingRuntimeContext();
}
});
+ notifyingConfigRegistry = new JMXNotifierConfigRegistry(this.configRegistry, platformMBeanServer);
try {
- configRegistryJMXRegistrator.registerToJMX(configRegistry);
+ configRegistryJMXRegistrator.registerToJMXNoNotifications(configRegistry);
+ configRegistryJMXRegistrator.registerToJMX(notifyingConfigRegistry);
} catch (InstanceAlreadyExistsException e) {
throw new RuntimeException(e);
}
@After
public final void cleanUpConfigTransactionManagerImpl() {
configRegistryJMXRegistrator.close();
+ notifyingConfigRegistry.close();
configRegistry.close();
TestingFixedThreadPool.cleanUp();
TestingScheduledThreadPoolImpl.cleanUp();
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Export-Package>org.opendaylight.controller.config.persist.api,
- org.opendaylight.controller.config.persist.api.storage,</Export-Package>
- </instructions>
- </configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<instructions>
<Fragment-Host>${project.groupId}.config-persister-impl</Fragment-Host>
<Provide-Capability>org.opendaylight.controller.config.persister.storage.adapter</Provide-Capability>
- <Import-Package>com.google.common.base,
- com.google.common.io,
- org.opendaylight.controller.config.persist.api,
- org.slf4j,
- com.google.common.collect,
- javax.xml.bind,
- javax.xml.bind.annotation,
- javax.xml.bind.annotation.adapters,
- javax.xml.transform,
- javax.xml.transform.stream,
- org.eclipse.persistence.jaxb,
- org.apache.commons.lang3</Import-Package>
<Private-Package>org.opendaylight.controller.config.persist.storage.file.xml.model,</Private-Package>
</instructions>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ ~
+ ~ This program and the accompanying materials are made available under the
+ ~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ ~ and is available at http://www.eclipse.org/legal/epl-v10.html
+ -->
+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
+ <artifactId>config-subsystem</artifactId>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
<version>0.4.0-SNAPSHOT</version>
- <relativePath>../</relativePath>
</parent>
<artifactId>config-persister-impl</artifactId>
<packaging>bundle</packaging>
<name>${project.artifactId}</name>
<dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-api</artifactId>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-util</artifactId>
- </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
-
- <!-- test dependencies -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-impl</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-util</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
</dependency>
+
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>config-persister-directory-xml-adapter</artifactId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
- <Bundle-Activator>org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator</Bundle-Activator>
+ <Bundle-Activator>org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator</Bundle-Activator>
<Require-Capability>org.opendaylight.controller.config.persister.storage.adapter</Require-Capability>
- <Export-Package></Export-Package>
</instructions>
</configuration>
</plugin>
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import com.google.common.annotations.VisibleForTesting;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
+import com.google.common.base.Optional;
import java.io.Closeable;
import java.io.IOException;
+import java.util.Set;
import javax.annotation.concurrent.ThreadSafe;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.jmx.notifications.CommitJMXNotification;
+import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.facade.xml.Datastore;
import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
-import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
-import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
/**
* Responsible for listening for notifications from netconf (via JMX) containing latest
private final NotificationListener listener;
- public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final Persister persisterAggregator) {
- this(mBeanServerConnection, new ConfigPersisterNotificationListener(persisterAggregator));
+ public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final Persister persisterAggregator, final ConfigSubsystemFacadeFactory facade) {
+ this(mBeanServerConnection, new ConfigPersisterNotificationListener(persisterAggregator, facade));
}
public ConfigPersisterNotificationHandler(final MBeanServerConnection mBeanServerConnection, final NotificationListener notificationListener) {
private static void registerAsJMXListener(final MBeanServerConnection mBeanServerConnection, final NotificationListener listener) {
LOG.trace("Called registerAsJMXListener");
try {
- mBeanServerConnection.addNotificationListener(DefaultCommitOperationMXBean.OBJECT_NAME, listener, null, null);
+ mBeanServerConnection.addNotificationListener(ConfigJMXNotification.OBJECT_NAME, listener, null, null);
} catch (InstanceNotFoundException | IOException e) {
throw new IllegalStateException("Cannot register as JMX listener to netconf", e);
}
@Override
public synchronized void close() {
// unregister from JMX
- final ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME;
+ final ObjectName on = ConfigJMXNotification.OBJECT_NAME;
try {
if (mBeanServerConnection.isRegistered(on)) {
mBeanServerConnection.removeNotificationListener(on, listener);
private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterNotificationListener.class);
private final Persister persisterAggregator;
+ private final ConfigSubsystemFacadeFactory facade;
- ConfigPersisterNotificationListener(final Persister persisterAggregator) {
+ ConfigPersisterNotificationListener(final Persister persisterAggregator, final ConfigSubsystemFacadeFactory facade) {
this.persisterAggregator = persisterAggregator;
+ this.facade = facade;
}
@Override
public void handleNotification(final Notification notification, final Object handback) {
- if (!(notification instanceof NetconfJMXNotification)) {
+ if (!(notification instanceof ConfigJMXNotification)) {
return;
}
LOG.trace("Received notification {}", notification);
if (notification instanceof CommitJMXNotification) {
try {
- handleAfterCommitNotification((CommitJMXNotification) notification);
+ handleAfterCommitNotification();
} catch (final Exception e) {
// log exceptions from notification Handler here since
// notificationBroadcastSupport logs only DEBUG level
}
}
- private void handleAfterCommitNotification(final CommitJMXNotification notification) {
+ private void handleAfterCommitNotification() {
try {
- persisterAggregator.persistConfig(new CapabilityStrippingConfigSnapshotHolder(notification.getConfigSnapshot(),
- notification.getCapabilities()));
+ final Set<Capability> currentCapabilities = facade.getCurrentCapabilities();
+ final Element configSnapshot = facade.createFacade("config-persister").getConfiguration(XmlUtil.newDocument(), Datastore.running, Optional.<String>absent());
+ persisterAggregator.persistConfig(new CapabilityStrippingConfigSnapshotHolder(configSnapshot,
+ ConfigPusherImpl.transformCapabilities(currentCapabilities)));
LOG.trace("Configuration persisted successfully");
} catch (final IOException e) {
throw new RuntimeException("Unable to persist configuration snapshot", e);
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.persist.impl;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.common.base.Function;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.Collections2;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.Immutable;
+import javax.management.MBeanServerConnection;
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.facade.xml.ConfigExecution;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.persist.api.ConfigPusher;
+import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
+import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+@Immutable
+public class ConfigPusherImpl implements ConfigPusher {
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
+
+ private static final Date NO_REVISION = new Date(0);
+ private static final int QUEUE_SIZE = 100;
+
+ private final long maxWaitForCapabilitiesMillis;
+ private final long conflictingVersionTimeoutMillis;
+ private BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<>(QUEUE_SIZE);
+
+ private ConfigSubsystemFacadeFactory facade;
+ private ConfigPersisterNotificationHandler jmxNotificationHandler;
+
+ public ConfigPusherImpl(ConfigSubsystemFacadeFactory facade, long maxWaitForCapabilitiesMillis,
+ long conflictingVersionTimeoutMillis) {
+ this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
+ this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
+ this.facade = facade;
+ }
+
+ public void process(List<AutoCloseable> autoCloseables, MBeanServerConnection platformMBeanServer, Persister persisterAggregator) throws InterruptedException {
+ while(true) {
+ processSingle(autoCloseables, platformMBeanServer, persisterAggregator);
+ }
+ }
+
+ void processSingle(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer, final Persister persisterAggregator) throws InterruptedException {
+ final List<? extends ConfigSnapshotHolder> configs = queue.take();
+ try {
+ internalPushConfigs(configs);
+
+ // Do not register multiple notification handlers
+ if(jmxNotificationHandler == null) {
+ jmxNotificationHandler =
+ new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator, facade);
+ synchronized (autoCloseables) {
+ autoCloseables.add(jmxNotificationHandler);
+ }
+ }
+
+ LOG.debug("ConfigPusher has pushed configs {}", configs);
+ } catch (DocumentedException e) {
+ LOG.error("Error pushing configs {}",configs);
+ throw new IllegalStateException(e);
+ }
+ }
+
+ public void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
+ LOG.debug("Requested to push configs {}", configs);
+ this.queue.put(configs);
+ }
+
+ private LinkedHashMap<? extends ConfigSnapshotHolder, Boolean> internalPushConfigs(List<? extends ConfigSnapshotHolder> configs)
+ throws DocumentedException {
+ LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
+ LinkedHashMap<ConfigSnapshotHolder, Boolean> result = new LinkedHashMap<>();
+ // start pushing snapshots
+ for (ConfigSnapshotHolder configSnapshotHolder : configs) {
+ if (configSnapshotHolder != null) {
+ boolean pushResult = false;
+ try {
+ pushResult = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
+ } catch (ConfigSnapshotFailureException e) {
+ LOG.warn("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
+ "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
+ throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
+ }
+ LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
+ result.put(configSnapshotHolder, pushResult);
+ }
+ }
+ LOG.debug("All configuration snapshots have been pushed successfully.");
+ return result;
+ }
+
+ private synchronized boolean pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
+ ConflictingVersionException lastException;
+ Stopwatch stopwatch = Stopwatch.createUnstarted();
+ do {
+ //TODO wait untill all expected modules are in yangStoreService, do we even need to with yangStoreService instead on netconfOperationService?
+ String idForReporting = configSnapshotHolder.toString();
+ SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
+ "Expected capabilities must not be null - %s, check %s", idForReporting,
+ configSnapshotHolder.getClass().getName());
+
+ // wait max time for required capabilities to appear
+ waitForCapabilities(expectedCapabilities, idForReporting);
+ try {
+ if(!stopwatch.isRunning()) {
+ stopwatch.start();
+ }
+ return pushConfig(configSnapshotHolder);
+ } catch (ConflictingVersionException e) {
+ lastException = e;
+ LOG.info("Conflicting version detected, will retry after timeout");
+ sleep();
+ }
+ } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
+ throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
+ lastException);
+ }
+
+ private void waitForCapabilities(Set<String> expectedCapabilities, String idForReporting) {
+ Stopwatch stopwatch = Stopwatch.createStarted();
+ ConfigPusherException lastException;
+ do {
+ try {
+ final Set<Capability> currentCaps = facade.getCurrentCapabilities();
+ final Set<String> notFoundCapabilities = computeNotFoundCapabilities(expectedCapabilities, currentCaps);
+ if (notFoundCapabilities.isEmpty()) {
+ return;
+ } else {
+ LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
+ "Expected but not found: {}, all expected {}, current {}",
+ notFoundCapabilities, expectedCapabilities, currentCaps
+ );
+ throw new NotEnoughCapabilitiesException(
+ "Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundCapabilities, notFoundCapabilities);
+ }
+ } catch (ConfigPusherException e) {
+ LOG.debug("Not enough capabilities: {}", e.toString());
+ lastException = e;
+ sleep();
+ }
+ } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
+
+ LOG.error("Unable to push configuration due to missing yang models." +
+ " Yang models that are missing, but required by the configuration: {}." +
+ " For each mentioned model check: " +
+ " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
+ " 2. the yang file is present in the system" +
+ " 3. the bundle with that yang file is present in the system and active" +
+ " 4. the yang parser did not fail while attempting to parse that model",
+ ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
+ throw new IllegalStateException("Unable to push configuration due to missing yang models." +
+ " Required yang models that are missing: "
+ + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
+ }
+
+ private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, Set<Capability> currentCapabilities) {
+ Collection<String> actual = transformCapabilities(currentCapabilities);
+ Set<String> allNotFound = new HashSet<>(expectedCapabilities);
+ allNotFound.removeAll(actual);
+ return allNotFound;
+ }
+
+ static Set<String> transformCapabilities(final Set<Capability> currentCapabilities) {
+ return new HashSet<>(Collections2.transform(currentCapabilities, new Function<Capability, String>() {
+ @Override
+ public String apply(@Nonnull final Capability input) {
+ return input.getCapabilityUri();
+ }
+ }));
+ }
+
+ static class ConfigPusherException extends Exception {
+
+ public ConfigPusherException(final String message) {
+ super(message);
+ }
+
+ public ConfigPusherException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+ }
+
+ static class NotEnoughCapabilitiesException extends ConfigPusherException {
+ private static final long serialVersionUID = 1L;
+ private Set<String> missingCaps;
+
+ NotEnoughCapabilitiesException(String message, Set<String> missingCaps) {
+ super(message);
+ this.missingCaps = missingCaps;
+ }
+
+ public Set<String> getMissingCaps() {
+ return missingCaps;
+ }
+ }
+
+ private static final class ConfigSnapshotFailureException extends ConfigPusherException {
+
+ private final String configIdForReporting;
+
+ public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
+ super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
+ this.configIdForReporting = configIdForReporting;
+ }
+
+ public String getConfigIdForReporting() {
+ return configIdForReporting;
+ }
+ }
+
+ private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, YangStoreService yangStoreService) {
+
+ Collection<String> actual = Collections2.transform(yangStoreService.getModules(), new Function<Module, String>() {
+ @Nullable
+ @Override
+ public String apply(Module input) {
+ final String withoutRevision = input.getNamespace().toString() + "?module=" + input.getName();
+ return !input.getRevision().equals(NO_REVISION) ? withoutRevision + "&revision=" + Util.writeDate(input.getRevision()) : withoutRevision;
+ }
+ });
+
+ Set<String> allNotFound = new HashSet<>(expectedCapabilities);
+ allNotFound.removeAll(actual);
+ return allNotFound;
+ }
+
+ private void sleep() {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private synchronized boolean pushConfig(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException, ConflictingVersionException {
+ Element xmlToBePersisted;
+ try {
+ xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
+ } catch (SAXException | IOException e) {
+ throw new IllegalStateException("Cannot parse " + configSnapshotHolder, e);
+ }
+ LOG.trace("Pushing last configuration to config mapping: {}", configSnapshotHolder);
+
+ Stopwatch stopwatch = Stopwatch.createStarted();
+ final ConfigSubsystemFacade currentFacade = this.facade.createFacade("config-push");
+ try {
+ ConfigExecution configExecution = createConfigExecution(xmlToBePersisted, currentFacade);
+ currentFacade.executeConfigExecution(configExecution);
+ } catch (ValidationException | DocumentedException e) {
+ LOG.trace("Validation for config: {} failed", configSnapshotHolder, e);
+ throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "edit", e);
+ }
+
+ try {
+ currentFacade.commitSilentTransaction();
+ } catch (ValidationException | DocumentedException e) {
+ throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "commit", e);
+ }
+
+ LOG.trace("Last configuration loaded successfully");
+ LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
+
+ return true;
+ }
+
+ private ConfigExecution createConfigExecution(Element xmlToBePersisted, final ConfigSubsystemFacade currentFacade) throws DocumentedException {
+ final Config configMapping = currentFacade.getConfigMapping();
+ return currentFacade.getConfigExecution(configMapping, xmlToBePersisted);
+ }
+
+}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import java.io.IOException;
import java.util.Collections;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import org.opendaylight.controller.config.persist.api.Persister;
import org.opendaylight.controller.config.persist.api.PropertiesProvider;
import org.opendaylight.controller.config.persist.api.StorageAdapter;
-import org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator;
+import org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import org.opendaylight.controller.config.persist.api.PropertiesProvider;
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.persist.impl.osgi;
+
+import com.google.common.collect.Lists;
+import java.lang.management.ManagementFactory;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import javax.management.MBeanServer;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.persist.api.ConfigPusher;
+import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
+import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.persist.impl.ConfigPusherImpl;
+import org.opendaylight.controller.config.persist.impl.PersisterAggregator;
+import org.opendaylight.controller.config.util.CloseableUtil;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ConfigPersisterActivator implements BundleActivator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterActivator.class);
+ private static final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
+
+ public static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY = "maxWaitForCapabilitiesMillis";
+ private static final long MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(2);
+ public static final String CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY = "conflictingVersionTimeoutMillis";
+ private static final long CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(1);
+
+ public static final String NETCONF_CONFIG_PERSISTER = "netconf.config.persister";
+
+ public static final String STORAGE_ADAPTER_CLASS_PROP_SUFFIX = "storageAdapterClass";
+
+ private final List<AutoCloseable> autoCloseables = Lists.newArrayList();
+ private volatile BundleContext context;
+
+ ServiceRegistration<?> registration;
+
+ @Override
+ public void start(final BundleContext context) throws Exception {
+ LOG.debug("ConfigPersister starting");
+ this.context = context;
+
+ PropertiesProviderBaseImpl propertiesProvider = new PropertiesProviderBaseImpl(context);
+
+ final PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(propertiesProvider);
+ autoCloseables.add(persisterAggregator);
+ final long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider);
+ final List<ConfigSnapshotHolder> configs = persisterAggregator.loadLastConfigs();
+ final long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider);
+ LOG.debug("Following configs will be pushed: {}", configs);
+
+ ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
+
+ @Override
+ public ConfigSubsystemFacadeFactory addingService(ServiceReference<ConfigSubsystemFacadeFactory> reference) {
+ LOG.debug("Got addingService(SchemaContextProvider) event");
+ // Yang store service should not be registered multiple times
+ ConfigSubsystemFacadeFactory ConfigSubsystemFacadeFactory = reference.getBundle().getBundleContext().getService(reference);
+ startPusherThread(configs, maxWaitForCapabilitiesMillis, ConfigSubsystemFacadeFactory, conflictingVersionTimeoutMillis, persisterAggregator);
+ return ConfigSubsystemFacadeFactory;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+ LOG.warn("Config manager facade was modified unexpectedly");
+ }
+
+ @Override
+ public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+ LOG.warn("Config manager facade was removed unexpectedly");
+ }
+ };
+
+ ServiceTracker<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaContextProviderServiceTracker =
+ new ServiceTracker<>(context, ConfigSubsystemFacadeFactory.class, schemaServiceTrackerCustomizer);
+ schemaContextProviderServiceTracker.open();
+ }
+
+ private long getConflictingVersionTimeoutMillis(PropertiesProviderBaseImpl propertiesProvider) {
+ String timeoutProperty = propertiesProvider.getProperty(CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY);
+ return timeoutProperty == null ? CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
+ }
+
+ private long getMaxWaitForCapabilitiesMillis(PropertiesProviderBaseImpl propertiesProvider) {
+ String timeoutProperty = propertiesProvider.getProperty(MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY);
+ return timeoutProperty == null ? MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
+ }
+
+ @Override
+ public void stop(BundleContext context) throws Exception {
+ synchronized(autoCloseables) {
+ CloseableUtil.closeAll(autoCloseables);
+ autoCloseables.clear();
+ if (registration != null) {
+ registration.unregister();
+ }
+ this.context = null;
+ }
+ }
+
+ private void startPusherThread(final List<? extends ConfigSnapshotHolder> configs, final long maxWaitForCapabilitiesMillis,
+ final ConfigSubsystemFacadeFactory service, final long conflictingVersionTimeoutMillis, final Persister persisterAggregator){
+ LOG.debug("Creating new job queue");
+ final ConfigPusherImpl configPusher = new ConfigPusherImpl(service,
+ maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
+ LOG.debug("Configuration Persister got {}", service);
+ LOG.debug("Context was {}", context);
+ LOG.debug("Registration was {}", registration);
+ final Thread pushingThread = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if(configs != null && !configs.isEmpty()) {
+ configPusher.pushConfigs(configs);
+ }
+ if(context != null) {
+ registration = context.registerService(ConfigPusher.class.getName(), configPusher, null);
+ configPusher.process(autoCloseables, platformMBeanServer, persisterAggregator);
+ } else {
+ LOG.warn("Unable to process configs as BundleContext is null");
+ }
+ } catch (InterruptedException e) {
+ LOG.info("ConfigPusher thread stopped",e);
+ }
+ LOG.info("Configuration Persister initialization completed.");
+ }
+ }, "config-pusher");
+ synchronized (autoCloseables) {
+ autoCloseables.add(new AutoCloseable() {
+ @Override
+ public void close() {
+ pushingThread.interrupt();
+ }
+ });
+ }
+ pushingThread.start();
+ }
+}
+
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl.osgi;
+package org.opendaylight.controller.config.persist.impl.osgi;
import org.opendaylight.controller.config.persist.api.PropertiesProvider;
import org.osgi.framework.BundleContext;
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import static org.junit.Assert.assertEquals;
+
import com.google.common.base.Charsets;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Element;
public class CapabilityStrippingConfigSnapshotHolderTest {
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.util.ConfigRegistryClient;
public class ConfigPersisterNotificationHandlerTest {
private MBeanServerConnection mBeanServer;
@Mock
private Persister notificationListener;
+ @Mock
+ private ConfigSubsystemFacadeFactory facadeFactory;
+ @Mock
+ private ConfigSubsystemFacade facade;
+ @Mock
+ private ConfigRegistryClient configRegistryClient;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+
+ doReturn(facade).when(facadeFactory).createFacade(anyString());
+
doNothing().when(mBeanServer).addNotificationListener(any(ObjectName.class), any(NotificationListener.class),
any(NotificationFilter.class), anyObject());
}
doReturn(true).when(mBeanServer).isRegistered(any(ObjectName.class));
doThrow(Exception.class).when(mBeanServer).removeNotificationListener(any(ObjectName.class), any(NotificationListener.class));
- final ConfigPersisterNotificationHandler testedHandler = new ConfigPersisterNotificationHandler(mBeanServer, notificationListener);
+ final ConfigPersisterNotificationHandler testedHandler = new ConfigPersisterNotificationHandler(mBeanServer, notificationListener, facadeFactory);
verify(mBeanServer).addNotificationListener(any(ObjectName.class), any(NotificationListener.class),
any(NotificationFilter.class), anyObject());
public void testNotificationHandlerCloseNotRegistered() throws Exception {
doReturn(false).when(mBeanServer).isRegistered(any(ObjectName.class));
- final ConfigPersisterNotificationHandler testedHandler = new ConfigPersisterNotificationHandler(mBeanServer, notificationListener);
+ final ConfigPersisterNotificationHandler testedHandler = new ConfigPersisterNotificationHandler(mBeanServer, notificationListener, facadeFactory);
testedHandler.close();
verify(mBeanServer, times(0)).removeNotificationListener(any(ObjectName.class), any(NotificationListener.class));
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
+
+import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import java.util.Collections;
import javax.management.Notification;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.api.jmx.notifications.CommitJMXNotification;
+import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.facade.xml.Datastore;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
-import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.w3c.dom.Document;
public class ConfigPersisterNotificationListenerTest {
private PersisterAggregator persisterAggregator;
@Mock
- private NetconfJMXNotification unknownNetconfNotif;
+ private ConfigJMXNotification unknownNetconfNotif;
@Mock
private CommitJMXNotification commitNetconfNotif;
@Mock
private Notification unknownNotif;
+ @Mock
+ private ConfigSubsystemFacadeFactory facadeFactory;
+ @Mock
+ private ConfigSubsystemFacade facade;
+ @Mock
+ private ConfigRegistryClient configRegistryClient;
+ @Mock
+ private Capability cap;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- Mockito.doNothing().when(mockPersister).persistConfig(Matchers.any(ConfigSnapshotHolder.class));
- Mockito.doReturn("persister").when(mockPersister).toString();
+ Mockito.doNothing().when(mockPersister).persistConfig(any(ConfigSnapshotHolder.class));
+ doReturn("persister").when(mockPersister).toString();
final PersisterAggregator.PersisterWithConfiguration withCfg = new PersisterAggregator.PersisterWithConfiguration(mockPersister, false);
persisterAggregator = new PersisterAggregator(Lists.newArrayList(withCfg));
- Mockito.doReturn("netconfUnknownNotification").when(unknownNetconfNotif).toString();
- Mockito.doReturn("netconfCommitNotification").when(commitNetconfNotif).toString();
+ doReturn("netconfUnknownNotification").when(unknownNetconfNotif).toString();
+ doReturn("netconfCommitNotification").when(commitNetconfNotif).toString();
+
+ doReturn("config client").when(configRegistryClient).toString();
- Mockito.doReturn(XmlUtil.readXmlToElement("<config-snapshot/>")).when(commitNetconfNotif).getConfigSnapshot();
- Mockito.doReturn(Collections.emptySet()).when(commitNetconfNotif).getCapabilities();
+ doReturn("cap").when(cap).getCapabilityUri();
+ doReturn(facade).when(facadeFactory).createFacade(anyString());
+ doReturn(Collections.singleton(cap)).when(facadeFactory).getCurrentCapabilities();
+ doReturn(XmlUtil.readXmlToElement("<snapshot/>")).when(facade)
+ .getConfiguration(any(Document.class), any(Datastore.class), any(Optional.class));
}
@Test
public void testNotificationListenerUnknownNotification() throws Exception {
- final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator);
+ final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator, facadeFactory);
testeListener.handleNotification(unknownNotif, null);
Mockito.verifyZeroInteractions(mockPersister);
}
@Test
public void testNotificationListenerUnknownNetconfNotification() throws Exception {
- final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator);
+ final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator, facadeFactory);
try {
testeListener.handleNotification(unknownNetconfNotif, null);
Assert.fail("Unknown netconf notification should fail");
@Test
public void testNotificationListenerCommitNetconfNotification() throws Exception {
- final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator);
+ final ConfigPersisterNotificationListener testeListener = new ConfigPersisterNotificationListener(persisterAggregator, facadeFactory);
testeListener.handleNotification(commitNetconfNotif, null);
- Mockito.verify(mockPersister).persistConfig(Matchers.any(ConfigSnapshotHolder.class));
+ Mockito.verify(mockPersister).persistConfig(any(ConfigSnapshotHolder.class));
}
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.config.persist.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+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;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import java.lang.management.ManagementFactory;
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.management.MBeanServerConnection;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.jmx.CommitStatus;
+import org.opendaylight.controller.config.facade.xml.ConfigExecution;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
+import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.spi.Module;
+import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
+import org.w3c.dom.Element;
+
+public class ConfigPusherImplTest {
+
+ @Mock
+ private YangStoreService yangStoreService;
+ @Mock
+ private ConfigSnapshotHolder mockedConfigSnapshot;
+ @Mock
+ private Persister mockedAggregator;
+ @Mock
+ private ConfigRegistryClient configRegistryClient;
+ @Mock
+ private org.opendaylight.yangtools.yang.model.api.Module module;
+ @Mock
+ private ConfigSubsystemFacadeFactory facadeFactory;
+ @Mock
+ private ConfigSubsystemFacade facade;
+ @Mock
+ private MBeanServerConnection mBeanServer;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ doReturn("content").when(yangStoreService).getModuleSource(any(ModuleIdentifier.class));
+ doReturn("mocked snapshot").when(mockedConfigSnapshot).toString();
+ doReturn("<mocked-snapshot/>").when(mockedConfigSnapshot).getConfigSnapshot();
+ doReturn(Collections.<Module>emptySet()).when(yangStoreService).getModules();
+ final Config mock = mock(Config.class);
+ doReturn("mocked config").when(mock).toString();
+ doReturn(facade).when(facadeFactory).createFacade(anyString());
+ doReturn(Sets.newHashSet()).when(facadeFactory).getCurrentCapabilities();
+ doReturn(mock).when(facade).getConfigMapping();
+ doNothing().when(mBeanServer).addNotificationListener(any(ObjectName.class), any(NotificationListener.class), any(NotificationFilter.class), anyObject());
+ }
+
+ @Test
+ public void testPersisterNotAllCapabilitiesProvided() throws Exception {
+ doReturn(new TreeSet<>(Lists.newArrayList("required-cap"))).when(mockedConfigSnapshot).getCapabilities();
+
+ final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 0, 0);
+
+ configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
+ try {
+ configPusher.process(Lists.<AutoCloseable>newArrayList(), ManagementFactory.getPlatformMBeanServer(), mockedAggregator);
+ } catch(IllegalStateException e) {
+ assertNotNull(e.getCause());
+ assertTrue(e.getCause() instanceof ConfigPusherImpl.NotEnoughCapabilitiesException);
+ final Set<String> missingCaps = ((ConfigPusherImpl.NotEnoughCapabilitiesException) e.getCause()).getMissingCaps();
+ assertEquals(missingCaps.size(), 1);
+ assertEquals(missingCaps.iterator().next(), "required-cap");
+ return;
+ }
+
+ fail();
+ }
+
+ @Test
+ public void testPersisterSuccessfulPush() throws Exception {
+ doReturn(new TreeSet<>(Lists.newArrayList("namespace?module=module&revision=2012-12-12"))).when(mockedConfigSnapshot).getCapabilities();
+ final Capability cap = mock(Capability.class);
+ doReturn("namespace?module=module&revision=2012-12-12").when(cap).getCapabilityUri();
+ doReturn(Sets.newHashSet(cap)).when(facadeFactory).getCurrentCapabilities();
+ final ConfigExecution cfgExec = mock(ConfigExecution.class);
+ doReturn("cfg exec").when(cfgExec).toString();
+ doReturn(cfgExec).when(facade).getConfigExecution(any(Config.class), any(Element.class));
+ doNothing().when(facade).executeConfigExecution(any(ConfigExecution.class));
+ doReturn(mock(CommitStatus.class)).when(facade).commitSilentTransaction();
+ doReturn(Sets.newHashSet(module)).when(yangStoreService).getModules();
+
+ final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 0, 0);
+
+ configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
+ configPusher.processSingle(Lists.<AutoCloseable>newArrayList(), mBeanServer, mockedAggregator);
+
+ verify(facade).executeConfigExecution(cfgExec);
+ verify(facade).commitSilentTransaction();
+ }
+
+ @Test
+ public void testPersisterConflictingVersionException() throws Exception {
+ doReturn(new TreeSet<>(Lists.newArrayList("namespace?module=module&revision=2012-12-12"))).when(mockedConfigSnapshot).getCapabilities();
+ final Capability cap = mock(Capability.class);
+ doReturn("namespace?module=module&revision=2012-12-12").when(cap).getCapabilityUri();
+ doReturn(Sets.newHashSet(cap)).when(facadeFactory).getCurrentCapabilities();
+ final ConfigExecution cfgExec = mock(ConfigExecution.class);
+ doReturn("cfg exec").when(cfgExec).toString();
+ doReturn(cfgExec).when(facade).getConfigExecution(any(Config.class), any(Element.class));
+ doNothing().when(facade).executeConfigExecution(any(ConfigExecution.class));
+ doThrow(ConflictingVersionException.class).when(facade).commitSilentTransaction();
+ doReturn(Sets.newHashSet(module)).when(yangStoreService).getModules();
+
+ final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 0, 0);
+
+ configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
+ try {
+ configPusher.processSingle(Lists.<AutoCloseable>newArrayList(), mBeanServer, mockedAggregator);
+ } catch (IllegalStateException e) {
+ assertNotNull(e.getCause());
+ assertTrue(e.getCause() instanceof ConflictingVersionException);
+ return;
+ }
+
+ fail();
+ }
+
+ @Test
+ public void testSuccessConflictingVersionException() throws Exception {
+ doReturn(new TreeSet<>(Lists.newArrayList("namespace?module=module&revision=2012-12-12"))).when(mockedConfigSnapshot).getCapabilities();
+ final Capability cap = mock(Capability.class);
+ doReturn("namespace?module=module&revision=2012-12-12").when(cap).getCapabilityUri();
+ doReturn(Sets.newHashSet(cap)).when(facadeFactory).getCurrentCapabilities();
+ final ConfigExecution cfgExec = mock(ConfigExecution.class);
+ doReturn("cfg exec").when(cfgExec).toString();
+ doReturn(cfgExec).when(facade).getConfigExecution(any(Config.class), any(Element.class));
+ doNothing().when(facade).executeConfigExecution(any(ConfigExecution.class));
+
+ doThrow(ConflictingVersionException.class)
+ .doThrow(ConflictingVersionException.class)
+ .doReturn(mock(CommitStatus.class)).when(facade).commitSilentTransaction();
+
+ doReturn(Sets.newHashSet(module)).when(yangStoreService).getModules();
+
+ final ConfigPusherImpl configPusher = new ConfigPusherImpl(facadeFactory, 5000, 5000);
+
+ configPusher.pushConfigs(Collections.singletonList(mockedConfigSnapshot));
+ configPusher.processSingle(Lists.<AutoCloseable>newArrayList(), mBeanServer, mockedAggregator);
+
+ verify(facade, times(3)).executeConfigExecution(cfgExec);
+ verify(facade, times(3)).commitSilentTransaction();
+ }
+
+}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import java.io.IOException;
import java.util.Collections;
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.persist.impl;
+package org.opendaylight.controller.config.persist.impl;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import static org.opendaylight.controller.netconf.persist.impl.PersisterAggregator.PersisterWithConfiguration;
+import static org.opendaylight.controller.config.persist.impl.PersisterAggregator.PersisterWithConfiguration;
import com.google.common.collect.Lists;
import java.io.IOException;
import org.junit.Test;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.persist.impl.osgi.ConfigPersisterActivator;
+import org.opendaylight.controller.config.persist.impl.osgi.PropertiesProviderBaseImpl;
import org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter;
-import org.opendaylight.controller.netconf.persist.impl.osgi.ConfigPersisterActivator;
-import org.opendaylight.controller.netconf.persist.impl.osgi.PropertiesProviderBaseImpl;
public class PersisterAggregatorTest {
netconf.config.persister.active=1
-netconf.config.persister.1.storageAdapterClass=org.opendaylight.controller.netconf.persist.impl.DummyAdapter
+netconf.config.persister.1.storageAdapterClass=org.opendaylight.controller.config.persist.impl.DummyAdapter
netconf.config.persister.1.properties.fileStorage=target/configuration/initial/
<groupId>${project.groupId}</groupId>
<artifactId>config-api</artifactId>
</dependency>
- <!-- test dependencies -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
+ <!-- test dependencies -->
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>mockito-configuration</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>xmlunit</groupId>
+ <artifactId>xmlunit</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
</dependencies>
<build>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
- <Export-Package>org.opendaylight.controller.config.util</Export-Package>
+ <Export-Package>org.opendaylight.controller.config.util.*</Export-Package>
</instructions>
</configuration>
</plugin>
import javax.management.ObjectName;
-/**
- * Created by mmarsale on 20.2.2015.
- */
public interface BeanReader {
Object getAttributeCurrentValue(ObjectName on, String attributeName);
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.util;
+
+public class CloseableUtil {
+
+ public static void closeAll(Iterable<? extends AutoCloseable> autoCloseables) throws Exception {
+ Exception lastException = null;
+ for (AutoCloseable autoCloseable : autoCloseables) {
+ try {
+ autoCloseable.close();
+ } catch (Exception e) {
+ if (lastException == null) {
+ lastException = e;
+ } else {
+ lastException.addSuppressed(e);
+ }
+ }
+ }
+ if (lastException != null) {
+ throw lastException;
+ }
+
+ }
+}
import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
+import org.opendaylight.controller.config.api.jmx.constants.ConfigRegistryConstants;
public class ConfigRegistryJMXClient implements ConfigRegistryClient {
private final ConfigRegistryMXBean configRegistryMXBeanProxy;
private final MBeanServer configMBeanServer;
public ConfigRegistryJMXClient(MBeanServer configMBeanServer) {
+ this(configMBeanServer, OBJECT_NAME);
+ }
+
+ private ConfigRegistryJMXClient(MBeanServer configMBeanServer, ObjectName configRegistryON) {
this.configMBeanServer = configMBeanServer;
- configRegistryON = OBJECT_NAME;
- Set<ObjectInstance> searchResult = configMBeanServer.queryMBeans(
- configRegistryON, null);
+ this.configRegistryON = configRegistryON;
+ Set<ObjectInstance> searchResult = configMBeanServer.queryMBeans(configRegistryON, null);
if (!(searchResult.size() == 1)) {
throw new IllegalStateException("Config registry not found");
}
false);
}
+ public static ConfigRegistryJMXClient createWithoutNotifications(MBeanServer configMBeanServer) {
+ return new ConfigRegistryJMXClient(configMBeanServer, ConfigRegistryConstants.OBJECT_NAME_NO_NOTIFICATIONS);
+ }
+
@Override
public ConfigTransactionJMXClient createTransaction() {
ObjectName configTransactionControllerON = beginConfig();
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.capability;
+package org.opendaylight.controller.config.util.capability;
import com.google.common.base.Optional;
import java.util.Collection;
import java.util.Collections;
-import org.opendaylight.controller.netconf.api.Capability;
/**
* Capability representing a basic, one-line, string based capability
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.api;
+package org.opendaylight.controller.config.util.capability;
import com.google.common.base.Optional;
import java.util.Collection;
* Contains capability URI announced by server hello message and optionally its
* corresponding yang schema that can be retrieved by get-schema rpc.
*/
+// TODO this should be placed into API bundle for netconf
public interface Capability {
public String getCapabilityUri();
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.util.capability;
+
+import java.util.Set;
+import org.opendaylight.yangtools.yang.model.api.Module;
+
+public interface ModuleListener {
+
+ void onCapabilitiesChanged(Set<Module> added, Set<Module> removed);
+}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.capability;
+package org.opendaylight.controller.config.util.capability;
import com.google.common.base.Optional;
import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.util.xml;
+
+import static org.opendaylight.controller.config.util.xml.XmlMappingConstants.RPC_REPLY_KEY;
+import static org.opendaylight.controller.config.util.xml.XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Checked exception to communicate an error that needs to be sent to the
+ * netconf client.
+ */
+public class DocumentedException extends Exception {
+
+ public static final String RPC_ERROR = "rpc-error";
+ public static final String ERROR_TYPE = "error-type";
+ public static final String ERROR_TAG = "error-tag";
+ public static final String ERROR_SEVERITY = "error-severity";
+ public static final String ERROR_APP_TAG = "error-app-tag";
+ public static final String ERROR_PATH = "error-path";
+ public static final String ERROR_MESSAGE = "error-message";
+ public static final String ERROR_INFO = "error-info";
+
+ private static final long serialVersionUID = 1L;
+
+ private final static Logger LOG = LoggerFactory.getLogger( DocumentedException.class );
+
+ private static final DocumentBuilderFactory BUILDER_FACTORY;
+
+ static {
+ BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
+ try {
+ BUILDER_FACTORY.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-general-entities", false);
+ BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+ BUILDER_FACTORY.setXIncludeAware(false);
+ BUILDER_FACTORY.setExpandEntityReferences(false);
+ } catch (ParserConfigurationException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ BUILDER_FACTORY.setNamespaceAware(true);
+ BUILDER_FACTORY.setCoalescing(true);
+ BUILDER_FACTORY.setIgnoringElementContentWhitespace(true);
+ BUILDER_FACTORY.setIgnoringComments(true);
+ }
+
+ public enum ErrorType {
+ transport, rpc, protocol, application;
+
+ public String getTagValue() {
+ return name();
+ }
+
+ public static ErrorType from( String text ) {
+ try {
+ return valueOf( text );
+ }
+ catch( Exception e ) {
+ return application;
+ }
+ }
+ }
+
+ public enum ErrorTag {
+ access_denied("access-denied"),
+ bad_attribute("bad-attribute"),
+ bad_element("bad-element"),
+ data_exists("data-exists"),
+ data_missing("data-missing"),
+ in_use("in-use"),
+ invalid_value("invalid-value"),
+ lock_denied("lock-denied"),
+ malformed_message("malformed-message"),
+ missing_attribute("missing-attribute"),
+ missing_element("missing-element"),
+ operation_failed("operation-failed"),
+ operation_not_supported("operation-not-supported"),
+ resource_denied("resource-denied"),
+ rollback_failed("rollback-failed"),
+ too_big("too-big"),
+ unknown_attribute("unknown-attribute"),
+ unknown_element("unknown-element"),
+ unknown_namespace("unknown-namespace");
+
+ private final String tagValue;
+
+ ErrorTag(final String tagValue) {
+ this.tagValue = tagValue;
+ }
+
+ public String getTagValue() {
+ return this.tagValue;
+ }
+
+ public static ErrorTag from( String text ) {
+ for( ErrorTag e: values() )
+ {
+ if( e.getTagValue().equals( text ) ) {
+ return e;
+ }
+ }
+
+ return operation_failed;
+ }
+ }
+
+ public enum ErrorSeverity {
+ error, warning;
+
+ public String getTagValue() {
+ return name();
+ }
+
+ public static ErrorSeverity from( String text ) {
+ try {
+ return valueOf( text );
+ }
+ catch( Exception e ) {
+ return error;
+ }
+ }
+ }
+
+ private final ErrorType errorType;
+ private final ErrorTag errorTag;
+ private final ErrorSeverity errorSeverity;
+ private final Map<String, String> errorInfo;
+
+ public DocumentedException(String message) {
+ this(message,
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error
+ );
+ }
+
+ public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity) {
+ this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public DocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+ final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message);
+ this.errorType = errorType;
+ this.errorTag = errorTag;
+ this.errorSeverity = errorSeverity;
+ this.errorInfo = errorInfo;
+ }
+
+ public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ this(message, cause, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ }
+
+ public DocumentedException(final String message, final Exception cause, final ErrorType errorType,
+ final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, cause);
+ this.errorType = errorType;
+ this.errorTag = errorTag;
+ this.errorSeverity = errorSeverity;
+ this.errorInfo = errorInfo;
+ }
+
+ public static <E extends Exception> DocumentedException wrap(E exception) throws DocumentedException {
+ final Map<String, String> errorInfo = new HashMap<>();
+ errorInfo.put(ErrorTag.operation_failed.name(), "Exception thrown");
+ throw new DocumentedException(exception.getMessage(), exception, ErrorType.application, ErrorTag.operation_failed,
+ ErrorSeverity.error, errorInfo);
+ }
+ public static DocumentedException wrap(ValidationException e) throws DocumentedException {
+ final Map<String, String> errorInfo = new HashMap<>();
+ errorInfo.put(ErrorTag.operation_failed.name(), "Validation failed");
+ throw new DocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
+ ErrorSeverity.error, errorInfo);
+ }
+
+ public static DocumentedException wrap(ConflictingVersionException e) throws DocumentedException {
+ final Map<String, String> errorInfo = new HashMap<>();
+ errorInfo.put(ErrorTag.operation_failed.name(), "Optimistic lock failed");
+ throw new DocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
+ ErrorSeverity.error, errorInfo);
+ }
+
+ public static DocumentedException fromXMLDocument( Document fromDoc ) {
+
+ ErrorType errorType = ErrorType.application;
+ ErrorTag errorTag = ErrorTag.operation_failed;
+ ErrorSeverity errorSeverity = ErrorSeverity.error;
+ Map<String, String> errorInfo = null;
+ String errorMessage = "";
+
+ Node rpcReply = fromDoc.getDocumentElement();
+
+ // FIXME: BUG? - we only handle one rpc-error.
+
+ NodeList replyChildren = rpcReply.getChildNodes();
+ for( int i = 0; i < replyChildren.getLength(); i++ ) {
+ Node replyChild = replyChildren.item( i );
+ if( RPC_ERROR.equals( replyChild.getNodeName() ) )
+ {
+ NodeList rpcErrorChildren = replyChild.getChildNodes();
+ for( int j = 0; j < rpcErrorChildren.getLength(); j++ )
+ {
+ Node rpcErrorChild = rpcErrorChildren.item( j );
+ if( ERROR_TYPE.equals( rpcErrorChild.getNodeName() ) ) {
+ errorType = ErrorType.from(rpcErrorChild.getTextContent());
+ }
+ else if( ERROR_TAG.equals( rpcErrorChild.getNodeName() ) ) {
+ errorTag = ErrorTag.from(rpcErrorChild.getTextContent());
+ }
+ else if( ERROR_SEVERITY.equals( rpcErrorChild.getNodeName() ) ) {
+ errorSeverity = ErrorSeverity.from(rpcErrorChild.getTextContent());
+ }
+ else if( ERROR_MESSAGE.equals( rpcErrorChild.getNodeName() ) ) {
+ errorMessage = rpcErrorChild.getTextContent();
+ }
+ else if( ERROR_INFO.equals( rpcErrorChild.getNodeName() ) ) {
+ errorInfo = parseErrorInfo( rpcErrorChild );
+ }
+ }
+
+ break;
+ }
+ }
+
+ return new DocumentedException( errorMessage, errorType, errorTag, errorSeverity, errorInfo );
+ }
+
+ private static Map<String, String> parseErrorInfo( Node node ) {
+ Map<String, String> infoMap = new HashMap<>();
+ NodeList children = node.getChildNodes();
+ for( int i = 0; i < children.getLength(); i++ ) {
+ Node child = children.item( i );
+ if( child.getNodeType() == Node.ELEMENT_NODE ) {
+ infoMap.put( child.getNodeName(), child.getTextContent() );
+ }
+ }
+
+ return infoMap;
+ }
+
+ public ErrorType getErrorType() {
+ return this.errorType;
+ }
+
+ public ErrorTag getErrorTag() {
+ return this.errorTag;
+ }
+
+ public ErrorSeverity getErrorSeverity() {
+ return this.errorSeverity;
+ }
+
+ public Map<String, String> getErrorInfo() {
+ return this.errorInfo;
+ }
+
+ public Document toXMLDocument() {
+ Document doc = null;
+ try {
+ doc = BUILDER_FACTORY.newDocumentBuilder().newDocument();
+
+ Node rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_REPLY_KEY);
+ doc.appendChild( rpcReply );
+
+ Node rpcError = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_ERROR );
+ rpcReply.appendChild( rpcError );
+
+ rpcError.appendChild( createTextNode( doc, ERROR_TYPE, getErrorType().getTagValue() ) );
+ rpcError.appendChild( createTextNode( doc, ERROR_TAG, getErrorTag().getTagValue() ) );
+ rpcError.appendChild( createTextNode( doc, ERROR_SEVERITY, getErrorSeverity().getTagValue() ) );
+ rpcError.appendChild( createTextNode( doc, ERROR_MESSAGE, getLocalizedMessage() ) );
+
+ Map<String, String> errorInfoMap = getErrorInfo();
+ if( errorInfoMap != null && !errorInfoMap.isEmpty() ) {
+ /*
+ * <error-info>
+ * <bad-attribute>message-id</bad-attribute>
+ * <bad-element>rpc</bad-element>
+ * </error-info>
+ */
+
+ Node errorInfoNode = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, ERROR_INFO );
+ errorInfoNode.setPrefix( rpcReply.getPrefix() );
+ rpcError.appendChild( errorInfoNode );
+
+ for ( Entry<String, String> entry : errorInfoMap.entrySet() ) {
+ errorInfoNode.appendChild( createTextNode( doc, entry.getKey(), entry.getValue() ) );
+ }
+ }
+ }
+ catch( ParserConfigurationException e ) {
+ LOG.error( "Error outputting to XML document", e ); // this shouldn't happen
+ }
+
+ return doc;
+ }
+
+ private Node createTextNode( Document doc, String tag, String textContent ) {
+ Node node = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, tag );
+ node.setTextContent( textContent );
+ return node;
+ }
+
+ @Override
+ public String toString() {
+ return "NetconfDocumentedException{" + "message=" + getMessage() + ", errorType=" + this.errorType
+ + ", errorTag=" + this.errorTag + ", errorSeverity=" + this.errorSeverity + ", errorInfo="
+ + this.errorInfo + '}';
+ }
+}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.exception;
+package org.opendaylight.controller.config.util.xml;
import java.util.Collections;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-public class MissingNameSpaceException extends NetconfDocumentedException {
+public class MissingNameSpaceException extends DocumentedException {
private static final long serialVersionUID = 1L;
- public MissingNameSpaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
+ public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
+ final DocumentedException.ErrorSeverity errorSeverity) {
this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
}
- public MissingNameSpaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ public MissingNameSpaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
+ final DocumentedException.ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
super(message,errorType,errorTag,errorSeverity,errorInfo);
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.exception;
+package org.opendaylight.controller.config.util.xml;
import java.util.Collections;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-public class UnexpectedElementException extends NetconfDocumentedException {
+public class UnexpectedElementException extends DocumentedException {
private static final long serialVersionUID = 1L;
- public UnexpectedElementException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
+ public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
+ final DocumentedException.ErrorSeverity errorSeverity) {
this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
}
- public UnexpectedElementException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ public UnexpectedElementException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
+ final DocumentedException.ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
super(message,errorType,errorTag,errorSeverity,errorInfo);
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.exception;
+package org.opendaylight.controller.config.util.xml;
import java.util.Collections;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-public class UnexpectedNamespaceException extends NetconfDocumentedException {
+public class UnexpectedNamespaceException extends DocumentedException {
private static final long serialVersionUID = 1L;
- public UnexpectedNamespaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
+ public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
+ final DocumentedException.ErrorSeverity errorSeverity) {
this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
}
- public UnexpectedNamespaceException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
+ public UnexpectedNamespaceException(final String message, final DocumentedException.ErrorType errorType, final DocumentedException.ErrorTag errorTag,
+ final DocumentedException.ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
super(message,errorType,errorTag,errorSeverity,errorInfo);
}
}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.xml;
+package org.opendaylight.controller.config.util.xml;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
return new XmlElement(xml.getDocumentElement());
}
- public static XmlElement fromString(String s) throws NetconfDocumentedException {
+ public static XmlElement fromString(String s) throws DocumentedException {
try {
return new XmlElement(XmlUtil.readXmlToElement(s));
} catch (IOException | SAXException e) {
- throw NetconfDocumentedException.wrap(e);
+ throw DocumentedException.wrap(e);
}
}
- public static XmlElement fromDomElementWithExpected(Element element, String expectedName) throws NetconfDocumentedException {
+ public static XmlElement fromDomElementWithExpected(Element element, String expectedName) throws DocumentedException {
XmlElement xmlElement = XmlElement.fromDomElement(element);
xmlElement.checkName(expectedName);
return xmlElement;
}
- public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) throws NetconfDocumentedException {
+ public static XmlElement fromDomElementWithExpected(Element element, String expectedName, String expectedNamespace) throws DocumentedException {
XmlElement xmlElement = XmlElement.fromDomElementWithExpected(element, expectedName);
xmlElement.checkNamespace(expectedNamespace);
return xmlElement;
}
- private Map<String, String> extractNamespaces() throws NetconfDocumentedException {
+ private Map<String, String> extractNamespaces() throws DocumentedException {
Map<String, String> namespaces = new HashMap<>();
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
prefix = DEFAULT_NAMESPACE_PREFIX;
} else {
if (!attribKey.startsWith(XmlUtil.XMLNS_ATTRIBUTE_KEY + ":")){
- throw new NetconfDocumentedException("Attribute doesn't start with :",
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Attribute doesn't start with :",
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
prefix = attribKey.substring(XmlUtil.XMLNS_ATTRIBUTE_KEY.length() + 1);
}
if (!getName().equals(expectedName)){
throw new UnexpectedElementException(String.format("Expected %s xml element but was %s", expectedName,
getName()),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
getNamespaceAttribute(),
expectedNamespace),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
throw new UnexpectedNamespaceException(String.format("Unexpected namespace %s should be %s",
getNamespace(),
expectedNamespace),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
}
});
}
- public XmlElement getOnlyChildElement(String childName) throws NetconfDocumentedException {
+ public XmlElement getOnlyChildElement(String childName) throws DocumentedException {
List<XmlElement> nameElements = getChildElements(childName);
if (nameElements.size() != 1){
- throw new NetconfDocumentedException("One element " + childName + " expected in " + toString(),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("One element " + childName + " expected in " + toString(),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
return nameElements.get(0);
}
return Optional.of(children.get(0));
}
- public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws NetconfDocumentedException {
+ public XmlElement getOnlyChildElementWithSameNamespace(String childName) throws DocumentedException {
return getOnlyChildElement(childName, getNamespace());
}
return Optional.absent();
}
- public XmlElement getOnlyChildElementWithSameNamespace() throws NetconfDocumentedException {
+ public XmlElement getOnlyChildElementWithSameNamespace() throws DocumentedException {
XmlElement childElement = getOnlyChildElement();
childElement.checkNamespace(getNamespace());
return childElement;
return Optional.absent();
}
- public XmlElement getOnlyChildElement(final String childName, String namespace) throws NetconfDocumentedException {
+ public XmlElement getOnlyChildElement(final String childName, String namespace) throws DocumentedException {
List<XmlElement> children = getChildElementsWithinNamespace(namespace);
children = Lists.newArrayList(Collections2.filter(children, new Predicate<XmlElement>() {
@Override
}
}));
if (children.size() != 1){
- throw new NetconfDocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
+ throw new DocumentedException(String.format("One element %s:%s expected in %s but was %s", namespace,
childName, toString(), children.size()),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
return children.get(0);
}
- public XmlElement getOnlyChildElement() throws NetconfDocumentedException {
+ public XmlElement getOnlyChildElement() throws DocumentedException {
List<XmlElement> children = getChildElements();
if (children.size() != 1){
- throw new NetconfDocumentedException(String.format( "One element expected in %s but was %s", toString(),
+ throw new DocumentedException(String.format( "One element expected in %s but was %s", toString(),
children.size()),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
return children.get(0);
}
return Optional.of(children.get(0));
}
- public String getTextContent() throws NetconfDocumentedException {
+ public String getTextContent() throws DocumentedException {
NodeList childNodes = element.getChildNodes();
if (childNodes.getLength() == 0) {
return DEFAULT_NAMESPACE_PREFIX;
return content.trim();
}
}
- throw new NetconfDocumentedException(getName() + " should contain text.",
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error
+ throw new DocumentedException(getName() + " should contain text.",
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error
);
}
if (attribute == null || attribute.equals(DEFAULT_NAMESPACE_PREFIX)){
throw new MissingNameSpaceException(String.format("Element %s must specify namespace",
toString()),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
return attribute;
}
Optional<String> namespaceURI = getNamespaceOptionally();
if (!namespaceURI.isPresent()){
throw new MissingNameSpaceException(String.format("No namespace defined for %s", this),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
return namespaceURI.get();
}
* namespace is returned with empty string as key. If no default namespace
* is found value will be null.
*/
- public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws NetconfDocumentedException {
+ public Map.Entry<String/* prefix */, String/* namespace */> findNamespaceOfTextContent() throws DocumentedException {
Map<String, String> namespaces = extractNamespaces();
String textContent = getTextContent();
int indexOfColon = textContent.indexOf(':');
}
public void checkUnrecognisedElements(List<XmlElement> recognisedElements,
- XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
+ XmlElement... additionalRecognisedElements) throws DocumentedException {
List<XmlElement> childElements = getChildElements();
childElements.removeAll(recognisedElements);
for (XmlElement additionalRecognisedElement : additionalRecognisedElements) {
childElements.remove(additionalRecognisedElement);
}
if (!childElements.isEmpty()){
- throw new NetconfDocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException(String.format("Unrecognised elements %s in %s", childElements, this),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
}
- public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws NetconfDocumentedException {
+ public void checkUnrecognisedElements(XmlElement... additionalRecognisedElements) throws DocumentedException {
checkUnrecognisedElements(Collections.<XmlElement>emptyList(), additionalRecognisedElements);
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.config.util.xml;
+
+public final class XmlMappingConstants {
+
+
+ private XmlMappingConstants() {}
+
+ public static final String RPC_REPLY_KEY = "rpc-reply";
+ public static final String TYPE_KEY = "type";
+ public static final String MODULE_KEY = "module";
+ public static final String INSTANCE_KEY = "instance";
+ public static final String OPERATION_ATTR_KEY = "operation";
+ public static final String SERVICES_KEY = "services";
+ public static final String CONFIG_KEY = "config";
+ public static final String MODULES_KEY = "modules";
+ public static final String DATA_KEY = "data";
+ public static final String NAME_KEY = "name";
+
+ public static final String PREFIX = "prefix";
+
+ public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = "urn:ietf:params:xml:ns:netconf:base:1.0";
+ public static final String URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG = "urn:opendaylight:params:xml:ns:yang:controller:config";
+}
/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.xml;
+package org.opendaylight.controller.config.util.xml;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import javax.xml.validation.SchemaFactory;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public static Element createTextElementWithNamespacedContent(final Document document, final String qName, final String prefix,
final String namespace, final String contentWithoutPrefix, final Optional<String> namespaceURI) {
- String content = createPrefixedValue(XmlNetconfConstants.PREFIX, contentWithoutPrefix);
+ String content = createPrefixedValue(XmlMappingConstants.PREFIX, contentWithoutPrefix);
Element element = createTextElement(document, qName, content, namespaceURI);
String prefixedNamespaceAttr = createPrefixedValue(XMLNS_ATTRIBUTE_KEY, prefix);
element.setAttributeNS(XMLNS_URI, prefixedNamespaceAttr, namespace);
transformer.transform(source, result);
return result.getWriter().toString();
- } catch (Exception | TransformerFactoryConfigurationError e) {
+ } catch (Exception | TransformerFactoryConfigurationError e) {
throw new IllegalStateException("Unable to serialize xml element " + xml, e);
}
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.xml;
+package org.opendaylight.controller.config.util.xml;
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
try {
XmlElement.fromString("notXml");
fail();
- } catch (final NetconfDocumentedException e) {}
+ } catch (final DocumentedException e) {}
try {
XmlElement.fromDomElementWithExpected(element, "notTop");
fail();
- } catch (final NetconfDocumentedException e) {}
+ } catch (final DocumentedException e) {}
try {
XmlElement.fromDomElementWithExpected(element, "top", "notNamespace");
fail();
- } catch (final NetconfDocumentedException e) {}
+ } catch (final DocumentedException e) {}
}
@Test
try {
xmlElement.checkUnrecognisedElements(xmlElement.getOnlyChildElement("inner"));
fail();
- } catch (final NetconfDocumentedException e) {
+ } catch (final DocumentedException e) {
assertThat(e.getMessage(), both(containsString("innerNamespace")).and(containsString("innerNamespace")));
}
}
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-package org.opendaylight.controller.netconf.util.xml;
+package org.opendaylight.controller.config.util.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.common.base.Optional;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
+import java.io.ByteArrayInputStream;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
public void testLoadSchema() throws Exception {
XmlUtil.loadSchema();
try {
- XmlUtil.loadSchema(getClass().getResourceAsStream("/netconfMessages/commit.xml"));
+ XmlUtil.loadSchema(new ByteArrayInputStream(xml.getBytes()));
fail("Input stream does not contain xsd");
} catch (final IllegalStateException e) {
assertTrue(e.getCause() instanceof SAXParseException);
" </hello>]]>]]>");
}
- @Test
- public void testXPath() throws Exception {
- final XPathExpression correctXPath = XMLNetconfUtil.compileXPath("/top/innerText");
- try {
- XMLNetconfUtil.compileXPath("!@(*&$!");
- fail("Incorrect xpath should fail");
- } catch (IllegalStateException e) {}
- final Object value = XmlUtil.evaluateXPath(correctXPath, XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
- assertEquals("value", ((Element) value).getTextContent());
- }
}
\ No newline at end of file
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
- <Private-Package></Private-Package>
<Export-Package>org.opendaylight.controller.config.yang.logback.config,
org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.logback.config.rev130716.*,</Export-Package>
</instructions>
<module>config-persister-api</module>
<module>config-persister-file-xml-adapter</module>
<module>config-persister-feature-adapter</module>
+ <module>config-manager-facade-xml</module>
<module>yang-jmx-generator</module>
<module>yang-jmx-generator-plugin</module>
<module>yang-test</module>
<module>yang-test-plugin</module>
<module>shutdown-api</module>
<module>shutdown-impl</module>
- <module>netconf-config-dispatcher</module>
<module>config-module-archetype</module>
<module>config-netty-config</module>
<module>config-artifacts</module>
<module>config-parent</module>
+ <module>config-persister-impl</module>
<module>config-it-base</module>
</modules>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Export-Package>org.opendaylight.controller.config.shutdown,
- org.opendaylight.controller.config.yang.shutdown,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.shutdown.rev131218</Export-Package>
- </instructions>
- </configuration>
</plugin>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<scope>runtime</scope>
</dependency>
- <!-- FIXME: move this into netconf-artifacts -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>sal-netconf-connector</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>features-netconf-connector</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- <scope>runtime</scope>
- </dependency>
-
<!-- FIXME: These below need splitting up -->
<!-- AD-SAL compatibility -->
<packaging>bundle</packaging>\r
\r
<dependencies>\r
- <dependency>\r
- <groupId>org.opendaylight.controller</groupId>\r
- <artifactId>ietf-netconf-notifications</artifactId>\r
- </dependency>\r
<dependency>\r
<groupId>org.opendaylight.controller</groupId>\r
<artifactId>sal-binding-api</artifactId>\r
<artifactId>messagebus-spi</artifactId>\r
<version>1.3.0-SNAPSHOT</version>\r
</dependency>\r
- <dependency>\r
- <groupId>org.opendaylight.controller</groupId>\r
- <artifactId>sal-netconf-connector</artifactId>\r
- </dependency>\r
+ <!--<dependency>-->\r
+ <!--<groupId>org.opendaylight.controller</groupId>-->\r
+ <!--<artifactId>sal-netconf-connector</artifactId>-->\r
+ <!--</dependency>-->\r
<dependency>\r
<groupId>org.opendaylight.controller</groupId>\r
<artifactId>sal-binding-config</artifactId>\r
import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
import org.opendaylight.controller.messagebus.app.impl.EventSourceTopology;
-import org.opendaylight.controller.messagebus.eventsources.netconf.NetconfEventSourceManager;
+//import org.opendaylight.controller.messagebus.eventsources.netconf.NetconfEventSourceManager;
import org.opendaylight.controller.messagebus.spi.EventSource;
import org.opendaylight.controller.messagebus.spi.EventSourceRegistration;
import org.opendaylight.controller.messagebus.spi.EventSourceRegistry;
final RpcProviderRegistry rpcRegistry = bindingCtx.getSALService(RpcProviderRegistry.class);
final MountPointService mountPointService = bindingCtx.getSALService(MountPointService.class);
final EventSourceRegistryWrapper eventSourceRegistryWrapper = new EventSourceRegistryWrapper(new EventSourceTopology(dataBroker, rpcRegistry));
- final NetconfEventSourceManager netconfEventSourceManager
- = NetconfEventSourceManager.create(dataBroker,
- domPublish,
- domMount,
- mountPointService,
- eventSourceRegistryWrapper,
- getNamespaceToStream());
- eventSourceRegistryWrapper.addAutoCloseable(netconfEventSourceManager);
+// final NetconfEventSourceManager netconfEventSourceManager
+// = NetconfEventSourceManager.create(dataBroker,
+// domPublish,
+// domMount,
+// mountPointService,
+// eventSourceRegistryWrapper,
+// getNamespaceToStream());
+// eventSourceRegistryWrapper.addAutoCloseable(netconfEventSourceManager);
LOGGER.info("Messagebus initialized");
return eventSourceRegistryWrapper;
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-import static com.google.common.util.concurrent.Futures.immediateFuture;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Future;
-import java.util.regex.Pattern;
-
-import javax.xml.stream.XMLStreamException;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.MountPoint;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
-import org.opendaylight.controller.messagebus.app.impl.TopicDOMNotification;
-import org.opendaylight.controller.messagebus.app.impl.Util;
-import org.opendaylight.controller.messagebus.spi.EventSource;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutput;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicStatus;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicInput;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.google.common.util.concurrent.CheckedFuture;
-
-public class NetconfEventSource implements EventSource, DOMNotificationListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSource.class);
-
- private static final NodeIdentifier TOPIC_NOTIFICATION_ARG = new NodeIdentifier(TopicNotification.QNAME);
- private static final NodeIdentifier EVENT_SOURCE_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "node-id"));
- private static final NodeIdentifier TOPIC_ID_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "topic-id"));
- private static final NodeIdentifier PAYLOAD_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "payload"));
- private static final String ConnectionNotificationSourceName = "ConnectionNotificationSource";
-
- private final String nodeId;
- private final Node node;
-
- private final DOMMountPoint netconfMount;
- private final MountPoint mountPoint;
- private final DOMNotificationPublishService domPublish;
-
- private final Map<String, String> urnPrefixToStreamMap; // key = urnPrefix, value = StreamName
- private final List<NotificationTopicRegistration> notificationTopicRegistrationList = new ArrayList<>();
-
- public NetconfEventSource(final Node node, final Map<String, String> streamMap, final DOMMountPoint netconfMount, final MountPoint mountPoint, final DOMNotificationPublishService publishService) {
- this.netconfMount = Preconditions.checkNotNull(netconfMount);
- this.mountPoint = Preconditions.checkNotNull(mountPoint);
- this.node = Preconditions.checkNotNull(node);
- this.urnPrefixToStreamMap = Preconditions.checkNotNull(streamMap);
- this.domPublish = Preconditions.checkNotNull(publishService);
- this.nodeId = node.getNodeId().getValue();
- this.initializeNotificationTopicRegistrationList();
-
- LOG.info("NetconfEventSource [{}] created.", this.nodeId);
- }
-
- private void initializeNotificationTopicRegistrationList() {
- notificationTopicRegistrationList.add(new ConnectionNotificationTopicRegistration(ConnectionNotificationSourceName, this));
- Optional<Map<String, Stream>> streamMap = getAvailableStreams();
- if(streamMap.isPresent()){
- LOG.debug("Stream configuration compare...");
- for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
- final String streamName = this.urnPrefixToStreamMap.get(urnPrefix);
- LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName);
- if(streamMap.get().containsKey(streamName)){
- LOG.debug("Stream containig on device");
- notificationTopicRegistrationList.add(new StreamNotificationTopicRegistration(streamMap.get().get(streamName),urnPrefix, this));
- }
- }
- }
- }
-
- private Optional<Map<String, Stream>> getAvailableStreams(){
-
- Map<String,Stream> streamMap = null;
- InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build();
- Optional<DataBroker> dataBroker = this.mountPoint.getService(DataBroker.class);
-
- if(dataBroker.isPresent()){
- LOG.debug("GET Available streams ...");
- ReadOnlyTransaction tx = dataBroker.get().newReadOnlyTransaction();
- CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = tx.read(LogicalDatastoreType.OPERATIONAL,pathStream);
-
- try {
- Optional<Streams> streams = checkFeature.checkedGet();
- if(streams.isPresent()){
- streamMap = new HashMap<>();
- for(Stream stream : streams.get().getStream()){
- LOG.debug("*** find stream {}", stream.getName().getValue());
- streamMap.put(stream.getName().getValue(), stream);
- }
- }
- } catch (ReadFailedException e) {
- LOG.warn("Can not read streams for node {}",this.nodeId);
- }
-
- } else {
- LOG.warn("No databroker on node {}", this.nodeId);
- }
-
- return Optional.fromNullable(streamMap);
- }
-
- @Override
- public Future<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) {
- LOG.debug("Join topic {} on {}", input.getTopicId().getValue(), this.nodeId);
- final NotificationPattern notificationPattern = input.getNotificationPattern();
- final List<SchemaPath> matchingNotifications = getMatchingNotifications(notificationPattern);
- return registerTopic(input.getTopicId(),matchingNotifications);
-
- }
-
- @Override
- public Future<RpcResult<Void>> disJoinTopic(DisJoinTopicInput input) {
- for(NotificationTopicRegistration reg : notificationTopicRegistrationList){
- reg.unRegisterNotificationTopic(input.getTopicId());
- }
- return Util.resultRpcSuccessFor((Void) null) ;
- }
-
- private synchronized Future<RpcResult<JoinTopicOutput>> registerTopic(final TopicId topicId, final List<SchemaPath> notificationsToSubscribe){
- LOG.debug("Join topic {} - register");
- JoinTopicStatus joinTopicStatus = JoinTopicStatus.Down;
- if(notificationsToSubscribe != null && notificationsToSubscribe.isEmpty() == false){
- LOG.debug("Notifications to subscribe has found - count {}",notificationsToSubscribe.size() );
- final Optional<DOMNotificationService> notifyService = getDOMMountPoint().getService(DOMNotificationService.class);
- if(notifyService.isPresent()){
- int registeredNotificationCount = 0;
- for(SchemaPath schemaNotification : notificationsToSubscribe){
- for(NotificationTopicRegistration reg : notificationTopicRegistrationList){
- LOG.debug("Try notification registratio {} on SchemaPathNotification {}", reg.getSourceName(), schemaNotification.getLastComponent().getLocalName());
- if(reg.checkNotificationPath(schemaNotification)){
- LOG.info("Source of notification {} is activating, TopicId {}", reg.getSourceName(), topicId.getValue() );
- boolean regSuccess = reg.registerNotificationTopic(schemaNotification, topicId);
- if(regSuccess){
- registeredNotificationCount = registeredNotificationCount +1;
- }
- }
- }
- }
- if(registeredNotificationCount > 0){
- joinTopicStatus = JoinTopicStatus.Up;
- }
- } else {
- LOG.warn("NO DOMNotification service on node {}", this.nodeId);
- }
- } else {
- LOG.debug("Notifications to subscribe has NOT found");
- }
-
- final JoinTopicOutput output = new JoinTopicOutputBuilder().setStatus(joinTopicStatus).build();
- return immediateFuture(RpcResultBuilder.success(output).build());
-
- }
-
- public void reActivateStreams(){
- for (NotificationTopicRegistration reg : notificationTopicRegistrationList) {
- LOG.info("Source of notification {} is reactivating on node {}", reg.getSourceName(), this.nodeId);
- reg.reActivateNotificationSource();
- }
- }
-
- public void deActivateStreams(){
- for (NotificationTopicRegistration reg : notificationTopicRegistrationList) {
- LOG.info("Source of notification {} is deactivating on node {}", reg.getSourceName(), this.nodeId);
- reg.deActivateNotificationSource();
- }
- }
-
- @Override
- public void onNotification(final DOMNotification notification) {
- SchemaPath notificationPath = notification.getType();
- Date notificationEventTime = null;
- if(notification instanceof DOMEvent){
- notificationEventTime = ((DOMEvent) notification).getEventTime();
- }
- for(NotificationTopicRegistration notifReg : notificationTopicRegistrationList){
- ArrayList<TopicId> topicIdsForNotification = notifReg.getNotificationTopicIds(notificationPath);
- if(topicIdsForNotification != null && topicIdsForNotification.isEmpty() == false){
-
- if(notifReg instanceof StreamNotificationTopicRegistration){
- StreamNotificationTopicRegistration streamReg = (StreamNotificationTopicRegistration)notifReg;
- streamReg.setLastEventTime(notificationEventTime);
- }
-
- for(TopicId topicId : topicIdsForNotification){
- publishNotification(notification, topicId);
- LOG.debug("Notification {} has been published for TopicId {}",notification.getType(), 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, this.nodeId))
- .withChild(encapsulate(notification))
- .build();
- try {
- domPublish.putNotification(new TopicDOMNotification(topicNotification));
- } catch (final InterruptedException e) {
- throw Throwables.propagate(e);
- }
- }
-
- private AnyXmlNode encapsulate(final DOMNotification body) {
- // FIXME: Introduce something like AnyXmlWithNormalizedNodeData in Yangtools
- final Document doc = XmlUtil.newDocument();
- final Optional<String> namespace = Optional.of(PAYLOAD_ARG.getNodeType().getNamespace().toString());
- final Element element = XmlUtil.createElement(doc , "payload", namespace);
-
- final DOMResult result = new DOMResult(element);
-
- final SchemaContext context = getDOMMountPoint().getSchemaContext();
- final SchemaPath schemaPath = body.getType();
- try {
- NetconfMessageTransformUtil.writeNormalizedNode(body.getBody(), result, schemaPath, context);
- return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG)
- .withValue(new DOMSource(element))
- .build();
- } catch (IOException | XMLStreamException e) {
- LOG.error("Unable to encapsulate notification.",e);
- throw Throwables.propagate(e);
- }
- }
-
- private List<SchemaPath> getMatchingNotifications(NotificationPattern notificationPattern){
- // FIXME: default language should already be regex
- final String regex = Util.wildcardToRegex(notificationPattern.getValue());
-
- final Pattern pattern = Pattern.compile(regex);
- List<SchemaPath> availableNotifications = getAvailableNotifications();
- if(availableNotifications == null || availableNotifications.isEmpty()){
- return null;
- }
- return Util.expandQname(availableNotifications, pattern);
- }
-
- @Override
- public void close() throws Exception {
- for(NotificationTopicRegistration streamReg : notificationTopicRegistrationList){
- streamReg.close();
- }
- }
-
- @Override
- public NodeKey getSourceNodeKey(){
- return getNode().getKey();
- }
-
- @Override
- public List<SchemaPath> getAvailableNotifications() {
-
- final List<SchemaPath> availNotifList = new ArrayList<>();
- // add Event Source Connection status notification
- availNotifList.add(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
-
- // FIXME: use SchemaContextListener to get changes asynchronously
- final Set<NotificationDefinition> availableNotifications = getDOMMountPoint().getSchemaContext().getNotifications();
- // add all known notifications from netconf device
- for (final NotificationDefinition nd : availableNotifications) {
- availNotifList.add(nd.getPath());
- }
- return availNotifList;
- }
-
- public Node getNode() {
- return node;
- }
-
- DOMMountPoint getDOMMountPoint() {
- return netconfMount;
- }
-
- MountPoint getMountPoint() {
- return mountPoint;
- }
-
- NetconfNode getNetconfNode(){
- return node.getAugmentation(NetconfNode.class);
- }
-
-}
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//import static com.google.common.util.concurrent.Futures.immediateFuture;
+//
+//import java.io.IOException;
+//import java.util.ArrayList;
+//import java.util.Date;
+//import java.util.HashMap;
+//import java.util.List;
+//import java.util.Map;
+//import java.util.Set;
+//import java.util.concurrent.Future;
+//import java.util.regex.Pattern;
+//
+//import javax.xml.stream.XMLStreamException;
+//import javax.xml.transform.dom.DOMResult;
+//import javax.xml.transform.dom.DOMSource;
+//
+//import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+//import org.opendaylight.controller.md.sal.binding.api.MountPoint;
+//import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+//import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+//import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+//import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
+//import org.opendaylight.controller.messagebus.app.impl.TopicDOMNotification;
+//import org.opendaylight.controller.messagebus.app.impl.Util;
+//import org.opendaylight.controller.messagebus.spi.EventSource;
+//import org.opendaylight.controller.config.util.xml.XmlUtil;
+//import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicNotification;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutput;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicOutputBuilder;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicStatus;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.DisJoinTopicInput;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
+//import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+//import org.opendaylight.yangtools.yang.common.QName;
+//import org.opendaylight.yangtools.yang.common.RpcResult;
+//import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+//import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+//import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
+//import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+//import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+//import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+//import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+//import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+//import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+//import org.slf4j.Logger;
+//import org.slf4j.LoggerFactory;
+//import org.w3c.dom.Document;
+//import org.w3c.dom.Element;
+//
+//import com.google.common.base.Optional;
+//import com.google.common.base.Preconditions;
+//import com.google.common.base.Throwables;
+//import com.google.common.util.concurrent.CheckedFuture;
+//
+//public class NetconfEventSource implements EventSource, DOMNotificationListener {
+//
+// private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSource.class);
+//
+// private static final NodeIdentifier TOPIC_NOTIFICATION_ARG = new NodeIdentifier(TopicNotification.QNAME);
+// private static final NodeIdentifier EVENT_SOURCE_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "node-id"));
+// private static final NodeIdentifier TOPIC_ID_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "topic-id"));
+// private static final NodeIdentifier PAYLOAD_ARG = new NodeIdentifier(QName.create(TopicNotification.QNAME, "payload"));
+// private static final String ConnectionNotificationSourceName = "ConnectionNotificationSource";
+//
+// private final String nodeId;
+// private final Node node;
+//
+// private final DOMMountPoint netconfMount;
+// private final MountPoint mountPoint;
+// private final DOMNotificationPublishService domPublish;
+//
+// private final Map<String, String> urnPrefixToStreamMap; // key = urnPrefix, value = StreamName
+// private final List<NotificationTopicRegistration> notificationTopicRegistrationList = new ArrayList<>();
+//
+// public NetconfEventSource(final Node node, final Map<String, String> streamMap, final DOMMountPoint netconfMount, final MountPoint mountPoint, final DOMNotificationPublishService publishService) {
+// this.netconfMount = Preconditions.checkNotNull(netconfMount);
+// this.mountPoint = Preconditions.checkNotNull(mountPoint);
+// this.node = Preconditions.checkNotNull(node);
+// this.urnPrefixToStreamMap = Preconditions.checkNotNull(streamMap);
+// this.domPublish = Preconditions.checkNotNull(publishService);
+// this.nodeId = node.getNodeId().getValue();
+// this.initializeNotificationTopicRegistrationList();
+//
+// LOG.info("NetconfEventSource [{}] created.", this.nodeId);
+// }
+//
+// private void initializeNotificationTopicRegistrationList() {
+// notificationTopicRegistrationList.add(new ConnectionNotificationTopicRegistration(ConnectionNotificationSourceName, this));
+// Optional<Map<String, Stream>> streamMap = getAvailableStreams();
+// if(streamMap.isPresent()){
+// LOG.debug("Stream configuration compare...");
+// for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
+// final String streamName = this.urnPrefixToStreamMap.get(urnPrefix);
+// LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName);
+// if(streamMap.get().containsKey(streamName)){
+// LOG.debug("Stream containig on device");
+// notificationTopicRegistrationList.add(new StreamNotificationTopicRegistration(streamMap.get().get(streamName),urnPrefix, this));
+// }
+// }
+// }
+// }
+//
+// private Optional<Map<String, Stream>> getAvailableStreams(){
+//
+// Map<String,Stream> streamMap = null;
+// InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build();
+// Optional<DataBroker> dataBroker = this.mountPoint.getService(DataBroker.class);
+//
+// if(dataBroker.isPresent()){
+// LOG.debug("GET Available streams ...");
+// ReadOnlyTransaction tx = dataBroker.get().newReadOnlyTransaction();
+// CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = tx.read(LogicalDatastoreType.OPERATIONAL,pathStream);
+//
+// try {
+// Optional<Streams> streams = checkFeature.checkedGet();
+// if(streams.isPresent()){
+// streamMap = new HashMap<>();
+// for(Stream stream : streams.get().getStream()){
+// LOG.debug("*** find stream {}", stream.getName().getValue());
+// streamMap.put(stream.getName().getValue(), stream);
+// }
+// }
+// } catch (ReadFailedException e) {
+// LOG.warn("Can not read streams for node {}",this.nodeId);
+// }
+//
+// } else {
+// LOG.warn("No databroker on node {}", this.nodeId);
+// }
+//
+// return Optional.fromNullable(streamMap);
+// }
+//
+// @Override
+// public Future<RpcResult<JoinTopicOutput>> joinTopic(final JoinTopicInput input) {
+// LOG.debug("Join topic {} on {}", input.getTopicId().getValue(), this.nodeId);
+// final NotificationPattern notificationPattern = input.getNotificationPattern();
+// final List<SchemaPath> matchingNotifications = getMatchingNotifications(notificationPattern);
+// return registerTopic(input.getTopicId(),matchingNotifications);
+//
+// }
+//
+// @Override
+// public Future<RpcResult<Void>> disJoinTopic(DisJoinTopicInput input) {
+// for(NotificationTopicRegistration reg : notificationTopicRegistrationList){
+// reg.unRegisterNotificationTopic(input.getTopicId());
+// }
+// return Util.resultRpcSuccessFor((Void) null) ;
+// }
+//
+// private synchronized Future<RpcResult<JoinTopicOutput>> registerTopic(final TopicId topicId, final List<SchemaPath> notificationsToSubscribe){
+// LOG.debug("Join topic {} - register");
+// JoinTopicStatus joinTopicStatus = JoinTopicStatus.Down;
+// if(notificationsToSubscribe != null && notificationsToSubscribe.isEmpty() == false){
+// LOG.debug("Notifications to subscribe has found - count {}",notificationsToSubscribe.size() );
+// final Optional<DOMNotificationService> notifyService = getDOMMountPoint().getService(DOMNotificationService.class);
+// if(notifyService.isPresent()){
+// int registeredNotificationCount = 0;
+// for(SchemaPath schemaNotification : notificationsToSubscribe){
+// for(NotificationTopicRegistration reg : notificationTopicRegistrationList){
+// LOG.debug("Try notification registratio {} on SchemaPathNotification {}", reg.getSourceName(), schemaNotification.getLastComponent().getLocalName());
+// if(reg.checkNotificationPath(schemaNotification)){
+// LOG.info("Source of notification {} is activating, TopicId {}", reg.getSourceName(), topicId.getValue() );
+// boolean regSuccess = reg.registerNotificationTopic(schemaNotification, topicId);
+// if(regSuccess){
+// registeredNotificationCount = registeredNotificationCount +1;
+// }
+// }
+// }
+// }
+// if(registeredNotificationCount > 0){
+// joinTopicStatus = JoinTopicStatus.Up;
+// }
+// } else {
+// LOG.warn("NO DOMNotification service on node {}", this.nodeId);
+// }
+// } else {
+// LOG.debug("Notifications to subscribe has NOT found");
+// }
+//
+// final JoinTopicOutput output = new JoinTopicOutputBuilder().setStatus(joinTopicStatus).build();
+// return immediateFuture(RpcResultBuilder.success(output).build());
+//
+// }
+//
+// public void reActivateStreams(){
+// for (NotificationTopicRegistration reg : notificationTopicRegistrationList) {
+// LOG.info("Source of notification {} is reactivating on node {}", reg.getSourceName(), this.nodeId);
+// reg.reActivateNotificationSource();
+// }
+// }
+//
+// public void deActivateStreams(){
+// for (NotificationTopicRegistration reg : notificationTopicRegistrationList) {
+// LOG.info("Source of notification {} is deactivating on node {}", reg.getSourceName(), this.nodeId);
+// reg.deActivateNotificationSource();
+// }
+// }
+//
+// @Override
+// public void onNotification(final DOMNotification notification) {
+// SchemaPath notificationPath = notification.getType();
+// Date notificationEventTime = null;
+// if(notification instanceof DOMEvent){
+// notificationEventTime = ((DOMEvent) notification).getEventTime();
+// }
+// for(NotificationTopicRegistration notifReg : notificationTopicRegistrationList){
+// ArrayList<TopicId> topicIdsForNotification = notifReg.getNotificationTopicIds(notificationPath);
+// if(topicIdsForNotification != null && topicIdsForNotification.isEmpty() == false){
+//
+// if(notifReg instanceof StreamNotificationTopicRegistration){
+// StreamNotificationTopicRegistration streamReg = (StreamNotificationTopicRegistration)notifReg;
+// streamReg.setLastEventTime(notificationEventTime);
+// }
+//
+// for(TopicId topicId : topicIdsForNotification){
+// publishNotification(notification, topicId);
+// LOG.debug("Notification {} has been published for TopicId {}",notification.getType(), 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, this.nodeId))
+// .withChild(encapsulate(notification))
+// .build();
+// try {
+// domPublish.putNotification(new TopicDOMNotification(topicNotification));
+// } catch (final InterruptedException e) {
+// throw Throwables.propagate(e);
+// }
+// }
+//
+// private AnyXmlNode encapsulate(final DOMNotification body) {
+// // FIXME: Introduce something like AnyXmlWithNormalizedNodeData in Yangtools
+// final Document doc = XmlUtil.newDocument();
+// final Optional<String> namespace = Optional.of(PAYLOAD_ARG.getNodeType().getNamespace().toString());
+// final Element element = XmlUtil.createElement(doc , "payload", namespace);
+//
+// final DOMResult result = new DOMResult(element);
+//
+// final SchemaContext context = getDOMMountPoint().getSchemaContext();
+// final SchemaPath schemaPath = body.getType();
+// try {
+// NetconfMessageTransformUtil.writeNormalizedNode(body.getBody(), result, schemaPath, context);
+// return Builders.anyXmlBuilder().withNodeIdentifier(PAYLOAD_ARG)
+// .withValue(new DOMSource(element))
+// .build();
+// } catch (IOException | XMLStreamException e) {
+// LOG.error("Unable to encapsulate notification.",e);
+// throw Throwables.propagate(e);
+// }
+// }
+//
+// private List<SchemaPath> getMatchingNotifications(NotificationPattern notificationPattern){
+// // FIXME: default language should already be regex
+// final String regex = Util.wildcardToRegex(notificationPattern.getValue());
+//
+// final Pattern pattern = Pattern.compile(regex);
+// List<SchemaPath> availableNotifications = getAvailableNotifications();
+// if(availableNotifications == null || availableNotifications.isEmpty()){
+// return null;
+// }
+// return Util.expandQname(availableNotifications, pattern);
+// }
+//
+// @Override
+// public void close() throws Exception {
+// for(NotificationTopicRegistration streamReg : notificationTopicRegistrationList){
+// streamReg.close();
+// }
+// }
+//
+// @Override
+// public NodeKey getSourceNodeKey(){
+// return getNode().getKey();
+// }
+//
+// @Override
+// public List<SchemaPath> getAvailableNotifications() {
+//
+// final List<SchemaPath> availNotifList = new ArrayList<>();
+// // add Event Source Connection status notification
+// availNotifList.add(ConnectionNotificationTopicRegistration.EVENT_SOURCE_STATUS_PATH);
+//
+// // FIXME: use SchemaContextListener to get changes asynchronously
+// final Set<NotificationDefinition> availableNotifications = getDOMMountPoint().getSchemaContext().getNotifications();
+// // add all known notifications from netconf device
+// for (final NotificationDefinition nd : availableNotifications) {
+// availNotifList.add(nd.getPath());
+// }
+// return availNotifList;
+// }
+//
+// public Node getNode() {
+// return node;
+// }
+//
+// DOMMountPoint getDOMMountPoint() {
+// return netconfMount;
+// }
+//
+// MountPoint getMountPoint() {
+// return mountPoint;
+// }
+//
+// NetconfNode getNetconfNode(){
+// return node.getAugmentation(NetconfNode.class);
+// }
+//
+//}
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.opendaylight.controller.config.yang.messagebus.app.impl.NamespaceToStream;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
-import org.opendaylight.controller.md.sal.binding.api.MountPointService;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
-import org.opendaylight.controller.messagebus.spi.EventSourceRegistry;
-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.network.topology.topology.topology.types.TopologyNetconf;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-
-public final class NetconfEventSourceManager implements DataChangeListener, AutoCloseable {
-
- private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSourceManager.class);
- private static final TopologyKey NETCONF_TOPOLOGY_KEY = new TopologyKey(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);
-
- private final Map<String, String> streamMap;
- private final ConcurrentHashMap<InstanceIdentifier<?>, NetconfEventSourceRegistration> registrationMap = new ConcurrentHashMap<>();
- private final DOMNotificationPublishService publishService;
- private final DOMMountPointService domMounts;
- private final MountPointService mountPointService;
- private ListenerRegistration<DataChangeListener> listenerRegistration;
- private final EventSourceRegistry eventSourceRegistry;
-
- public static NetconfEventSourceManager create(final DataBroker dataBroker,
- final DOMNotificationPublishService domPublish,
- final DOMMountPointService domMount,
- final MountPointService bindingMount,
- final EventSourceRegistry eventSourceRegistry,
- final List<NamespaceToStream> namespaceMapping){
-
- final NetconfEventSourceManager eventSourceManager =
- new NetconfEventSourceManager(domPublish, domMount,bindingMount, eventSourceRegistry, namespaceMapping);
-
- eventSourceManager.initialize(dataBroker);
-
- return eventSourceManager;
-
- }
-
- private NetconfEventSourceManager(final DOMNotificationPublishService domPublish,
- final DOMMountPointService domMount,
- final MountPointService bindingMount,
- final EventSourceRegistry eventSourceRegistry,
- final List<NamespaceToStream> namespaceMapping) {
-
- Preconditions.checkNotNull(domPublish);
- Preconditions.checkNotNull(domMount);
- Preconditions.checkNotNull(bindingMount);
- Preconditions.checkNotNull(eventSourceRegistry);
- Preconditions.checkNotNull(namespaceMapping);
- this.streamMap = namespaceToStreamMapping(namespaceMapping);
- this.domMounts = domMount;
- this.mountPointService = bindingMount;
- this.publishService = domPublish;
- this.eventSourceRegistry = eventSourceRegistry;
- }
-
- private void initialize(final DataBroker dataBroker){
- Preconditions.checkNotNull(dataBroker);
- listenerRegistration = dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, NETCONF_DEVICE_PATH, this, DataChangeScope.SUBTREE);
- LOG.info("NetconfEventSourceManager initialized.");
- }
-
- private Map<String,String> namespaceToStreamMapping(final List<NamespaceToStream> namespaceMapping) {
- final Map<String, String> streamMap = new HashMap<>(namespaceMapping.size());
-
- for (final NamespaceToStream nToS : namespaceMapping) {
- streamMap.put(nToS.getUrnPrefix(), nToS.getStreamName());
- }
-
- return streamMap;
- }
-
- @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()) {
- if (changeEntry.getValue() instanceof Node) {
- nodeCreated(changeEntry.getKey(),(Node) changeEntry.getValue());
- }
- }
-
- for (final Map.Entry<InstanceIdentifier<?>, DataObject> changeEntry : event.getUpdatedData().entrySet()) {
- if (changeEntry.getValue() instanceof Node) {
- nodeUpdated(changeEntry.getKey(),(Node) changeEntry.getValue());
- }
- }
-
- for(InstanceIdentifier<?> removePath : event.getRemovedPaths()){
- DataObject removeObject = event.getOriginalData().get(removePath);
- if(removeObject instanceof Node){
- nodeRemoved(removePath);
- }
- }
-
- }
-
- private void nodeCreated(final InstanceIdentifier<?> key, final Node node){
- Preconditions.checkNotNull(key);
- if(validateNode(node) == false){
- LOG.warn("NodeCreated event : Node [{}] is null or not valid.", key.toString());
- return;
- }
- LOG.info("Netconf event source [{}] is creating...", key.toString());
- NetconfEventSourceRegistration nesr = NetconfEventSourceRegistration.create(key, node, this);
- if(nesr != null){
- NetconfEventSourceRegistration nesrOld = registrationMap.put(key, nesr);
- if(nesrOld != null){
- nesrOld.close();
- }
- }
- }
-
- private void nodeUpdated(final InstanceIdentifier<?> key, final Node node){
- Preconditions.checkNotNull(key);
- if(validateNode(node) == false){
- LOG.warn("NodeUpdated event : Node [{}] is null or not valid.", key.toString());
- return;
- }
-
- LOG.info("Netconf event source [{}] is updating...", key.toString());
- NetconfEventSourceRegistration nesr = registrationMap.get(key);
- if(nesr != null){
- nesr.updateStatus();
- } else {
- nodeCreated(key, node);
- }
- }
-
- private void nodeRemoved(final InstanceIdentifier<?> key){
- Preconditions.checkNotNull(key);
- LOG.info("Netconf event source [{}] is removing...", key.toString());
- NetconfEventSourceRegistration nesr = registrationMap.remove(key);
- if(nesr != null){
- nesr.close();
- }
- }
-
- private boolean validateNode(final Node node){
- if(node == null){
- return false;
- }
- return isNetconfNode(node);
- }
-
- Map<String, String> getStreamMap() {
- return streamMap;
- }
-
- DOMNotificationPublishService getPublishService() {
- return publishService;
- }
-
- DOMMountPointService getDomMounts() {
- return domMounts;
- }
-
- EventSourceRegistry getEventSourceRegistry() {
- return eventSourceRegistry;
- }
-
- MountPointService getMountPointService() {
- return mountPointService;
- }
-
- private boolean isNetconfNode(final Node node) {
- return node.getAugmentation(NetconfNode.class) != null ;
- }
-
- @Override
- public void close() {
- listenerRegistration.close();
- for(final NetconfEventSourceRegistration reg : registrationMap.values()){
- reg.close();
- }
- registrationMap.clear();
- }
-
-}
\ No newline at end of file
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//import java.util.HashMap;
+//import java.util.List;
+//import java.util.Map;
+//import java.util.concurrent.ConcurrentHashMap;
+//
+//import org.opendaylight.controller.config.yang.messagebus.app.impl.NamespaceToStream;
+//import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+//import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
+//import org.opendaylight.controller.md.sal.binding.api.MountPointService;
+//import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+//import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+//import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
+//import org.opendaylight.controller.messagebus.spi.EventSourceRegistry;
+//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.network.topology.topology.topology.types.TopologyNetconf;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+//import org.opendaylight.yangtools.concepts.ListenerRegistration;
+//import org.opendaylight.yangtools.yang.binding.DataObject;
+//import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+//import org.slf4j.Logger;
+//import org.slf4j.LoggerFactory;
+//
+//import com.google.common.base.Preconditions;
+//
+//public final class NetconfEventSourceManager implements DataChangeListener, AutoCloseable {
+//
+// private static final Logger LOG = LoggerFactory.getLogger(NetconfEventSourceManager.class);
+// private static final TopologyKey NETCONF_TOPOLOGY_KEY = new TopologyKey(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);
+//
+// private final Map<String, String> streamMap;
+// private final ConcurrentHashMap<InstanceIdentifier<?>, NetconfEventSourceRegistration> registrationMap = new ConcurrentHashMap<>();
+// private final DOMNotificationPublishService publishService;
+// private final DOMMountPointService domMounts;
+// private final MountPointService mountPointService;
+// private ListenerRegistration<DataChangeListener> listenerRegistration;
+// private final EventSourceRegistry eventSourceRegistry;
+//
+// public static NetconfEventSourceManager create(final DataBroker dataBroker,
+// final DOMNotificationPublishService domPublish,
+// final DOMMountPointService domMount,
+// final MountPointService bindingMount,
+// final EventSourceRegistry eventSourceRegistry,
+// final List<NamespaceToStream> namespaceMapping){
+//
+// final NetconfEventSourceManager eventSourceManager =
+// new NetconfEventSourceManager(domPublish, domMount,bindingMount, eventSourceRegistry, namespaceMapping);
+//
+// eventSourceManager.initialize(dataBroker);
+//
+// return eventSourceManager;
+//
+// }
+//
+// private NetconfEventSourceManager(final DOMNotificationPublishService domPublish,
+// final DOMMountPointService domMount,
+// final MountPointService bindingMount,
+// final EventSourceRegistry eventSourceRegistry,
+// final List<NamespaceToStream> namespaceMapping) {
+//
+// Preconditions.checkNotNull(domPublish);
+// Preconditions.checkNotNull(domMount);
+// Preconditions.checkNotNull(bindingMount);
+// Preconditions.checkNotNull(eventSourceRegistry);
+// Preconditions.checkNotNull(namespaceMapping);
+// this.streamMap = namespaceToStreamMapping(namespaceMapping);
+// this.domMounts = domMount;
+// this.mountPointService = bindingMount;
+// this.publishService = domPublish;
+// this.eventSourceRegistry = eventSourceRegistry;
+// }
+//
+// private void initialize(final DataBroker dataBroker){
+// Preconditions.checkNotNull(dataBroker);
+// listenerRegistration = dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, NETCONF_DEVICE_PATH, this, DataChangeScope.SUBTREE);
+// LOG.info("NetconfEventSourceManager initialized.");
+// }
+//
+// private Map<String,String> namespaceToStreamMapping(final List<NamespaceToStream> namespaceMapping) {
+// final Map<String, String> streamMap = new HashMap<>(namespaceMapping.size());
+//
+// for (final NamespaceToStream nToS : namespaceMapping) {
+// streamMap.put(nToS.getUrnPrefix(), nToS.getStreamName());
+// }
+//
+// return streamMap;
+// }
+//
+// @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()) {
+// if (changeEntry.getValue() instanceof Node) {
+// nodeCreated(changeEntry.getKey(),(Node) changeEntry.getValue());
+// }
+// }
+//
+// for (final Map.Entry<InstanceIdentifier<?>, DataObject> changeEntry : event.getUpdatedData().entrySet()) {
+// if (changeEntry.getValue() instanceof Node) {
+// nodeUpdated(changeEntry.getKey(),(Node) changeEntry.getValue());
+// }
+// }
+//
+// for(InstanceIdentifier<?> removePath : event.getRemovedPaths()){
+// DataObject removeObject = event.getOriginalData().get(removePath);
+// if(removeObject instanceof Node){
+// nodeRemoved(removePath);
+// }
+// }
+//
+// }
+//
+// private void nodeCreated(final InstanceIdentifier<?> key, final Node node){
+// Preconditions.checkNotNull(key);
+// if(validateNode(node) == false){
+// LOG.warn("NodeCreated event : Node [{}] is null or not valid.", key.toString());
+// return;
+// }
+// LOG.info("Netconf event source [{}] is creating...", key.toString());
+// NetconfEventSourceRegistration nesr = NetconfEventSourceRegistration.create(key, node, this);
+// if(nesr != null){
+// NetconfEventSourceRegistration nesrOld = registrationMap.put(key, nesr);
+// if(nesrOld != null){
+// nesrOld.close();
+// }
+// }
+// }
+//
+// private void nodeUpdated(final InstanceIdentifier<?> key, final Node node){
+// Preconditions.checkNotNull(key);
+// if(validateNode(node) == false){
+// LOG.warn("NodeUpdated event : Node [{}] is null or not valid.", key.toString());
+// return;
+// }
+//
+// LOG.info("Netconf event source [{}] is updating...", key.toString());
+// NetconfEventSourceRegistration nesr = registrationMap.get(key);
+// if(nesr != null){
+// nesr.updateStatus();
+// } else {
+// nodeCreated(key, node);
+// }
+// }
+//
+// private void nodeRemoved(final InstanceIdentifier<?> key){
+// Preconditions.checkNotNull(key);
+// LOG.info("Netconf event source [{}] is removing...", key.toString());
+// NetconfEventSourceRegistration nesr = registrationMap.remove(key);
+// if(nesr != null){
+// nesr.close();
+// }
+// }
+//
+// private boolean validateNode(final Node node){
+// if(node == null){
+// return false;
+// }
+// return isNetconfNode(node);
+// }
+//
+// Map<String, String> getStreamMap() {
+// return streamMap;
+// }
+//
+// DOMNotificationPublishService getPublishService() {
+// return publishService;
+// }
+//
+// DOMMountPointService getDomMounts() {
+// return domMounts;
+// }
+//
+// EventSourceRegistry getEventSourceRegistry() {
+// return eventSourceRegistry;
+// }
+//
+// MountPointService getMountPointService() {
+// return mountPointService;
+// }
+//
+// private boolean isNetconfNode(final Node node) {
+// return node.getAugmentation(NetconfNode.class) != null ;
+// }
+//
+// @Override
+// public void close() {
+// listenerRegistration.close();
+// for(final NetconfEventSourceRegistration reg : registrationMap.values()){
+// reg.close();
+// }
+// registrationMap.clear();
+// }
+//
+//}
\ No newline at end of file
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-import java.util.List;
-
-import org.opendaylight.controller.md.sal.binding.api.MountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.messagebus.spi.EventSourceRegistration;
-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.NetconfNodeFields.ConnectionStatus;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-
-/**
- * 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();
- 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 final Node node;
- private final InstanceIdentifier<?> instanceIdent;
- private final NetconfEventSourceManager netconfEventSourceManager;
- private ConnectionStatus currentNetconfConnStatus;
- private EventSourceRegistration<NetconfEventSource> eventSourceRegistration;
-
- public static NetconfEventSourceRegistration create(final InstanceIdentifier<?> instanceIdent, final Node node,
- final NetconfEventSourceManager netconfEventSourceManager){
- Preconditions.checkNotNull(instanceIdent);
- Preconditions.checkNotNull(node);
- Preconditions.checkNotNull(netconfEventSourceManager);
- if(isEventSource(node) == false){
- return null;
- }
- NetconfEventSourceRegistration nesr = new NetconfEventSourceRegistration(instanceIdent, node, netconfEventSourceManager);
- nesr.updateStatus();
- LOG.debug("NetconfEventSourceRegistration for node {} has been initialized...",node.getNodeId().getValue());
- return nesr;
- }
-
- private static boolean isEventSource(final Node node) {
- final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
- if(netconfNode == null){
- return false;
- }
- if (netconfNode.getAvailableCapabilities() == null) {
- return false;
- }
- final List<String> capabilities = netconfNode.getAvailableCapabilities().getAvailableCapability();
- if(capabilities == null || capabilities.isEmpty()) {
- return false;
- }
- for (final String capability : netconfNode.getAvailableCapabilities().getAvailableCapability()) {
- if(capability.startsWith(NotificationCapabilityPrefix)) {
- return true;
- }
- }
-
- return false;
- }
-
- private NetconfEventSourceRegistration(final InstanceIdentifier<?> instanceIdent, final Node node, final NetconfEventSourceManager netconfEventSourceManager) {
- this.instanceIdent = instanceIdent;
- this.node = node;
- this.netconfEventSourceManager = netconfEventSourceManager;
- this.eventSourceRegistration =null;
- }
-
- public Node getNode() {
- return node;
- }
-
- Optional<EventSourceRegistration<NetconfEventSource>> getEventSourceRegistration() {
- return Optional.fromNullable(eventSourceRegistration);
- }
-
- NetconfNode getNetconfNode(){
- return node.getAugmentation(NetconfNode.class);
- }
-
- void updateStatus(){
- ConnectionStatus netconfConnStatus = getNetconfNode().getConnectionStatus();
- LOG.info("Change status on node {}, new status is {}",this.node.getNodeId().getValue(),netconfConnStatus);
- if(netconfConnStatus.equals(currentNetconfConnStatus)){
- return;
- }
- changeStatus(netconfConnStatus);
- }
-
- private boolean checkConnectionStatusType(ConnectionStatus status){
- if( status == ConnectionStatus.Connected
- || status == ConnectionStatus.Connecting
- || status == ConnectionStatus.UnableToConnect){
- return true;
- }
- return false;
- }
-
- private void changeStatus(ConnectionStatus newStatus){
- Preconditions.checkNotNull(newStatus);
- if(checkConnectionStatusType(newStatus) == false){
- throw new IllegalStateException("Unknown new Netconf Connection Status");
- }
- if(this.currentNetconfConnStatus == null){
- if (newStatus == ConnectionStatus.Connected){
- registrationEventSource();
- }
- } else if (this.currentNetconfConnStatus == ConnectionStatus.Connecting){
- if (newStatus == ConnectionStatus.Connected){
- if(this.eventSourceRegistration == null){
- registrationEventSource();
- } else {
- // reactivate stream on registered event source (invoke publish notification about connection)
- this.eventSourceRegistration.getInstance().reActivateStreams();
- }
- }
- } else if (this.currentNetconfConnStatus == ConnectionStatus.Connected) {
-
- if(newStatus == ConnectionStatus.Connecting || newStatus == ConnectionStatus.UnableToConnect){
- // deactivate streams on registered event source (invoke publish notification about connection)
- this.eventSourceRegistration.getInstance().deActivateStreams();
- }
- } else if (this.currentNetconfConnStatus == ConnectionStatus.UnableToConnect){
- if(newStatus == ConnectionStatus.Connected){
- if(this.eventSourceRegistration == null){
- registrationEventSource();
- } else {
- // reactivate stream on registered event source (invoke publish notification about connection)
- this.eventSourceRegistration.getInstance().reActivateStreams();
- }
- }
- } else {
- throw new IllegalStateException("Unknown current Netconf Connection Status");
- }
- this.currentNetconfConnStatus = newStatus;
- }
-
- private void registrationEventSource(){
- final Optional<MountPoint> mountPoint = netconfEventSourceManager.getMountPointService().getMountPoint(instanceIdent);
- final Optional<DOMMountPoint> domMountPoint = netconfEventSourceManager.getDomMounts().getMountPoint(domMountPath(node.getNodeId()));
- EventSourceRegistration<NetconfEventSource> registration = null;
- if(domMountPoint.isPresent() && mountPoint.isPresent()) {
- final NetconfEventSource netconfEventSource = new NetconfEventSource(
- node,
- netconfEventSourceManager.getStreamMap(),
- domMountPoint.get(),
- mountPoint.get(),
- netconfEventSourceManager.getPublishService());
- registration = netconfEventSourceManager.getEventSourceRegistry().registerEventSource(netconfEventSource);
- LOG.info("Event source {} has been registered",node.getNodeId().getValue());
- }
- this.eventSourceRegistration = registration;
- }
-
- private YangInstanceIdentifier domMountPath(final NodeId nodeId) {
- return YangInstanceIdentifier.builder(NETCONF_DEVICE_DOM_PATH).nodeWithKey(Node.QNAME, NODE_ID_QNAME, nodeId.getValue()).build();
- }
-
- private void closeEventSourceRegistration(){
- if(getEventSourceRegistration().isPresent()){
- getEventSourceRegistration().get().close();
- }
- }
-
- @Override
- public void close() {
- closeEventSourceRegistration();
- }
-
-}
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//import java.util.List;
+//
+//import org.opendaylight.controller.md.sal.binding.api.MountPoint;
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
+//import org.opendaylight.controller.messagebus.spi.EventSourceRegistration;
+//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.NetconfNodeFields.ConnectionStatus;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+//import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+//import org.opendaylight.yangtools.yang.common.QName;
+//import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+//import org.slf4j.Logger;
+//import org.slf4j.LoggerFactory;
+//
+//import com.google.common.base.Optional;
+//import com.google.common.base.Preconditions;
+//
+///**
+// * 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();
+// 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 final Node node;
+// private final InstanceIdentifier<?> instanceIdent;
+// private final NetconfEventSourceManager netconfEventSourceManager;
+// private ConnectionStatus currentNetconfConnStatus;
+// private EventSourceRegistration<NetconfEventSource> eventSourceRegistration;
+//
+// public static NetconfEventSourceRegistration create(final InstanceIdentifier<?> instanceIdent, final Node node,
+// final NetconfEventSourceManager netconfEventSourceManager){
+// Preconditions.checkNotNull(instanceIdent);
+// Preconditions.checkNotNull(node);
+// Preconditions.checkNotNull(netconfEventSourceManager);
+// if(isEventSource(node) == false){
+// return null;
+// }
+// NetconfEventSourceRegistration nesr = new NetconfEventSourceRegistration(instanceIdent, node, netconfEventSourceManager);
+// nesr.updateStatus();
+// LOG.debug("NetconfEventSourceRegistration for node {} has been initialized...",node.getNodeId().getValue());
+// return nesr;
+// }
+//
+// private static boolean isEventSource(final Node node) {
+// final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
+// if(netconfNode == null){
+// return false;
+// }
+// if (netconfNode.getAvailableCapabilities() == null) {
+// return false;
+// }
+// final List<String> capabilities = netconfNode.getAvailableCapabilities().getAvailableCapability();
+// if(capabilities == null || capabilities.isEmpty()) {
+// return false;
+// }
+// for (final String capability : netconfNode.getAvailableCapabilities().getAvailableCapability()) {
+// if(capability.startsWith(NotificationCapabilityPrefix)) {
+// return true;
+// }
+// }
+//
+// return false;
+// }
+//
+// private NetconfEventSourceRegistration(final InstanceIdentifier<?> instanceIdent, final Node node, final NetconfEventSourceManager netconfEventSourceManager) {
+// this.instanceIdent = instanceIdent;
+// this.node = node;
+// this.netconfEventSourceManager = netconfEventSourceManager;
+// this.eventSourceRegistration =null;
+// }
+//
+// public Node getNode() {
+// return node;
+// }
+//
+// Optional<EventSourceRegistration<NetconfEventSource>> getEventSourceRegistration() {
+// return Optional.fromNullable(eventSourceRegistration);
+// }
+//
+// NetconfNode getNetconfNode(){
+// return node.getAugmentation(NetconfNode.class);
+// }
+//
+// void updateStatus(){
+// ConnectionStatus netconfConnStatus = getNetconfNode().getConnectionStatus();
+// LOG.info("Change status on node {}, new status is {}",this.node.getNodeId().getValue(),netconfConnStatus);
+// if(netconfConnStatus.equals(currentNetconfConnStatus)){
+// return;
+// }
+// changeStatus(netconfConnStatus);
+// }
+//
+// private boolean checkConnectionStatusType(ConnectionStatus status){
+// if( status == ConnectionStatus.Connected
+// || status == ConnectionStatus.Connecting
+// || status == ConnectionStatus.UnableToConnect){
+// return true;
+// }
+// return false;
+// }
+//
+// private void changeStatus(ConnectionStatus newStatus){
+// Preconditions.checkNotNull(newStatus);
+// if(checkConnectionStatusType(newStatus) == false){
+// throw new IllegalStateException("Unknown new Netconf Connection Status");
+// }
+// if(this.currentNetconfConnStatus == null){
+// if (newStatus == ConnectionStatus.Connected){
+// registrationEventSource();
+// }
+// } else if (this.currentNetconfConnStatus == ConnectionStatus.Connecting){
+// if (newStatus == ConnectionStatus.Connected){
+// if(this.eventSourceRegistration == null){
+// registrationEventSource();
+// } else {
+// // reactivate stream on registered event source (invoke publish notification about connection)
+// this.eventSourceRegistration.getInstance().reActivateStreams();
+// }
+// }
+// } else if (this.currentNetconfConnStatus == ConnectionStatus.Connected) {
+//
+// if(newStatus == ConnectionStatus.Connecting || newStatus == ConnectionStatus.UnableToConnect){
+// // deactivate streams on registered event source (invoke publish notification about connection)
+// this.eventSourceRegistration.getInstance().deActivateStreams();
+// }
+// } else if (this.currentNetconfConnStatus == ConnectionStatus.UnableToConnect){
+// if(newStatus == ConnectionStatus.Connected){
+// if(this.eventSourceRegistration == null){
+// registrationEventSource();
+// } else {
+// // reactivate stream on registered event source (invoke publish notification about connection)
+// this.eventSourceRegistration.getInstance().reActivateStreams();
+// }
+// }
+// } else {
+// throw new IllegalStateException("Unknown current Netconf Connection Status");
+// }
+// this.currentNetconfConnStatus = newStatus;
+// }
+//
+// private void registrationEventSource(){
+// final Optional<MountPoint> mountPoint = netconfEventSourceManager.getMountPointService().getMountPoint(instanceIdent);
+// final Optional<DOMMountPoint> domMountPoint = netconfEventSourceManager.getDomMounts().getMountPoint(domMountPath(node.getNodeId()));
+// EventSourceRegistration<NetconfEventSource> registration = null;
+// if(domMountPoint.isPresent() && mountPoint.isPresent()) {
+// final NetconfEventSource netconfEventSource = new NetconfEventSource(
+// node,
+// netconfEventSourceManager.getStreamMap(),
+// domMountPoint.get(),
+// mountPoint.get(),
+// netconfEventSourceManager.getPublishService());
+// registration = netconfEventSourceManager.getEventSourceRegistry().registerEventSource(netconfEventSource);
+// LOG.info("Event source {} has been registered",node.getNodeId().getValue());
+// }
+// this.eventSourceRegistration = registration;
+// }
+//
+// private YangInstanceIdentifier domMountPath(final NodeId nodeId) {
+// return YangInstanceIdentifier.builder(NETCONF_DEVICE_DOM_PATH).nodeWithKey(Node.QNAME, NODE_ID_QNAME, nodeId.getValue()).build();
+// }
+//
+// private void closeEventSourceRegistration(){
+// if(getEventSourceRegistration().isPresent()){
+// getEventSourceRegistration().get().close();
+// }
+// }
+//
+// @Override
+// public void close() {
+// closeEventSourceRegistration();
+// }
+//
+//}
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-public class StreamNotificationTopicRegistration extends NotificationTopicRegistration {
-
- private static final Logger LOG = LoggerFactory.getLogger(StreamNotificationTopicRegistration.class);
- private static final NodeIdentifier STREAM_QNAME = new NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME,"stream"));
- private static final SchemaPath CREATE_SUBSCRIPTION = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
- private static final NodeIdentifier START_TIME_SUBSCRIPTION = new NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME,"startTime"));
-
- final private DOMMountPoint domMountPoint;
- final private String nodeId;
- final private NetconfEventSource netconfEventSource;
- final private Stream stream;
- private Date lastEventTime;
-
- private ConcurrentHashMap<SchemaPath, ListenerRegistration<NetconfEventSource>> notificationRegistrationMap = new ConcurrentHashMap<>();
- private ConcurrentHashMap<SchemaPath, ArrayList<TopicId>> notificationTopicMap = new ConcurrentHashMap<>();
-
- public StreamNotificationTopicRegistration(final Stream stream, final String notificationPrefix, NetconfEventSource netconfEventSource) {
- super(NotificationSourceType.NetconfDeviceStream, stream.getName().getValue(), notificationPrefix);
- this.domMountPoint = netconfEventSource.getDOMMountPoint();
- this.nodeId = netconfEventSource.getNode().getNodeId().getValue().toString();
- this.netconfEventSource = netconfEventSource;
- this.stream = stream;
- this.lastEventTime= null;
- setReplaySupported(this.stream.isReplaySupport());
- setActive(false);
- LOG.info("StreamNotificationTopicRegistration initialized for {}", getStreamName());
- }
-
- void activateNotificationSource() {
- if(isActive() == false){
- LOG.info("Stream {} is not active on node {}. Will subscribe.", this.getStreamName(), this.nodeId);
- final ContainerNode input = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CreateSubscriptionInput.QNAME))
- .withChild(ImmutableNodes.leafNode(STREAM_QNAME, this.getStreamName()))
- .build();
- CheckedFuture<DOMRpcResult, DOMRpcException> csFuture = domMountPoint.getService(DOMRpcService.class).get().invokeRpc(CREATE_SUBSCRIPTION, input);
- try {
- csFuture.checkedGet();
- setActive(true);
- } catch (DOMRpcException e) {
- LOG.warn("Can not subscribe stream {} on node {}", this.getSourceName(), this.nodeId);
- setActive(false);
- return;
- }
- } else {
- LOG.info("Stream {} is now active on node {}", this.getStreamName(), this.nodeId);
- }
- }
-
- void reActivateNotificationSource(){
- if(isActive()){
- LOG.info("Stream {} is reactivating on node {}.", this.getStreamName(), this.nodeId);
- DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> inputBuilder =
- Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CreateSubscriptionInput.QNAME))
- .withChild(ImmutableNodes.leafNode(STREAM_QNAME, this.getStreamName()));
- if(isReplaySupported() && this.getLastEventTime() != null){
- inputBuilder.withChild(ImmutableNodes.leafNode(START_TIME_SUBSCRIPTION, this.getLastEventTime()));
- }
- final ContainerNode input = inputBuilder.build();
- CheckedFuture<DOMRpcResult, DOMRpcException> csFuture = domMountPoint.getService(DOMRpcService.class).get().invokeRpc(CREATE_SUBSCRIPTION, input);
- try {
- csFuture.checkedGet();
- setActive(true);
- } catch (DOMRpcException e) {
- LOG.warn("Can not resubscribe stream {} on node {}", this.getSourceName(), this.nodeId);
- setActive(false);
- return;
- }
- }
- }
-
- @Override
- void deActivateNotificationSource() {
- // no operations need
- }
-
- private void closeStream() {
- if(isActive()){
- for(ListenerRegistration<NetconfEventSource> reg : notificationRegistrationMap.values()){
- reg.close();
- }
- notificationRegistrationMap.clear();
- notificationTopicMap.clear();
- setActive(false);
- }
- }
-
- private String getStreamName() {
- return getSourceName();
- }
-
- @Override
- ArrayList<TopicId> getNotificationTopicIds(SchemaPath notificationPath){
- return notificationTopicMap.get(notificationPath);
- }
-
- @Override
- boolean registerNotificationTopic(SchemaPath notificationPath, TopicId topicId){
-
- if(checkNotificationPath(notificationPath) == false){
- LOG.debug("Bad SchemaPath for notification try to register");
- return false;
- }
-
- final Optional<DOMNotificationService> notifyService = domMountPoint.getService(DOMNotificationService.class);
- if(notifyService.isPresent() == false){
- LOG.debug("DOMNotificationService is not present");
- return false;
- }
-
- activateNotificationSource();
- if(isActive() == false){
- LOG.warn("Stream {} is not active, listener for notification {} is not registered.", getStreamName(), notificationPath.toString());
- return false;
- }
-
- ListenerRegistration<NetconfEventSource> registration =
- notifyService.get().registerNotificationListener(this.netconfEventSource,notificationPath);
- notificationRegistrationMap.put(notificationPath, registration);
- ArrayList<TopicId> topicIds = getNotificationTopicIds(notificationPath);
- if(topicIds == null){
- topicIds = new ArrayList<>();
- topicIds.add(topicId);
- } else {
- if(topicIds.contains(topicId) == false){
- topicIds.add(topicId);
- }
- }
-
- notificationTopicMap.put(notificationPath, topicIds);
- return true;
- }
-
- @Override
- synchronized void unRegisterNotificationTopic(TopicId topicId) {
- List<SchemaPath> notificationPathToRemove = new ArrayList<>();
- for(SchemaPath notifKey : notificationTopicMap.keySet()){
- ArrayList<TopicId> topicList = notificationTopicMap.get(notifKey);
- if(topicList != null){
- topicList.remove(topicId);
- if(topicList.isEmpty()){
- notificationPathToRemove.add(notifKey);
- }
- }
- }
- for(SchemaPath notifKey : notificationPathToRemove){
- notificationTopicMap.remove(notifKey);
- ListenerRegistration<NetconfEventSource> reg = notificationRegistrationMap.remove(notifKey);
- if(reg != null){
- reg.close();
- }
- }
- }
-
- Optional<Date> getLastEventTime() {
- return Optional.fromNullable(lastEventTime);
- }
-
-
- void setLastEventTime(Date lastEventTime) {
- this.lastEventTime = lastEventTime;
- }
-
- @Override
- public void close() throws Exception {
- closeStream();
- }
-
-}
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//import java.util.ArrayList;
+//import java.util.Date;
+//import java.util.List;
+//import java.util.concurrent.ConcurrentHashMap;
+//
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
+//import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
+//import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
+//import org.opendaylight.yangtools.concepts.ListenerRegistration;
+//import org.opendaylight.yangtools.yang.common.QName;
+//import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+//import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+//import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+//import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+//import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
+//import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+//import org.slf4j.Logger;
+//import org.slf4j.LoggerFactory;
+//
+//import com.google.common.base.Optional;
+//import com.google.common.util.concurrent.CheckedFuture;
+//
+//public class StreamNotificationTopicRegistration extends NotificationTopicRegistration {
+//
+// private static final Logger LOG = LoggerFactory.getLogger(StreamNotificationTopicRegistration.class);
+// private static final NodeIdentifier STREAM_QNAME = new NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME,"stream"));
+// private static final SchemaPath CREATE_SUBSCRIPTION = SchemaPath.create(true, QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
+// private static final NodeIdentifier START_TIME_SUBSCRIPTION = new NodeIdentifier(QName.create(CreateSubscriptionInput.QNAME,"startTime"));
+//
+// final private DOMMountPoint domMountPoint;
+// final private String nodeId;
+// final private NetconfEventSource netconfEventSource;
+// final private Stream stream;
+// private Date lastEventTime;
+//
+// private ConcurrentHashMap<SchemaPath, ListenerRegistration<NetconfEventSource>> notificationRegistrationMap = new ConcurrentHashMap<>();
+// private ConcurrentHashMap<SchemaPath, ArrayList<TopicId>> notificationTopicMap = new ConcurrentHashMap<>();
+//
+// public StreamNotificationTopicRegistration(final Stream stream, final String notificationPrefix, NetconfEventSource netconfEventSource) {
+// super(NotificationSourceType.NetconfDeviceStream, stream.getName().getValue(), notificationPrefix);
+// this.domMountPoint = netconfEventSource.getDOMMountPoint();
+// this.nodeId = netconfEventSource.getNode().getNodeId().getValue().toString();
+// this.netconfEventSource = netconfEventSource;
+// this.stream = stream;
+// this.lastEventTime= null;
+// setReplaySupported(this.stream.isReplaySupport());
+// setActive(false);
+// LOG.info("StreamNotificationTopicRegistration initialized for {}", getStreamName());
+// }
+//
+// void activateNotificationSource() {
+// if(isActive() == false){
+// LOG.info("Stream {} is not active on node {}. Will subscribe.", this.getStreamName(), this.nodeId);
+// final ContainerNode input = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CreateSubscriptionInput.QNAME))
+// .withChild(ImmutableNodes.leafNode(STREAM_QNAME, this.getStreamName()))
+// .build();
+// CheckedFuture<DOMRpcResult, DOMRpcException> csFuture = domMountPoint.getService(DOMRpcService.class).get().invokeRpc(CREATE_SUBSCRIPTION, input);
+// try {
+// csFuture.checkedGet();
+// setActive(true);
+// } catch (DOMRpcException e) {
+// LOG.warn("Can not subscribe stream {} on node {}", this.getSourceName(), this.nodeId);
+// setActive(false);
+// return;
+// }
+// } else {
+// LOG.info("Stream {} is now active on node {}", this.getStreamName(), this.nodeId);
+// }
+// }
+//
+// void reActivateNotificationSource(){
+// if(isActive()){
+// LOG.info("Stream {} is reactivating on node {}.", this.getStreamName(), this.nodeId);
+// DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> inputBuilder =
+// Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CreateSubscriptionInput.QNAME))
+// .withChild(ImmutableNodes.leafNode(STREAM_QNAME, this.getStreamName()));
+// if(isReplaySupported() && this.getLastEventTime() != null){
+// inputBuilder.withChild(ImmutableNodes.leafNode(START_TIME_SUBSCRIPTION, this.getLastEventTime()));
+// }
+// final ContainerNode input = inputBuilder.build();
+// CheckedFuture<DOMRpcResult, DOMRpcException> csFuture = domMountPoint.getService(DOMRpcService.class).get().invokeRpc(CREATE_SUBSCRIPTION, input);
+// try {
+// csFuture.checkedGet();
+// setActive(true);
+// } catch (DOMRpcException e) {
+// LOG.warn("Can not resubscribe stream {} on node {}", this.getSourceName(), this.nodeId);
+// setActive(false);
+// return;
+// }
+// }
+// }
+//
+// @Override
+// void deActivateNotificationSource() {
+// // no operations need
+// }
+//
+// private void closeStream() {
+// if(isActive()){
+// for(ListenerRegistration<NetconfEventSource> reg : notificationRegistrationMap.values()){
+// reg.close();
+// }
+// notificationRegistrationMap.clear();
+// notificationTopicMap.clear();
+// setActive(false);
+// }
+// }
+//
+// private String getStreamName() {
+// return getSourceName();
+// }
+//
+// @Override
+// ArrayList<TopicId> getNotificationTopicIds(SchemaPath notificationPath){
+// return notificationTopicMap.get(notificationPath);
+// }
+//
+// @Override
+// boolean registerNotificationTopic(SchemaPath notificationPath, TopicId topicId){
+//
+// if(checkNotificationPath(notificationPath) == false){
+// LOG.debug("Bad SchemaPath for notification try to register");
+// return false;
+// }
+//
+// final Optional<DOMNotificationService> notifyService = domMountPoint.getService(DOMNotificationService.class);
+// if(notifyService.isPresent() == false){
+// LOG.debug("DOMNotificationService is not present");
+// return false;
+// }
+//
+// activateNotificationSource();
+// if(isActive() == false){
+// LOG.warn("Stream {} is not active, listener for notification {} is not registered.", getStreamName(), notificationPath.toString());
+// return false;
+// }
+//
+// ListenerRegistration<NetconfEventSource> registration =
+// notifyService.get().registerNotificationListener(this.netconfEventSource,notificationPath);
+// notificationRegistrationMap.put(notificationPath, registration);
+// ArrayList<TopicId> topicIds = getNotificationTopicIds(notificationPath);
+// if(topicIds == null){
+// topicIds = new ArrayList<>();
+// topicIds.add(topicId);
+// } else {
+// if(topicIds.contains(topicId) == false){
+// topicIds.add(topicId);
+// }
+// }
+//
+// notificationTopicMap.put(notificationPath, topicIds);
+// return true;
+// }
+//
+// @Override
+// synchronized void unRegisterNotificationTopic(TopicId topicId) {
+// List<SchemaPath> notificationPathToRemove = new ArrayList<>();
+// for(SchemaPath notifKey : notificationTopicMap.keySet()){
+// ArrayList<TopicId> topicList = notificationTopicMap.get(notifKey);
+// if(topicList != null){
+// topicList.remove(topicId);
+// if(topicList.isEmpty()){
+// notificationPathToRemove.add(notifKey);
+// }
+// }
+// }
+// for(SchemaPath notifKey : notificationPathToRemove){
+// notificationTopicMap.remove(notifKey);
+// ListenerRegistration<NetconfEventSource> reg = notificationRegistrationMap.remove(notifKey);
+// if(reg != null){
+// reg.close();
+// }
+// }
+// }
+//
+// Optional<Date> getLastEventTime() {
+// return Optional.fromNullable(lastEventTime);
+// }
+//
+//
+// void setLastEventTime(Date lastEventTime) {
+// this.lastEventTime = lastEventTime;
+// }
+//
+// @Override
+// public void close() throws Exception {
+// closeStream();
+// }
+//
+//}
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.notNull;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.controller.config.yang.messagebus.app.impl.NamespaceToStream;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.MountPoint;
-import org.opendaylight.controller.md.sal.binding.api.MountPointService;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
-import org.opendaylight.controller.messagebus.app.impl.EventSourceTopology;
-import org.opendaylight.controller.messagebus.spi.EventSource;
-import org.opendaylight.controller.messagebus.spi.EventSourceRegistration;
-import org.opendaylight.controller.messagebus.spi.EventSourceRegistry;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-public class NetconfEventSourceManagerTest {
-
- NetconfEventSourceManager netconfEventSourceManager;
- ListenerRegistration listenerRegistrationMock;
- DOMMountPointService domMountPointServiceMock;
- MountPointService mountPointServiceMock;
- EventSourceTopology eventSourceTopologyMock;
- AsyncDataChangeEvent asyncDataChangeEventMock;
- RpcProviderRegistry rpcProviderRegistryMock;
- EventSourceRegistry eventSourceRegistry;
- @BeforeClass
- public static void initTestClass() throws IllegalAccessException, InstantiationException {
- }
-
- @Before
- public void setUp() throws Exception {
- DataBroker dataBrokerMock = mock(DataBroker.class);
- DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
- domMountPointServiceMock = mock(DOMMountPointService.class);
- mountPointServiceMock = mock(MountPointService.class);
- eventSourceTopologyMock = mock(EventSourceTopology.class);
- rpcProviderRegistryMock = mock(RpcProviderRegistry.class);
- eventSourceRegistry = mock(EventSourceRegistry.class);
- List<NamespaceToStream> namespaceToStreamList = new ArrayList<>();
-
- listenerRegistrationMock = mock(ListenerRegistration.class);
- doReturn(listenerRegistrationMock).when(dataBrokerMock).registerDataChangeListener(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(NetconfEventSourceManager.class), eq(AsyncDataBroker.DataChangeScope.SUBTREE));
-
- Optional<DOMMountPoint> optionalDomMountServiceMock = (Optional<DOMMountPoint>) mock(Optional.class);
- doReturn(true).when(optionalDomMountServiceMock).isPresent();
- doReturn(optionalDomMountServiceMock).when(domMountPointServiceMock).getMountPoint((YangInstanceIdentifier)notNull());
-
- DOMMountPoint domMountPointMock = mock(DOMMountPoint.class);
- doReturn(domMountPointMock).when(optionalDomMountServiceMock).get();
-
-
- Optional optionalBindingMountMock = mock(Optional.class);
- doReturn(true).when(optionalBindingMountMock).isPresent();
-
- MountPoint mountPointMock = mock(MountPoint.class);
- doReturn(optionalBindingMountMock).when(mountPointServiceMock).getMountPoint(any(InstanceIdentifier.class));
- doReturn(mountPointMock).when(optionalBindingMountMock).get();
-
- Optional optionalMpDataBroker = mock(Optional.class);
- DataBroker mpDataBroker = mock(DataBroker.class);
- doReturn(optionalMpDataBroker).when(mountPointMock).getService(DataBroker.class);
- doReturn(true).when(optionalMpDataBroker).isPresent();
- doReturn(mpDataBroker).when(optionalMpDataBroker).get();
-
- ReadOnlyTransaction rtx = mock(ReadOnlyTransaction.class);
- doReturn(rtx).when(mpDataBroker).newReadOnlyTransaction();
- CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = (CheckedFuture<Optional<Streams>, ReadFailedException>)mock(CheckedFuture.class);
- InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build();
- doReturn(checkFeature).when(rtx).read(LogicalDatastoreType.OPERATIONAL, pathStream);
- Optional<Streams> avStreams = NetconfTestUtils.getAvailableStream("stream01", true);
- doReturn(avStreams).when(checkFeature).checkedGet();
-
- EventSourceRegistration esrMock = mock(EventSourceRegistration.class);
-
- netconfEventSourceManager =
- NetconfEventSourceManager.create(dataBrokerMock,
- domNotificationPublishServiceMock,
- domMountPointServiceMock,
- mountPointServiceMock,
- eventSourceRegistry,
- namespaceToStreamList);
- }
-
- @Test
- public void onDataChangedCreateEventSourceTestByCreateEntry() throws Exception {
- 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);
- 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);
- netconfEventSourceManager.onDataChanged(asyncDataChangeEventMock);
- verify(eventSourceRegistry, times(0)).registerEventSource(any(EventSource.class));
- }
-
- @Test
- public void onDataChangedCreateEventSourceTestNotNotificationCapability() throws Exception {
- 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{
- asyncDataChangeEventMock = mock(AsyncDataChangeEvent.class);
- Map<InstanceIdentifier, DataObject> mapCreate = new HashMap<>();
- Map<InstanceIdentifier, DataObject> mapUpdate = new HashMap<>();
-
- Node node01;
- String nodeId = "Node01";
- doReturn(mapCreate).when(asyncDataChangeEventMock).getCreatedData();
- doReturn(mapUpdate).when(asyncDataChangeEventMock).getUpdatedData();
-
- if(isNetconf){
- node01 = NetconfTestUtils.getNetconfNode(nodeId, "node01.test.local", ConnectionStatus.Connected, notificationCapabilityPrefix);
-
- } else {
- node01 = NetconfTestUtils.getNode(nodeId);
- }
-
- if(create){
- mapCreate.put(NetconfTestUtils.getInstanceIdentifier(node01), node01);
- }
- if(update){
- mapUpdate.put(NetconfTestUtils.getInstanceIdentifier(node01), node01);
- }
-
- }
-
-}
\ No newline at end of file
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//import static org.mockito.Matchers.any;
+//import static org.mockito.Matchers.eq;
+//import static org.mockito.Matchers.notNull;
+//import static org.mockito.Mockito.doReturn;
+//import static org.mockito.Mockito.mock;
+//import static org.mockito.Mockito.times;
+//import static org.mockito.Mockito.verify;
+//
+//import java.util.ArrayList;
+//import java.util.HashMap;
+//import java.util.List;
+//import java.util.Map;
+//
+//import org.junit.Before;
+//import org.junit.BeforeClass;
+//import org.junit.Test;
+//import org.opendaylight.controller.config.yang.messagebus.app.impl.NamespaceToStream;
+//import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+//import org.opendaylight.controller.md.sal.binding.api.MountPoint;
+//import org.opendaylight.controller.md.sal.binding.api.MountPointService;
+//import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+//import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
+//import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+//import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+//import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
+//import org.opendaylight.controller.messagebus.app.impl.EventSourceTopology;
+//import org.opendaylight.controller.messagebus.spi.EventSource;
+//import org.opendaylight.controller.messagebus.spi.EventSourceRegistration;
+//import org.opendaylight.controller.messagebus.spi.EventSourceRegistry;
+//import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+//import org.opendaylight.yangtools.concepts.ListenerRegistration;
+//import org.opendaylight.yangtools.yang.binding.DataObject;
+//import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+//import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+//
+//import com.google.common.base.Optional;
+//import com.google.common.util.concurrent.CheckedFuture;
+//
+//public class NetconfEventSourceManagerTest {
+//
+// NetconfEventSourceManager netconfEventSourceManager;
+// ListenerRegistration listenerRegistrationMock;
+// DOMMountPointService domMountPointServiceMock;
+// MountPointService mountPointServiceMock;
+// EventSourceTopology eventSourceTopologyMock;
+// AsyncDataChangeEvent asyncDataChangeEventMock;
+// RpcProviderRegistry rpcProviderRegistryMock;
+// EventSourceRegistry eventSourceRegistry;
+// @BeforeClass
+// public static void initTestClass() throws IllegalAccessException, InstantiationException {
+// }
+//
+// @Before
+// public void setUp() throws Exception {
+// DataBroker dataBrokerMock = mock(DataBroker.class);
+// DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
+// domMountPointServiceMock = mock(DOMMountPointService.class);
+// mountPointServiceMock = mock(MountPointService.class);
+// eventSourceTopologyMock = mock(EventSourceTopology.class);
+// rpcProviderRegistryMock = mock(RpcProviderRegistry.class);
+// eventSourceRegistry = mock(EventSourceRegistry.class);
+// List<NamespaceToStream> namespaceToStreamList = new ArrayList<>();
+//
+// listenerRegistrationMock = mock(ListenerRegistration.class);
+// doReturn(listenerRegistrationMock).when(dataBrokerMock).registerDataChangeListener(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(NetconfEventSourceManager.class), eq(AsyncDataBroker.DataChangeScope.SUBTREE));
+//
+// Optional<DOMMountPoint> optionalDomMountServiceMock = (Optional<DOMMountPoint>) mock(Optional.class);
+// doReturn(true).when(optionalDomMountServiceMock).isPresent();
+// doReturn(optionalDomMountServiceMock).when(domMountPointServiceMock).getMountPoint((YangInstanceIdentifier)notNull());
+//
+// DOMMountPoint domMountPointMock = mock(DOMMountPoint.class);
+// doReturn(domMountPointMock).when(optionalDomMountServiceMock).get();
+//
+//
+// Optional optionalBindingMountMock = mock(Optional.class);
+// doReturn(true).when(optionalBindingMountMock).isPresent();
+//
+// MountPoint mountPointMock = mock(MountPoint.class);
+// doReturn(optionalBindingMountMock).when(mountPointServiceMock).getMountPoint(any(InstanceIdentifier.class));
+// doReturn(mountPointMock).when(optionalBindingMountMock).get();
+//
+// Optional optionalMpDataBroker = mock(Optional.class);
+// DataBroker mpDataBroker = mock(DataBroker.class);
+// doReturn(optionalMpDataBroker).when(mountPointMock).getService(DataBroker.class);
+// doReturn(true).when(optionalMpDataBroker).isPresent();
+// doReturn(mpDataBroker).when(optionalMpDataBroker).get();
+//
+// ReadOnlyTransaction rtx = mock(ReadOnlyTransaction.class);
+// doReturn(rtx).when(mpDataBroker).newReadOnlyTransaction();
+// CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = (CheckedFuture<Optional<Streams>, ReadFailedException>)mock(CheckedFuture.class);
+// InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build();
+// doReturn(checkFeature).when(rtx).read(LogicalDatastoreType.OPERATIONAL, pathStream);
+// Optional<Streams> avStreams = NetconfTestUtils.getAvailableStream("stream01", true);
+// doReturn(avStreams).when(checkFeature).checkedGet();
+//
+// EventSourceRegistration esrMock = mock(EventSourceRegistration.class);
+//
+// netconfEventSourceManager =
+// NetconfEventSourceManager.create(dataBrokerMock,
+// domNotificationPublishServiceMock,
+// domMountPointServiceMock,
+// mountPointServiceMock,
+// eventSourceRegistry,
+// namespaceToStreamList);
+// }
+//
+// @Test
+// public void onDataChangedCreateEventSourceTestByCreateEntry() throws Exception {
+// 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);
+// 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);
+// netconfEventSourceManager.onDataChanged(asyncDataChangeEventMock);
+// verify(eventSourceRegistry, times(0)).registerEventSource(any(EventSource.class));
+// }
+//
+// @Test
+// public void onDataChangedCreateEventSourceTestNotNotificationCapability() throws Exception {
+// 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{
+// asyncDataChangeEventMock = mock(AsyncDataChangeEvent.class);
+// Map<InstanceIdentifier, DataObject> mapCreate = new HashMap<>();
+// Map<InstanceIdentifier, DataObject> mapUpdate = new HashMap<>();
+//
+// Node node01;
+// String nodeId = "Node01";
+// doReturn(mapCreate).when(asyncDataChangeEventMock).getCreatedData();
+// doReturn(mapUpdate).when(asyncDataChangeEventMock).getUpdatedData();
+//
+// if(isNetconf){
+// node01 = NetconfTestUtils.getNetconfNode(nodeId, "node01.test.local", ConnectionStatus.Connected, notificationCapabilityPrefix);
+//
+// } else {
+// node01 = NetconfTestUtils.getNode(nodeId);
+// }
+//
+// if(create){
+// mapCreate.put(NetconfTestUtils.getInstanceIdentifier(node01), node01);
+// }
+// if(update){
+// mapUpdate.put(NetconfTestUtils.getInstanceIdentifier(node01), node01);
+// }
+//
+// }
+//
+//}
\ No newline at end of file
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import java.net.URI;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.BindingService;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.MountPoint;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
-import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.md.sal.dom.api.DOMService;
-import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
-import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.NotificationsService;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
-public class NetconfEventSourceTest {
-
- NetconfEventSource netconfEventSource;
- DOMMountPoint domMountPointMock;
- MountPoint mountPointMock;
- JoinTopicInput joinTopicInputMock;
-
- @Before
- public void setUp() throws Exception {
- Map<String, String> streamMap = new HashMap<>();
- streamMap.put("uriStr1", "string2");
- domMountPointMock = mock(DOMMountPoint.class);
- mountPointMock = mock(MountPoint.class);
- DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
- RpcConsumerRegistry rpcConsumerRegistryMock = mock(RpcConsumerRegistry.class);
- Optional<BindingService> onlyOptionalMock = (Optional<BindingService>) mock(Optional.class);
- NotificationsService notificationsServiceMock = mock(NotificationsService.class);
- doReturn(notificationsServiceMock).when(rpcConsumerRegistryMock).getRpcService(NotificationsService.class);
-
- Optional<DataBroker> optionalMpDataBroker = (Optional<DataBroker>) mock(Optional.class);
- DataBroker mpDataBroker = mock(DataBroker.class);
- doReturn(optionalMpDataBroker).when(mountPointMock).getService(DataBroker.class);
- doReturn(true).when(optionalMpDataBroker).isPresent();
- doReturn(mpDataBroker).when(optionalMpDataBroker).get();
-
- ReadOnlyTransaction rtx = mock(ReadOnlyTransaction.class);
- doReturn(rtx).when(mpDataBroker).newReadOnlyTransaction();
- CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = (CheckedFuture<Optional<Streams>, ReadFailedException>)mock(CheckedFuture.class);
- InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build();
- doReturn(checkFeature).when(rtx).read(LogicalDatastoreType.OPERATIONAL, pathStream);
- Optional<Streams> avStreams = NetconfTestUtils.getAvailableStream("stream01", true);
- doReturn(avStreams).when(checkFeature).checkedGet();
-
- netconfEventSource = new NetconfEventSource(
- NetconfTestUtils.getNetconfNode("NodeId1", "node.test.local", ConnectionStatus.Connected, NetconfTestUtils.notification_capability_prefix),
- streamMap,
- domMountPointMock,
- mountPointMock ,
- domNotificationPublishServiceMock);
-
- }
-
- @Test
- public void joinTopicTest() throws Exception{
- joinTopicTestHelper();
- assertNotNull("JoinTopic return value has not been created correctly.", netconfEventSource.joinTopic(joinTopicInputMock));
- }
-
- private void joinTopicTestHelper() throws Exception{
- joinTopicInputMock = mock(JoinTopicInput.class);
- TopicId topicId = new TopicId("topicID007");
- doReturn(topicId).when(joinTopicInputMock).getTopicId();
- NotificationPattern notificationPatternMock = mock(NotificationPattern.class);
- doReturn(notificationPatternMock).when(joinTopicInputMock).getNotificationPattern();
- doReturn("uriStr1").when(notificationPatternMock).getValue();
-
- SchemaContext schemaContextMock = mock(SchemaContext.class);
- doReturn(schemaContextMock).when(domMountPointMock).getSchemaContext();
- Set<NotificationDefinition> notificationDefinitionSet = new HashSet<>();
- NotificationDefinition notificationDefinitionMock = mock(NotificationDefinition.class);
- notificationDefinitionSet.add(notificationDefinitionMock);
-
- URI uri = new URI("uriStr1");
- QName qName = new QName(uri, "localName1");
- org.opendaylight.yangtools.yang.model.api.SchemaPath schemaPath = SchemaPath.create(true, qName);
- doReturn(notificationDefinitionSet).when(schemaContextMock).getNotifications();
- doReturn(schemaPath).when(notificationDefinitionMock).getPath();
-
- Optional<DOMNotificationService> domNotificationServiceOptionalMock = (Optional<DOMNotificationService>) mock(Optional.class);
- doReturn(domNotificationServiceOptionalMock).when(domMountPointMock).getService(DOMNotificationService.class);
- doReturn(true).when(domNotificationServiceOptionalMock).isPresent();
-
- DOMNotificationService domNotificationServiceMock = mock(DOMNotificationService.class);
- doReturn(domNotificationServiceMock).when(domNotificationServiceOptionalMock).get();
- ListenerRegistration<NetconfEventSource> listenerRegistrationMock = (ListenerRegistration<NetconfEventSource>)mock(ListenerRegistration.class);
- doReturn(listenerRegistrationMock).when(domNotificationServiceMock).registerNotificationListener(any(NetconfEventSource.class), any(SchemaPath.class));
-
- Optional<DOMService> optionalMock = (Optional<DOMService>) mock(Optional.class);
- doReturn(optionalMock).when(domMountPointMock).getService(DOMRpcService.class);
- doReturn(true).when(optionalMock).isPresent();
- DOMRpcService domRpcServiceMock = mock(DOMRpcService.class);
- doReturn(domRpcServiceMock).when(optionalMock).get();
- CheckedFuture checkedFutureMock = mock(CheckedFuture.class);
- doReturn(checkedFutureMock).when(domRpcServiceMock).invokeRpc(any(SchemaPath.class), any(ContainerNode.class));
-
- }
-
-}
\ No newline at end of file
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//
+//import static org.junit.Assert.assertNotNull;
+//import static org.mockito.Matchers.any;
+//import static org.mockito.Mockito.doReturn;
+//import static org.mockito.Mockito.mock;
+//
+//import java.net.URI;
+//import java.util.HashMap;
+//import java.util.HashSet;
+//import java.util.Map;
+//import java.util.Set;
+//
+//import org.junit.Before;
+//import org.junit.Test;
+//import org.opendaylight.controller.md.sal.binding.api.BindingService;
+//import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+//import org.opendaylight.controller.md.sal.binding.api.MountPoint;
+//import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+//import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+//import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+//import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationPublishService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+//import org.opendaylight.controller.md.sal.dom.api.DOMService;
+//import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.TopicId;
+//import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.JoinTopicInput;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.NotificationsService;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
+//import org.opendaylight.yangtools.concepts.ListenerRegistration;
+//import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+//import org.opendaylight.yangtools.yang.common.QName;
+//import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+//import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+//import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+//import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+//
+//import com.google.common.base.Optional;
+//import com.google.common.util.concurrent.CheckedFuture;
+//
+//public class NetconfEventSourceTest {
+//
+// NetconfEventSource netconfEventSource;
+// DOMMountPoint domMountPointMock;
+// MountPoint mountPointMock;
+// JoinTopicInput joinTopicInputMock;
+//
+// @Before
+// public void setUp() throws Exception {
+// Map<String, String> streamMap = new HashMap<>();
+// streamMap.put("uriStr1", "string2");
+// domMountPointMock = mock(DOMMountPoint.class);
+// mountPointMock = mock(MountPoint.class);
+// DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
+// RpcConsumerRegistry rpcConsumerRegistryMock = mock(RpcConsumerRegistry.class);
+// Optional<BindingService> onlyOptionalMock = (Optional<BindingService>) mock(Optional.class);
+// NotificationsService notificationsServiceMock = mock(NotificationsService.class);
+// doReturn(notificationsServiceMock).when(rpcConsumerRegistryMock).getRpcService(NotificationsService.class);
+//
+// Optional<DataBroker> optionalMpDataBroker = (Optional<DataBroker>) mock(Optional.class);
+// DataBroker mpDataBroker = mock(DataBroker.class);
+// doReturn(optionalMpDataBroker).when(mountPointMock).getService(DataBroker.class);
+// doReturn(true).when(optionalMpDataBroker).isPresent();
+// doReturn(mpDataBroker).when(optionalMpDataBroker).get();
+//
+// ReadOnlyTransaction rtx = mock(ReadOnlyTransaction.class);
+// doReturn(rtx).when(mpDataBroker).newReadOnlyTransaction();
+// CheckedFuture<Optional<Streams>, ReadFailedException> checkFeature = (CheckedFuture<Optional<Streams>, ReadFailedException>)mock(CheckedFuture.class);
+// InstanceIdentifier<Streams> pathStream = InstanceIdentifier.builder(Netconf.class).child(Streams.class).build();
+// doReturn(checkFeature).when(rtx).read(LogicalDatastoreType.OPERATIONAL, pathStream);
+// Optional<Streams> avStreams = NetconfTestUtils.getAvailableStream("stream01", true);
+// doReturn(avStreams).when(checkFeature).checkedGet();
+//
+// netconfEventSource = new NetconfEventSource(
+// NetconfTestUtils.getNetconfNode("NodeId1", "node.test.local", ConnectionStatus.Connected, NetconfTestUtils.notification_capability_prefix),
+// streamMap,
+// domMountPointMock,
+// mountPointMock ,
+// domNotificationPublishServiceMock);
+//
+// }
+//
+// @Test
+// public void joinTopicTest() throws Exception{
+// joinTopicTestHelper();
+// assertNotNull("JoinTopic return value has not been created correctly.", netconfEventSource.joinTopic(joinTopicInputMock));
+// }
+//
+// private void joinTopicTestHelper() throws Exception{
+// joinTopicInputMock = mock(JoinTopicInput.class);
+// TopicId topicId = new TopicId("topicID007");
+// doReturn(topicId).when(joinTopicInputMock).getTopicId();
+// NotificationPattern notificationPatternMock = mock(NotificationPattern.class);
+// doReturn(notificationPatternMock).when(joinTopicInputMock).getNotificationPattern();
+// doReturn("uriStr1").when(notificationPatternMock).getValue();
+//
+// SchemaContext schemaContextMock = mock(SchemaContext.class);
+// doReturn(schemaContextMock).when(domMountPointMock).getSchemaContext();
+// Set<NotificationDefinition> notificationDefinitionSet = new HashSet<>();
+// NotificationDefinition notificationDefinitionMock = mock(NotificationDefinition.class);
+// notificationDefinitionSet.add(notificationDefinitionMock);
+//
+// URI uri = new URI("uriStr1");
+// QName qName = new QName(uri, "localName1");
+// org.opendaylight.yangtools.yang.model.api.SchemaPath schemaPath = SchemaPath.create(true, qName);
+// doReturn(notificationDefinitionSet).when(schemaContextMock).getNotifications();
+// doReturn(schemaPath).when(notificationDefinitionMock).getPath();
+//
+// Optional<DOMNotificationService> domNotificationServiceOptionalMock = (Optional<DOMNotificationService>) mock(Optional.class);
+// doReturn(domNotificationServiceOptionalMock).when(domMountPointMock).getService(DOMNotificationService.class);
+// doReturn(true).when(domNotificationServiceOptionalMock).isPresent();
+//
+// DOMNotificationService domNotificationServiceMock = mock(DOMNotificationService.class);
+// doReturn(domNotificationServiceMock).when(domNotificationServiceOptionalMock).get();
+// ListenerRegistration<NetconfEventSource> listenerRegistrationMock = (ListenerRegistration<NetconfEventSource>)mock(ListenerRegistration.class);
+// doReturn(listenerRegistrationMock).when(domNotificationServiceMock).registerNotificationListener(any(NetconfEventSource.class), any(SchemaPath.class));
+//
+// Optional<DOMService> optionalMock = (Optional<DOMService>) mock(Optional.class);
+// doReturn(optionalMock).when(domMountPointMock).getService(DOMRpcService.class);
+// doReturn(true).when(optionalMock).isPresent();
+// DOMRpcService domRpcServiceMock = mock(DOMRpcService.class);
+// doReturn(domRpcServiceMock).when(optionalMock).get();
+// CheckedFuture checkedFutureMock = mock(CheckedFuture.class);
+// doReturn(checkedFutureMock).when(domRpcServiceMock).invokeRpc(any(SchemaPath.class), any(ContainerNode.class));
+//
+// }
+//
+//}
\ No newline at end of file
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.messagebus.eventsources.netconf;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.StreamsBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.StreamBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.DomainName;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
-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.NetconfNodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.AvailableCapabilities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.AvailableCapabilitiesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-import com.google.common.base.Optional;
-
-public final class NetconfTestUtils {
-
- 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){
-
- DomainName dn = new DomainName(hostName);
- Host host = new Host(dn);
-
- List<String> avCapList = new ArrayList<>();
- avCapList.add(notificationCapabilityPrefix +"_availableCapabilityString1");
- AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
- NetconfNode nn = new NetconfNodeBuilder()
- .setConnectionStatus(cs)
- .setHost(host)
- .setAvailableCapabilities(avCaps)
- .build();
-
- NodeId nodeId = new NodeId(nodeIdent);
- NodeKey nk = new NodeKey(nodeId);
- NodeBuilder nb = new NodeBuilder();
- nb.setKey(nk);
-
- nb.addAugmentation(NetconfNode.class, nn);
- return nb.build();
- }
-
- public static Node getNode(String nodeIdent){
- NodeId nodeId = new NodeId(nodeIdent);
- NodeKey nk = new NodeKey(nodeId);
- NodeBuilder nb = new NodeBuilder();
- nb.setKey(nk);
- return nb.build();
- }
-
- public static InstanceIdentifier<Node> getInstanceIdentifier(Node node){
- TopologyKey NETCONF_TOPOLOGY_KEY = 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());
- return nodeII;
- }
-
- 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();
- return Optional.of(streams);
- }
-
-}
+///*
+// * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+// *
+// * This program and the accompanying materials are made available under the
+// * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+// * and is available at http://www.eclipse.org/legal/epl-v10.html
+// */
+//package org.opendaylight.controller.messagebus.eventsources.netconf;
+//
+//import java.util.ArrayList;
+//import java.util.List;
+//
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.StreamsBuilder;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.StreamBuilder;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.DomainName;
+//import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
+//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.NetconfNodeBuilder;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.AvailableCapabilities;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.AvailableCapabilitiesBuilder;
+//import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
+//import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
+//import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+//
+//import com.google.common.base.Optional;
+//
+//public final class NetconfTestUtils {
+//
+// 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){
+//
+// DomainName dn = new DomainName(hostName);
+// Host host = new Host(dn);
+//
+// List<String> avCapList = new ArrayList<>();
+// avCapList.add(notificationCapabilityPrefix +"_availableCapabilityString1");
+// AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
+// NetconfNode nn = new NetconfNodeBuilder()
+// .setConnectionStatus(cs)
+// .setHost(host)
+// .setAvailableCapabilities(avCaps)
+// .build();
+//
+// NodeId nodeId = new NodeId(nodeIdent);
+// NodeKey nk = new NodeKey(nodeId);
+// NodeBuilder nb = new NodeBuilder();
+// nb.setKey(nk);
+//
+// nb.addAugmentation(NetconfNode.class, nn);
+// return nb.build();
+// }
+//
+// public static Node getNode(String nodeIdent){
+// NodeId nodeId = new NodeId(nodeIdent);
+// NodeKey nk = new NodeKey(nodeId);
+// NodeBuilder nb = new NodeBuilder();
+// nb.setKey(nk);
+// return nb.build();
+// }
+//
+// public static InstanceIdentifier<Node> getInstanceIdentifier(Node node){
+// TopologyKey NETCONF_TOPOLOGY_KEY = 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());
+// return nodeII;
+// }
+//
+// 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();
+// return Optional.of(streams);
+// }
+//
+//}
<module>sal-connector-api</module>
<module>sal-rest-connector</module>
<module>sal-rest-connector-config</module>
- <module>sal-netconf-connector</module>
<!-- Documentation -->
<module>sal-rest-docgen</module>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>config-netconf-connector</artifactId>
+ <artifactId>config-manager-facade-xml</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>logback-config</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-client</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-monitoring</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-notifications-api</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-binding-broker-impl</artifactId>
mavenBundle("commons-codec", "commons-codec").versionAsInProject(),
systemPackages("sun.nio.ch", "sun.misc"),
- mavenBundle("io.netty", "netty-common").versionAsInProject(), //
- mavenBundle("io.netty", "netty-buffer").versionAsInProject(), //
- mavenBundle("io.netty", "netty-handler").versionAsInProject(), //
- mavenBundle("io.netty", "netty-codec").versionAsInProject(), //
- mavenBundle("io.netty", "netty-transport").versionAsInProject(), //
mavenBundle(CONTROLLER, "config-manager").versionAsInProject(), // //
mavenBundle(CONTROLLER, "config-util").versionAsInProject(), // //
mavenBundle("commons-io", "commons-io").versionAsInProject(), //
- mavenBundle(CONTROLLER, "config-manager").versionAsInProject(), //
+ mavenBundle(CONTROLLER, "config-manager-facade-xml").versionAsInProject(), //
mavenBundle(CONTROLLER, "yang-jmx-generator").versionAsInProject(), //
mavenBundle(CONTROLLER, "logback-config").versionAsInProject(), //
mavenBundle(CONTROLLER, "config-persister-api").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-api").versionAsInProject(), //
- mavenBundle(CONTROLLER, "ietf-netconf-monitoring").versionAsInProject(), //
- mavenBundle(CONTROLLER, "ietf-netconf-monitoring-extension").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-monitoring").versionAsInProject(), //
-
- mavenBundle(CONTROLLER, "netty-config-api").versionAsInProject(), //
- mavenBundle(CONTROLLER, "protocol-framework").versionAsInProject(), //
-
- mavenBundle(CONTROLLER, "netconf-client").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-util").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-netty-util").versionAsInProject(), //
- mavenBundle("org.apache.sshd", "sshd-core").versionAsInProject(), //
- mavenBundle("openexi", "nagasena").versionAsInProject(), //
- mavenBundle("openexi", "nagasena-rta").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-mapping-api").versionAsInProject(), //
mavenBundle(CONTROLLER, "config-persister-impl").versionAsInProject(), //
mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xerces", "2.11.0_1"),
mavenBundle("org.eclipse.birt.runtime.3_7_1", "org.apache.xml.resolver", "1.2.0"),
- mavenBundle(CONTROLLER, "config-netconf-connector").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-notifications-api").versionAsInProject(), //
- mavenBundle(CONTROLLER, "ietf-netconf").versionAsInProject(), //
- mavenBundle(CONTROLLER, "ietf-netconf-notifications").versionAsInProject(), //
- mavenBundle(CONTROLLER, "netconf-impl").versionAsInProject(), //
-
mavenBundle(CONTROLLER, "config-persister-file-xml-adapter").versionAsInProject().noStart(),
mavenBundle("org.eclipse.persistence", "org.eclipse.persistence.moxy").versionAsInProject(),
mavenBundle("org.eclipse.persistence", "org.eclipse.persistence.core").versionAsInProject());
mavenBundle(CONTROLLER, "sal-broker-impl").versionAsInProject(), // //
mavenBundle(CONTROLLER, "sal-core-spi").versionAsInProject().update(), //
-
- systemProperty("netconf.tcp.address").value("0.0.0.0"), //
- systemProperty("netconf.tcp.port").value("18383"), //
- systemProperty("netconf.tcp.client.address").value("127.0.0.1"), //
- systemProperty("netconf.tcp.client.port").value("18383"), //
systemProperty("netconf.config.persister.active").value("1"), //
systemProperty("netconf.config.persister.1.storageAdapterClass").value(
"org.opendaylight.controller.config.persist.storage.file.xml.XmlFileStorageAdapter"), //
}
+ public static Option protocolFrameworkBundles() {
+ return new DefaultCompositeOption(
+ mavenBundle("io.netty", "netty-common").versionAsInProject(), //
+ mavenBundle("io.netty", "netty-buffer").versionAsInProject(), //
+ mavenBundle("io.netty", "netty-handler").versionAsInProject(), //
+ mavenBundle("io.netty", "netty-codec").versionAsInProject(), //
+ mavenBundle("io.netty", "netty-transport").versionAsInProject(), //
+ mavenBundle(CONTROLLER, "netty-config-api").versionAsInProject(), //
+ mavenBundle(CONTROLLER, "protocol-framework").versionAsInProject()
+ );
+
+ }
+
public static Option flowCapableModelBundles() {
return new DefaultCompositeOption( //
mavenBundle(CONTROLLER_MODELS, "model-inventory").versionAsInProject() //
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import com.google.inject.Inject;
import java.util.concurrent.Future;
-
import org.junit.Test;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ConsumerContext;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import com.google.inject.Inject;
-
/**
* covers creating, reading and deleting of an item in dataStore
*/
assertNotNull(readedData);
assertEquals(nodeData1.getKey(), readedData.getKey());
-
DataModificationTransaction transaction2 = consumerDataService.beginTransaction();
assertNotNull(transaction2);
<capability>
urn:opendaylight:params:xml:ns:yang:controller:config?module=config&revision=2013-04-05
</capability>
- <capability>urn:ietf:params:netconf:capability:candidate:1.0</capability>
- <capability>urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&revision=2010-10-04</capability>
<capability>urn:ietf:params:xml:ns:yang:rpc-context?module=rpc-context&revision=2013-06-17
</capability>
<capability>
</dependency>
<!-- OpenDaylight -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-util</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>util</artifactId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-common-impl</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-util</artifactId>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-commons</artifactId>
<groupId>${project.groupId}</groupId>
<artifactId>config-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-util</artifactId>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netconf-impl</artifactId>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-mapping-api</artifactId>
<artifactId>binding-generator-impl</artifactId>
</dependency>
<dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
+ <artifactId>slf4j-simple</artifactId>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>config-manager</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netconf-impl</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<configuration>
<instructions>
<Bundle-Activator>org.opendaylight.controller.netconf.confignetconfconnector.osgi.Activator</Bundle-Activator>
- <Private-Package>org.opendaylight.controller.netconf.confignetconfconnector.mapping.*,
- org.opendaylight.controller.netconf.confignetconfconnector.operations.*,
- org.opendaylight.controller.netconf.confignetconfconnector.transactions,
- org.opendaylight.controller.netconf.confignetconfconnector.util,
- org.opendaylight.controller.netconf.confignetconfconnector.osgi,
- org.opendaylight.controller.netconf.confignetconfconnector.exception,</Private-Package>
</instructions>
</configuration>
</plugin>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.netconf.confignetconfconnector.exception;
-
-import java.util.Collections;
-import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-
-public class NetconfConfigHandlingException extends NetconfDocumentedException {
- private static final long serialVersionUID = 1L;
-
- public NetconfConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String>emptyMap());
- }
-
- public NetconfConfigHandlingException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo){
- super(message,errorType,errorTag,errorSeverity,errorInfo);
- }
-}
package org.opendaylight.controller.netconf.confignetconfconnector.operations;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
public abstract class AbstractConfigNetconfOperation extends AbstractLastNetconfOperation {
- private final ConfigRegistryClient configRegistryClient;
+ private final ConfigSubsystemFacade configSubsystemFacade;
- protected AbstractConfigNetconfOperation(ConfigRegistryClient configRegistryClient,
+ protected AbstractConfigNetconfOperation(ConfigSubsystemFacade configSubsystemFacade,
String netconfSessionIdForReporting) {
super(netconfSessionIdForReporting);
- this.configRegistryClient = configRegistryClient;
+ this.configSubsystemFacade = configSubsystemFacade;
}
- public ConfigRegistryClient getConfigRegistryClient() {
- return configRegistryClient;
+ public ConfigSubsystemFacade getConfigSubsystemFacade() {
+ return configSubsystemFacade;
}
}
import org.opendaylight.controller.config.api.ConflictingVersionException;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
private static final Logger LOG = LoggerFactory.getLogger(Commit.class);
- private final TransactionProvider transactionProvider;
-
- public Commit(TransactionProvider transactionProvider, ConfigRegistryClient configRegistryClient,
- String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.transactionProvider = transactionProvider;
+ public Commit(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
}
- private static void checkXml(XmlElement xml) throws NetconfDocumentedException {
+ private static void checkXml(XmlElement xml) throws DocumentedException {
xml.checkName(XmlNetconfConstants.COMMIT);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
checkXml(xml);
CommitStatus status;
try {
- status = this.transactionProvider.commitTransaction();
+ status = getConfigSubsystemFacade().commitTransaction();
LOG.trace("Datastore {} committed successfully: {}", Datastore.candidate, status);
} catch (ConflictingVersionException | ValidationException e) {
- throw NetconfDocumentedException.wrap(e);
+ throw DocumentedException.wrap(e);
}
LOG.trace("Datastore {} committed successfully: {}", Datastore.candidate, status);
import com.google.common.base.Optional;
import java.util.HashMap;
import java.util.Map;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
private static final Logger LOG = LoggerFactory.getLogger(DiscardChanges.class);
- private final TransactionProvider transactionProvider;
-
- public DiscardChanges(final TransactionProvider transactionProvider, ConfigRegistryClient configRegistryClient,
- String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.transactionProvider = transactionProvider;
+ public DiscardChanges(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
}
- private static void fromXml(XmlElement xml) throws NetconfDocumentedException {
+ private static void fromXml(XmlElement xml) throws DocumentedException {
xml.checkName(DISCARD);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
fromXml(xml);
try {
- if (transactionProvider.getTransaction().isPresent()) {
- this.transactionProvider.abortTransaction();
- }
+ getConfigSubsystemFacade().abortConfiguration();
} catch (final RuntimeException e) {
LOG.warn("Abort failed: ", e);
final Map<String, String> errorInfo = new HashMap<>();
errorInfo
.put(ErrorTag.operation_failed.name(),
"Abort failed.");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
+ throw new DocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
ErrorSeverity.error, errorInfo);
}
LOG.trace("Changes discarded successfully from datastore {}", Datastore.candidate);
package org.opendaylight.controller.netconf.confignetconfconnector.operations;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
if(targetDatastore == Datastore.candidate) {
// Since candidate datastore instances are allocated per session and not accessible anywhere else, no need to lock
}
// Not supported running lock
- throw new NetconfDocumentedException("Unable to lock " + Datastore.running + " datastore", NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_not_supported, NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Unable to lock " + Datastore.running + " datastore", DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_not_supported, DocumentedException.ErrorSeverity.error);
}
- static Datastore extractTargetParameter(final XmlElement operationElement) throws NetconfDocumentedException {
- final XmlElement targetChildNode;
- try {
- final XmlElement targetElement = operationElement.getOnlyChildElementWithSameNamespace(TARGET_KEY);
- targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
- } catch (final MissingNameSpaceException | UnexpectedNamespaceException e) {
- LOG.trace("Can't get only child element with same namespace", e);
- throw NetconfDocumentedException.wrap(e);
- }
+ static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
+ final XmlElement targetElement = operationElement.getOnlyChildElementWithSameNamespace(TARGET_KEY);
+ final XmlElement targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
return Datastore.valueOf(targetChildNode.getName());
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
if(targetDatastore == Datastore.candidate) {
// Since candidate datastore instances are allocated per session and not accessible anywhere else, no need to lock
}
// Not supported running lock
- throw new NetconfDocumentedException("Unable to unlock " + Datastore.running + " datastore", NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_not_supported, NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Unable to unlock " + Datastore.running + " datastore", DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_not_supported, DocumentedException.ErrorSeverity.error);
}
@Override
import java.util.HashMap;
import java.util.Map;
import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
private static final Logger LOG = LoggerFactory.getLogger(Validate.class);
- private final TransactionProvider transactionProvider;
-
- public Validate(final TransactionProvider transactionProvider, ConfigRegistryClient configRegistryClient,
- String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.transactionProvider = transactionProvider;
+ public Validate(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
}
- private void checkXml(XmlElement xml) throws NetconfDocumentedException {
+ private void checkXml(XmlElement xml) throws DocumentedException {
xml.checkName(VALIDATE);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
Datastore sourceDatastore = Datastore.valueOf(datastoreValue);
if (sourceDatastore != Datastore.candidate){
- throw new NetconfDocumentedException( "Only " + Datastore.candidate
- + " is supported as source for " + VALIDATE + " but was " + datastoreValue,ErrorType.application,ErrorTag.data_missing,ErrorSeverity.error);
+ throw new DocumentedException( "Only " + Datastore.candidate
+ + " is supported as source for " + VALIDATE + " but was " + datastoreValue, ErrorType.application, ErrorTag.data_missing, ErrorSeverity.error);
}
}
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
checkXml(xml);
try {
- transactionProvider.validateTransaction();
+ getConfigSubsystemFacade().validateConfiguration();
} catch (ValidationException e) {
LOG.warn("Validation failed", e);
- throw NetconfDocumentedException.wrap(e);
+ throw DocumentedException.wrap(e);
} catch (IllegalStateException e) {
LOG.warn("Validation failed", e);
final Map<String, String> errorInfo = new HashMap<>();
errorInfo
.put(ErrorTag.operation_failed.name(),
"Datastore is not present. Use 'get-config' or 'edit-config' before triggering 'operations' operation");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
+ throw new DocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
ErrorSeverity.error, errorInfo);
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
-
-import java.util.Map;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.exception.NetconfConfigHandlingException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class DeleteEditConfigStrategy extends AbstractEditConfigStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(DeleteEditConfigStrategy.class);
-
-
- @Override
- void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
- String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
- throw new NetconfConfigHandlingException(String.format("Unable to delete %s : %s , ServiceInstance not found", module ,instance),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
- }
-
- @Override
- void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
- try {
- ta.destroyModule(on);
- LOG.debug("ServiceInstance {} deleted successfully", on);
- } catch (InstanceNotFoundException e) {
- throw new NetconfConfigHandlingException(
- String.format("Unable to delete %s because of exception %s" + on, e.getMessage()),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
- }
- }
-}
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
-import java.util.Date;
import java.util.HashMap;
import java.util.Map;
-import java.util.Set;
-import javax.management.InstanceNotFoundException;
-import javax.management.ObjectName;
import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.util.BeanReader;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.facade.xml.ConfigExecution;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfigElementResolved;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementDefinition;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementResolved;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services.ServiceInstance;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser.EditConfigExecution;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
private static final Logger LOG = LoggerFactory.getLogger(EditConfig.class);
- private final YangStoreContext yangStoreSnapshot;
-
- private final TransactionProvider transactionProvider;
private EditConfigXmlParser editConfigXmlParser;
- public EditConfig(YangStoreContext yangStoreSnapshot, TransactionProvider transactionProvider,
- ConfigRegistryClient configRegistryClient, String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.yangStoreSnapshot = yangStoreSnapshot;
- this.transactionProvider = transactionProvider;
+ public EditConfig(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
this.editConfigXmlParser = new EditConfigXmlParser();
}
@VisibleForTesting
Element getResponseInternal(final Document document,
- final EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
-
- if (editConfigExecution.shouldTest()) {
- executeTests(getConfigRegistryClient(), editConfigExecution);
- }
-
- if (editConfigExecution.shouldSet()) {
- executeSet(getConfigRegistryClient(), editConfigExecution);
- }
-
- LOG.trace("Operation {} successful", EditConfigXmlParser.EDIT_CONFIG);
-
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
- }
+ final ConfigExecution configExecution) throws DocumentedException {
- private void executeSet(ConfigRegistryClient configRegistryClient,
- EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
- set(configRegistryClient, editConfigExecution);
- LOG.debug("Set phase for {} operation successful", EditConfigXmlParser.EDIT_CONFIG);
- }
-
- private void executeTests(ConfigRegistryClient configRegistryClient,
- EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
try {
- test(configRegistryClient, editConfigExecution, editConfigExecution.getDefaultStrategy());
- } catch (final ValidationException e) {
+ getConfigSubsystemFacade().executeConfigExecution(configExecution);
+ } catch (ValidationException e) {
LOG.warn("Test phase for {} failed", EditConfigXmlParser.EDIT_CONFIG, e);
final Map<String, String> errorInfo = new HashMap<>();
errorInfo.put(ErrorTag.operation_failed.name(), e.getMessage());
- throw new NetconfDocumentedException("Test phase: " + e.getMessage(), e, ErrorType.application,
+ throw new DocumentedException("Test phase: " + e.getMessage(), e, ErrorType.application,
ErrorTag.operation_failed, ErrorSeverity.error, errorInfo);
}
- LOG.debug("Test phase for {} operation successful", EditConfigXmlParser.EDIT_CONFIG);
- }
-
- private void test(ConfigRegistryClient configRegistryClient, EditConfigExecution execution,
- EditStrategyType editStrategyType) throws ValidationException, NetconfDocumentedException {
- ObjectName taON = transactionProvider.getTestTransaction();
- try {
- // default strategy = replace wipes config
- if (editStrategyType == EditStrategyType.replace) {
- transactionProvider.wipeTestTransaction(taON);
- }
-
- ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
-
- handleMisssingInstancesOnTransaction(ta, execution);
- setServicesOnTransaction(ta, execution);
- setOnTransaction(ta, execution);
- transactionProvider.validateTestTransaction(taON);
- } finally {
- transactionProvider.abortTestTransaction(taON);
- }
- }
-
- private void set(ConfigRegistryClient configRegistryClient,
- EditConfigXmlParser.EditConfigExecution editConfigExecution) throws NetconfDocumentedException {
- ObjectName taON = transactionProvider.getOrCreateTransaction();
-
- // default strategy = replace wipes config
- if (editConfigExecution.getDefaultStrategy() == EditStrategyType.replace) {
- transactionProvider.wipeTransaction();
- }
-
- ConfigTransactionClient ta = configRegistryClient.getConfigTransactionClient(taON);
-
- handleMisssingInstancesOnTransaction(ta, editConfigExecution);
- setServicesOnTransaction(ta, editConfigExecution);
- setOnTransaction(ta, editConfigExecution);
- }
-
- private void setServicesOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) throws NetconfDocumentedException {
-
- Services services = execution.getServices();
-
- Map<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceNameToRefNameToInstance = services
- .getNamespaceToServiceNameToRefNameToInstance();
-
- for (Map.Entry<String, Map<String, Map<String, Services.ServiceInstance>>> namespaceToServiceToRefEntry : namespaceToServiceNameToRefNameToInstance.entrySet()) {
- for (Map.Entry<String, Map<String, Services.ServiceInstance>> serviceToRefEntry : namespaceToServiceToRefEntry.getValue().entrySet()) {
-
- String qnameOfService = getQname(ta, namespaceToServiceToRefEntry.getKey(), serviceToRefEntry.getKey());
- Map<String, Services.ServiceInstance> refNameToInstance = serviceToRefEntry.getValue();
-
- for (Map.Entry<String, Services.ServiceInstance> refNameToServiceEntry : refNameToInstance.entrySet()) {
- ObjectName on = refNameToServiceEntry.getValue().getObjectName(ta.getTransactionName());
- try {
- if (ServiceInstance.EMPTY_SERVICE_INSTANCE == refNameToServiceEntry.getValue()) {
- ta.removeServiceReference(qnameOfService, refNameToServiceEntry.getKey());
- LOG.debug("Removing service {} with name {}", qnameOfService, refNameToServiceEntry.getKey());
- } else {
- ObjectName saved = ta.saveServiceReference(qnameOfService, refNameToServiceEntry.getKey(), on);
- LOG.debug("Saving service {} with on {} under name {} with service on {}", qnameOfService,
- on, refNameToServiceEntry.getKey(), saved);
- }
- } catch (InstanceNotFoundException e) {
- throw new NetconfDocumentedException(String.format("Unable to edit ref name " + refNameToServiceEntry.getKey() + " for instance " + on, e),
- ErrorType.application,
- ErrorTag.operation_failed,
- ErrorSeverity.error);
- }
- }
- }
- }
- }
-
- private String getQname(ConfigTransactionClient ta, String namespace, String serviceName) {
- return ta.getServiceInterfaceName(namespace, serviceName);
- }
-
- private void setOnTransaction(ConfigTransactionClient ta, EditConfigExecution execution) throws NetconfDocumentedException {
-
- for (Multimap<String, ModuleElementResolved> modulesToResolved : execution.getResolvedXmlElements(ta).values()) {
-
- for (Map.Entry<String, ModuleElementResolved> moduleToResolved : modulesToResolved.entries()) {
- String moduleName = moduleToResolved.getKey();
-
- ModuleElementResolved moduleElementResolved = moduleToResolved.getValue();
- String instanceName = moduleElementResolved.getInstanceName();
- InstanceConfigElementResolved ice = moduleElementResolved.getInstanceConfigElementResolved();
- EditConfigStrategy strategy = ice.getEditStrategy();
- strategy.executeConfiguration(moduleName, instanceName, ice.getConfiguration(), ta, execution.getServiceRegistryWrapper(ta));
- }
- }
- }
-
- private void handleMisssingInstancesOnTransaction(ConfigTransactionClient ta,
- EditConfigExecution execution) throws NetconfDocumentedException {
-
- for (Multimap<String,ModuleElementDefinition> modulesToResolved : execution.getModulesDefinition(ta).values()) {
- for (Map.Entry<String, ModuleElementDefinition> moduleToResolved : modulesToResolved.entries()) {
- String moduleName = moduleToResolved.getKey();
-
- ModuleElementDefinition moduleElementDefinition = moduleToResolved.getValue();
-
- EditConfigStrategy strategy = moduleElementDefinition.getEditStrategy();
- strategy.executeConfiguration(moduleName, moduleElementDefinition.getInstanceName(), null, ta, execution.getServiceRegistryWrapper(ta));
- }
- }
- }
-
- public static Config getConfigMapping(ConfigRegistryClient configRegistryClient, YangStoreContext yangStoreSnapshot) {
- Map<String, Map<String, ModuleConfig>> factories = transformMbeToModuleConfigs(configRegistryClient,
- yangStoreSnapshot.getModuleMXBeanEntryMap());
- Map<String, Map<Date, IdentityMapping>> identitiesMap = transformIdentities(yangStoreSnapshot.getModules());
- return new Config(factories, identitiesMap, yangStoreSnapshot.getEnumResolver());
- }
-
-
- public static class IdentityMapping {
- private final Map<String, IdentitySchemaNode> identityNameToSchemaNode;
-
- public IdentityMapping() {
- this.identityNameToSchemaNode = Maps.newHashMap();
- }
-
- void addIdSchemaNode(IdentitySchemaNode node) {
- String name = node.getQName().getLocalName();
- Preconditions.checkState(!identityNameToSchemaNode.containsKey(name));
- identityNameToSchemaNode.put(name, node);
- }
-
- public boolean containsIdName(String idName) {
- return identityNameToSchemaNode.containsKey(idName);
- }
-
- }
-
- private static Map<String, Map<Date, IdentityMapping>> transformIdentities(Set<Module> modules) {
- Map<String, Map<Date, IdentityMapping>> mappedIds = Maps.newHashMap();
- for (Module module : modules) {
- String namespace = module.getNamespace().toString();
- Map<Date, IdentityMapping> revisionsByNamespace= mappedIds.get(namespace);
- if(revisionsByNamespace == null) {
- revisionsByNamespace = Maps.newHashMap();
- mappedIds.put(namespace, revisionsByNamespace);
- }
-
- Date revision = module.getRevision();
-
- IdentityMapping identityMapping = revisionsByNamespace.get(revision);
- if(identityMapping == null) {
- identityMapping = new IdentityMapping();
- revisionsByNamespace.put(revision, identityMapping);
- }
-
- for (IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
- identityMapping.addIdSchemaNode(identitySchemaNode);
- }
-
- }
-
- return mappedIds;
- }
-
- public static Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleConfig>> transformMbeToModuleConfigs (
- final BeanReader configRegistryClient, Map<String/* Namespace from yang file */,
- Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> mBeanEntries) {
-
- Map<String, Map<String, ModuleConfig>> namespaceToModuleNameToModuleConfig = Maps.newHashMap();
-
- for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleToMbe : mBeanEntries.entrySet()) {
- for (Map.Entry<String, ModuleMXBeanEntry> moduleNameToMbe : namespaceToModuleToMbe.getValue().entrySet()) {
- String moduleName = moduleNameToMbe.getKey();
- ModuleMXBeanEntry moduleMXBeanEntry = moduleNameToMbe.getValue();
-
- ModuleConfig moduleConfig = new ModuleConfig(moduleName,
- new InstanceConfig(configRegistryClient,moduleMXBeanEntry.getAttributes(), moduleMXBeanEntry.getNullableDummyContainerName()));
-
- Map<String, ModuleConfig> moduleNameToModuleConfig = namespaceToModuleNameToModuleConfig.get(namespaceToModuleToMbe.getKey());
- if(moduleNameToModuleConfig == null) {
- moduleNameToModuleConfig = Maps.newHashMap();
- namespaceToModuleNameToModuleConfig.put(namespaceToModuleToMbe.getKey(), moduleNameToModuleConfig);
- }
-
- moduleNameToModuleConfig.put(moduleName, moduleConfig);
- }
- }
+ LOG.trace("Operation {} successful", EditConfigXmlParser.EDIT_CONFIG);
- return namespaceToModuleNameToModuleConfig;
+ return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
@Override
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
- EditConfigXmlParser.EditConfigExecution editConfigExecution;
- Config cfg = getConfigMapping(getConfigRegistryClient(), yangStoreSnapshot);
- editConfigExecution = editConfigXmlParser.fromXml(xml, cfg);
-
- Element responseInternal;
- responseInternal = getResponseInternal(document, editConfigExecution);
- return responseInternal;
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
+ ConfigExecution configExecution;
+ // FIXME config mapping getter works on dynamic yang store service and so does later executeConfigExecution method
+ // They might have different view of current yangs in ODL and might cause race conditions
+ Config cfg = getConfigSubsystemFacade().getConfigMapping();
+ configExecution = editConfigXmlParser.fromXml(xml, cfg);
+
+ return getResponseInternal(document, configExecution);
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
-import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
-import com.google.common.collect.Multimap;
-import java.util.Arrays;
-import java.util.Map;
-import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.ConfigExecution;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.facade.xml.TestOption;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementDefinition;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementResolved;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.Datastore;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public EditConfigXmlParser() {
}
- EditConfigXmlParser.EditConfigExecution fromXml(final XmlElement xml, final Config cfgMapping)
- throws NetconfDocumentedException {
+ ConfigExecution fromXml(final XmlElement xml, final Config cfgMapping)
+ throws DocumentedException {
//TODO remove transactionProvider and CfgRegistry from parameters, accept only service ref store
XmlElement targetElement = null;
XmlElement targetChildNode = null;
- try {
- targetElement = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
- targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
- } catch (final MissingNameSpaceException | UnexpectedNamespaceException e) {
- LOG.trace("Can't get only child element with same namespace", e);
- throw NetconfDocumentedException.wrap(e);
- }
+ targetElement = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
+ targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
+
String datastoreValue = targetChildNode.getName();
Datastore targetDatastore = Datastore.valueOf(datastoreValue);
LOG.debug("Setting {} to '{}'", EditConfigXmlParser.TARGET_KEY, targetDatastore);
// check target
if (targetDatastore != Datastore.candidate){
- throw new NetconfDocumentedException(String.format(
+ throw new DocumentedException(String.format(
"Only %s datastore supported for edit config but was: %s",
Datastore.candidate,
targetDatastore),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error);
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.invalid_value,
+ DocumentedException.ErrorSeverity.error);
}
// Test option
.getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.TEST_OPTION_KEY);
if (testOptionElementOpt.isPresent()) {
String testOptionValue = testOptionElementOpt.get().getTextContent();
- testOption = EditConfigXmlParser.TestOption.getFromXmlName(testOptionValue);
+ testOption = TestOption.getFromXmlName(testOptionValue);
} else {
- testOption = EditConfigXmlParser.TestOption.getDefault();
+ testOption = TestOption.getDefault();
}
LOG.debug("Setting {} to '{}'", EditConfigXmlParser.TEST_OPTION_KEY, testOption);
}
XmlElement configElement = null;
- try {
- configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
- } catch (MissingNameSpaceException e) {
- LOG.trace("Can't get only child element with same namespace due to ",e);
- throw NetconfDocumentedException.wrap(e);
- }
-
- return new EditConfigXmlParser.EditConfigExecution(cfgMapping, configElement, testOption, editStrategyType);
- }
-
- @VisibleForTesting
- static enum TestOption {
- testOnly, set, testThenSet;
-
- static TestOption getFromXmlName(String testOptionXmlName) {
- switch (testOptionXmlName) {
- case "test-only":
- return testOnly;
- case "test-then-set":
- return testThenSet;
- case "set":
- return set;
- default:
- throw new IllegalArgumentException("Unsupported test option " + testOptionXmlName + " supported: "
- + Arrays.toString(TestOption.values()));
- }
- }
-
- public static TestOption getDefault() {
- return testThenSet;
- }
-
- }
-
- @VisibleForTesting
- static class EditConfigExecution {
-
- private final TestOption testOption;
- private final EditStrategyType defaultEditStrategyType;
- private final Services services;
- private final Config configResolver;
- private final XmlElement configElement;
-
- EditConfigExecution(Config configResolver, XmlElement configElement, TestOption testOption, EditStrategyType defaultStrategy) throws NetconfDocumentedException {
- Config.checkUnrecognisedChildren(configElement);
- this.configResolver = configResolver;
- this.configElement = configElement;
- this.services = configResolver.fromXmlServices(configElement);
- this.testOption = testOption;
- this.defaultEditStrategyType = defaultStrategy;
- }
+ configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
- boolean shouldTest() {
- return testOption == TestOption.testOnly || testOption == TestOption.testThenSet;
- }
-
- boolean shouldSet() {
- return testOption == TestOption.set || testOption == TestOption.testThenSet;
- }
-
- Map<String, Multimap<String, ModuleElementResolved>> getResolvedXmlElements(ServiceReferenceReadableRegistry serviceRegistry) throws NetconfDocumentedException {
- return configResolver.fromXmlModulesResolved(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
- }
-
- ServiceRegistryWrapper getServiceRegistryWrapper(ServiceReferenceReadableRegistry serviceRegistry) {
- // TODO cache service registry
- return new ServiceRegistryWrapper(serviceRegistry);
- }
-
- Map<String, Multimap<String,ModuleElementDefinition>> getModulesDefinition(ServiceReferenceReadableRegistry serviceRegistry) throws NetconfDocumentedException {
- return configResolver.fromXmlModulesMap(configElement, defaultEditStrategyType, getServiceRegistryWrapper(serviceRegistry));
- }
-
- EditStrategyType getDefaultStrategy() {
- return defaultEditStrategyType;
- }
-
- Services getServices() {
- return services;
- }
+ return new ConfigExecution(cfgMapping, configElement, testOption, editStrategyType);
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.get;
-import com.google.common.collect.Maps;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime.InstanceRuntime;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime.ModuleRuntime;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.runtime.Runtime;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.Datastore;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
public class Get extends AbstractConfigNetconfOperation {
- private final TransactionProvider transactionProvider;
- private final YangStoreContext yangStoreSnapshot;
private static final Logger LOG = LoggerFactory.getLogger(Get.class);
- public Get(final TransactionProvider transactionProvider, YangStoreContext yangStoreSnapshot, ConfigRegistryClient configRegistryClient,
- String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.transactionProvider = transactionProvider;
- this.yangStoreSnapshot = yangStoreSnapshot;
+ public Get(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
}
- private Map<String, Map<String, ModuleRuntime>> createModuleRuntimes(ConfigRegistryClient configRegistryClient,
- Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries) {
- Map<String, Map<String, ModuleRuntime>> retVal = Maps.newHashMap();
-
- for (Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mBeanEntries.entrySet()) {
-
- Map<String, ModuleRuntime> innerMap = Maps.newHashMap();
- Map<String, ModuleMXBeanEntry> entriesFromNamespace = namespaceToModuleEntry.getValue();
- for (Map.Entry<String, ModuleMXBeanEntry> moduleToMXEntry : entriesFromNamespace.entrySet()) {
-
- ModuleMXBeanEntry mbe = moduleToMXEntry.getValue();
-
- Map<RuntimeBeanEntry, InstanceConfig> cache = Maps.newHashMap();
- RuntimeBeanEntry root = null;
- for (RuntimeBeanEntry rbe : mbe.getRuntimeBeans()) {
- cache.put(rbe, new InstanceConfig(configRegistryClient, rbe.getYangPropertiesToTypesMap(), mbe.getNullableDummyContainerName()));
- if (rbe.isRoot()){
- root = rbe;
- }
- }
-
- if (root == null){
- continue;
- }
-
- InstanceRuntime rootInstanceRuntime = createInstanceRuntime(root, cache);
- ModuleRuntime moduleRuntime = new ModuleRuntime(rootInstanceRuntime);
- innerMap.put(moduleToMXEntry.getKey(), moduleRuntime);
- }
-
- retVal.put(namespaceToModuleEntry.getKey(), innerMap);
- }
- return retVal;
- }
-
- private InstanceRuntime createInstanceRuntime(RuntimeBeanEntry root, Map<RuntimeBeanEntry, InstanceConfig> cache) {
- Map<String, InstanceRuntime> children = Maps.newHashMap();
- for (RuntimeBeanEntry child : root.getChildren()) {
- children.put(child.getJavaNamePrefix(), createInstanceRuntime(child, cache));
- }
-
- return new InstanceRuntime(cache.get(root), children, createJmxToYangMap(root.getChildren()));
- }
-
- private Map<String, String> createJmxToYangMap(List<RuntimeBeanEntry> children) {
- Map<String, String> jmxToYangNamesForChildRbe = Maps.newHashMap();
- for (RuntimeBeanEntry rbe : children) {
- jmxToYangNamesForChildRbe.put(rbe.getJavaNamePrefix(), rbe.getYangName());
- }
- return jmxToYangNamesForChildRbe;
- }
-
- private static void checkXml(XmlElement xml) throws UnexpectedElementException, UnexpectedNamespaceException, MissingNameSpaceException {
+ private static void checkXml(XmlElement xml) throws DocumentedException {
xml.checkName(XmlNetconfConstants.GET);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
checkXml(xml);
-
- final ObjectName testTransaction = transactionProvider.getOrCreateReadTransaction();
- final ConfigTransactionClient registryClient = getConfigRegistryClient().getConfigTransactionClient(testTransaction);
-
- try {
- // Runtime beans are not parts of transactions and have to be queried against the central registry
- final Set<ObjectName> runtimeBeans = getConfigRegistryClient().lookupRuntimeBeans();
-
- final Set<ObjectName> configBeans = Datastore.getInstanceQueryStrategy(Datastore.running, transactionProvider)
- .queryInstances(getConfigRegistryClient());
-
- final Map<String, Map<String, ModuleRuntime>> moduleRuntimes = createModuleRuntimes(getConfigRegistryClient(),
- yangStoreSnapshot.getModuleMXBeanEntryMap());
- final Map<String, Map<String, ModuleConfig>> moduleConfigs = EditConfig.transformMbeToModuleConfigs(
- registryClient, yangStoreSnapshot.getModuleMXBeanEntryMap());
-
- final Runtime runtime = new Runtime(moduleRuntimes, moduleConfigs);
-
- final Element element = runtime.toXml(runtimeBeans, configBeans, document, yangStoreSnapshot.getEnumResolver());
-
- LOG.trace("{} operation successful", XmlNetconfConstants.GET);
-
- return element;
- } finally {
- transactionProvider.closeReadTransaction();
- }
+ final Element element = getConfigSubsystemFacade().get(document);
+ LOG.trace("{} operation successful", XmlNetconfConstants.GET);
+ return element;
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig;
import com.google.common.base.Optional;
-import java.util.Set;
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.Datastore;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Config;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.Datastore;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedElementException;
-import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
public static final String GET_CONFIG = "get-config";
- private final YangStoreContext yangStoreSnapshot;
private final Optional<String> maybeNamespace;
- private final TransactionProvider transactionProvider;
-
private static final Logger LOG = LoggerFactory.getLogger(GetConfig.class);
- public GetConfig(YangStoreContext yangStoreSnapshot, Optional<String> maybeNamespace,
- TransactionProvider transactionProvider, ConfigRegistryClient configRegistryClient,
- String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.yangStoreSnapshot = yangStoreSnapshot;
+ public GetConfig(final ConfigSubsystemFacade configSubsystemFacade, final Optional<String> maybeNamespace, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
this.maybeNamespace = maybeNamespace;
- this.transactionProvider = transactionProvider;
}
- public static Datastore fromXml(XmlElement xml) throws UnexpectedNamespaceException, UnexpectedElementException, MissingNameSpaceException, NetconfDocumentedException {
+ public static Datastore fromXml(XmlElement xml) throws DocumentedException {
xml.checkName(GET_CONFIG);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
- private Element getResponseInternal(final Document document, final ConfigRegistryClient configRegistryClient,
- final Datastore source) {
-
- final ConfigTransactionClient registryClient;
- // Read current state from a transaction, if running is source, then start new transaction just for reading
- // in case of candidate, get current transaction representing candidate
- if(source == Datastore.running) {
- final ObjectName readTx = transactionProvider.getOrCreateReadTransaction();
- registryClient = getConfigRegistryClient().getConfigTransactionClient(readTx);
- } else {
- registryClient = getConfigRegistryClient().getConfigTransactionClient(transactionProvider.getOrCreateTransaction());
- }
-
- try {
- Element dataElement = XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
- final Set<ObjectName> instances = Datastore.getInstanceQueryStrategy(source, this.transactionProvider)
- .queryInstances(configRegistryClient);
-
- final Config configMapping = new Config(EditConfig.transformMbeToModuleConfigs(registryClient,
- yangStoreSnapshot.getModuleMXBeanEntryMap()), yangStoreSnapshot.getEnumResolver());
-
- ServiceRegistryWrapper serviceTracker = new ServiceRegistryWrapper(registryClient);
- dataElement = configMapping.toXml(instances, this.maybeNamespace, document, dataElement, serviceTracker);
-
- LOG.trace("{} operation successful", GET_CONFIG);
-
- return dataElement;
- } finally {
- if(source == Datastore.running) {
- transactionProvider.closeReadTransaction();
- }
- }
- }
-
@Override
protected String getOperationName() {
return GET_CONFIG;
}
@Override
- public Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
- Datastore source;
- source = fromXml(xml);
- return getResponseInternal(document, getConfigRegistryClient(), source);
+ public Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
+ return getConfigSubsystemFacade().getConfiguration(document, fromXml(xml), maybeNamespace);
}
}
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-import javax.management.ObjectName;
-import javax.management.openmbean.OpenType;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
-import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
-import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.RpcFacade;
+import org.opendaylight.controller.config.facade.xml.rpc.InstanceRuntimeRpc;
+import org.opendaylight.controller.config.facade.xml.rpc.ModuleRpcs;
+import org.opendaylight.controller.config.facade.xml.rpc.Rpcs;
+import org.opendaylight.controller.config.facade.xml.rpc.RuntimeRpcElementResolved;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.InstanceRuntimeRpc;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.ModuleRpcs;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.Rpcs;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
public class RuntimeRpc extends AbstractConfigNetconfOperation {
private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
- public static final String CONTEXT_INSTANCE = "context-instance";
- private final YangStoreContext yangStoreSnapshot;
-
- public RuntimeRpc(final YangStoreContext yangStoreSnapshot, ConfigRegistryClient configRegistryClient,
- String netconfSessionIdForReporting) {
- super(configRegistryClient, netconfSessionIdForReporting);
- this.yangStoreSnapshot = yangStoreSnapshot;
- }
-
- private Element toXml(Document doc, Object result, AttributeIfc returnType, String namespace, String elementName) throws NetconfDocumentedException {
- AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper().prepareStrategy(returnType);
- Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
- Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, returnType.getOpenType());
-
- // FIXME: multiple return values defined as leaf-list and list in yang should not be wrapped in output xml element,
- // they need to be appended directly under rpc-reply element
- //
- // Either allow List of Elements to be returned from NetconfOperation or
- // pass reference to parent output xml element for netconf operations to
- // append result(s) on their own
- Element tempParent = XmlUtil.createElement(doc, "output", Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
- new ObjectXmlWriter().prepareWritingStrategy(elementName, returnType, doc).writeElement(tempParent, namespace, mappedAttributeOpt.get());
-
- XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
- return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
+ public RuntimeRpc(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+ super(configSubsystemFacade, netconfSessionIdForReporting);
}
- private Object executeOperation(final ConfigRegistryClient configRegistryClient, final ObjectName on,
- final String name, final Map<String, AttributeConfigElement> attributes) {
- final Object[] params = new Object[attributes.size()];
- final String[] signature = new String[attributes.size()];
-
- int i = 0;
- for (final AttributeConfigElement attribute : attributes.values()) {
- final Optional<?> resolvedValueOpt = attribute.getResolvedValue();
-
- params[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
- signature[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName() : attribute
- .getResolvedDefaultValue().getClass().getName();
- i++;
- }
-
- return configRegistryClient.invokeMethod(on, name, params, signature);
- }
-
- public NetconfOperationExecution fromXml(final XmlElement xml) throws NetconfDocumentedException {
- final String namespace;
- try {
- namespace = xml.getNamespace();
- } catch (MissingNameSpaceException e) {
- LOG.trace("Can't get namespace from xml element due to ",e);
- throw NetconfDocumentedException.wrap(e);
- }
- final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
- final String operationName = xml.getName();
-
- final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(
- contextInstanceElement.getTextContent(), operationName, namespace);
-
- final Rpcs rpcs = mapRpcs(yangStoreSnapshot.getModuleMXBeanEntryMap(), yangStoreSnapshot.getEnumResolver());
-
- final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
- final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(), operationName);
-
- // TODO move to Rpcs after xpath attribute is redesigned
-
- final ObjectName on = id.getObjectName(rpcMapping);
- Map<String, AttributeConfigElement> attributes = instanceRuntimeRpc.fromXml(xml);
- attributes = sortAttributes(attributes, xml);
-
- return new NetconfOperationExecution(on, instanceRuntimeRpc.getName(), attributes,
- instanceRuntimeRpc.getReturnType(), namespace);
- }
@Override
- public HandlingPriority canHandle(Document message) throws NetconfDocumentedException {
+ public HandlingPriority canHandle(Document message) throws DocumentedException {
XmlElement requestElement = null;
requestElement = getRequestElementWithCheck(message);
final String netconfOperationNamespace;
try {
netconfOperationNamespace = operationElement.getNamespace();
- } catch (MissingNameSpaceException e) {
+ } catch (DocumentedException e) {
LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
return HandlingPriority.CANNOT_HANDLE;
}
final Optional<XmlElement> contextInstanceElement = operationElement
- .getOnlyChildElementOptionally(CONTEXT_INSTANCE);
+ .getOnlyChildElementOptionally(RpcFacade.CONTEXT_INSTANCE);
if (!contextInstanceElement.isPresent()){
return HandlingPriority.CANNOT_HANDLE;
.getTextContent(), netconfOperationName, netconfOperationNamespace);
// TODO reuse rpcs instance in fromXml method
- final Rpcs rpcs = mapRpcs(yangStoreSnapshot.getModuleMXBeanEntryMap(), yangStoreSnapshot.getEnumResolver());
+ final Rpcs rpcs = getConfigSubsystemFacade().getRpcFacade().mapRpcs();
try {
-
final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(),
netconfOperationName);
Preconditions.checkState(instanceRuntimeRpc != null, "No rpc found for %s:%s", netconfOperationNamespace,
netconfOperationName);
-
} catch (IllegalStateException e) {
LOG.debug("Cannot handle runtime operation {}:{}", netconfOperationNamespace, netconfOperationName, e);
return HandlingPriority.CANNOT_HANDLE;
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws DocumentedException {
// TODO check for namespaces and unknown elements
- final NetconfOperationExecution execution = fromXml(xml);
+ final RpcFacade.OperationExecution execution = getConfigSubsystemFacade().getRpcFacade().fromXml(xml);
- LOG.debug("Invoking operation {} on {} with arguments {}", execution.operationName, execution.on,
- execution.attributes);
- final Object result = executeOperation(getConfigRegistryClient(), execution.on, execution.operationName,
- execution.attributes);
+ LOG.debug("Invoking operation {} on {} with arguments {}", execution.getOperationName(), execution.getOn(),
+ execution.getAttributes());
+ final Object result = getConfigSubsystemFacade().getRpcFacade().executeOperation(execution);
- LOG.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.operationName,
- execution.on, execution.attributes, result);
+ LOG.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.getOperationName(),
+ execution.getOn(), execution.getAttributes(), result);
if (execution.isVoid()) {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
} else {
- return toXml(document, result, execution.returnType, execution.namespace,
- execution.returnType.getAttributeYangName());
- }
- }
-
- private static class NetconfOperationExecution {
-
- private final ObjectName on;
- private final String operationName;
- private final Map<String, AttributeConfigElement> attributes;
- private final AttributeIfc returnType;
- private final String namespace;
-
- public NetconfOperationExecution(final ObjectName on, final String name,
- final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType, final String namespace) {
- this.on = on;
- this.operationName = name;
- this.attributes = attributes;
- this.returnType = returnType;
- this.namespace = namespace;
- }
-
- boolean isVoid() {
- return returnType == VoidAttribute.getInstance();
+ return getConfigSubsystemFacade().getRpcFacade().toXml(document, result, execution);
}
-
- }
-
- private static Map<String, AttributeConfigElement> sortAttributes(
- final Map<String, AttributeConfigElement> attributes, final XmlElement xml) {
- final Map<String, AttributeConfigElement> sorted = Maps.newLinkedHashMap();
-
- for (XmlElement xmlElement : xml.getChildElements()) {
- final String name = xmlElement.getName();
- if (!CONTEXT_INSTANCE.equals(name)) { // skip context
- // instance child node
- // because it
- // specifies
- // ObjectName
- final AttributeConfigElement value = attributes.get(name);
- if (value == null) {
- throw new IllegalArgumentException("Cannot find yang mapping for node " + xmlElement);
- }
- sorted.put(name, value);
- }
- }
-
- return sorted;
- }
-
- private static Rpcs mapRpcs(final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries, final EnumResolver enumResolver) {
-
- final Map<String, Map<String, ModuleRpcs>> map = Maps.newHashMap();
-
- for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : mBeanEntries.entrySet()) {
-
- Map<String, ModuleRpcs> namespaceToModules = map.get(namespaceToModuleEntry.getKey());
- if (namespaceToModules == null) {
- namespaceToModules = Maps.newHashMap();
- map.put(namespaceToModuleEntry.getKey(), namespaceToModules);
- }
-
- for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue().entrySet()) {
-
- ModuleRpcs rpcMapping = namespaceToModules.get(moduleEntry.getKey());
- if (rpcMapping == null) {
- rpcMapping = new ModuleRpcs(enumResolver);
- namespaceToModules.put(moduleEntry.getKey(), rpcMapping);
- }
-
- final ModuleMXBeanEntry entry = moduleEntry.getValue();
-
- for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
- rpcMapping.addNameMapping(runtimeEntry);
- for (final Rpc rpc : runtimeEntry.getRpcs()) {
- rpcMapping.addRpc(runtimeEntry, rpc);
- }
- }
- }
- }
-
- return new Rpcs(map);
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
-import static com.google.common.base.Preconditions.checkState;
-
import java.util.Dictionary;
import java.util.Hashtable;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
import org.opendaylight.controller.netconf.api.util.NetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
- private BundleContext context;
private ServiceRegistration<?> osgiRegistration;
- private ConfigRegistryLookupThread configRegistryLookup = null;
@Override
public void start(final BundleContext context) throws Exception {
- this.context = context;
+ ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
- ServiceTrackerCustomizer<SchemaContextProvider, ConfigRegistryLookupThread> customizer = new ServiceTrackerCustomizer<SchemaContextProvider, ConfigRegistryLookupThread>() {
@Override
- public ConfigRegistryLookupThread addingService(ServiceReference<SchemaContextProvider> reference) {
- LOG.debug("Got addingService(SchemaContextProvider) event, starting ConfigRegistryLookupThread");
- checkState(configRegistryLookup == null, "More than one onYangStoreAdded received");
-
- SchemaContextProvider schemaContextProvider = reference.getBundle().getBundleContext().getService(reference);
-
- YangStoreService yangStoreService = new YangStoreService(schemaContextProvider, context);
- configRegistryLookup = new ConfigRegistryLookupThread(yangStoreService);
- configRegistryLookup.start();
- return configRegistryLookup;
+ public ConfigSubsystemFacadeFactory addingService(ServiceReference<ConfigSubsystemFacadeFactory> reference) {
+ LOG.debug("Got addingService(SchemaContextProvider) event");
+ // Yang store service should not be registered multiple times
+ ConfigSubsystemFacadeFactory configSubsystemFacade = reference.getBundle().getBundleContext().getService(reference);
+ osgiRegistration = startNetconfServiceFactory(configSubsystemFacade, context);
+ return configSubsystemFacade;
}
@Override
- public void modifiedService(ServiceReference<SchemaContextProvider> reference, ConfigRegistryLookupThread configRegistryLookup) {
- LOG.debug("Got modifiedService(SchemaContextProvider) event");
- final BindingRuntimeContext runtimeContext = (BindingRuntimeContext) reference.getProperty(BindingRuntimeContext.class.getName());
- LOG.debug("BindingRuntimeContext retrieved as {}", runtimeContext);
- configRegistryLookup.yangStoreService.refresh(runtimeContext);
-
+ public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+ LOG.warn("Config manager facade was modified unexpectedly");
}
@Override
- public void removedService(ServiceReference<SchemaContextProvider> reference, ConfigRegistryLookupThread configRegistryLookup) {
- configRegistryLookup.interrupt();
- if (osgiRegistration != null) {
- osgiRegistration.unregister();
- }
- osgiRegistration = null;
- Activator.this.configRegistryLookup = null;
+ public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+ LOG.warn("Config manager facade was removed unexpectedly");
}
};
- ServiceTracker<SchemaContextProvider, ConfigRegistryLookupThread> listenerTracker = new ServiceTracker<>(context, SchemaContextProvider.class, customizer);
- listenerTracker.open();
+ ServiceTracker<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaContextProviderServiceTracker =
+ new ServiceTracker<>(context, ConfigSubsystemFacadeFactory.class, schemaServiceTrackerCustomizer);
+ schemaContextProviderServiceTracker.open();
}
@Override
- public void stop(BundleContext context) {
- if (configRegistryLookup != null) {
- configRegistryLookup.interrupt();
+ public void stop(final BundleContext bundleContext) throws Exception {
+ if (osgiRegistration != null) {
+ osgiRegistration.unregister();
}
}
- private class ConfigRegistryLookupThread extends Thread {
- private final YangStoreService yangStoreService;
-
- private ConfigRegistryLookupThread(YangStoreService yangStoreService) {
- super("config-registry-lookup");
- this.yangStoreService = yangStoreService;
- }
-
- @Override
- public void run() {
- NetconfOperationServiceFactoryImpl factory = new NetconfOperationServiceFactoryImpl(yangStoreService);
- LOG.debug("Registering into OSGi");
- Dictionary<String, String> properties = new Hashtable<>();
- properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.CONFIG_NETCONF_CONNECTOR);
- osgiRegistration = context.registerService(NetconfOperationServiceFactory.class, factory, properties);
- }
+ private ServiceRegistration<NetconfOperationServiceFactory> startNetconfServiceFactory(final ConfigSubsystemFacadeFactory configSubsystemFacade, final BundleContext context) {
+ final NetconfOperationServiceFactoryImpl netconfOperationServiceFactory = new NetconfOperationServiceFactoryImpl(configSubsystemFacade);
+ // Add properties to autowire with netconf-impl instance for cfg subsystem
+ final Dictionary<String, String> properties = new Hashtable<>();
+ properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.CONFIG_NETCONF_CONNECTOR);
+ return context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
}
+
}
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
import java.util.Set;
-import org.opendaylight.controller.config.util.ConfigRegistryClient;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
final class NetconfOperationProvider {
private final Set<NetconfOperation> operations;
- NetconfOperationProvider(YangStoreContext yangStoreSnapshot, ConfigRegistryClient configRegistryClient,
- TransactionProvider transactionProvider, String netconfSessionIdForReporting) {
+ NetconfOperationProvider(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
- operations = setUpOperations(yangStoreSnapshot, configRegistryClient, transactionProvider,
- netconfSessionIdForReporting);
+ operations = setUpOperations(configSubsystemFacade, netconfSessionIdForReporting);
}
Set<NetconfOperation> getOperations() {
return operations;
}
- private static Set<NetconfOperation> setUpOperations(YangStoreContext yangStoreSnapshot,
- ConfigRegistryClient configRegistryClient, TransactionProvider transactionProvider,
+ private static Set<NetconfOperation> setUpOperations(final ConfigSubsystemFacade configSubsystemFacade,
String netconfSessionIdForReporting) {
Set<NetconfOperation> ops = Sets.newHashSet();
- GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
- configRegistryClient, netconfSessionIdForReporting);
+ GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String> absent(), netconfSessionIdForReporting);
ops.add(getConfigOp);
- ops.add(new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
- netconfSessionIdForReporting));
- ops.add(new Commit(transactionProvider, configRegistryClient, netconfSessionIdForReporting));
+ ops.add(new EditConfig(configSubsystemFacade, netconfSessionIdForReporting));
+ ops.add(new Commit(configSubsystemFacade, netconfSessionIdForReporting));
ops.add(new Lock(netconfSessionIdForReporting));
ops.add(new UnLock(netconfSessionIdForReporting));
- ops.add(new Get(transactionProvider, yangStoreSnapshot, configRegistryClient, netconfSessionIdForReporting));
- ops.add(new DiscardChanges(transactionProvider, configRegistryClient, netconfSessionIdForReporting));
- ops.add(new Validate(transactionProvider, configRegistryClient, netconfSessionIdForReporting));
- ops.add(new RuntimeRpc(yangStoreSnapshot, configRegistryClient, netconfSessionIdForReporting));
+ ops.add(new Get(configSubsystemFacade, netconfSessionIdForReporting));
+ ops.add(new DiscardChanges(configSubsystemFacade, netconfSessionIdForReporting));
+ ops.add(new Validate(configSubsystemFacade, netconfSessionIdForReporting));
+ ops.add(new RuntimeRpc(configSubsystemFacade, netconfSessionIdForReporting));
return ops;
}
package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
-import java.lang.management.ManagementFactory;
-import java.util.HashSet;
+import com.google.common.base.Function;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Sets;
import java.util.Set;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.capability.ModuleListener;
+import org.opendaylight.controller.config.util.capability.YangModuleCapability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.util.capability.BasicCapability;
-import org.opendaylight.controller.netconf.util.capability.YangModuleCapability;
import org.opendaylight.yangtools.yang.model.api.Module;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class NetconfOperationServiceFactoryImpl implements NetconfOperationServiceFactory {
- public static final int ATTEMPT_TIMEOUT_MS = 1000;
- private static final int SILENT_ATTEMPTS = 30;
+ private final ConfigSubsystemFacadeFactory configFacadeFactory;
- private final YangStoreService yangStoreService;
- private final ConfigRegistryJMXClient jmxClient;
-
- private static final Logger LOG = LoggerFactory.getLogger(NetconfOperationServiceFactoryImpl.class);
-
- public NetconfOperationServiceFactoryImpl(YangStoreService yangStoreService) {
- this(yangStoreService, ManagementFactory.getPlatformMBeanServer());
- }
-
- public NetconfOperationServiceFactoryImpl(YangStoreService yangStoreService, MBeanServer mBeanServer) {
- this.yangStoreService = yangStoreService;
-
- ConfigRegistryJMXClient configRegistryJMXClient;
- int i = 0;
- // Config registry might not be present yet, but will be eventually
- while(true) {
-
- try {
- configRegistryJMXClient = new ConfigRegistryJMXClient(mBeanServer);
- break;
- } catch (IllegalStateException e) {
- ++i;
- if (i > SILENT_ATTEMPTS) {
- LOG.info("JMX client not created after {} attempts, still trying", i, e);
- } else {
- LOG.debug("JMX client could not be created, reattempting, try {}", i, e);
- }
- try {
- Thread.sleep(ATTEMPT_TIMEOUT_MS);
- } catch (InterruptedException e1) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException("Interrupted while reattempting connection", e1);
- }
- }
- }
-
- jmxClient = configRegistryJMXClient;
- if (i > SILENT_ATTEMPTS) {
- LOG.info("Created JMX client after {} attempts", i);
- } else {
- LOG.debug("Created JMX client after {} attempts", i);
- }
+ public NetconfOperationServiceFactoryImpl(ConfigSubsystemFacadeFactory configFacadeFactory) {
+ this.configFacadeFactory = configFacadeFactory;
}
@Override
public NetconfOperationServiceImpl createService(String netconfSessionIdForReporting) {
- return new NetconfOperationServiceImpl(yangStoreService, jmxClient, netconfSessionIdForReporting);
+ return new NetconfOperationServiceImpl(configFacadeFactory.createFacade(netconfSessionIdForReporting), netconfSessionIdForReporting);
}
-
@Override
public Set<Capability> getCapabilities() {
- return setupCapabilities(yangStoreService);
+ return configFacadeFactory.getCurrentCapabilities();
}
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- return yangStoreService.registerCapabilityListener(listener);
+ return configFacadeFactory.getYangStoreService().registerModuleListener(new ModuleListener() {
+ @Override
+ public void onCapabilitiesChanged(Set<Module> added, Set<Module> removed) {
+ listener.onCapabilitiesChanged(
+ transformModulesToCapabilities(added), transformModulesToCapabilities(removed));
+ }
+ });
}
- public static Set<Capability> setupCapabilities(final YangStoreContext yangStoreSnapshot) {
- Set<Capability> capabilities = new HashSet<>();
- // [RFC6241] 8.3. Candidate Configuration Capability
- capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
-
- // TODO rollback on error not supported EditConfigXmlParser:100
- // [RFC6241] 8.5. Rollback-on-Error Capability
- // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
-
- Set<Module> modules = yangStoreSnapshot.getModules();
- for (Module module : modules) {
- capabilities.add(new YangModuleCapability(module, yangStoreSnapshot.getModuleSource(module)));
+ private static final Function<Module, Capability> MODULE_TO_CAPABILITY = new Function<Module, Capability>() {
+ @Override
+ public Capability apply(final Module module) {
+ return new YangModuleCapability(module, module.getSource());
}
+ };
- return capabilities;
+ public static Set<Capability> transformModulesToCapabilities(Set<Module> modules) {
+ return Sets.newHashSet(Collections2.transform(modules, MODULE_TO_CAPABILITY));
}
}
package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
import java.util.Set;
-import org.opendaylight.controller.config.util.ConfigRegistryJMXClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-/**
- * Manages life cycle of {@link YangStoreContext}.
- */
public class NetconfOperationServiceImpl implements NetconfOperationService {
private final NetconfOperationProvider operationProvider;
- private final TransactionProvider transactionProvider;
+ private ConfigSubsystemFacade configSubsystemFacade;
- public NetconfOperationServiceImpl(final YangStoreService yangStoreService, final ConfigRegistryJMXClient jmxClient,
+ public NetconfOperationServiceImpl(final ConfigSubsystemFacade configSubsystemFacade,
final String netconfSessionIdForReporting) {
-
- transactionProvider = new TransactionProvider(jmxClient, netconfSessionIdForReporting);
- operationProvider = new NetconfOperationProvider(yangStoreService, jmxClient, transactionProvider,
- netconfSessionIdForReporting);
+ this.configSubsystemFacade = configSubsystemFacade;
+ operationProvider = new NetconfOperationProvider(configSubsystemFacade, netconfSessionIdForReporting);
}
@Override
@Override
public void close() {
- transactionProvider.close();
+ configSubsystemFacade.close();
}
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import java.lang.ref.SoftReference;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicReference;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.netconf.api.Capability;
-import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
-import org.opendaylight.controller.netconf.notifications.BaseNetconfNotificationListener;
-import org.opendaylight.controller.netconf.notifications.BaseNotificationPublisherRegistration;
-import org.opendaylight.controller.netconf.notifications.NetconfNotificationCollector;
-import org.opendaylight.controller.netconf.util.capability.YangModuleCapability;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChangeBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.changed.by.parms.ChangedByBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.changed.by.parms.changed.by.server.or.user.ServerBuilder;
-import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class YangStoreService implements YangStoreContext {
-
- private static final Logger LOG = LoggerFactory.getLogger(YangStoreService.class);
-
- /**
- * This is a rather interesting locking model. We need to guard against both the
- * cache expiring from GC and being invalidated by schema context change. The
- * context can change while we are doing processing, so we do not want to block
- * it, so no synchronization can happen on the methods.
- *
- * So what we are doing is the following:
- *
- * We synchronize with GC as usual, using a SoftReference.
- *
- * The atomic reference is used to synchronize with {@link #refresh(org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext)}, e.g. when
- * refresh happens, it will push a SoftReference(null), e.g. simulate the GC. Now
- * that may happen while the getter is already busy acting on the old schema context,
- * so it needs to understand that a refresh has happened and retry. To do that, it
- * attempts a CAS operation -- if it fails, in knows that the SoftReference has
- * been replaced and thus it needs to retry.
- *
- * Note that {@link #getYangStoreSnapshot()} will still use synchronize() internally
- * to stop multiple threads doing the same work.
- */
- private final AtomicReference<SoftReference<YangStoreSnapshot>> ref =
- new AtomicReference<>(new SoftReference<YangStoreSnapshot>(null));
-
- private final AtomicReference<SoftReference<BindingRuntimeContext>> refBindingContext =
- new AtomicReference<>(new SoftReference<BindingRuntimeContext>(null));
-
- private final SchemaContextProvider schemaContextProvider;
- private final BaseNetconfNotificationListener notificationPublisher;
-
- private final ExecutorService notificationExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
- @Override
- public Thread newThread(final Runnable r) {
- return new Thread(r, "config-netconf-connector-capability-notifications");
- }
- });
-
- private final Set<CapabilityListener> listeners = Collections.synchronizedSet(new HashSet<CapabilityListener>());
-
- public YangStoreService(final SchemaContextProvider schemaContextProvider, final BundleContext context) {
- this(schemaContextProvider, new NotificationCollectorTracker(context));
- }
-
- public YangStoreService(final SchemaContextProvider schemaContextProvider, final BaseNetconfNotificationListener notificationHandler) {
- this.schemaContextProvider = schemaContextProvider;
- this.notificationPublisher = notificationHandler;
- }
-
- private synchronized YangStoreContext getYangStoreSnapshot() {
- SoftReference<YangStoreSnapshot> r = ref.get();
- YangStoreSnapshot ret = r.get();
-
- while (ret == null) {
- // We need to be compute a new value
- ret = new YangStoreSnapshot(schemaContextProvider.getSchemaContext(), refBindingContext.get().get());
-
- if (!ref.compareAndSet(r, new SoftReference<>(ret))) {
- LOG.debug("Concurrent refresh detected, recomputing snapshot");
- r = ref.get();
- ret = null;
- }
- }
-
- return ret;
- }
-
- @Override
- public Map<String, Map<String, ModuleMXBeanEntry>> getModuleMXBeanEntryMap() {
- return getYangStoreSnapshot().getModuleMXBeanEntryMap();
- }
-
- @Override
- public Map<QName, Map<String, ModuleMXBeanEntry>> getQNamesToIdentitiesToModuleMXBeanEntries() {
- return getYangStoreSnapshot().getQNamesToIdentitiesToModuleMXBeanEntries();
- }
-
- @Override
- public Set<Module> getModules() {
- return getYangStoreSnapshot().getModules();
- }
-
- @Override
- public String getModuleSource(final ModuleIdentifier moduleIdentifier) {
- return getYangStoreSnapshot().getModuleSource(moduleIdentifier);
- }
-
- @Override
- public EnumResolver getEnumResolver() {
- return getYangStoreSnapshot().getEnumResolver();
- }
-
- public void refresh(final BindingRuntimeContext runtimeContext) {
- final YangStoreSnapshot previous = ref.get().get();
- ref.set(new SoftReference<YangStoreSnapshot>(null));
- refBindingContext.set(new SoftReference<>(runtimeContext));
- notificationExecutor.submit(new CapabilityChangeNotifier(previous));
- }
-
- public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
-
- YangStoreContext context = ref.get().get();
-
- if(context == null) {
- context = getYangStoreSnapshot();
- }
-
- this.listeners.add(listener);
- listener.onCapabilitiesAdded(NetconfOperationServiceFactoryImpl.setupCapabilities(context));
-
- return new AutoCloseable() {
- @Override
- public void close() throws Exception {
- YangStoreService.this.listeners.remove(listener);
- }
- };
- }
-
- private static final Function<Module, Capability> MODULE_TO_CAPABILITY = new Function<Module, Capability>() {
- @Override
- public Capability apply(final Module module) {
- return new YangModuleCapability(module, module.getSource());
- }
- };
-
- private final class CapabilityChangeNotifier implements Runnable {
-
- private final YangStoreSnapshot previous;
-
- public CapabilityChangeNotifier(final YangStoreSnapshot previous) {
- this.previous = previous;
- }
-
- @Override
- public void run() {
- final YangStoreContext current = getYangStoreSnapshot();
-
- if(current.equals(previous) == false) {
- final Sets.SetView<Module> removed = Sets.difference(previous.getModules(), current.getModules());
- final Sets.SetView<Module> added = Sets.difference(current.getModules(), previous.getModules());
-
- // Notify notification manager
- notificationPublisher.onCapabilityChanged(computeDiff(removed, added));
-
- // Notify direct capability listener TODO would it not be better if the capability listeners went through notification manager ?
- for (final CapabilityListener listener : listeners) {
- listener.onCapabilitiesAdded(Sets.newHashSet(Collections2.transform(added, MODULE_TO_CAPABILITY)));
- }
- for (final CapabilityListener listener : listeners) {
- listener.onCapabilitiesRemoved(Sets.newHashSet(Collections2.transform(removed, MODULE_TO_CAPABILITY)));
- }
- }
- }
- }
-
- private static final Function<Module, Uri> MODULE_TO_URI = new Function<Module, Uri>() {
- @Override
- public Uri apply(final Module input) {
- return new Uri(new YangModuleCapability(input, input.getSource()).getCapabilityUri());
- }
- };
-
- static NetconfCapabilityChange computeDiff(final Sets.SetView<Module> removed, final Sets.SetView<Module> added) {
- final NetconfCapabilityChangeBuilder netconfCapabilityChangeBuilder = new NetconfCapabilityChangeBuilder();
- netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build()).build());
- netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2.transform(removed, MODULE_TO_URI)));
- netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2.transform(added, MODULE_TO_URI)));
- // TODO modified should be computed ... but why ?
- netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
- return netconfCapabilityChangeBuilder.build();
- }
-
-
- /**
- * Looks for NetconfNotificationCollector service and publishes base netconf notifications if possible
- */
- private static class NotificationCollectorTracker implements ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>, BaseNetconfNotificationListener, AutoCloseable {
-
- private final BundleContext context;
- private final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector> listenerTracker;
- private BaseNotificationPublisherRegistration publisherReg;
-
- public NotificationCollectorTracker(final BundleContext context) {
- this.context = context;
- listenerTracker = new ServiceTracker<>(context, NetconfNotificationCollector.class, this);
- listenerTracker.open();
- }
-
- @Override
- public synchronized NetconfNotificationCollector addingService(final ServiceReference<NetconfNotificationCollector> reference) {
- closePublisherRegistration();
- publisherReg = context.getService(reference).registerBaseNotificationPublisher();
- return null;
- }
-
- @Override
- public synchronized void modifiedService(final ServiceReference<NetconfNotificationCollector> reference, final NetconfNotificationCollector service) {
- closePublisherRegistration();
- publisherReg = context.getService(reference).registerBaseNotificationPublisher();
- }
-
- @Override
- public synchronized void removedService(final ServiceReference<NetconfNotificationCollector> reference, final NetconfNotificationCollector service) {
- closePublisherRegistration();
- publisherReg = null;
- }
-
- private void closePublisherRegistration() {
- if(publisherReg != null) {
- publisherReg.close();
- }
- }
-
- @Override
- public synchronized void close() {
- closePublisherRegistration();
- listenerTracker.close();
- }
-
- @Override
- public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
- if(publisherReg == null) {
- LOG.warn("Omitting notification due to missing notification service: {}", capabilityChange);
- return;
- }
-
- publisherReg.onCapabilityChanged(capabilityChange);
- }
- }
-}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.opendaylight.controller.config.util.xml.XmlUtil.readXmlToElement;
import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
-import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.config.api.ValidationException;
import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
import org.opendaylight.controller.config.yang.test.impl.ComplexList;
import org.opendaylight.controller.config.yang.test.impl.Deep;
import org.opendaylight.controller.config.yang.test.impl.Peers;
import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
private TestImplModuleFactory factory4;
@Mock
- YangStoreContext yangStoreSnapshot;
+ YangStoreService yangStoreSnapshot;
@Mock
NetconfOperationRouter netconfOperationRouter;
@Mock
private TransactionProvider transactionProvider;
+ private ConfigSubsystemFacade configSubsystemFacade;
+
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
+ doReturn(yangStoreSnapshot).when(yangStoreSnapshot).getCurrentSnapshot();
doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
doReturn(new EnumResolver() {
this.factory3, factory4));
transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
+
+ configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot, "mapping-test");
}
private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
try {
edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
fail("Should've failed, non-existing service instance");
- } catch (NetconfDocumentedException e) {
- assertEquals(e.getErrorSeverity(), ErrorSeverity.error);
- assertEquals(e.getErrorTag(), ErrorTag.operation_failed);
- assertEquals(e.getErrorType(), ErrorType.application);
+ } catch (DocumentedException e) {
+ assertEquals(e.getErrorSeverity(), DocumentedException.ErrorSeverity.error);
+ assertEquals(e.getErrorTag(), DocumentedException.ErrorTag.operation_failed);
+ assertEquals(e.getErrorType(), DocumentedException.ErrorType.application);
}
edit("netconfMessages/editConfig_replace_default.xml");
}
- private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
- IOException {
+ private void closeSession() throws ParserConfigurationException, SAXException,
+ IOException, DocumentedException {
final Channel channel = mock(Channel.class);
doReturn("channel").when(channel).toString();
final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
}
private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
- NetconfDocumentedException {
- EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
- NETCONF_SESSION_ID);
+ DocumentedException {
+ EditConfig editOp = new EditConfig(configSubsystemFacade, NETCONF_SESSION_ID);
executeOp(editOp, resource);
}
- private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
- Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
+ private void commit() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+ Commit commitOp = new Commit(configSubsystemFacade, NETCONF_SESSION_ID);
executeOp(commitOp, "netconfMessages/commit.xml");
}
- private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
+ private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
Lock commitOp = new Lock(NETCONF_SESSION_ID);
return executeOp(commitOp, "netconfMessages/lock.xml");
}
- private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
+ private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
return executeOp(commitOp, "netconfMessages/unlock.xml");
}
private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
- NetconfDocumentedException {
- GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
- configRegistryClient, NETCONF_SESSION_ID);
+ DocumentedException {
+ GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String> absent(), NETCONF_SESSION_ID);
return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
}
private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
- NetconfDocumentedException {
- GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
- configRegistryClient, NETCONF_SESSION_ID);
+ DocumentedException {
+ GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String> absent(), NETCONF_SESSION_ID);
return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
}
@Ignore("second edit message corrupted")
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testConfigNetconfReplaceDefaultEx() throws Exception {
createModule(INSTANCE_NAME);
try {
edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
fail();
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
String message = e.getMessage();
assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
assertContainsString(message, TEST_NAMESPACE);
- assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ assertContainsString(message, XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
}
try {
edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
fail();
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
String message = e.getMessage();
assertContainsString(message, "Unrecognised elements");
assertContainsString(message, "simple-int2");
try {
edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
fail();
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
String message = e.getMessage();
assertContainsString(message, "Element allow-user present multiple times with different namespaces");
assertContainsString(message, TEST_NAMESPACE);
- assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
+ assertContainsString(message, XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
}
}
}
// TODO add <modules operation="replace"> functionality
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testConfigNetconfReplaceModuleEx() throws Exception {
createModule(INSTANCE_NAME);
LOG.info("Reading {}", file);
try {
edit(file);
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertContainsString(e.getMessage(), "Unrecognised elements");
assertContainsString(e.getMessage(), "unknownAttribute");
continue;
assertEquals(3 + 3, afterReplace);
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testEx() throws Exception {
commit();
@Test
public void testFailedDiscardChangesAbort() throws Exception {
+ final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
+ doThrow(new RuntimeException("Mocked runtime exception, Abort has to fail")).when(facade).abortConfiguration();
- TransactionProvider mockedTxProvider = mock(TransactionProvider.class);
- doThrow(new RuntimeException("Mocked runtime exception, Abort has to fail")).when(mockedTxProvider).abortTransaction();
- doReturn(Optional.of(ObjectName.getInstance("dummyDomain", "DummyKey", "DummyValue"))).when(mockedTxProvider).getTransaction();
-
- DiscardChanges discardOp = new DiscardChanges(mockedTxProvider, configRegistryClient, NETCONF_SESSION_ID);
+ DiscardChanges discardOp = new DiscardChanges(facade, NETCONF_SESSION_ID);
try {
executeOp(discardOp, "netconfMessages/discardChanges.xml");
fail("Should've failed, abort on mocked is supposed to throw RuntimeException");
- } catch (NetconfDocumentedException e) {
- assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
- assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
- assertTrue(e.getErrorType() == ErrorType.application);
+ } catch (DocumentedException e) {
+ assertTrue(e.getErrorTag() == DocumentedException.ErrorTag.operation_failed);
+ assertTrue(e.getErrorSeverity() == DocumentedException.ErrorSeverity.error);
+ assertTrue(e.getErrorType() == DocumentedException.ErrorType.application);
}
-
}
- private Document discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
- DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
+ private Document discard() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+ DiscardChanges discardOp = new DiscardChanges(configSubsystemFacade, NETCONF_SESSION_ID);
return executeOp(discardOp, "netconfMessages/discardChanges.xml");
}
public SchemaContext getSchemaContext() {
return schemaContext ;
}
- }, mockedContext);
+ });
final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
yangStoreService.refresh(bindingRuntimeContext);
assertEquals(8, getElementsSize(response, "deep4"));
// TODO assert keys
- RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
+ RuntimeRpc netconf = new RuntimeRpc(configSubsystemFacade, NETCONF_SESSION_ID);
response = executeOp(netconf, "netconfMessages/rpc.xml");
assertContainsElementWithText(response, "testarg1");
assertContainsElementWithText(response, "2");
}
- private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
- Get getOp = new Get(transactionProvider, yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
+ private Document get() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+ Get getOp = new Get(configSubsystemFacade, NETCONF_SESSION_ID);
return executeOp(getOp, "netconfMessages/get.xml");
}
}
private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
- SAXException, IOException, NetconfDocumentedException {
+ SAXException, IOException, DocumentedException {
final Document request = XmlFileLoader.xmlFileToDocument(filename);
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services.ServiceInstance;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Services.ServiceInstance;
public class ServiceTrackerTest {
import org.junit.Test;
import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Element;
public class ValidateTest {
public static final String NETCONF_SESSION_ID_FOR_REPORTING = "foo";
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void test() throws Exception {
final XmlElement xml = XmlElement.fromString("<abc></abc>");
- final Validate validate = new Validate(null, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
validate.handleWithNoSubsequentOperations(null, xml);
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testNoSource() throws Exception {
final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 + "\"/>");
- final Validate validate = new Validate(null, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
validate.handleWithNoSubsequentOperations(null, xml);
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testNoNamespace() throws Exception {
final XmlElement xml = XmlElement.fromString("<validate/>");
- final Validate validate = new Validate(null, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
validate.handleWithNoSubsequentOperations(null, xml);
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testRunningSource() throws Exception {
final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
+ "\"><source><running></running></source></validate>");
- final Validate validate = new Validate(null, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final Validate validate = new Validate(null, NETCONF_SESSION_ID_FOR_REPORTING);
validate.handleWithNoSubsequentOperations(null, xml);
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testNoTransaction() throws Exception {
final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
+ "\"><source><candidate/></source></validate>");
- final TransactionProvider transactionProvider = mock(TransactionProvider.class);
- doThrow(IllegalStateException.class).when(transactionProvider).validateTransaction();
- final Validate validate = new Validate(transactionProvider, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
+ doThrow(IllegalStateException.class).when(facade).validateConfiguration();
+ final Validate validate = new Validate(facade, NETCONF_SESSION_ID_FOR_REPORTING);
validate.handleWithNoSubsequentOperations(null, xml);
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testValidationException() throws Exception {
final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
+ "\">><source><candidate/></source></validate>");
- final TransactionProvider transactionProvider = mock(TransactionProvider.class);
- doThrow(ValidationException.class).when(transactionProvider).validateTransaction();
- final Validate validate = new Validate(transactionProvider, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
+ doThrow(ValidationException.class).when(facade).validateConfiguration();
+ final Validate validate = new Validate(facade, NETCONF_SESSION_ID_FOR_REPORTING);
validate.handleWithNoSubsequentOperations(null, xml);
}
final XmlElement xml = XmlElement.fromString("<validate xmlns=\""
+ XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0
+ "\"><source><candidate/></source></validate>");
- final TransactionProvider transactionProvider = mock(TransactionProvider.class);
final Element okElement = XmlUtil.readXmlToElement("<ok/>");
- doNothing().when(transactionProvider).validateTransaction();
- final Validate validate = new Validate(transactionProvider, null, NETCONF_SESSION_ID_FOR_REPORTING);
+ final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
+ doNothing().when(facade).validateConfiguration();
+ final Validate validate = new Validate(facade, NETCONF_SESSION_ID_FOR_REPORTING);
Element ok = validate.handleWithNoSubsequentOperations(XmlUtil.newDocument(), xml);
assertEquals(XmlUtil.toString(okElement), XmlUtil.toString(ok));
}
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
-import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.facade.xml.ConfigExecution;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.InstanceConfigElementResolved;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementDefinition;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ModuleElementResolved;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.facade.xml.mapping.config.Services;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
+import org.opendaylight.controller.config.facade.xml.strategy.EditConfigStrategy;
+import org.opendaylight.controller.config.facade.xml.strategy.EditStrategyType;
+import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
import org.opendaylight.controller.config.util.ConfigRegistryClient;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.InstanceConfigElementResolved;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementDefinition;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ModuleElementResolved;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.Services;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.ValidateTest;
-import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser.EditConfigExecution;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
-import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
public class EditConfigTest {
@Mock
- private YangStoreContext yangStoreSnapshot;
+ private YangStoreService yangStoreSnapshot;
@Mock
private TransactionProvider provider;
@Mock
@Mock
private ObjectName mockOn;
+ private ConfigSubsystemFacade cfgFacade;
+
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
doReturn("mockConfigTransactionClient").when(configTransactionClient).toString();
doReturn(mockOn).when(configTransactionClient).lookupConfigBean(anyString(), anyString());
+
+ cfgFacade = new ConfigSubsystemFacade(configRegistry, configRegistry, yangStoreSnapshot, provider);
}
@Test
- public void test() throws NetconfDocumentedException, ValidationException {
- EditConfig edit = new EditConfig(yangStoreSnapshot, provider, configRegistry,
- ValidateTest.NETCONF_SESSION_ID_FOR_REPORTING);
+ public void test() throws Exception {
+ EditConfig edit = new EditConfig(cfgFacade, ValidateTest.NETCONF_SESSION_ID_FOR_REPORTING);
EditConfigStrategy editStrat = mock(EditConfigStrategy.class);
doNothing().when(editStrat).executeConfiguration(anyString(), anyString(), anyMapOf(String.class, AttributeConfigElement.class),
any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
- EditConfigExecution editConfigExecution = mockExecution(editStrat);
+ ConfigExecution editConfigExecution = mockExecution(editStrat);
edit.getResponseInternal(XmlUtil.newDocument(), editConfigExecution);
any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
}
- private EditConfigExecution mockExecution(EditConfigStrategy editStrat) throws NetconfDocumentedException {
- EditConfigExecution mock = mock(EditConfigExecution.class);
+ private ConfigExecution mockExecution(EditConfigStrategy editStrat) throws Exception {
+ ConfigExecution mock = mock(ConfigExecution.class);
doReturn(getMapping(editStrat)).when(mock).getResolvedXmlElements(any(ConfigTransactionClient.class));
doReturn(getMappingDefinition(editStrat)).when(mock).getModulesDefinition(any(ConfigTransactionClient.class));
doReturn(EditStrategyType.merge).when(mock).getDefaultStrategy();
doReturn(true).when(mock).shouldTest();
doReturn(mockServices()).when(mock).getServiceRegistryWrapper(any(ConfigTransactionClient.class));
doReturn(new Services()).when(mock).getServices();
+ doReturn(XmlElement.fromDomElement(XmlUtil.readXmlToElement("<abc/>"))).when(mock).getConfigElement();
return mock;
}
import javax.management.ObjectName;
import org.junit.Before;
import org.junit.Test;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.mapping.config.ServiceRegistryWrapper;
+import org.opendaylight.controller.config.facade.xml.strategy.MergeEditConfigStrategy;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModule;
import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
public class MergeEditConfigStrategyTest extends AbstractConfigTest {
private static final MultipleDependenciesModuleFactory factory = new MultipleDependenciesModuleFactory();
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.facade.xml.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.config.facade.xml.strategy.ReplaceEditConfigStrategy;
import org.opendaylight.controller.config.util.ConfigTransactionClient;
-import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
public class ReplaceEditConfigStrategyTest {
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
-
-import static org.junit.Assert.assertEquals;
-import com.google.common.collect.ImmutableMap;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-@RunWith(Parameterized.class)
-public class RuntimeRpcElementResolvedTest {
-
- private static final String MODULE_TYPE = "moduleType";
- private static final String INSTANCE_NAME = "instanceName";
- @Parameterized.Parameter(0)
- public String xpath;
- @Parameterized.Parameter(1)
- public Map<String, String> additional;
-
- @Parameterized.Parameters(name = "{index}: parsed({0}) contains moduleName:{1} and instanceName:{2}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
- // With namespaces
- { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']/b:listener-state[b:peer-id='127.0.0.1']",
- new HashMap<>(ImmutableMap.of("listener-state", "127.0.0.1"))},
- { "/a:modules/a:module[a:name='instanceName'][a:type='moduleType']",
- null},
-
- // Without namespaces
- { "/modules/module[name=instanceName][type=moduleType]", null},
- { "/modules/module[type=moduleType][name='instanceName']", null},
- { "/modules/module[name=\'instanceName\'][type=\"moduleType\"]", null},
- { "/modules/module[type=moduleType and name=instanceName]", null},
- { "/modules/module[name=\"instanceName\" and type=moduleType]", null},
- { "/modules/module[type=\"moduleType\" and name=instanceName]", null},
- { "/modules/module[name=\'instanceName\' and type=\"moduleType\"]", null},
-
- // With inner beans
- { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key=b]", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=b]", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=\'b\']", Collections.singletonMap("inner", "b")},
- { "/modules/module[name=instanceName and type=moduleType]/inner[key=\"b\"]", Collections.singletonMap("inner", "b")},
-
- { "/modules/module[name=instanceName and type=\"moduleType\"]/inner[key2=a]/inner2[key=b]",
- new HashMap<>(ImmutableMap.of("inner", "a", "inner2", "b"))
- },
- });
- }
-
- @Test
- public void testFromXpath() throws Exception {
- final RuntimeRpcElementResolved resolved = RuntimeRpcElementResolved.fromXpath(xpath, "element", "namespace");
- assertEquals(MODULE_TYPE, resolved.getModuleName());
- assertEquals(INSTANCE_NAME, resolved.getInstanceName());
- if (additional != null) {
- assertEquals(additional, resolved.getAdditionalAttributes());
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.persist.impl;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.base.Function;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.Collections2;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeMap;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import javax.annotation.Nonnull;
-import javax.annotation.concurrent.Immutable;
-import javax.management.MBeanServerConnection;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.netconf.api.Capability;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.util.NetconfUtil;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXException;
-
-@Immutable
-public class ConfigPusherImpl implements ConfigPusher {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
-
- private final long maxWaitForCapabilitiesMillis;
- private final long conflictingVersionTimeoutMillis;
- private final NetconfOperationServiceFactory configNetconfConnector;
- private static final int QUEUE_SIZE = 100;
- private BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<List<? extends ConfigSnapshotHolder>>(QUEUE_SIZE);
-
- public ConfigPusherImpl(NetconfOperationServiceFactory configNetconfConnector, long maxWaitForCapabilitiesMillis,
- long conflictingVersionTimeoutMillis) {
- this.configNetconfConnector = configNetconfConnector;
- this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
- this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
- }
-
- public void process(List<AutoCloseable> autoCloseables, MBeanServerConnection platformMBeanServer, Persister persisterAggregator) throws InterruptedException {
- List<? extends ConfigSnapshotHolder> configs;
- while(true) {
- configs = queue.take();
- try {
- internalPushConfigs(configs);
- ConfigPersisterNotificationHandler jmxNotificationHandler = new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator);
- synchronized (autoCloseables) {
- autoCloseables.add(jmxNotificationHandler);
- }
-
- LOG.debug("ConfigPusher has pushed configs {}", configs);
- } catch (NetconfDocumentedException e) {
- LOG.error("Error pushing configs {}",configs);
- throw new IllegalStateException(e);
- }
- }
- }
-
- public void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
- LOG.debug("Requested to push configs {}", configs);
- this.queue.put(configs);
- }
-
- private LinkedHashMap<? extends ConfigSnapshotHolder, EditAndCommitResponse> internalPushConfigs(List<? extends ConfigSnapshotHolder> configs) throws NetconfDocumentedException {
- LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
- LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> result = new LinkedHashMap<>();
- // start pushing snapshots:
- for (ConfigSnapshotHolder configSnapshotHolder : configs) {
- if(configSnapshotHolder != null) {
- EditAndCommitResponse editAndCommitResponseWithRetries = null;
- try {
- editAndCommitResponseWithRetries = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
- } catch (ConfigSnapshotFailureException e) {
- LOG.warn("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
- "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
- throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
- }
- LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
- result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
- }
- }
- LOG.debug("All configuration snapshots have been pushed successfully.");
- return result;
- }
-
- /**
- * First calls {@link #getOperationServiceWithRetries(java.util.Set, String)} in order to wait until
- * expected capabilities are present, then tries to push configuration. If {@link ConflictingVersionException}
- * is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
- * {@link NetconfOperationService} after each use.
- */
- private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
- ConflictingVersionException lastException;
- Stopwatch stopwatch = Stopwatch.createUnstarted();
- do {
- String idForReporting = configSnapshotHolder.toString();
- SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
- "Expected capabilities must not be null - %s, check %s", idForReporting,
- configSnapshotHolder.getClass().getName());
- try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
- if(!stopwatch.isRunning()) {
- stopwatch.start();
- }
- return pushConfig(configSnapshotHolder, operationService);
- } catch (ConflictingVersionException e) {
- lastException = e;
- LOG.info("Conflicting version detected, will retry after timeout");
- sleep();
- }
- } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
- throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
- lastException);
- }
-
- private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities, String idForReporting) {
- Stopwatch stopwatch = Stopwatch.createStarted();
- ConfigPusherException lastException;
- do {
- try {
- return getOperationService(expectedCapabilities, idForReporting);
- } catch (ConfigPusherException e) {
- LOG.debug("Not enough capabilities: {}", e.toString());
- lastException = e;
- sleep();
- }
- } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
-
- if(lastException instanceof NotEnoughCapabilitiesException) {
- LOG.error("Unable to push configuration due to missing yang models." +
- " Yang models that are missing, but required by the configuration: {}." +
- " For each mentioned model check: " +
- " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
- " 2. the yang file is present in the system" +
- " 3. the bundle with that yang file is present in the system and active" +
- " 4. the yang parser did not fail while attempting to parse that model",
- ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
- throw new IllegalStateException("Unable to push configuration due to missing yang models." +
- " Required yang models that are missing: "
- + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
- } else {
- final String msg = "Unable to push configuration due to missing netconf service";
- LOG.error(msg, lastException);
- throw new IllegalStateException(msg, lastException);
- }
- }
-
- private static class ConfigPusherException extends Exception {
-
- public ConfigPusherException(final String message) {
- super(message);
- }
-
- public ConfigPusherException(final String message, final Throwable cause) {
- super(message, cause);
- }
- }
-
- private static class NotEnoughCapabilitiesException extends ConfigPusherException {
- private static final long serialVersionUID = 1L;
- private Set<String> missingCaps;
-
- private NotEnoughCapabilitiesException(String message, Set<String> missingCaps) {
- super(message);
- this.missingCaps = missingCaps;
- }
-
- public Set<String> getMissingCaps() {
- return missingCaps;
- }
- }
-
- private static final class NetconfServiceNotAvailableException extends ConfigPusherException {
-
- public NetconfServiceNotAvailableException(final String s, final RuntimeException e) {
- super(s, e);
- }
- }
-
- private static final class ConfigSnapshotFailureException extends ConfigPusherException {
-
- private final String configIdForReporting;
-
- public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
- super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
- this.configIdForReporting = configIdForReporting;
- }
-
- public String getConfigIdForReporting() {
- return configIdForReporting;
- }
- }
-
- /**
- * Get NetconfOperationService iif all required capabilities are present.
- *
- * @param expectedCapabilities that must be provided by configNetconfConnector
- * @param idForReporting
- * @return service if capabilities are present, otherwise absent value
- */
- private NetconfOperationService getOperationService(Set<String> expectedCapabilities, String idForReporting) throws ConfigPusherException {
- NetconfOperationService serviceCandidate;
- try {
- serviceCandidate = configNetconfConnector.createService(idForReporting);
- } catch(RuntimeException e) {
- throw new NetconfServiceNotAvailableException("Netconf service not stable for config pusher." +
- " Cannot push any configuration", e);
- }
- Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, configNetconfConnector);
- if (notFoundDiff.isEmpty()) {
- return serviceCandidate;
- } else {
- serviceCandidate.close();
- LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
- "Expected but not found: {}, all expected {}, current {}",
- notFoundDiff, expectedCapabilities, configNetconfConnector.getCapabilities()
- );
- throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff, notFoundDiff);
- }
- }
-
- private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationServiceFactory serviceCandidate) {
- Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
- @Override
- public String apply(@Nonnull final Capability input) {
- return input.getCapabilityUri();
- }
- });
- Set<String> allNotFound = new HashSet<>(expectedCapabilities);
- allNotFound.removeAll(actual);
- return allNotFound;
- }
-
- private void sleep() {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Sends two RPCs to the netconf server: edit-config and commit.
- *
- * @param configSnapshotHolder
- * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
- * @throws java.lang.RuntimeException if edit-config or commit fails otherwise
- */
- private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
- throws ConflictingVersionException, ConfigSnapshotFailureException {
-
- Element xmlToBePersisted;
- try {
- xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
- } catch (SAXException | IOException e) {
- throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
- }
- LOG.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
- Stopwatch stopwatch = Stopwatch.createStarted();
- NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
-
- Document editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, operationService,
- "edit-config", configSnapshotHolder.toString());
-
- Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService,
- "commit", configSnapshotHolder.toString());
-
- if (LOG.isTraceEnabled()) {
- StringBuilder response = new StringBuilder("editConfig response = {");
- response.append(XmlUtil.toString(editResponseMessage));
- response.append("}");
- response.append("commit response = {");
- response.append(XmlUtil.toString(commitResponseMessage));
- response.append("}");
- LOG.trace("Last configuration loaded successfully");
- LOG.trace("Detailed message {}", response);
- LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
- }
- return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
- }
-
- private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) {
- TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
- Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
- if (netconfOperations.isEmpty()) {
- throw new IllegalStateException("Possible code error: no config operations");
- }
- for (NetconfOperation netconfOperation : netconfOperations) {
- HandlingPriority handlingPriority = null;
- try {
- handlingPriority = netconfOperation.canHandle(request.getDocument());
- } catch (NetconfDocumentedException e) {
- throw new IllegalStateException("Possible code error: canHandle threw exception", e);
- }
- allOperations.put(handlingPriority, netconfOperation);
- }
- Entry<HandlingPriority, NetconfOperation> highestEntry = allOperations.lastEntry();
- if (highestEntry.getKey().isCannotHandle()) {
- throw new IllegalStateException("Possible code error: operation with highest priority is CANNOT_HANDLE");
- }
- return highestEntry.getValue();
- }
-
- private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
- String operationNameForReporting, String configIdForReporting)
- throws ConflictingVersionException, ConfigSnapshotFailureException {
-
- NetconfOperation operation = findOperation(request, operationService);
- Document response;
- try {
- response = operation.handle(request.getDocument(), NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
- return NetconfUtil.checkIsMessageOk(response);
- } catch (NetconfDocumentedException e) {
- if (e.getCause() instanceof ConflictingVersionException) {
- throw (ConflictingVersionException) e.getCause();
- }
- throw new ConfigSnapshotFailureException(configIdForReporting, operationNameForReporting, e);
- }
- }
-
- // load editConfig.xml template, populate /rpc/edit-config/config with parameter
- private static NetconfMessage createEditConfigMessage(Element dataElement) {
- String editConfigResourcePath = "/netconfOp/editConfig.xml";
- try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
- checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
-
- Document doc = XmlUtil.readXmlToDocument(stream);
-
- XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
- XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
- editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
- for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
- boolean deep = true;
- configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
- }
- editConfigElement.appendChild(configWrapper.getDomElement());
- return new NetconfMessage(doc);
- } catch (IOException | SAXException | NetconfDocumentedException e) {
- // error reading the xml file bundled into the jar
- throw new IllegalStateException("Error while opening local resource " + editConfigResourcePath, e);
- }
- }
-
- private static NetconfMessage getCommitMessage() {
- String resource = "/netconfOp/commit.xml";
- try (InputStream stream = ConfigPusherImpl.class.getResourceAsStream(resource)) {
- checkNotNull(stream, "Unable to load resource " + resource);
- return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
- } catch (SAXException | IOException e) {
- // error reading the xml file bundled into the jar
- throw new IllegalStateException("Error while opening local resource " + resource, e);
- }
- }
-
- static class EditAndCommitResponse {
- private final Document editResponse, commitResponse;
-
- EditAndCommitResponse(Document editResponse, Document commitResponse) {
- this.editResponse = editResponse;
- this.commitResponse = commitResponse;
- }
-
- public Document getEditResponse() {
- return editResponse;
- }
-
- public Document getCommitResponse() {
- return commitResponse;
- }
-
- @Override
- public String toString() {
- return "EditAndCommitResponse{" +
- "editResponse=" + editResponse +
- ", commitResponse=" + commitResponse +
- '}';
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.persist.impl.osgi;
-
-import com.google.common.annotations.VisibleForTesting;
-import java.lang.management.ManagementFactory;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.management.MBeanServer;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.persist.impl.ConfigPusherImpl;
-import org.opendaylight.controller.netconf.persist.impl.PersisterAggregator;
-import org.opendaylight.controller.netconf.util.CloseableUtil;
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Filter;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ConfigPersisterActivator implements BundleActivator {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterActivator.class);
- private static final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
-
- public static final String MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY = "maxWaitForCapabilitiesMillis";
- private static final long MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(2);
- public static final String CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY = "conflictingVersionTimeoutMillis";
- private static final long CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT = TimeUnit.MINUTES.toMillis(1);
-
- public static final String NETCONF_CONFIG_PERSISTER = "netconf.config.persister";
-
- public static final String STORAGE_ADAPTER_CLASS_PROP_SUFFIX = "storageAdapterClass";
-
- private List<AutoCloseable> autoCloseables;
- private volatile BundleContext context;
-
- ServiceRegistration<?> registration;
-
- @Override
- public void start(final BundleContext context) throws Exception {
- LOG.debug("ConfigPersister starting");
- this.context = context;
-
- autoCloseables = new ArrayList<>();
- PropertiesProviderBaseImpl propertiesProvider = new PropertiesProviderBaseImpl(context);
-
- final PersisterAggregator persisterAggregator = PersisterAggregator.createFromProperties(propertiesProvider);
- autoCloseables.add(persisterAggregator);
- long maxWaitForCapabilitiesMillis = getMaxWaitForCapabilitiesMillis(propertiesProvider);
- List<ConfigSnapshotHolder> configs = persisterAggregator.loadLastConfigs();
- long conflictingVersionTimeoutMillis = getConflictingVersionTimeoutMillis(propertiesProvider);
- LOG.debug("Following configs will be pushed: {}", configs);
-
- InnerCustomizer innerCustomizer = new InnerCustomizer(configs, maxWaitForCapabilitiesMillis,
- conflictingVersionTimeoutMillis, persisterAggregator);
- OuterCustomizer outerCustomizer = new OuterCustomizer(context, innerCustomizer);
- new ServiceTracker<>(context, NetconfOperationServiceFactory.class, outerCustomizer).open();
- }
-
- private long getConflictingVersionTimeoutMillis(PropertiesProviderBaseImpl propertiesProvider) {
- String timeoutProperty = propertiesProvider.getProperty(CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY);
- return timeoutProperty == null ? CONFLICTING_VERSION_TIMEOUT_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
- }
-
- private long getMaxWaitForCapabilitiesMillis(PropertiesProviderBaseImpl propertiesProvider) {
- String timeoutProperty = propertiesProvider.getProperty(MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY);
- return timeoutProperty == null ? MAX_WAIT_FOR_CAPABILITIES_MILLIS_DEFAULT : Long.valueOf(timeoutProperty);
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- synchronized(autoCloseables) {
- CloseableUtil.closeAll(autoCloseables);
- if (registration != null) {
- registration.unregister();
- }
- this.context = null;
- }
- }
-
-
- @VisibleForTesting
- public static String getFilterString() {
- return "(&" +
- "(" + Constants.OBJECTCLASS + "=" + NetconfOperationServiceFactory.class.getName() + ")" +
- "(name" + "=" + "config-netconf-connector" + ")" +
- ")";
- }
-
- class OuterCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> {
- private final BundleContext context;
- private final InnerCustomizer innerCustomizer;
-
- OuterCustomizer(BundleContext context, InnerCustomizer innerCustomizer) {
- this.context = context;
- this.innerCustomizer = innerCustomizer;
- }
-
- @Override
- public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
- LOG.trace("Got OuterCustomizer.addingService {}", reference);
- // JMX was registered, track config-netconf-connector
- Filter filter;
- try {
- filter = context.createFilter(getFilterString());
- } catch (InvalidSyntaxException e) {
- throw new IllegalStateException(e);
- }
- new ServiceTracker<>(context, filter, innerCustomizer).open();
- return null;
- }
-
- @Override
- public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
-
- }
-
- @Override
- public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
-
- }
- }
-
- class InnerCustomizer implements ServiceTrackerCustomizer<NetconfOperationServiceFactory, NetconfOperationServiceFactory> {
- private final List<ConfigSnapshotHolder> configs;
- private final PersisterAggregator persisterAggregator;
- private final long maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis;
- // This inner customizer has its filter to find the right operation service, but it gets triggered after any
- // operation service appears. This means that it could start pushing thread up to N times (N = number of operation services spawned in OSGi)
- private final AtomicBoolean alreadyStarted = new AtomicBoolean(false);
-
- InnerCustomizer(List<ConfigSnapshotHolder> configs, long maxWaitForCapabilitiesMillis, long conflictingVersionTimeoutMillis,
- PersisterAggregator persisterAggregator) {
- this.configs = configs;
- this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
- this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
- this.persisterAggregator = persisterAggregator;
- }
-
- @Override
- public NetconfOperationServiceFactory addingService(ServiceReference<NetconfOperationServiceFactory> reference) {
- if(alreadyStarted.compareAndSet(false, true) == false) {
- //Prevents multiple calls to this method spawning multiple pushing threads
- return reference.getBundle().getBundleContext().getService(reference);
- }
- LOG.trace("Got InnerCustomizer.addingService {}", reference);
- NetconfOperationServiceFactory service = reference.getBundle().getBundleContext().getService(reference);
-
- LOG.debug("Creating new job queue");
-
- final ConfigPusherImpl configPusher = new ConfigPusherImpl(service, maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
- LOG.debug("Configuration Persister got {}", service);
- LOG.debug("Context was {}", context);
- LOG.debug("Registration was {}", registration);
-
- final Thread pushingThread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- if(configs != null && !configs.isEmpty()) {
- configPusher.pushConfigs(configs);
- }
- if(context != null) {
- registration = context.registerService(ConfigPusher.class.getName(), configPusher, null);
- configPusher.process(autoCloseables, platformMBeanServer, persisterAggregator);
- } else {
- LOG.warn("Unable to process configs as BundleContext is null");
- }
- } catch (InterruptedException e) {
- LOG.info("ConfigPusher thread stopped",e);
- }
- LOG.info("Configuration Persister initialization completed.");
- }
- }, "config-pusher");
- synchronized (autoCloseables) {
- autoCloseables.add(new AutoCloseable() {
- @Override
- public void close() {
- pushingThread.interrupt();
- }
- });
- }
- pushingThread.start();
- return service;
- }
-
- @Override
- public void modifiedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
- LOG.trace("Got InnerCustomizer.modifiedService {}", reference);
- }
-
- @Override
- public void removedService(ServiceReference<NetconfOperationServiceFactory> reference, NetconfOperationServiceFactory service) {
- LOG.trace("Got InnerCustomizer.removedService {}", reference);
- }
-
- }
-}
-
+++ /dev/null
- <hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- <capabilities>
- <capability>urn:ietf:params:netconf:base:1.0</capability>
- </capabilities>
- </hello>
+++ /dev/null
-<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="persister_commit" notify="false">
- <commit></commit>
-</rpc>
\ No newline at end of file
+++ /dev/null
-<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="persister_edit">
- <edit-config>
- <target>
- <candidate/>
- </target>
- <default-operation>merge</default-operation>
-
- <config>
- </config>
-
- </edit-config>
-</rpc>
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.netconf.persist.impl.osgi;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-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 com.google.common.collect.Sets;
-import java.io.IOException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.netconf.api.Capability;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.persist.impl.osgi.MockedBundleContext.DummyAdapterWithInitialSnapshot;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-public class ConfigPersisterTest {
- private static final Logger LOG = LoggerFactory.getLogger(ConfigPersisterTest.class);
-
- private MockedBundleContext ctx;
- private ConfigPersisterActivator configPersisterActivator;
- private TestingExceptionHandler handler;
-
- private void setUpContext(String requiredCapability) throws Exception {
- DummyAdapterWithInitialSnapshot.expectedCapability = requiredCapability;
- ctx = new MockedBundleContext(1000, 1000);
- configPersisterActivator = new ConfigPersisterActivator();
- }
-
- private void setUpContextAndStartPersister(String requiredCapability, final NetconfOperationService conflictingService) throws Exception {
- setUpContext(requiredCapability);
- doReturn(conflictingService).when(ctx.serviceFactory).createService(anyString());
- configPersisterActivator.start(ctx.getBundleContext());
- }
-
- @Before
- public void setUp() {
- handler = new TestingExceptionHandler();
- Thread.setDefaultUncaughtExceptionHandler(handler);
- }
-
- @After
- public void tearDown() throws Exception {
- Thread.setDefaultUncaughtExceptionHandler(null);
- configPersisterActivator.stop(ctx.getBundleContext());
- }
-
- @Test
- public void testPersisterNotAllCapabilitiesProvided() throws Exception {
- setUpContextAndStartPersister("required-cap", getConflictingService());
- Thread.sleep(2000);
- handler.assertException(IllegalStateException.class, "Required yang models that are missing: [required-cap]");
-
- }
-
- @Test
- public void testPersisterSuccessfulPush() throws Exception {
- setUpContextAndStartPersister("cap1", getWorkingService(getOKDocument()));
- Thread.sleep(2000);
- assertCannotRegisterAsJMXListener_pushWasSuccessful();
- }
-
- // this means pushing of config was successful
- public void assertCannotRegisterAsJMXListener_pushWasSuccessful() {
- handler.assertException(IllegalStateException.class, "Cannot register as JMX listener to netconf");
- }
-
- public NetconfOperationService getWorkingService(Document document) throws SAXException, IOException, NetconfDocumentedException {
- NetconfOperationService service = mock(NetconfOperationService.class);
- Capability capability = mock(Capability.class);
-// doReturn(Sets.newHashSet(capability)).when(service).getCapabilities();
- doReturn("cap1").when(capability).getCapabilityUri();
-
-
- NetconfOperation mockedOperation = mock(NetconfOperation.class);
- doReturn(Sets.newHashSet(mockedOperation)).when(service).getNetconfOperations();
- doReturn(HandlingPriority.getHandlingPriority(1)).when(mockedOperation).canHandle(any(Document.class));
- doReturn(document).when(mockedOperation).handle(any(Document.class), any(NetconfOperationChainedExecution.class));
- doNothing().when(service).close();
- return service;
- }
-
- private Document getOKDocument() throws SAXException, IOException {
- return XmlUtil.readXmlToDocument(
- "<rpc-reply message-id=\"1\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "<ok/>\n" +
- "</rpc-reply>"
- );
- }
-
-
- @Test
- public void testPersisterConflictingVersionException() throws Exception {
- setUpContextAndStartPersister("cap1", getConflictingService());
-
- Thread.sleep(2000);
- handler.assertException(IllegalStateException.class, "Max wait for conflicting version stabilization timeout");
- }
-
- private NetconfOperationService getConflictingService() throws Exception {
- NetconfOperationService service = getWorkingService(getOKDocument());
- ConflictingVersionException cve = new ConflictingVersionException("");
- try {
- NetconfDocumentedException.wrap(cve);
- throw new AssertionError("Should throw an exception");
- }catch(NetconfDocumentedException e) {
- NetconfOperation mockedOperation = service.getNetconfOperations().iterator().next();
- doThrow(e).when(mockedOperation).handle(any(Document.class), any(NetconfOperationChainedExecution.class));
- return service;
- }
- }
-
- @Test
- public void testSuccessConflictingVersionException() throws Exception {
- LOG.info("testSuccessConflictingVersionException starting");
-
- setUpContext("cap1");
-
- NetconfOperationService conflictingService = getConflictingService();
- NetconfOperationService workingService = getWorkingService(getOKDocument());
-
- doReturn(conflictingService).doReturn(conflictingService).doReturn(conflictingService).
- doReturn(workingService).when(ctx.serviceFactory).createService(anyString());
-
- configPersisterActivator.start(ctx.getBundleContext());
-
- Thread.sleep(1000);
- assertCannotRegisterAsJMXListener_pushWasSuccessful();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.netconf.persist.impl.osgi;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.Collections;
-import java.util.Dictionary;
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.persist.api.ConfigPusher;
-import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
-import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.persist.api.PropertiesProvider;
-import org.opendaylight.controller.netconf.api.Capability;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.persist.impl.DummyAdapter;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Filter;
-import org.osgi.framework.ServiceListener;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-final class MockedBundleContext {
- @Mock
- private BundleContext context;
- @Mock
- private Filter outerFilter, innerFilter;
- @Mock
- private ServiceReference<?> serviceReference;
- @Mock
- private Bundle bundle;
- @Mock
- NetconfOperationServiceFactory serviceFactory;
- @Mock
- private NetconfOperationService service;
- @Mock
- private ServiceRegistration<?> registration;
-
- MockedBundleContext(long maxWaitForCapabilitiesMillis, long conflictingVersionTimeoutMillis) throws Exception {
- MockitoAnnotations.initMocks(this);
- doReturn(null).when(context).getProperty(anyString());
- initContext(maxWaitForCapabilitiesMillis, conflictingVersionTimeoutMillis);
-
- String outerFilterString = "(objectClass=org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory)";
- doReturn(outerFilter).when(context).createFilter(outerFilterString);
- doNothing().when(context).addServiceListener(any(ServiceListener.class), eq(outerFilterString));
- ServiceReference<?>[] toBeReturned = {serviceReference};
- doReturn(toBeReturned).when(context).getServiceReferences(NetconfOperationServiceFactory.class.getName(), null);
-
- String innerFilterString = "innerfilter";
- doReturn(innerFilterString).when(outerFilter).toString();
-
- doReturn(innerFilter).when(context).createFilter(ConfigPersisterActivator.getFilterString());
- doReturn(innerFilterString).when(innerFilter).toString();
- doNothing().when(context).addServiceListener(any(ServiceListener.class), eq(innerFilterString));
-
- doReturn(toBeReturned).when(context).getServiceReferences((String) null, innerFilterString);
- doReturn(bundle).when(serviceReference).getBundle();
- doReturn(context).when(bundle).getBundleContext();
- doReturn("").when(serviceReference).toString();
- doReturn("context").when(context).toString();
- doReturn(serviceFactory).when(context).getService(any(ServiceReference.class));
- doReturn(service).when(serviceFactory).createService(anyString());
- final Capability cap = mock(Capability.class);
- doReturn("cap1").when(cap).getCapabilityUri();
- doReturn(Collections.singleton(cap)).when(serviceFactory).getCapabilities();
- doNothing().when(service).close();
- doReturn("serviceFactoryMock").when(serviceFactory).toString();
-
- doNothing().when(registration).unregister();
- doReturn(registration).when(context).registerService(
- eq(ConfigPusher.class.getName()), any(Closeable.class),
- any(Dictionary.class));
- }
-
- public BundleContext getBundleContext() {
- return context;
- }
-
- private void initContext(long maxWaitForCapabilitiesMillis, long conflictingVersionTimeoutMillis) {
- initProp(context, "active", "1");
- initProp(context, "1." + ConfigPersisterActivator.STORAGE_ADAPTER_CLASS_PROP_SUFFIX, DummyAdapterWithInitialSnapshot.class.getName());
- initProp(context, "1." + "readonly", "false");
- initProp(context, "1." + ".properties.fileStorage", "target/configuration-persister-test/initial/");
- initProp(context, ConfigPersisterActivator.MAX_WAIT_FOR_CAPABILITIES_MILLIS_PROPERTY, String.valueOf(maxWaitForCapabilitiesMillis));
- initProp(context, ConfigPersisterActivator.CONFLICTING_VERSION_TIMEOUT_MILLIS_PROPERTY, String.valueOf(conflictingVersionTimeoutMillis));
- }
-
- private void initProp(BundleContext context, String key, String value) {
- initPropNoPrefix(context, ConfigPersisterActivator.NETCONF_CONFIG_PERSISTER + "." + key, value);
- }
-
- private void initPropNoPrefix(BundleContext context, String key, String value) {
- doReturn(value).when(context).getProperty(key);
- }
-
- public static class DummyAdapterWithInitialSnapshot extends DummyAdapter {
-
- public static final String CONFIG_SNAPSHOT = "config-snapshot";
- public static String expectedCapability = "cap2";
-
- @Override
- public List<ConfigSnapshotHolder> loadLastConfigs() throws IOException {
- return Lists.newArrayList(getConfigSnapshot());
- }
-
- @Override
- public Persister instantiate(PropertiesProvider propertiesProvider) {
- return this;
- }
-
- public ConfigSnapshotHolder getConfigSnapshot() {
- return new ConfigSnapshotHolder() {
- @Override
- public String getConfigSnapshot() {
- return "<data><" + CONFIG_SNAPSHOT + "/></data>";
- }
-
- @Override
- public SortedSet<String> getCapabilities() {
- TreeSet<String> strings = Sets.newTreeSet();
- strings.add(expectedCapability);
- return strings;
- }
-
- @Override
- public String toString() {
- return getConfigSnapshot();
- }
- };
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.netconf.persist.impl.osgi;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-final class TestingExceptionHandler implements Thread.UncaughtExceptionHandler {
-
- private static final Logger LOG = LoggerFactory.getLogger(TestingExceptionHandler.class);
-
- private Throwable t;
-
- @Override
- public void uncaughtException(Thread t, Throwable e) {
- LOG.debug("Uncaught exception in thread {}", t, e);
- this.t = e;
- }
-
- public void assertException(Class<? extends Exception> exType, String exMessageToContain) {
- assertException(exMessageToContain, exType, exMessageToContain);
- }
-
- public void assertException(String failMessageSuffix, Class<? extends Exception> exType, String exMessageToContain) {
- if(t == null) {
- fail("Should fail to " + failMessageSuffix);
- }
- else {
- assertException(t, exType, exMessageToContain);
- }
- }
-
- public void assertNoException() {
- assertNull("No exception expected but was " + t, t);
- }
-
- private void assertException(Throwable t, Class<? extends Exception> exType, String exMessageToContain) {
- assertEquals("Expected exception of type " + exType + " but was " + t, exType, t.getClass());
- if(exMessageToContain!=null) {
- assertThat(t.getMessage(), containsString(exMessageToContain));
- }
- }
-
- public void assertException(String failMessageSuffix, Class<? extends Exception> exType,
- String exMessageToContain, Class<? extends Exception> nestedExType, String nestedExMessageToContain,
- int nestedExDepth) {
- assertException(failMessageSuffix, exType, exMessageToContain);
- assertNotNull("Expected nested exception in " + t, t.getCause());
- assertException(getNestedException(t, nestedExDepth), nestedExType, nestedExMessageToContain);
- }
-
- private Throwable getNestedException(Throwable t, int nestedExDepth) {
-
- int depth = 0;
- while(t.getCause() != null) {
- t = t.getCause();
- depth++;
- if(nestedExDepth == depth)
- return t;
- }
- throw new IllegalArgumentException("Unable to get nested exception from " + t + " from depth " + nestedExDepth);
- }
-}
and is available at http://www.eclipse.org/legal/epl-v10.html
--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-parent</artifactId>
- <version>1.3.0-SNAPSHOT</version>
- <relativePath>../../opendaylight/md-sal</relativePath>
- </parent>
- <!--
- Necessary TODO: Hookup your parent pom here, else you will not get necessary versions,
- maven repos etc. If you run this archetype in a subdirectory of your project, it
- will pick the pom.xml from the parent directory as the parent pom, which may or may
- not be correct.
- -->
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ <relativePath>../../</relativePath>
+ </parent>
<artifactId>features-netconf-connector</artifactId>
- <!-- Optional TODO: Uncomment version if you are not using a parent pom.xml
- <version>1.2.0-SNAPSHOT</version>
- -->
+
+ <!-- Preserve mdsal version-->
+ <version>${mdsal.version}</version>
<packaging>jar</packaging>
<properties>
<features.file>features.xml</features.file>
</properties>
<dependencies>
- <!--
- Necessary TODO: Put dependencies on any feature repos
- you use in your features.xml file.
-
- Note: they will need to be <type>xml</xml>
- and <classifier>features</classifier>.
- One other thing to watch for is to make sure they are
- <scope>compile</compile>, which they should be by default,
- but be cautious lest they be at a different scope in a parent pom.
-
- Examples:
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>features-yangtools</artifactId>
- <version>0.8.0-SNAPSHOT</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>features-mdsal</artifactId>
- <version>1.3.0-SNAPSHOT</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin</groupId>
- <artifactId>features-openflowplugin</artifactId>
- <version>0.2.0-SNAPSHOT</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
- -->
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>features-yangtools</artifactId>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-netconf</artifactId>
- <version>${netconf.version}</version>
<classifier>features</classifier>
<type>xml</type>
</dependency>
<classifier>features</classifier>
<type>xml</type>
</dependency>
-
- <!--
- Necessary TODO: Put dependencies for bundles directly referenced
- in your features.xml file. For every <bundle> reference in your
- features.xml file, you need a corresponding dependency here.
-
- Examples:
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>controller-provider</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>controller-model</artifactId>
- <version>${project.version}</version>
- </dependency>
- -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-netconf-connector</artifactId>
<artifactId>bcprov-jdk15on</artifactId>
</dependency>
-
- <!-- message-bus -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>messagebus-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>messagebus-impl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>messagebus-config</artifactId>
- <version>${mdsal.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-connector-config</artifactId>
<classifier>config</classifier>
</dependency>
- <!--
- Necessary TODO: Put dependencies for configfiles directly referenced
- in your features.xml file. For every <configfile> reference in your
- features.xml file, you need a corresponding dependency here.
-
- Example (presuming here version is coming from the parent pom):
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>controller-config</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
- -->
-
<!--
Optional TODO: Remove TODO comments.
-->
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+-->
+<features name="odl-controller-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
+ <repository>mvn:org.opendaylight.controller/features-mdsal/${mdsal.version}/xml/features</repository>
+ <repository>mvn:org.opendaylight.yangtools/features-yangtools/${yangtools.version}/xml/features</repository>
+ <repository>mvn:org.opendaylight.controller/features-netconf/${netconf.version}/xml/features</repository>
+
+ <feature name='odl-netconf-connector-all' version='${project.version}' description='OpenDaylight :: Netconf Connector :: All'>
+ <feature version='${project.version}'>odl-netconf-connector</feature>
+ <feature version='${project.version}'>odl-netconf-connector-ssh</feature>
+ </feature>
+
+ <feature name='odl-netconf-connector' version='${project.version}' description="OpenDaylight :: Netconf Connector :: Netconf Connector">
+ <feature version='${mdsal.version}'>odl-mdsal-broker</feature>
+ <feature version='${netconf.version}'>odl-netconf-client</feature>
+ <feature version='${yangtools.version}'>odl-yangtools-models</feature>
+ <bundle>mvn:org.opendaylight.controller/sal-netconf-connector/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller.model/model-inventory/${mdsal.version}</bundle>
+ </feature>
+
+ <feature name='odl-netconf-connector-ssh' version='${project.version}' description="OpenDaylight :: Netconf Connector :: Netconf Connector + Netconf SSH Server + loopback connection configuration">
+ <feature version='${netconf.version}'>odl-netconf-ssh</feature>
+ <feature version='${project.version}'>odl-netconf-connector</feature>
+ <configfile finalname="${config.configfile.directory}/${config.netconf.connector.configfile}">mvn:org.opendaylight.controller/netconf-connector-config/${netconf.version}/xml/config</configfile>
+ </feature>
+
+</features>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-subsystem</artifactId>
<version>0.4.0-SNAPSHOT</version>
- <relativePath>../../opendaylight/netconf</relativePath>
+ <relativePath>../../</relativePath>
</parent>
<artifactId>features-netconf</artifactId>
</properties>
<dependencies>
+ <!-- FIXME AAA netconf dependency loop-->
+ <dependency>
+ <groupId>org.opendaylight.aaa</groupId>
+ <artifactId>features-aaa</artifactId>
+ <version>${aaa.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-config</artifactId>
<type>xml</type>
<scope>runtime</scope>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>features-config-persister</artifactId>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-api</artifactId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-impl</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <version>${config.version}</version>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>config-netconf-connector</artifactId>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-connector-config</artifactId>
- <version>${config.version}</version>
+ <version>${netconf.version}</version>
<type>xml</type>
<classifier>config</classifier>
</dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-monitoring</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>mdsal-netconf-monitoring</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>mdsal-netconf-connector</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-mdsal-config</artifactId>
+ <classifier>config</classifier>
+ <type>xml</type>
+ </dependency>
<!-- test to validate features.xml -->
<dependency>
<groupId>org.opendaylight.odlparent</groupId>
</execution>
</executions>
</plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>${surefire.version}</version>
- <configuration>
- <systemPropertyVariables>
- <karaf.distro.groupId>org.opendaylight.controller</karaf.distro.groupId>
- <karaf.distro.artifactId>opendaylight-karaf-empty</karaf.distro.artifactId>
- <karaf.distro.version>${commons.opendaylight.version}</karaf.distro.version>
- </systemPropertyVariables>
- <dependenciesToScan>
- <dependency>org.opendaylight.odlparent:features-test</dependency>
- </dependenciesToScan>
- </configuration>
- </plugin>
+ <!-- FIXME uncomment after merge -->
+ <!--<plugin>-->
+ <!--<groupId>org.apache.maven.plugins</groupId>-->
+ <!--<artifactId>maven-surefire-plugin</artifactId>-->
+ <!--<version>${surefire.version}</version>-->
+ <!--<configuration>-->
+ <!--<systemPropertyVariables>-->
+ <!--<karaf.distro.groupId>org.opendaylight.controller</karaf.distro.groupId>-->
+ <!--<karaf.distro.artifactId>opendaylight-karaf-empty</karaf.distro.artifactId>-->
+ <!--<karaf.distro.version>${commons.opendaylight.version}</karaf.distro.version>-->
+ <!--</systemPropertyVariables>-->
+ <!--<dependenciesToScan>-->
+ <!--<dependency>org.opendaylight.odlparent:features-test</dependency>-->
+ <!--</dependenciesToScan>-->
+ <!--</configuration>-->
+ <!--</plugin>-->
</plugins>
</build>
<scm>
xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
<repository>mvn:org.opendaylight.controller/features-protocol-framework/${protocol-framework.version}/xml/features</repository>
<repository>mvn:org.opendaylight.controller/features-config/${config.version}/xml/features</repository>
+ <repository>mvn:org.opendaylight.controller/features-config-persister/${config.version}/xml/features</repository>
+ <!-- FIXME: This introduces cycle between projects, which makes version updates
+ harder. Should be moved to different.
+ -->
+ <repository>mvn:org.opendaylight.aaa/features-aaa/${aaa.version}/xml/features</repository>
<feature name='odl-netconf-all' version='${project.version}' description="OpenDaylight :: Netconf :: All">
<feature version='${project.version}'>odl-netconf-api</feature>
<feature name='odl-netconf-api' version='${project.version}' description="OpenDaylight :: Netconf :: API">
<feature version='${protocol-framework.version}'>odl-protocol-framework</feature>
+ <bundle>mvn:org.opendaylight.yangtools/yang-model-api/${yangtools.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/config-util/${config.version}</bundle>
<bundle>mvn:org.opendaylight.controller/netconf-api/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/netconf-auth/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/ietf-netconf-monitoring/${project.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types/${ietf-yang-types.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types-20130715/2013.07.15.8-SNAPSHOT</bundle>
</feature>
+
<feature name='odl-netconf-mapping-api' version='${project.version}' description="OpenDaylight :: Netconf :: Mapping API">
<feature version='${project.version}'>odl-netconf-api</feature>
<bundle>mvn:org.opendaylight.controller/netconf-mapping-api/${project.version}</bundle>
</feature>
+
<feature name='odl-netconf-util' version='${project.version}'>
<feature version='${project.version}'>odl-netconf-mapping-api</feature>
<bundle>mvn:org.opendaylight.yangtools/yang-model-api/${yangtools.version}</bundle>
<bundle>mvn:org.opendaylight.yangtools/yang-data-api/${yangtools.version}</bundle>
<bundle>mvn:org.opendaylight.controller/netconf-util/${project.version}</bundle>
</feature>
- <feature name='odl-netconf-impl' version='${project.version}' description="OpenDaylight :: Netconf :: Impl">
+
+ <feature name='odl-netconf-impl' version='${project.version}' description="OpenDaylight :: Netconf :: Impl">
+ <bundle>mvn:org.opendaylight.controller/yang-jmx-generator/${project.version}</bundle>
<feature version='${project.version}'>odl-netconf-api</feature>
<feature version='${project.version}'>odl-netconf-mapping-api</feature>
<feature version='${project.version}'>odl-netconf-util</feature>
<!-- Netconf server without config connector is just an empty shell -->
<feature version='${project.version}'>odl-config-netconf-connector</feature>
<!-- Netconf will not provide schemas without monitoring -->
+ <bundle>mvn:org.opendaylight.controller/config-manager-facade-xml/${project.version}</bundle>
<feature version='${project.version}'>odl-netconf-monitoring</feature>
<feature version='${project.version}'>odl-netconf-notifications-impl</feature>
<bundle>mvn:org.opendaylight.controller/netconf-impl/${project.version}</bundle>
</feature>
+
<feature name='odl-config-netconf-connector' version='${project.version}' description="OpenDaylight :: Netconf :: Connector">
+ <bundle>mvn:org.opendaylight.controller/yang-jmx-generator/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/config-manager-facade-xml/${project.version}</bundle>
<feature version='${config.version}'>odl-config-manager</feature>
- <feature version='${project.version}'>odl-netconf-api</feature>
- <feature version='${project.version}'>odl-netconf-mapping-api</feature>
- <feature version='${project.version}'>odl-netconf-util</feature>
+ <feature version='${project.version}'>odl-netconf-netty-util</feature>
+ <bundle>mvn:org.opendaylight.controller/netconf-impl/${project.version}</bundle>
<feature version='${project.version}'>odl-netconf-notifications-api</feature>
+ <bundle>mvn:org.opendaylight.controller/netconf-notifications-impl/${project.version}</bundle>
<bundle>mvn:org.opendaylight.controller/config-netconf-connector/${project.version}</bundle>
</feature>
+
<feature name='odl-netconf-netty-util' version='${project.version}' description="OpenDaylight :: Netconf :: Netty Util">
<feature version='${project.version}'>odl-netconf-api</feature>
<feature version='${project.version}'>odl-netconf-mapping-api</feature>
<bundle>mvn:io.netty/netty-buffer/${netty.version}</bundle>
<bundle>mvn:io.netty/netty-transport/${netty.version}</bundle>
</feature>
+
<feature name='odl-netconf-client' version='${project.version}' description="OpenDaylight :: Netconf :: Client">
+ <feature version='${config.version}'>odl-config-all</feature>
<feature version='${project.version}'>odl-netconf-netty-util</feature>
<bundle>mvn:org.opendaylight.controller/netconf-client/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/netconf-config-dispatcher/${config.version}</bundle>
+ <configfile finalname='${config.configfile.directory}/${config.netconf.client.configfile}'>mvn:org.opendaylight.controller/netconf-config/${project.version}/xml/config</configfile>
</feature>
+
<feature name='odl-netconf-monitoring' version='${project.version}' description="OpenDaylight :: Netconf :: Monitoring">
<feature version='${project.version}'>odl-netconf-util</feature>
<bundle>mvn:org.opendaylight.controller/netconf-monitoring/${project.version}</bundle>
</feature>
+
<feature name='odl-netconf-notifications-api' version='${project.version}' description="OpenDaylight :: Netconf :: Notification :: Api">
+ <feature version='${project.version}'>odl-config-manager-facade-xml</feature>
<feature version='${project.version}'>odl-netconf-api</feature>
<bundle>mvn:org.opendaylight.controller/netconf-notifications-api/${project.version}</bundle>
</feature>
+
<feature name='odl-netconf-notifications-impl' version='${project.version}' description="OpenDaylight :: Netconf :: Monitoring :: Impl">
<feature version='${project.version}'>odl-netconf-notifications-api</feature>
<feature version='${project.version}'>odl-netconf-util</feature>
- <feature version='${yangtools.version}'>odl-yangtools-binding-generator</feature>
<bundle>mvn:org.opendaylight.controller/netconf-notifications-impl/${project.version}</bundle>
</feature>
+ <feature name='odl-netconf-ssh' version='${project.version}' description="OpenDaylight :: Netconf Connector :: SSH">
+ <feature version='${project.version}'>odl-netconf-tcp</feature>
+ <!-- FIXME: This introduces cycle between projects, which makes version updates
+ harder. Should be moved to different.
+ -->
+ <feature version='${aaa.version}'>odl-aaa-netconf-plugin</feature>
+ <bundle>mvn:org.opendaylight.controller/netconf-ssh/${project.version}</bundle>
+ </feature>
+
+ <feature name='odl-netconf-tcp' version='${project.version}' description="OpenDaylight :: Netconf Connector :: TCP">
+ <feature version='${project.version}'>odl-netconf-impl</feature>
+ <feature version='${config.version}'>odl-config-netty</feature>
+ <bundle>mvn:org.opendaylight.controller/netconf-tcp/${project.version}</bundle>
+ </feature>
+
+ <feature name='odl-netconf-mdsal' version='${mdsal.version}' description="OpenDaylight :: Netconf :: Mdsal">
+ <feature version='${config.version}'>odl-config-all</feature>
+ <feature version='${project.version}'>odl-netconf-all</feature>
+ <feature version='${project.version}'>odl-netconf-tcp</feature>
+ <feature version='${project.version}'>odl-netconf-ssh</feature>
+ <feature version='${project.version}'>odl-netconf-client</feature>
+ <feature version='${mdsal.version}'>odl-mdsal-broker</feature>
+ <bundle>mvn:org.opendaylight.controller/mdsal-netconf-connector/${project.version}</bundle>
+ <bundle>mvn:org.opendaylight.controller/mdsal-netconf-monitoring/${project.version}</bundle>
+ <configfile finalname='${config.configfile.directory}/${config.netconf.mdsal.configfile}'>mvn:org.opendaylight.controller/netconf-mdsal-config/${project.version}/xml/config</configfile>
+ </feature>
</features>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ <relativePath>../</relativePath>
+ </parent>
+ <artifactId>features-netconf-parent</artifactId>
+ <packaging>pom</packaging>
+
+ <modules>
+ <module>netconf</module>
+ <module>netconf-connector</module>
+ </modules>
+</project>
</instructions>
</configuration>
</plugin>
- <!--FIXME extract yang plugin definition into parent-->
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
public class CurrentSchemaContext implements SchemaContextListener, AutoCloseable {
final AtomicReference<SchemaContext> currentContext = new AtomicReference<SchemaContext>();
private final ListenerRegistration<SchemaContextListener> schemaContextListenerListenerRegistration;
- private final Set<CapabilityListener> listeners = Collections.synchronizedSet(Sets.<CapabilityListener>newHashSet());
+ private final Set<CapabilityListener> listeners1 = Collections.synchronizedSet(Sets.<CapabilityListener>newHashSet());
public SchemaContext getCurrentContext() {
Preconditions.checkState(currentContext.get() != null, "Current context not received");
currentContext.set(schemaContext);
// FIXME is notifying all the listeners from this callback wise ?
final Set<Capability> addedCaps = MdsalNetconfOperationServiceFactory.transformCapabilities(currentContext.get());
- for (final CapabilityListener listener : listeners) {
- listener.onCapabilitiesAdded(addedCaps);
+ for (final CapabilityListener listener : listeners1) {
+ listener.onCapabilitiesChanged(addedCaps, Collections.<Capability>emptySet());
}
}
@Override
public void close() throws Exception {
- listeners.clear();
+ listeners1.clear();
schemaContextListenerListenerRegistration.close();
currentContext.set(null);
}
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- listener.onCapabilitiesAdded(MdsalNetconfOperationServiceFactory.transformCapabilities(currentContext.get()));
- listeners.add(listener);
+ listener.onCapabilitiesChanged(MdsalNetconfOperationServiceFactory.transformCapabilities(currentContext.get()), Collections.<Capability>emptySet());
+ listeners1.add(listener);
return new AutoCloseable() {
@Override
public void close() throws Exception {
- listeners.remove(listener);
+ listeners1.remove(listener);
}
};
}
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.capability.YangModuleCapability;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.netconf.api.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
-import org.opendaylight.controller.netconf.util.capability.BasicCapability;
-import org.opendaylight.controller.netconf.util.capability.YangModuleCapability;
import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
import org.opendaylight.controller.sal.core.api.Consumer;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
static Set<Capability> transformCapabilities(final SchemaContext currentContext) {
final Set<Capability> capabilities = new HashSet<>();
- // [RFC6241] 8.3. Candidate Configuration Capability
- capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+
+ // Added by netconf-impl by default
+// capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
final Set<Module> modules = currentContext.getModules();
for (final Module module : modules) {
import com.google.common.util.concurrent.CheckedFuture;
import java.util.ArrayList;
import java.util.List;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
return candidateTransaction;
}
- public synchronized boolean commitTransaction() throws NetconfDocumentedException {
+ public synchronized boolean commitTransaction() throws DocumentedException {
if (!getCandidateTransaction().isPresent()) {
- throw new NetconfDocumentedException(NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting,
+ throw new DocumentedException(NO_TRANSACTION_FOUND_FOR_SESSION + netconfSessionIdForReporting,
ErrorType.application, ErrorTag.operation_failed, ErrorSeverity.error);
}
future.checkedGet();
} catch (TransactionCommitFailedException e) {
LOG.debug("Transaction {} failed on", candidateTransaction, e);
- throw new NetconfDocumentedException("Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting,
+ throw new DocumentedException("Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting,
ErrorType.application, ErrorTag.operation_failed, ErrorSeverity.error);
}
allOpenReadWriteTransactions.remove(candidateTransaction);
return runningTransaction;
}
- public synchronized boolean commitRunningTransaction(DOMDataReadWriteTransaction tx) throws NetconfDocumentedException {
+ public synchronized boolean commitRunningTransaction(DOMDataReadWriteTransaction tx) throws DocumentedException {
allOpenReadWriteTransactions.remove(tx);
CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
future.checkedGet();
} catch (TransactionCommitFailedException e) {
LOG.debug("Transaction {} failed on", tx, e);
- throw new NetconfDocumentedException("Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting,
+ throw new DocumentedException("Transaction commit failed on " + e.getMessage() + " " + netconfSessionIdForReporting,
ErrorType.application, ErrorTag.operation_failed, ErrorSeverity.error);
}
package org.opendaylight.controller.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
boolean commitStatus = transactionProvider.commitTransaction();
LOG.trace("Transaction commited succesfuly {}", commitStatus);
import com.google.common.base.Optional;
import java.util.HashMap;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
try {
transactionProvider.abortTransaction();
errorInfo
.put(ErrorTag.operation_failed.name(),
"Operation failed. Use 'get-config' or 'edit-config' before triggering 'discard-changes' operation");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
+ throw new DocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
ErrorSeverity.error, errorInfo);
}
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.controller.netconf.mdsal.connector.ops.DataTreeChangeTracker.DataTreeChange;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
if (targetDatastore == Datastore.running) {
- throw new NetconfDocumentedException("edit-config on running datastore is not supported",
+ throw new DocumentedException("edit-config on running datastore is not supported",
ErrorType.protocol,
ErrorTag.operation_not_supported,
ErrorSeverity.error);
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
- private void executeOperations(final DataTreeChangeTracker changeTracker) throws NetconfDocumentedException {
+ private void executeOperations(final DataTreeChangeTracker changeTracker) throws DocumentedException {
final DOMDataReadWriteTransaction rwTx = transactionProvider.getOrCreateTransaction();
final List<DataTreeChange> aa = changeTracker.getDataTreeChanges();
final ListIterator<DataTreeChange> iterator = aa.listIterator(aa.size());
}
}
- private void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) throws NetconfDocumentedException {
+ private void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) throws DocumentedException {
switch (change.getAction()) {
case NONE:
return;
try {
final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(change.getPath())).checkedGet();
if (readResult.isPresent()) {
- throw new NetconfDocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.protocol, ErrorTag.data_exists, ErrorSeverity.error);
+ throw new DocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.protocol, ErrorTag.data_exists, ErrorSeverity.error);
}
rwtx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(change.getPath()), change.getChangeRoot());
} catch (ReadFailedException e) {
try {
final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(change.getPath())).checkedGet();
if (!readResult.isPresent()) {
- throw new NetconfDocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
+ throw new DocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
}
rwtx.delete(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(change.getPath()));
} catch (ReadFailedException e) {
throw new UnsupportedOperationException("implement exception if parse fails");
}
- private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws NetconfDocumentedException{
+ private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws DocumentedException{
Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
try {
//returns module with newest revision since findModuleByNamespace returns a set of modules and we only need the newest one
if (schemaNode != null) {
dataSchemaNode = Optional.of(module.getDataChildByName(element.getName()));
} else {
- throw new NetconfDocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
+ throw new DocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
ErrorType.application,
ErrorTag.unknown_namespace,
ErrorSeverity.error);
return dataSchemaNode;
}
- private Datastore extractTargetParameter(final XmlElement operationElement) throws NetconfDocumentedException {
+ private Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(TARGET_KEY);
// Direct lookup instead of using XmlElement class due to performance
if (elementsByTagName.getLength() == 0) {
- throw new NetconfDocumentedException("Missing target element", ErrorType.rpc, ErrorTag.missing_attribute, ErrorSeverity.error);
+ throw new DocumentedException("Missing target element", ErrorType.rpc, ErrorTag.missing_attribute, ErrorSeverity.error);
} else if (elementsByTagName.getLength() > 1) {
- throw new NetconfDocumentedException("Multiple target elements", ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
+ throw new DocumentedException("Multiple target elements", ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
} else {
final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
return Datastore.valueOf(targetChildNode.getName());
}
}
- private ModifyAction getDefaultOperation(final XmlElement operationElement) throws NetconfDocumentedException {
+ private ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(DEFAULT_OPERATION_KEY);
if(elementsByTagName.getLength() == 0) {
return ModifyAction.MERGE;
} else if(elementsByTagName.getLength() > 1) {
- throw new NetconfDocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements",
+ throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements",
ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
} else {
return ModifyAction.fromXmlValue(elementsByTagName.item(0).getTextContent());
}
- private XmlElement getElement(final XmlElement operationElement, String elementName) throws NetconfDocumentedException {
+ private XmlElement getElement(final XmlElement operationElement, String elementName) throws DocumentedException {
final Optional<XmlElement> childNode = operationElement.getOnlyChildElementOptionally(elementName);
if (!childNode.isPresent()) {
- throw new NetconfDocumentedException(elementName + " element is missing",
+ throw new DocumentedException(elementName + " element is missing",
ErrorType.protocol,
ErrorTag.missing_element,
ErrorSeverity.error);
package org.opendaylight.controller.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = extractTargetParameter(operationElement);
if (targetDatastore == Datastore.candidate) {
LOG.debug("Locking candidate datastore on session: {}", getNetconfSessionIdForReporting());
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
- throw new NetconfDocumentedException("Unable to lock " + targetDatastore + " datastore", NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_not_supported, NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Unable to lock " + targetDatastore + " datastore", DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_not_supported, DocumentedException.ErrorSeverity.error);
}
- static Datastore extractTargetParameter(final XmlElement operationElement) throws NetconfDocumentedException {
+ static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
final XmlElement targetElement = operationElement.getOnlyChildElementWithSameNamespace(TARGET_KEY);
final XmlElement targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
return Datastore.valueOf(targetChildNode.getName());
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.util.OrderedNormalizedNodeWriter;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final String netconfOperationName = operationElement.getName();
final String netconfOperationNamespace;
try {
netconfOperationNamespace = operationElement.getNamespace();
- } catch (MissingNameSpaceException e) {
+ } catch (DocumentedException e) {
LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
- throw new NetconfDocumentedException("Cannot retrieve netconf operation namespace from message",
+ throw new DocumentedException("Cannot retrieve netconf operation namespace from message",
ErrorType.protocol, ErrorTag.unknown_namespace, ErrorSeverity.error);
}
final Optional<Module> moduleOptional = getModule(namespaceURI);
if (!moduleOptional.isPresent()) {
- throw new NetconfDocumentedException("Unable to find module in Schema Context with namespace and name : " +
+ throw new DocumentedException("Unable to find module in Schema Context with namespace and name : " +
namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
ErrorType.application, ErrorTag.bad_element, ErrorSeverity.error);
}
final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(), namespaceURI, netconfOperationName);
if (!rpcDefinitionOptional.isPresent()) {
- throw new NetconfDocumentedException("Unable to find RpcDefinition with namespace and name : " + namespaceURI + " " + netconfOperationName,
+ throw new DocumentedException("Unable to find RpcDefinition with namespace and name : " + namespaceURI + " " + netconfOperationName,
ErrorType.application, ErrorTag.bad_element, ErrorSeverity.error);
}
}
return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
} catch (DOMRpcException e) {
- throw NetconfDocumentedException.wrap(e);
+ throw DocumentedException.wrap(e);
}
}
@Override
public Document handle(final Document requestMessage,
- final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
final Map<String, Attr> attributes = requestElement.getAttributes();
final Element response = handle(document, operationElement, subsequentOperation);
- final Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
if(XmlElement.fromDomElement(response).hasNamespace()) {
rpcReply.appendChild(response);
//TODO move all occurences of this method in mdsal netconf(and xml factories) to a utility class
private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data, final SchemaPath rpcOutputPath) {
- final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.RPC_REPLY_KEY));
+ final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
package org.opendaylight.controller.netconf.mdsal.connector.ops;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
if (targetDatastore == Datastore.candidate) {
LOG.debug("Unlocking candidate datastore on session: {}", getNetconfSessionIdForReporting());
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
- throw new NetconfDocumentedException("Unable to unlock " + targetDatastore + " datastore", NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_not_supported, NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException("Unable to unlock " + targetDatastore + " datastore", DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_not_supported, DocumentedException.ErrorSeverity.error);
}
@Override
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.mdsal.connector.ops.Datastore;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
}
}
- private DataSchemaNode getSchemaNodeFromNamespace(final XmlElement element) throws NetconfDocumentedException {
+ private DataSchemaNode getSchemaNodeFromNamespace(final XmlElement element) throws DocumentedException {
try {
final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(element.getNamespace()), null);
throw new IllegalArgumentException("Unable to parse element namespace, this should not happen since " +
"namespace of an xml element is valid and if the xml was parsed then the URI should be as well");
}
- throw new NetconfDocumentedException("Unable to find node with namespace: " + element.getNamespace() + "in schema context: " + schemaContext.getCurrentContext().toString(),
+ throw new DocumentedException("Unable to find node with namespace: " + element.getNamespace() + "in schema context: " + schemaContext.getCurrentContext().toString(),
ErrorType.application,
ErrorTag.unknown_namespace,
ErrorSeverity.error);
* @return if Filter is present and not empty returns Optional of the InstanceIdentifier to the read location in datastore.
* empty filter returns Optional.absent() which should equal an empty <data/> container in the response.
* if filter is not present we want to read the entire datastore - return ROOT.
- * @throws NetconfDocumentedException
+ * @throws DocumentedException
*/
- protected Optional<YangInstanceIdentifier> getDataRootFromFilter(XmlElement operationElement) throws NetconfDocumentedException {
+ protected Optional<YangInstanceIdentifier> getDataRootFromFilter(XmlElement operationElement) throws DocumentedException {
Optional<XmlElement> filterElement = operationElement.getOnlyChildElementOptionally(FILTER);
if (filterElement.isPresent()) {
if (filterElement.get().getChildElements().size() == 0) {
}
@VisibleForTesting
- protected YangInstanceIdentifier getInstanceIdentifierFromFilter(XmlElement filterElement) throws NetconfDocumentedException {
+ protected YangInstanceIdentifier getInstanceIdentifierFromFilter(XmlElement filterElement) throws DocumentedException {
if (filterElement.getChildElements().size() != 1) {
- throw new NetconfDocumentedException("Multiple filter roots not supported yet",
+ throw new DocumentedException("Multiple filter roots not supported yet",
ErrorType.application, ErrorTag.operation_not_supported, ErrorSeverity.error);
}
return path;
}
- private NormalizedNode filterToNormalizedNode(XmlElement element, DataSchemaNode schemaNode) throws NetconfDocumentedException {
+ private NormalizedNode filterToNormalizedNode(XmlElement element, DataSchemaNode schemaNode) throws DocumentedException {
DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory
.getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext());
} else if (schemaNode instanceof ListSchemaNode) {
parsedNode = parserFactory.getMapNodeParser().parse(Collections.singletonList(element.getDomElement()), (ListSchemaNode) schemaNode);
} else {
- throw new NetconfDocumentedException("Schema node of the top level element is not an instance of container or list",
+ throw new DocumentedException("Schema node of the top level element is not an instance of container or list",
ErrorType.application, ErrorTag.unknown_element, ErrorSeverity.error);
}
return parsedNode;
return datastore;
}
- static GetConfigExecution fromXml(final XmlElement xml, final String operationName) throws NetconfDocumentedException {
+ static GetConfigExecution fromXml(final XmlElement xml, final String operationName) throws DocumentedException {
try {
validateInputRpc(xml, operationName);
- } catch (final NetconfDocumentedException e) {
- throw new NetconfDocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+ } catch (final DocumentedException e) {
+ throw new DocumentedException("Incorrect RPC: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
final Optional<Datastore> sourceDatastore;
try {
sourceDatastore = parseSource(xml);
- } catch (final NetconfDocumentedException e) {
- throw new NetconfDocumentedException("Get-config source attribute error: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+ } catch (final DocumentedException e) {
+ throw new DocumentedException("Get-config source attribute error: " + e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
return new GetConfigExecution(sourceDatastore);
}
- private static Optional<Datastore> parseSource(final XmlElement xml) throws NetconfDocumentedException {
+ private static Optional<Datastore> parseSource(final XmlElement xml) throws DocumentedException {
final Optional<XmlElement> sourceElement = xml.getOnlyChildElementOptionally(XmlNetconfConstants.SOURCE_KEY,
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
Optional.of(Datastore.valueOf(sourceElement.get().getOnlyChildElement().getName())) : Optional.<Datastore>absent();
}
- private static void validateInputRpc(final XmlElement xml, String operationName) throws NetconfDocumentedException{
+ private static void validateInputRpc(final XmlElement xml, String operationName) throws DocumentedException{
xml.checkName(operationName);
xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
package org.opendaylight.controller.netconf.mdsal.connector.ops.get;
import com.google.common.base.Optional;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.controller.netconf.mdsal.connector.ops.Datastore;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.slf4j.Logger;
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException {
final Optional<YangInstanceIdentifier> dataRootOptional = getDataRootFromFilter(operationElement);
if (!dataRootOptional.isPresent()) {
}
}
- private DOMDataReadWriteTransaction getTransaction(Datastore datastore) throws NetconfDocumentedException{
+ private DOMDataReadWriteTransaction getTransaction(Datastore datastore) throws DocumentedException{
if (datastore == Datastore.candidate) {
return transactionProvider.getOrCreateTransaction();
} else if (datastore == Datastore.running) {
return transactionProvider.createRunningTransaction();
}
- throw new NetconfDocumentedException("Incorrect Datastore: ", ErrorType.protocol, ErrorTag.bad_element, ErrorSeverity.error);
+ throw new DocumentedException("Incorrect Datastore: ", ErrorType.protocol, ErrorTag.bad_element, ErrorSeverity.error);
}
@Override
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
import org.opendaylight.controller.netconf.mdsal.connector.ops.Datastore;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.slf4j.Logger;
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException {
GetConfigExecution getConfigExecution = null;
try {
getConfigExecution = GetConfigExecution.fromXml(operationElement, OPERATION_NAME);
- } catch (final NetconfDocumentedException e) {
+ } catch (final DocumentedException e) {
LOG.warn("Get request processing failed on session: {}", getNetconfSessionIdForReporting(), e);
throw e;
}
}
}
- private DOMDataReadWriteTransaction getTransaction(Datastore datastore) throws NetconfDocumentedException{
+ private DOMDataReadWriteTransaction getTransaction(Datastore datastore) throws DocumentedException{
if (datastore == Datastore.candidate) {
return transactionProvider.getOrCreateTransaction();
} else if (datastore == Datastore.running) {
return transactionProvider.createRunningTransaction();
}
- throw new NetconfDocumentedException("Incorrect Datastore: ", ErrorType.protocol, ErrorTag.bad_element, ErrorSeverity.error);
+ throw new DocumentedException("Incorrect Datastore: ", ErrorType.protocol, ErrorTag.bad_element, ErrorSeverity.error);
}
@Override
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.ConcurrentDOMDataBroker;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.mdsal.connector.ops.get.GetConfig;
import org.opendaylight.controller.netconf.util.test.NetconfXmlUnitRecursiveQualifier;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.controller.sal.core.spi.data.DOMStore;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
try {
discardChanges();
fail("Should have failed, need to execute an edit before discard");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
assertTrue(e.getErrorType() == ErrorType.application);
try {
executeOperation(new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider), "messages/mapping/bad_getConfig.xml");
fail("Should have failed, this is an incorrect request");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
assertTrue(e.getErrorType() == ErrorType.application);
try {
executeOperation(new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider), "messages/mapping/bad_namespace_getConfig.xml");
fail("Should have failed, this is an incorrect request");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
assertTrue(e.getErrorType() == ErrorType.application);
try {
edit("messages/mapping/editConfigs/editConfig_running.xml");
fail("Should have failed - edit config on running datastore is not supported");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
assertTrue(e.getErrorType() == ErrorType.protocol);
try {
lock();
fail("Should have failed - locking of running datastore is not supported");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
assertTrue(e.getErrorType() == ErrorType.application);
try {
lockWithoutTarget();
fail("Should have failed, target is missing");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.invalid_value);
assertTrue(e.getErrorType() == ErrorType.application);
try {
unlock();
fail("Should have failed - unlocking of running datastore is not supported");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_not_supported);
assertTrue(e.getErrorType() == ErrorType.application);
try {
unlockWithoutTarget();
fail("Should have failed, target is missing");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.invalid_value);
assertTrue(e.getErrorType() == ErrorType.application);
try {
edit("messages/mapping/editConfigs/editConfig_create.xml");
fail("Create should have failed - data already exists");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.data_exists);
assertTrue(e.getErrorType() == ErrorType.protocol);
try {
edit("messages/mapping/editConfigs/editConfig_delete-top.xml");
fail("Delete should have failed - data is missing");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.data_missing);
assertTrue(e.getErrorType() == ErrorType.protocol);
try {
edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_create_existing.xml");
fail();
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.data_exists);
assertTrue(e.getErrorType() == ErrorType.protocol);
try {
edit("messages/mapping/editConfigs/editConfig_merge_multiple_operations_4_delete-non-existing.xml");
fail();
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.data_missing);
assertTrue(e.getErrorType() == ErrorType.protocol);
super(sessionId, schemaContext, transactionProvider);
}
- public YangInstanceIdentifier getInstanceIdentifierFromDocument(Document request) throws NetconfDocumentedException {
+ public YangInstanceIdentifier getInstanceIdentifierFromDocument(Document request) throws DocumentedException {
XmlElement filterElement = XmlElement.fromDomDocument(request).getOnlyChildElement(GET_CONFIG).getOnlyChildElement(FILTER_NODE);
return getInstanceIdentifierFromFilter(filterElement);
}
}
- private Document commit() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document commit() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Commit commit = new Commit(sessionIdForReporting, transactionProvider);
return executeOperation(commit, "messages/mapping/commit.xml");
}
- private Document discardChanges() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document discardChanges() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
DiscardChanges discardOp = new DiscardChanges(sessionIdForReporting, transactionProvider);
return executeOperation(discardOp, "messages/mapping/discardChanges.xml");
}
- private Document edit(String resource) throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document edit(String resource) throws DocumentedException, ParserConfigurationException, SAXException, IOException {
EditConfig editConfig = new EditConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
return executeOperation(editConfig, resource);
}
- private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document get() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Get get = new Get(sessionIdForReporting, currentSchemaContext, transactionProvider);
return executeOperation(get, "messages/mapping/get.xml");
}
- private Document getWithFilter(String resource) throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document getWithFilter(String resource) throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Get get = new Get(sessionIdForReporting, currentSchemaContext, transactionProvider);
return executeOperation(get, resource);
}
- private Document getConfigRunning() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document getConfigRunning() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
return executeOperation(getConfig, "messages/mapping/getConfig.xml");
}
- private Document getConfigCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document getConfigCandidate() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
return executeOperation(getConfig, "messages/mapping/getConfig_candidate.xml");
}
- private Document getConfigWithFilter(String resource) throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document getConfigWithFilter(String resource) throws DocumentedException, ParserConfigurationException, SAXException, IOException {
GetConfig getConfig = new GetConfig(sessionIdForReporting, currentSchemaContext, transactionProvider);
return executeOperation(getConfig, resource);
}
- private Document lock() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document lock() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Lock lock = new Lock(sessionIdForReporting);
return executeOperation(lock, "messages/mapping/lock.xml");
}
- private Document unlock() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document unlock() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Unlock unlock = new Unlock(sessionIdForReporting);
return executeOperation(unlock, "messages/mapping/unlock.xml");
}
- private Document lockWithoutTarget() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document lockWithoutTarget() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Lock lock = new Lock(sessionIdForReporting);
return executeOperation(lock, "messages/mapping/lock_notarget.xml");
}
- private Document unlockWithoutTarget() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document unlockWithoutTarget() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Unlock unlock = new Unlock(sessionIdForReporting);
return executeOperation(unlock, "messages/mapping/unlock_notarget.xml");
}
- private Document lockCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document lockCandidate() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Lock lock = new Lock(sessionIdForReporting);
return executeOperation(lock, "messages/mapping/lock_candidate.xml");
}
- private Document unlockCandidate() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
+ private Document unlockCandidate() throws DocumentedException, ParserConfigurationException, SAXException, IOException {
Unlock unlock = new Unlock(sessionIdForReporting);
return executeOperation(unlock, "messages/mapping/unlock_candidate.xml");
}
- private Document executeOperation(NetconfOperation op, String filename) throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
+ private Document executeOperation(NetconfOperation op, String filename) throws ParserConfigurationException, SAXException, IOException, DocumentedException {
final Document request = XmlFileLoader.xmlFileToDocument(filename);
final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.core.api.model.SchemaService;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.common.RpcError;
try {
rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
fail("should have failed with rpc invocation not implemented yet");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorType() == ErrorType.application);
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
try {
rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
fail("Should have failed, rpc has bad namespace");
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
assertTrue(e.getErrorTag() == ErrorTag.bad_element);
assertTrue(e.getErrorType() == ErrorType.application);
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
+ <artifactId>netconf-models</artifactId>
<version>0.4.0-SNAPSHOT</version>
</parent>
<artifactId>ietf-netconf-monitoring-extension</artifactId>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
+ <artifactId>netconf-models</artifactId>
<version>0.4.0-SNAPSHOT</version>
</parent>
<artifactId>ietf-netconf-monitoring</artifactId>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
+ <artifactId>netconf-models</artifactId>
<version>0.4.0-SNAPSHOT</version>
</parent>
<artifactId>ietf-netconf-notifications</artifactId>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
+ <artifactId>netconf-models</artifactId>
<version>0.4.0-SNAPSHOT</version>
</parent>
<artifactId>ietf-netconf</artifactId>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>netconf-models</artifactId>
+
+ <version>0.4.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <name>${project.artifactId}</name>
+
+ <modules>
+ <module>ietf-netconf</module>
+ <module>ietf-netconf-monitoring</module>
+ <module>ietf-netconf-notifications</module>
+ <module>ietf-netconf-monitoring-extension</module>
+ </modules>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
+ </instructions>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin</artifactId>
+ </plugin>
+ </plugins>
+
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <failsOnError>false</failsOnError>
+ <failOnViolation>true</failOnViolation>
+ <configLocation>checkstyle-logging.xml</configLocation>
+ <consoleOutput>true</consoleOutput>
+ <includeTestSourceDirectory>true</includeTestSourceDirectory>
+ <sourceDirectory>${project.basedir}</sourceDirectory>
+ <includes>**\/*.java,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat,**\/*.yang</includes>
+ <excludes>**\/target\/,**\/bin\/,**\/target-ide\/,**\/${jmxGeneratorPath}\/,**\/${salGeneratorPath}\/,**\/netconf\/test\/tool\/Main.java, **\/netconf\/test\/tool\/client\/stress\/StressClient.java</excludes>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>checkstyle-logging</artifactId>
+ <version>${yangtools.version}</version>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>
<groupId>org.opendaylight.controller</groupId>
<artifactId>config-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>protocol-framework</artifactId>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
package org.opendaylight.controller.netconf.api;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.ERROR_INFO;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.ERROR_MESSAGE;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.ERROR_SEVERITY;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.ERROR_TAG;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.ERROR_TYPE;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_ERROR;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
-
-import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
-import java.util.Map.Entry;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
/**
* Checked exception to communicate an error that needs to be sent to the
* netconf client.
*/
-public class NetconfDocumentedException extends Exception {
-
- private static final long serialVersionUID = 1L;
-
- private final static Logger LOG = LoggerFactory.getLogger( NetconfDocumentedException.class );
-
- private static final DocumentBuilderFactory BUILDER_FACTORY;
-
- static {
- BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
- try {
- BUILDER_FACTORY.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
- BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-general-entities", false);
- BUILDER_FACTORY.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- BUILDER_FACTORY.setXIncludeAware(false);
- BUILDER_FACTORY.setExpandEntityReferences(false);
- } catch (ParserConfigurationException e) {
- throw new ExceptionInInitializerError(e);
- }
- BUILDER_FACTORY.setNamespaceAware(true);
- BUILDER_FACTORY.setCoalescing(true);
- BUILDER_FACTORY.setIgnoringElementContentWhitespace(true);
- BUILDER_FACTORY.setIgnoringComments(true);
- }
-
- public enum ErrorType {
- transport, rpc, protocol, application;
-
- public String getTagValue() {
- return name();
- }
-
- public static ErrorType from( String text ) {
- try {
- return valueOf( text );
- }
- catch( Exception e ) {
- return application;
- }
- }
- }
-
- public enum ErrorTag {
- access_denied("access-denied"),
- bad_attribute("bad-attribute"),
- bad_element("bad-element"),
- data_exists("data-exists"),
- data_missing("data-missing"),
- in_use("in-use"),
- invalid_value("invalid-value"),
- lock_denied("lock-denied"),
- malformed_message("malformed-message"),
- missing_attribute("missing-attribute"),
- missing_element("missing-element"),
- operation_failed("operation-failed"),
- operation_not_supported("operation-not-supported"),
- resource_denied("resource-denied"),
- rollback_failed("rollback-failed"),
- too_big("too-big"),
- unknown_attribute("unknown-attribute"),
- unknown_element("unknown-element"),
- unknown_namespace("unknown-namespace");
-
- private final String tagValue;
-
- ErrorTag(final String tagValue) {
- this.tagValue = tagValue;
- }
-
- public String getTagValue() {
- return this.tagValue;
- }
+public class NetconfDocumentedException extends DocumentedException {
- public static ErrorTag from( String text ) {
- for( ErrorTag e: values() )
- {
- if( e.getTagValue().equals( text ) ) {
- return e;
- }
- }
-
- return operation_failed;
- }
- }
-
- public enum ErrorSeverity {
- error, warning;
-
- public String getTagValue() {
- return name();
- }
-
- public static ErrorSeverity from( String text ) {
- try {
- return valueOf( text );
- }
- catch( Exception e ) {
- return error;
- }
- }
- }
-
- private final ErrorType errorType;
- private final ErrorTag errorTag;
- private final ErrorSeverity errorSeverity;
- private final Map<String, String> errorInfo;
-
- public NetconfDocumentedException(String message) {
- this(message,
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.invalid_value,
- NetconfDocumentedException.ErrorSeverity.error
- );
- }
-
- public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity) {
- this(message, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
- }
-
- public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
- final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ public NetconfDocumentedException(final String message) {
super(message);
- this.errorType = errorType;
- this.errorTag = errorTag;
- this.errorSeverity = errorSeverity;
- this.errorInfo = errorInfo;
}
- public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType,
- final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
- this(message, cause, errorType, errorTag, errorSeverity, Collections.<String, String> emptyMap());
+ public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ super(message, errorType, errorTag, errorSeverity);
}
- public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType,
- final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
- super(message, cause);
- this.errorType = errorType;
- this.errorTag = errorTag;
- this.errorSeverity = errorSeverity;
- this.errorInfo = errorInfo;
+ public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, errorType, errorTag, errorSeverity, errorInfo);
}
- public static <E extends Exception> NetconfDocumentedException wrap(E exception) throws NetconfDocumentedException {
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_failed.name(), "Exception thrown");
- throw new NetconfDocumentedException(exception.getMessage(), exception, ErrorType.application, ErrorTag.operation_failed,
- ErrorSeverity.error, errorInfo);
- }
- public static NetconfDocumentedException wrap(ValidationException e) throws NetconfDocumentedException {
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_failed.name(), "Validation failed");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
- ErrorSeverity.error, errorInfo);
+ public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+ super(message, cause, errorType, errorTag, errorSeverity);
}
- public static NetconfDocumentedException wrap(ConflictingVersionException e) throws NetconfDocumentedException {
- final Map<String, String> errorInfo = new HashMap<>();
- errorInfo.put(ErrorTag.operation_failed.name(), "Optimistic lock failed");
- throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.application, ErrorTag.operation_failed,
- ErrorSeverity.error, errorInfo);
- }
-
- public static NetconfDocumentedException fromXMLDocument( Document fromDoc ) {
-
- ErrorType errorType = ErrorType.application;
- ErrorTag errorTag = ErrorTag.operation_failed;
- ErrorSeverity errorSeverity = ErrorSeverity.error;
- Map<String, String> errorInfo = null;
- String errorMessage = "";
-
- Node rpcReply = fromDoc.getDocumentElement();
-
- // FIXME: BUG? - we only handle one rpc-error.
-
- NodeList replyChildren = rpcReply.getChildNodes();
- for( int i = 0; i < replyChildren.getLength(); i++ ) {
- Node replyChild = replyChildren.item( i );
- if( RPC_ERROR.equals( replyChild.getNodeName() ) )
- {
- NodeList rpcErrorChildren = replyChild.getChildNodes();
- for( int j = 0; j < rpcErrorChildren.getLength(); j++ )
- {
- Node rpcErrorChild = rpcErrorChildren.item( j );
- if( ERROR_TYPE.equals( rpcErrorChild.getNodeName() ) ) {
- errorType = ErrorType.from( rpcErrorChild.getTextContent() );
- }
- else if( ERROR_TAG.equals( rpcErrorChild.getNodeName() ) ) {
- errorTag = ErrorTag.from( rpcErrorChild.getTextContent() );
- }
- else if( ERROR_SEVERITY.equals( rpcErrorChild.getNodeName() ) ) {
- errorSeverity = ErrorSeverity.from( rpcErrorChild.getTextContent() );
- }
- else if( ERROR_MESSAGE.equals( rpcErrorChild.getNodeName() ) ) {
- errorMessage = rpcErrorChild.getTextContent();
- }
- else if( ERROR_INFO.equals( rpcErrorChild.getNodeName() ) ) {
- errorInfo = parseErrorInfo( rpcErrorChild );
- }
- }
-
- break;
- }
- }
-
- return new NetconfDocumentedException( errorMessage, errorType, errorTag, errorSeverity, errorInfo );
- }
-
- private static Map<String, String> parseErrorInfo( Node node ) {
- Map<String, String> infoMap = new HashMap<>();
- NodeList children = node.getChildNodes();
- for( int i = 0; i < children.getLength(); i++ ) {
- Node child = children.item( i );
- if( child.getNodeType() == Node.ELEMENT_NODE ) {
- infoMap.put( child.getNodeName(), child.getTextContent() );
- }
- }
-
- return infoMap;
- }
-
- public ErrorType getErrorType() {
- return this.errorType;
- }
-
- public ErrorTag getErrorTag() {
- return this.errorTag;
- }
-
- public ErrorSeverity getErrorSeverity() {
- return this.errorSeverity;
- }
-
- public Map<String, String> getErrorInfo() {
- return this.errorInfo;
- }
-
- public Document toXMLDocument() {
- Document doc = null;
- try {
- doc = BUILDER_FACTORY.newDocumentBuilder().newDocument();
-
- Node rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_REPLY_KEY );
- doc.appendChild( rpcReply );
-
- Node rpcError = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_ERROR );
- rpcReply.appendChild( rpcError );
-
- rpcError.appendChild( createTextNode( doc, ERROR_TYPE, getErrorType().getTagValue() ) );
- rpcError.appendChild( createTextNode( doc, ERROR_TAG, getErrorTag().getTagValue() ) );
- rpcError.appendChild( createTextNode( doc, ERROR_SEVERITY, getErrorSeverity().getTagValue() ) );
- rpcError.appendChild( createTextNode( doc, ERROR_MESSAGE, getLocalizedMessage() ) );
-
- Map<String, String> errorInfoMap = getErrorInfo();
- if( errorInfoMap != null && !errorInfoMap.isEmpty() ) {
- /*
- * <error-info>
- * <bad-attribute>message-id</bad-attribute>
- * <bad-element>rpc</bad-element>
- * </error-info>
- */
-
- Node errorInfoNode = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, ERROR_INFO );
- errorInfoNode.setPrefix( rpcReply.getPrefix() );
- rpcError.appendChild( errorInfoNode );
-
- for ( Entry<String, String> entry : errorInfoMap.entrySet() ) {
- errorInfoNode.appendChild( createTextNode( doc, entry.getKey(), entry.getValue() ) );
- }
- }
- }
- catch( ParserConfigurationException e ) {
- LOG.error( "Error outputting to XML document", e ); // this shouldn't happen
- }
-
- return doc;
+ public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+ super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
}
- private Node createTextNode( Document doc, String tag, String textContent ) {
- Node node = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, tag );
- node.setTextContent( textContent );
- return node;
+ public NetconfDocumentedException(DocumentedException e) {
+ super(e.getMessage(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
}
- @Override
- public String toString() {
- return "NetconfDocumentedException{" + "message=" + getMessage() + ", errorType=" + this.errorType
- + ", errorTag=" + this.errorTag + ", errorSeverity=" + this.errorSeverity + ", errorInfo="
- + this.errorInfo + '}';
+ public static NetconfDocumentedException fromXMLDocument( Document fromDoc) {
+ return new NetconfDocumentedException(DocumentedException.fromXMLDocument(fromDoc));
}
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.api.jmx;
-
-import java.util.Set;
-import javax.management.NotificationBroadcasterSupport;
-import org.w3c.dom.Element;
-
-public class CommitJMXNotification extends NetconfJMXNotification {
-
- private final Element configSnapshot;
-
- private static final String AFTER_COMMIT_MESSAGE_TEMPLATE = "Commit successful: %s";
- private final Set<String> capabilities;
-
- CommitJMXNotification(NotificationBroadcasterSupport source, String message, Element cfgSnapshot,
- Set<String> capabilities) {
- super(TransactionProviderJMXNotificationType.commit, source, String.format(AFTER_COMMIT_MESSAGE_TEMPLATE, message));
- this.configSnapshot = cfgSnapshot;
- this.capabilities = capabilities;
- }
-
- public Element getConfigSnapshot() {
- return configSnapshot;
- }
-
- public Set<String> getCapabilities() {
- return capabilities;
- }
-
- @Override
- public String toString() {
- final StringBuffer sb = new StringBuffer("CommitJMXNotification{");
- sb.append("configSnapshot=").append(configSnapshot);
- sb.append(", capabilities=").append(getCapabilities());
- sb.append('}');
- return sb.toString();
- }
-
- /**
- *
- */
- private static final long serialVersionUID = -8587623362011695514L;
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.api.jmx;
-
-import javax.management.ObjectName;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
-
-public interface DefaultCommitOperationMXBean {
-
- String TYPE_NAME = "NetconfNotificationProvider";
- ObjectName OBJECT_NAME = ObjectNameUtil.createONWithDomainAndType(TYPE_NAME);
-
-}
package org.opendaylight.controller.netconf.api.monitoring;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
public interface CapabilityListener {
- void onCapabilitiesAdded(Set<Capability> addedCaps);
+ void onCapabilitiesChanged(Set<Capability> added, Set<Capability> removed);
- void onCapabilitiesRemoved(Set<Capability> removedCaps);
}
package org.opendaylight.controller.netconf.api.util;
+/**
+ * These constants mark operation service factories that are auto wired with netconf endpoint
+ * for config subsystem
+ */
public final class NetconfConstants {
/*
* TODO define marker interface in mapping-api that the serviceFactories in cofing subsystem
*/
package org.opendaylight.controller.netconf.api.xml;
-public final class XmlNetconfConstants {
-
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+public final class XmlNetconfConstants {
private XmlNetconfConstants() {}
- public static final String MOUNTPOINTS = "mountpoints";
- public static final String MOUNTPOINT = "mountpoint";
- public static final String ID = "id";
public static final String CAPABILITY = "capability";
public static final String CAPABILITIES = "capabilities";
public static final String COMMIT = "commit";
- public static final String TYPE_KEY = "type";
- public static final String MODULE_KEY = "module";
- public static final String INSTANCE_KEY = "instance";
public static final String OPERATION_ATTR_KEY = "operation";
- public static final String SERVICES_KEY = "services";
public static final String CONFIG_KEY = "config";
- public static final String MODULES_KEY = "modules";
- public static final String CONFIGURATION_KEY = "configuration";
public static final String DATA_KEY = "data";
public static final String OK = "ok";
public static final String FILTER = "filter";
public static final String SOURCE_KEY = "source";
public static final String RPC_KEY = "rpc";
- public static final String RPC_REPLY_KEY = "rpc-reply";
- public static final String RPC_ERROR = "rpc-error";
- public static final String ERROR_TYPE = "error-type";
- public static final String ERROR_TAG = "error-tag";
- public static final String ERROR_SEVERITY = "error-severity";
- public static final String ERROR_APP_TAG = "error-app-tag";
- public static final String ERROR_PATH = "error-path";
- public static final String ERROR_MESSAGE = "error-message";
- public static final String ERROR_INFO = "error-info";
- public static final String NAME_KEY = "name";
public static final String NOTIFICATION_ELEMENT_NAME = "notification";
- public static final String PREFIX = "prefix";
-
public static final String MESSAGE_ID = "message-id";
public static final String SESSION_ID = "session-id";
- //
- // TODO duplicate
- public static final String RFC4741_TARGET_NAMESPACE = "urn:ietf:params:xml:ns:netconf:base:1.0";
- public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = "urn:ietf:params:xml:ns:netconf:base:1.0";
-// public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_1 = "urn:ietf:params:xml:ns:netconf:base:1.1";
+ public static final String GET = "get";
+ public static final String GET_CONFIG = "get-config";
+
+ public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
public static final String URN_IETF_PARAMS_NETCONF_BASE_1_0 = "urn:ietf:params:netconf:base:1.0";
public static final String URN_IETF_PARAMS_NETCONF_BASE_1_1 = "urn:ietf:params:netconf:base:1.1";
public static final String URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0 = "urn:ietf:params:xml:ns:netconf:exi:1.0";
public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0 = "urn:ietf:params:netconf:capability:exi:1.0";
public static final String URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
- // TODO where to store namespace of config ?
- public static final String URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG = "urn:opendaylight:params:xml:ns:yang:controller:config";
- public static final String GET = "get";
- public static final String GET_CONFIG = "get-config";
}
import javax.xml.xpath.XPathFactory;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@Test
public void testToAndFromXMLDocument() throws XPathExpressionException {
String errorMessage = "mock error message";
- NetconfDocumentedException ex = new NetconfDocumentedException( errorMessage, null,
- ErrorType.protocol,
- ErrorTag.data_exists,
- ErrorSeverity.warning,
+ DocumentedException ex = new NetconfDocumentedException( errorMessage, null,
+ DocumentedException.ErrorType.protocol,
+ DocumentedException.ErrorTag.data_exists,
+ DocumentedException.ErrorSeverity.warning,
ImmutableMap.of( "foo", "bar" ) );
Document doc = ex.toXMLDocument();
Node errorTypeNode = getNode( "netconf:error-type", rpcErrorNode );
assertNotNull( "error-type not found", errorTypeNode );
- assertEquals( "error-type", ErrorType.protocol.getTagValue(),
+ assertEquals( "error-type", DocumentedException.ErrorType.protocol.getTagValue(),
errorTypeNode.getTextContent() );
Node errorTagNode = getNode( "netconf:error-tag", rpcErrorNode );
assertNotNull( "error-tag not found", errorTagNode );
- assertEquals( "error-tag", ErrorTag.data_exists.getTagValue(),
+ assertEquals( "error-tag", DocumentedException.ErrorTag.data_exists.getTagValue(),
errorTagNode.getTextContent() );
Node errorSeverityNode = getNode( "netconf:error-severity", rpcErrorNode );
assertNotNull( "error-severity not found", errorSeverityNode );
- assertEquals( "error-severity", ErrorSeverity.warning.getTagValue(),
+ assertEquals( "error-severity", DocumentedException.ErrorSeverity.warning.getTagValue(),
errorSeverityNode.getTextContent() );
Node errorInfoNode = getNode( "netconf:error-info/netconf:foo", rpcErrorNode );
// Test fromXMLDocument
- ex = NetconfDocumentedException.fromXMLDocument( doc );
+ ex = DocumentedException.fromXMLDocument( doc );
assertNotNull( "NetconfDocumentedException is null", ex );
- assertEquals( "getErrorSeverity", ErrorSeverity.warning, ex.getErrorSeverity() );
- assertEquals( "getErrorTag", ErrorTag.data_exists, ex.getErrorTag() );
- assertEquals( "getErrorType", ErrorType.protocol, ex.getErrorType() );
+ assertEquals( "getErrorSeverity", DocumentedException.ErrorSeverity.warning, ex.getErrorSeverity() );
+ assertEquals( "getErrorTag", DocumentedException.ErrorTag.data_exists, ex.getErrorTag() );
+ assertEquals( "getErrorType", DocumentedException.ErrorType.protocol, ex.getErrorType() );
assertEquals( "getLocalizedMessage", errorMessage, ex.getLocalizedMessage() );
assertEquals( "getErrorInfo", ImmutableMap.of( "foo", "bar" ), ex.getErrorInfo() );
}
<version>0.4.0-SNAPSHOT</version>
<packaging>pom</packaging>
+ <properties>
+ <mdsal.version>1.3.0-SNAPSHOT</mdsal.version>
+ </properties>
+
<dependencyManagement>
<dependencies>
<dependency>
<artifactId>mdsal-netconf-monitoring</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>mdsal-netconf-monitoring</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-netty-util</artifactId>
<artifactId>netconf-util</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>netconf-mdsal-config</artifactId>
+ <version>${project.version}</version>
+ <classifier>config</classifier>
+ <type>xml</type>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>sal-netconf-connector</artifactId>
+ <version>${mdsal.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>features-netconf-connector</artifactId>
+ <version>${mdsal.version}</version>
+ <classifier>features</classifier>
+ <type>xml</type>
+ <scope>runtime</scope>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
import java.util.Collection;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfClientSessionPreferences;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
import org.opendaylight.controller.netconf.util.xml.XMLNetconfUtil;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-plugin-parent</artifactId>
- <version>0.4.0-SNAPSHOT</version>
- <relativePath>../config-plugin-parent</relativePath>
- </parent>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </parent>
<artifactId>netconf-config-dispatcher</artifactId>
<packaging>bundle</packaging>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Export-Package>org.opendaylight.controller.config.yang.config.netconf,
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.netconf.rev140408,</Export-Package>
- <Import-Package>*</Import-Package>
- </instructions>
- </configuration>
</plugin>
- <plugin>
+ <plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- </plugin>
+ </plugin>
</plugins>
</build>
</project>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-mapping-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-notifications-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-notifications-impl</artifactId>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-netty-util</artifactId>
<artifactId>ietf-inet-types</artifactId>
</dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
import org.opendaylight.controller.config.api.JmxAttributeValidationException;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.impl.CommitNotifier;
import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
import org.opendaylight.controller.netconf.impl.SessionIdProvider;
final AggregatedNetconfOperationServiceFactory aggregatedOpProvider = getAggregatedOpProvider();
final NetconfMonitoringService monitoringService = getServerMonitorDependency();
final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
- getTimerDependency(), aggregatedOpProvider, new SessionIdProvider(), getConnectionTimeoutMillis(), CommitNotifier.NoopCommitNotifier.getInstance(), monitoringService);
+ getTimerDependency(), aggregatedOpProvider, new SessionIdProvider(), getConnectionTimeoutMillis(), monitoringService);
final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
serverNegotiatorFactory);
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl;
-
-import java.util.Set;
-import org.w3c.dom.Element;
-
-public interface CommitNotifier {
- void sendCommitNotification(String message, Element cfgSnapshot, Set<String> capabilities);
-
- public static final class NoopCommitNotifier implements CommitNotifier {
-
- private static final CommitNotifier INSTANCE = new NoopCommitNotifier();
-
- private NoopCommitNotifier() {}
-
- public static CommitNotifier getInstance() {
- return INSTANCE;
- }
-
- @Override
- public void sendCommitNotification(final String message, final Element cfgSnapshot, final Set<String> capabilities) {
- // NOOP
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl;
-
-import java.util.Set;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.NotCompliantMBeanException;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.ObjectName;
-import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
-import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
-import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-
-public class DefaultCommitNotificationProducer extends NotificationBroadcasterSupport implements
- DefaultCommitOperationMXBean, AutoCloseable, CommitNotifier {
-
- private static final Logger LOG = LoggerFactory.getLogger(DefaultCommitNotificationProducer.class);
-
- private final MBeanServer mbeanServer;
-
- private final ObjectName on = DefaultCommitOperationMXBean.OBJECT_NAME;
-
- public DefaultCommitNotificationProducer(MBeanServer mBeanServer) {
- this.mbeanServer = mBeanServer;
- LOG.debug("Registering to JMX under {}", on);
- registerMBean(this, mbeanServer, on);
- }
-
- private static void registerMBean(final Object instance, final MBeanServer mbs, final ObjectName on) {
- try {
- mbs.registerMBean(instance, on);
- } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
- throw new IllegalStateException("Unable to register " + instance + " as " + on, e);
- }
- }
-
- @Override
- public void sendCommitNotification(String message, Element cfgSnapshot, Set<String> capabilities) {
- CommitJMXNotification notif = NetconfJMXNotification.afterCommit(this, message, cfgSnapshot, capabilities);
- LOG.debug("Notification about commit {} sent", notif);
- sendNotification(notif);
- }
-
- @Override
- public void close() {
- try {
- mbeanServer.unregisterMBean(on);
- } catch (InstanceNotFoundException | MBeanRegistrationException e) {
- LOG.warn("Ignoring exception while unregistering {} as {}", this, on, e);
- }
- }
-}
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfSessionListener;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.util.messages.SendErrorExceptionUtil;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
LOG.error("Unexpected exception", e);
session.onIncommingRpcFail();
throw new IllegalStateException("Unable to process incoming message " + netconfMessage, e);
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
LOG.trace("Error occurred while processing message",e);
session.onOutgoingRpcError();
session.onIncommingRpcFail();
}
private NetconfMessage processDocument(final NetconfMessage netconfMessage, final NetconfServerSession session)
- throws NetconfDocumentedException {
+ throws DocumentedException {
final Document incomingDocument = netconfMessage.getDocument();
final Node rootNode = incomingDocument.getDocumentElement();
* unexpected element Description: An unexpected element is present.
*/
// TODO add message to error info
- throw new NetconfDocumentedException("Unknown tag " + rootNode.getNodeName(),
- NetconfDocumentedException.ErrorType.protocol, NetconfDocumentedException.ErrorTag.unknown_element,
- NetconfDocumentedException.ErrorSeverity.error, ImmutableMap.of("bad-element",
+ throw new DocumentedException("Unknown tag " + rootNode.getNodeName(),
+ DocumentedException.ErrorType.protocol, DocumentedException.ErrorTag.unknown_element,
+ DocumentedException.ErrorSeverity.error, ImmutableMap.of("bad-element",
rootNode.getNodeName()));
}
}
- private static void checkMessageId(final Node rootNode) throws NetconfDocumentedException {
+ private static void checkMessageId(final Node rootNode) throws DocumentedException {
NamedNodeMap attributes = rootNode.getAttributes();
return;
}
- throw new NetconfDocumentedException("Missing attribute" + rootNode.getNodeName(),
- NetconfDocumentedException.ErrorType.protocol, NetconfDocumentedException.ErrorTag.missing_attribute,
- NetconfDocumentedException.ErrorSeverity.error,
- ImmutableMap.of(NetconfDocumentedException.ErrorTag.missing_attribute.toString(),
+ throw new DocumentedException("Missing attribute" + rootNode.getNodeName(),
+ DocumentedException.ErrorType.protocol, DocumentedException.ErrorTag.missing_attribute,
+ DocumentedException.ErrorSeverity.error,
+ ImmutableMap.of(DocumentedException.ErrorTag.missing_attribute.toString(),
XmlNetconfConstants.MESSAGE_ID));
}
}
package org.opendaylight.controller.netconf.impl;
+import com.google.common.base.Function;
import com.google.common.base.Preconditions;
+import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.netty.channel.Channel;
import org.opendaylight.controller.netconf.api.NetconfServerSessionPreferences;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCommit;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouterImpl;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.protocol.framework.SessionListenerFactory;
import org.opendaylight.protocol.framework.SessionNegotiator;
import org.opendaylight.protocol.framework.SessionNegotiatorFactory;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Capabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final SessionIdProvider idProvider;
private final NetconfOperationServiceFactory aggregatedOpService;
private final long connectionTimeoutMillis;
- private final CommitNotifier commitNotificationProducer;
private final NetconfMonitoringService monitoringService;
private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
private final Set<String> baseCapabilities;
// TODO too many params, refactor
public NetconfServerSessionNegotiatorFactory(final Timer timer, final NetconfOperationServiceFactory netconfOperationProvider,
final SessionIdProvider idProvider, final long connectionTimeoutMillis,
- final CommitNotifier commitNot,
final NetconfMonitoringService monitoringService) {
- this(timer, netconfOperationProvider, idProvider, connectionTimeoutMillis, commitNot, monitoringService, DEFAULT_BASE_CAPABILITIES);
+ this(timer, netconfOperationProvider, idProvider, connectionTimeoutMillis, monitoringService, DEFAULT_BASE_CAPABILITIES);
}
// TODO too many params, refactor
public NetconfServerSessionNegotiatorFactory(final Timer timer, final NetconfOperationServiceFactory netconfOperationProvider,
final SessionIdProvider idProvider, final long connectionTimeoutMillis,
- final CommitNotifier commitNot,
final NetconfMonitoringService monitoringService, final Set<String> baseCapabilities) {
this.timer = timer;
this.aggregatedOpService = netconfOperationProvider;
this.idProvider = idProvider;
this.connectionTimeoutMillis = connectionTimeoutMillis;
- this.commitNotificationProducer = commitNot;
this.monitoringService = monitoringService;
this.baseCapabilities = validateBaseCapabilities(baseCapabilities);
}
final NetconfOperationService service =
this.aggregatedOpService.createService(netconfSessionIdForReporting);
final NetconfOperationRouter operationRouter =
- new NetconfOperationRouterImpl(service, commitNotificationProducer, monitoringService, netconfSessionIdForReporting);
+ new NetconfOperationRouterImpl(service, monitoringService, netconfSessionIdForReporting);
return new NetconfServerSessionListener(operationRouter, monitoringService, service);
}
private NetconfHelloMessage createHelloMessage(final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
- return NetconfHelloMessage.createServerHello(Sets.union(DefaultCommit.transformCapabilities(capabilityProvider.getCapabilities()), baseCapabilities), sessionId);
+ return NetconfHelloMessage.createServerHello(Sets.union(transformCapabilities(capabilityProvider.getCapabilities()), baseCapabilities), sessionId);
+ }
+
+ public static Set<String> transformCapabilities(final Capabilities capabilities) {
+ return Sets.newHashSet(Collections2.transform(capabilities.getCapability(), new Function<Uri, String>() {
+ @Override
+ public String apply(final Uri uri) {
+ return uri.getValue();
+ }
+ }));
}
}
import com.google.common.base.Optional;
import java.io.IOException;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation.OperationNameAndNamespace;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
public class SubtreeFilter {
private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
- static Document applySubtreeFilter(Document requestDocument, Document rpcReply) throws NetconfDocumentedException {
+ static Document applySubtreeFilter(Document requestDocument, Document rpcReply) throws DocumentedException {
OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument);
if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace()) &&
XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName()) ||
rpcReply = XmlUtil.readXmlToDocument(XmlUtil.toString(rpcReply, true));
} catch (SAXException | IOException e) {
LOG.error("Cannot transform document", e);
- throw new NetconfDocumentedException("Cannot transform document" + e);
+ throw new DocumentedException("Cannot transform document" + e);
}
XmlElement filter = maybeFilter.get();
if ("subtree".equals(filter.getAttribute("type"))||
return rpcReply; // return identical document
}
- private static Document filtered(XmlElement filter, Document originalReplyDocument) throws NetconfDocumentedException {
+ private static Document filtered(XmlElement filter, Document originalReplyDocument) throws DocumentedException {
Document result = XmlUtil.newDocument();
// even if filter is empty, copy /rpc/data
Element rpcReply = originalReplyDocument.getDocumentElement();
Node rpcReplyDst = result.importNode(rpcReply, false);
result.appendChild(rpcReplyDst);
- XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data", XmlNetconfConstants.RFC4741_TARGET_NAMESPACE);
+ XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
rpcReplyDst.appendChild(dataDst);
addSubtree(filter, dataSrc, XmlElement.fromDomElement(dataDst));
return result;
}
- private static void addSubtree(XmlElement filter, XmlElement src, XmlElement dst) throws NetconfDocumentedException {
+ private static void addSubtree(XmlElement filter, XmlElement src, XmlElement dst) throws DocumentedException {
for (XmlElement srcChild : src.getChildElements()) {
for (XmlElement filterChild : filter.getChildElements()) {
addSubtree2(filterChild, srcChild, dst);
}
}
- private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) throws NetconfDocumentedException {
+ private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) throws DocumentedException {
Document document = dstParent.getDomElement().getOwnerDocument();
MatchingResult matches = matches(src, filter);
if (matches != MatchingResult.NO_MATCH && matches != MatchingResult.CONTENT_MISMATCH) {
* Shallow compare src node to filter: tag name and namespace must match.
* If filter node has no children and has text content, it also must match.
*/
- private static MatchingResult matches(XmlElement src, XmlElement filter) throws NetconfDocumentedException {
+ private static MatchingResult matches(XmlElement src, XmlElement filter) throws DocumentedException {
boolean tagMatch = src.getName().equals(filter.getName()) &&
src.getNamespaceOptionally().equals(filter.getNamespaceOptionally());
MatchingResult result = null;
return result;
}
- private static boolean prefixedContentMatches(final XmlElement filter, final XmlElement src) throws NetconfDocumentedException {
+ private static boolean prefixedContentMatches(final XmlElement filter, final XmlElement src) throws DocumentedException {
final Map.Entry<String, String> prefixToNamespaceOfFilter;
final Map.Entry<String, String> prefixToNamespaceOfSrc;
try {
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import java.util.Collections;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
*/
@Override
protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement)
- throws NetconfDocumentedException {
+ throws DocumentedException {
try {
sessionResources.close();
Preconditions.checkNotNull(session, "Session was not set").delayedClose();
LOG.info("Session {} closing", session.getSessionId());
} catch (Exception e) {
- throw new NetconfDocumentedException("Unable to properly close session "
- + getNetconfSessionIdForReporting(), NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error, Collections.singletonMap(
- NetconfDocumentedException.ErrorSeverity.error.toString(), e.getMessage()));
+ throw new DocumentedException("Unable to properly close session "
+ + getNetconfSessionIdForReporting(), DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error, Collections.singletonMap(
+ DocumentedException.ErrorSeverity.error.toString(), e.getMessage()));
}
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl.mapping.operations;
-
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Sets;
-import java.io.InputStream;
-import java.util.Set;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.impl.CommitNotifier;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
-import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Capabilities;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class DefaultCommit extends AbstractNetconfOperation {
-
- private static final Logger LOG = LoggerFactory.getLogger(DefaultCommit.class);
-
- private static final String NOTIFY_ATTR = "notify";
-
- //TODO make commit notification optional
- private final CommitNotifier notificationProducer;
- private final NetconfMonitoringService cap;
- private final NetconfOperationRouter operationRouter;
-
- public DefaultCommit(final CommitNotifier notifier, final NetconfMonitoringService cap,
- final String netconfSessionIdForReporting, final NetconfOperationRouter netconfOperationRouter) {
- super(netconfSessionIdForReporting);
- this.notificationProducer = notifier;
- this.cap = cap;
- this.operationRouter = netconfOperationRouter;
- this.getConfigMessage = loadGetConfigMessage();
- }
-
- private final Document getConfigMessage;
- public static final String GET_CONFIG_CANDIDATE_XML_LOCATION = "/getConfig_candidate.xml";
-
- private static Document loadGetConfigMessage() {
- try (InputStream asStream = DefaultCommit.class.getResourceAsStream(GET_CONFIG_CANDIDATE_XML_LOCATION)) {
- return XmlUtil.readXmlToDocument(asStream);
- } catch (Exception e) {
- throw new IllegalStateException("Unable to load getConfig message for notifications from "
- + GET_CONFIG_CANDIDATE_XML_LOCATION);
- }
- }
-
- @Override
- protected String getOperationName() {
- return XmlNetconfConstants.COMMIT;
- }
-
- @Override
- public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
- Preconditions.checkArgument(!subsequentOperation.isExecutionTermination(),
- "Subsequent netconf operation expected by %s", this);
-
- if (isCommitWithoutNotification(requestMessage)) {
- LOG.debug("Skipping commit notification");
- } else {
- // Send commit notification if commit was not issued by persister
- removePersisterAttributes(requestMessage);
- Element cfgSnapshot = getConfigSnapshot(operationRouter);
- LOG.debug("Config snapshot retrieved successfully {}", cfgSnapshot);
- notificationProducer.sendCommitNotification("ok", cfgSnapshot, transformCapabilities(cap.getCapabilities()));
- }
-
- return subsequentOperation.execute(requestMessage);
- }
-
- // FIXME move somewhere to util since this is required also by negotiatiorFactory
- public static Set<String> transformCapabilities(final Capabilities capabilities) {
- return Sets.newHashSet(Collections2.transform(capabilities.getCapability(), new Function<Uri, String>() {
- @Override
- public String apply(final Uri uri) {
- return uri.getValue();
- }
- }));
- }
-
- @Override
- protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
- throw new UnsupportedOperationException("Never gets called");
- }
-
- @Override
- protected HandlingPriority getHandlingPriority() {
- return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.increasePriority(1);
- }
-
- private static void removePersisterAttributes(final Document message) {
- message.getDocumentElement().removeAttribute(NOTIFY_ATTR);
- }
-
- private static boolean isCommitWithoutNotification(final Document message) {
- XmlElement xmlElement = null;
- try {
- xmlElement = XmlElement.fromDomElementWithExpected(message.getDocumentElement(),
- XmlNetconfConstants.RPC_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- } catch (NetconfDocumentedException e) {
- LOG.trace("Commit operation is not valid due to ",e);
- return false;
- }
-
- String attr = xmlElement.getAttribute(NOTIFY_ATTR);
-
- if (attr == null || attr.equals("")){
- return false;
- } else if (attr.equals(Boolean.toString(false))) {
- LOG.debug("Commit operation received with notify=false attribute {}", message);
- return true;
- } else {
- return false;
- }
- }
-
- private Element getConfigSnapshot(final NetconfOperationRouter opRouter) throws NetconfDocumentedException {
- final Document responseDocument = opRouter.onNetconfMessage(
- getConfigMessage, null);
-
- XmlElement dataElement;
- XmlElement xmlElement = XmlElement.fromDomElementWithExpected(responseDocument.getDocumentElement(),
- XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
- dataElement = xmlElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY);
- return dataElement.getDomElement();
- }
-
-}
*/
package org.opendaylight.controller.netconf.impl.mapping.operations;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
+import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
+
public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation {
public static final String START_EXI = "start-exi";
@Override
public Document handle(final Document message,
- final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
if (LOG.isDebugEnabled()) {
LOG.debug("Received start-exi message {} ", XmlUtil.toString(message));
}
try {
netconfSession.startExiCommunication(new NetconfMessage(message));
} catch (IllegalArgumentException e) {
- throw new NetconfDocumentedException("Failed to parse EXI parameters", ErrorType.protocol,
+ throw new DocumentedException("Failed to parse EXI parameters", ErrorType.protocol,
ErrorTag.operation_failed, ErrorSeverity.error);
}
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
LOG.trace("{} operation successful", START_EXI);
return getSchemaResult;
*/
package org.opendaylight.controller.netconf.impl.mapping.operations;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException {
LOG.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
netconfSession.stopExiCommunication();
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactoryListener;
import org.opendaylight.controller.netconf.util.CloseableUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* NetconfOperationService aggregator. Makes a collection of operation services accessible as one.
*/
public class AggregatedNetconfOperationServiceFactory implements NetconfOperationServiceFactory, NetconfOperationServiceFactoryListener, AutoCloseable {
+ private static final Logger LOG = LoggerFactory.getLogger(AggregatedNetconfOperationServiceFactory.class);
+
private final Set<NetconfOperationServiceFactory> factories = new HashSet<>();
private final Multimap<NetconfOperationServiceFactory, AutoCloseable> registrations = HashMultimap.create();
private final Set<CapabilityListener> listeners = Sets.newHashSet();
try {
autoCloseable.close();
} catch (Exception e) {
- // FIXME Issue warning
+ LOG.warn("Unable to close listener registration", e);
}
}
import io.netty.channel.local.LocalAddress;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
-import java.lang.management.ManagementFactory;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
import org.opendaylight.controller.netconf.impl.SessionIdProvider;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactoryListener;
+import org.opendaylight.controller.netconf.notifications.BaseNotificationPublisherRegistration;
+import org.opendaylight.controller.netconf.notifications.NetconfNotificationCollector;
import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
+import org.osgi.util.tracker.ServiceTracker;
+import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(NetconfImplActivator.class);
private NetconfOperationServiceFactoryTracker factoriesTracker;
- private DefaultCommitNotificationProducer commitNot;
private NioEventLoopGroup eventLoopGroup;
private HashedWheelTimer timer;
private ServiceRegistration<NetconfMonitoringService> regMonitoring;
+ private BaseNotificationPublisherRegistration listenerReg;
+
@Override
public void start(final BundleContext context) {
-
- AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
- startOperationServiceFactoryTracker(context, factoriesListener);
-
- SessionIdProvider idProvider = new SessionIdProvider();
- timer = new HashedWheelTimer();
- long connectionTimeoutMillis = NetconfConfigUtil.extractTimeoutMillis(context);
-
-
- commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
-
- NetconfMonitoringService monitoringService = startMonitoringService(context, factoriesListener);
-
- NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
- timer, factoriesListener, idProvider, connectionTimeoutMillis, commitNot, monitoringService);
-
- eventLoopGroup = new NioEventLoopGroup();
-
- NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
- serverNegotiatorFactory);
- NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, eventLoopGroup, eventLoopGroup);
-
- LocalAddress address = NetconfConfigUtil.getNetconfLocalAddress();
- LOG.trace("Starting local netconf server at {}", address);
- dispatch.createLocalServer(address);
+ try {
+ AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
+ startOperationServiceFactoryTracker(context, factoriesListener);
+
+ SessionIdProvider idProvider = new SessionIdProvider();
+ timer = new HashedWheelTimer();
+ long connectionTimeoutMillis = NetconfConfigUtil.extractTimeoutMillis(context);
+
+ final NetconfMonitoringServiceImpl monitoringService = startMonitoringService(context, factoriesListener);
+
+ NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
+ timer, factoriesListener, idProvider, connectionTimeoutMillis, monitoringService);
+
+ eventLoopGroup = new NioEventLoopGroup();
+
+ NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
+ serverNegotiatorFactory);
+ NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, eventLoopGroup, eventLoopGroup);
+
+ LocalAddress address = NetconfConfigUtil.getNetconfLocalAddress();
+ LOG.trace("Starting local netconf server at {}", address);
+ dispatch.createLocalServer(address);
+
+ final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector> notificationServiceTracker =
+ new ServiceTracker<>(context, NetconfNotificationCollector.class, new ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>() {
+ @Override
+ public NetconfNotificationCollector addingService(ServiceReference<NetconfNotificationCollector> reference) {
+ listenerReg = context.getService(reference).registerBaseNotificationPublisher();
+ monitoringService.setNotificationPublisher(listenerReg);
+ return null;
+ }
+
+ @Override
+ public void modifiedService(ServiceReference<NetconfNotificationCollector> reference, NetconfNotificationCollector service) {
+
+ }
+
+ @Override
+ public void removedService(ServiceReference<NetconfNotificationCollector> reference, NetconfNotificationCollector service) {
+ listenerReg.close();
+ listenerReg = null;
+ monitoringService.setNotificationPublisher(listenerReg);
+ }
+ });
+ notificationServiceTracker.open();
+ } catch (Exception e) {
+ LOG.warn("Unable to start NetconfImplActivator", e);
+ }
}
private void startOperationServiceFactoryTracker(BundleContext context, NetconfOperationServiceFactoryListener factoriesListener) {
public void stop(final BundleContext context) {
LOG.info("Shutting down netconf because YangStoreService service was removed");
- commitNot.close();
eventLoopGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS);
timer.stop();
import io.netty.util.internal.ConcurrentSet;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.BasicCapability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
+import org.opendaylight.controller.netconf.notifications.BaseNotificationPublisherRegistration;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfStateBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.SchemaBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.SchemaKey;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.sessions.Session;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChangeBuilder;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.changed.by.parms.ChangedByBuilder;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.changed.by.parms.changed.by.server.or.user.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final Map<Uri, Capability> capabilities = new ConcurrentHashMap<>();
private final Set<MonitoringListener> listeners = Sets.newHashSet();
+ private volatile BaseNotificationPublisherRegistration notificationPublisher;
public NetconfMonitoringServiceImpl(final NetconfOperationServiceFactory netconfOperationProvider) {
this.netconfOperationProvider = netconfOperationProvider;
return b.build();
}
+ public static Set<Capability> setupCapabilities(final Set<Capability> caps) {
+ Set<Capability> capabilities = new HashSet<>(caps);
+ capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+ // TODO rollback on error not supported EditConfigXmlParser:100
+ // [RFC6241] 8.5. Rollback-on-Error Capability
+ // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
+ return capabilities;
+ }
+
@Override
- public synchronized void onCapabilitiesAdded(final Set<Capability> addedCaps) {
- // FIXME howto check for duplicates
- this.capabilities.putAll(Maps.uniqueIndex(addedCaps, CAPABILITY_TO_URI));
+ public synchronized void close() throws Exception {
+ listeners.clear();
+ sessions.clear();
+ capabilities.clear();
+ }
+
+ @Override
+ public void onCapabilitiesChanged(Set<Capability> added, Set<Capability> removed) {
+ onCapabilitiesAdded(added);
+ onCapabilitiesRemoved(removed);
notifyListeners();
+
+ // publish notification to notification collector about changed capabilities
+ if (notificationPublisher != null) {
+ notificationPublisher.onCapabilityChanged(computeDiff(added, removed));
+ }
+ }
+
+ static NetconfCapabilityChange computeDiff(final Set<Capability> removed, final Set<Capability> added) {
+ final NetconfCapabilityChangeBuilder netconfCapabilityChangeBuilder = new NetconfCapabilityChangeBuilder();
+ netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build()).build());
+ netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2.transform(removed, CAPABILITY_TO_URI)));
+ netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2.transform(added, CAPABILITY_TO_URI)));
+ // TODO modified should be computed ... but why ?
+ netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
+ return netconfCapabilityChangeBuilder.build();
+ }
+
+
+ private synchronized void onCapabilitiesAdded(final Set<Capability> addedCaps) {
+ // FIXME howto check for duplicates
+ this.capabilities.putAll(Maps.uniqueIndex(setupCapabilities(addedCaps), CAPABILITY_TO_URI));
}
private void notifyListeners() {
}
}
- @Override
- public synchronized void onCapabilitiesRemoved(final Set<Capability> addedCaps) {
+ private synchronized void onCapabilitiesRemoved(final Set<Capability> addedCaps) {
for (final Capability addedCap : addedCaps) {
- capabilities.remove(addedCap.getCapabilityUri());
+ capabilities.remove(CAPABILITY_TO_URI.apply(addedCap));
}
- notifyListeners();
}
- @Override
- public synchronized void close() throws Exception {
- listeners.clear();
- sessions.clear();
- capabilities.clear();
+ public void setNotificationPublisher(final BaseNotificationPublisherRegistration notificationPublisher) {
+ this.notificationPublisher = notificationPublisher;
}
}
package org.opendaylight.controller.netconf.impl.osgi;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.w3c.dom.Document;
public interface NetconfOperationRouter extends AutoCloseable {
Document onNetconfMessage(Document message, NetconfServerSession session)
- throws NetconfDocumentedException;
+ throws DocumentedException;
}
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.impl.CommitNotifier;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
-import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCommit;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultNetconfOperation;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStartExi;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultStopExi;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.controller.netconf.mapping.api.SessionAwareNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
private final Collection<NetconfOperation> allNetconfOperations;
public NetconfOperationRouterImpl(final NetconfOperationService netconfOperationServiceSnapshot,
- final CommitNotifier commitNotifier, final NetconfMonitoringService netconfMonitoringService, final String sessionId) {
+ final NetconfMonitoringService netconfMonitoringService, final String sessionId) {
this.netconfOperationServiceSnapshot = Preconditions.checkNotNull(netconfOperationServiceSnapshot);
final Set<NetconfOperation> ops = new HashSet<>();
ops.add(new DefaultCloseSession(sessionId, this));
ops.add(new DefaultStartExi(sessionId));
ops.add(new DefaultStopExi(sessionId));
- ops.add(new DefaultCommit(commitNotifier, netconfMonitoringService, sessionId, this));
ops.addAll(netconfOperationServiceSnapshot.getNetconfOperations());
}
@Override
- public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws NetconfDocumentedException {
+ public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws DocumentedException {
Preconditions.checkNotNull(allNetconfOperations, "Operation router was not initialized properly");
final NetconfOperationExecution netconfOperationExecution;
final String messageAsString = XmlUtil.toString(message);
LOG.warn("Unable to handle rpc {} on session {}", messageAsString, session, e);
- final NetconfDocumentedException.ErrorTag tag;
+ final DocumentedException.ErrorTag tag;
if (e instanceof IllegalArgumentException) {
- tag = NetconfDocumentedException.ErrorTag.operation_not_supported;
+ tag = DocumentedException.ErrorTag.operation_not_supported;
} else {
- tag = NetconfDocumentedException.ErrorTag.operation_failed;
+ tag = DocumentedException.ErrorTag.operation_failed;
}
- throw new NetconfDocumentedException(
+ throw new DocumentedException(
String.format("Unable to handle rpc %s on session %s", messageAsString, session),
- e, NetconfDocumentedException.ErrorType.application,
- tag, NetconfDocumentedException.ErrorSeverity.error,
+ e, DocumentedException.ErrorType.application,
+ tag, DocumentedException.ErrorSeverity.error,
Collections.singletonMap(tag.toString(), e.getMessage()));
} catch (RuntimeException e) {
throw handleUnexpectedEx("Unexpected exception during netconf operation sort", e);
netconfOperationServiceSnapshot.close();
}
- private static NetconfDocumentedException handleUnexpectedEx(final String s, final Exception e) throws NetconfDocumentedException {
+ private static DocumentedException handleUnexpectedEx(final String s, final Exception e) throws DocumentedException {
LOG.error("{}", s, e);
- return new NetconfDocumentedException("Unexpected error",
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error,
- Collections.singletonMap(NetconfDocumentedException.ErrorSeverity.error.toString(), e.toString()));
+ return new DocumentedException("Unexpected error",
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error,
+ Collections.singletonMap(DocumentedException.ErrorSeverity.error.toString(), e.toString()));
}
private Document executeOperationWithHighestPriority(final Document message,
final NetconfOperationExecution netconfOperationExecution)
- throws NetconfDocumentedException {
+ throws DocumentedException {
if (LOG.isDebugEnabled()) {
LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution.netconfOperation);
}
}
private NetconfOperationExecution getNetconfOperationWithHighestPriority(
- final Document message, final NetconfServerSession session) throws NetconfDocumentedException {
+ final Document message, final NetconfServerSession session) throws DocumentedException {
NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
message, session);
}
private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(final Document message,
- final NetconfServerSession session) throws NetconfDocumentedException {
+ final NetconfServerSession session) throws DocumentedException {
TreeMap<HandlingPriority, NetconfOperation> sortedPriority = Maps.newTreeMap();
for (NetconfOperation netconfOperation : allNetconfOperations) {
}
@Override
- public Document execute(final Document requestMessage) throws NetconfDocumentedException {
- throw new NetconfDocumentedException("This execution represents the termination point in operation execution and cannot be executed itself",
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ public Document execute(final Document requestMessage) throws DocumentedException {
+ throw new DocumentedException("This execution represents the termination point in operation execution and cannot be executed itself",
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
};
}
@Override
- public Document execute(final Document message) throws NetconfDocumentedException {
+ public Document execute(final Document message) throws DocumentedException {
return netconfOperation.handle(message, subsequentExecution);
}
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.netconf.util.messages.SendErrorExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Map<String, String> info = Maps.newHashMap();
info.put("cause", cause.getMessage());
- NetconfDocumentedException ex = new NetconfDocumentedException(cause.getMessage(),
- NetconfDocumentedException.ErrorType.rpc, NetconfDocumentedException.ErrorTag.malformed_message,
- NetconfDocumentedException.ErrorSeverity.error, info);
+ DocumentedException ex = new DocumentedException(cause.getMessage(),
+ DocumentedException.ErrorType.rpc, DocumentedException.ErrorTag.malformed_message,
+ DocumentedException.ErrorSeverity.error, info);
SendErrorExceptionUtil.sendErrorMessage(ctx.channel(), ex);
}
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import org.opendaylight.controller.netconf.api.Capability;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.protocol.framework.NeverReconnectStrategy;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.CapabilitiesBuilder;
private EventLoopGroup nettyGroup;
private NetconfClientDispatcher netconfClientDispatcher;
- private DefaultCommitNotificationProducer commitNot;
-
HashedWheelTimer hashedWheelTimer;
private TestingNetconfOperation testingNetconfOperation;
}
}).when(monitoring).registerListener(any(NetconfMonitoringService.MonitoringListener.class));
- doNothing().when(monitoring).onCapabilitiesAdded(anySetOf(Capability.class));
- doNothing().when(monitoring).onCapabilitiesRemoved(anySetOf(Capability.class));
+ doNothing().when(monitoring).onCapabilitiesChanged(anySetOf(Capability.class), anySetOf(Capability.class));
doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring).getCapabilities();
return monitoring;
}
SessionIdProvider idProvider = new SessionIdProvider();
NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
- hashedWheelTimer, factoriesListener, idProvider, 5000, commitNot, createMockedMonitoringService(), serverCaps);
-
- commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
+ hashedWheelTimer, factoriesListener, idProvider, 5000, createMockedMonitoringService(), serverCaps);
NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
final NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
@After
public void tearDown(){
- commitNot.close();
hashedWheelTimer.stop();
try {
nettyGroup.shutdownGracefully().get();
}
@Override
- public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
try {
LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
counter.getAndIncrement();
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.HashedWheelTimer;
-import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import org.junit.After;
import org.junit.Before;
private EventLoopGroup nettyGroup;
private NetconfServerDispatcherImpl dispatch;
- private DefaultCommitNotificationProducer commitNot;
private HashedWheelTimer hashedWheelTimer;
public void setUp() throws Exception {
nettyGroup = new NioEventLoopGroup();
- commitNot = new DefaultCommitNotificationProducer(
- ManagementFactory.getPlatformMBeanServer());
AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
SessionIdProvider idProvider = new SessionIdProvider();
hashedWheelTimer = new HashedWheelTimer();
NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
- hashedWheelTimer, factoriesListener, idProvider, 5000, commitNot, ConcurrentClientsTest.createMockedMonitoringService());
+ hashedWheelTimer, factoriesListener, idProvider, 5000, ConcurrentClientsTest.createMockedMonitoringService());
NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
@After
public void tearDown() throws Exception {
hashedWheelTimer.stop();
- commitNot.close();
nettyGroup.shutdownGracefully();
}
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
public class DefaultCloseSessionTest {
verify(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testDefaultCloseSession2() throws Exception {
AutoCloseable res = mock(AutoCloseable.class);
doThrow(NetconfDocumentedException.class).when(res).close();
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.netconf.impl.mapping.operations;
-
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anySetOf;
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import java.util.Collections;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
-import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
-import org.opendaylight.controller.netconf.impl.NetconfServerSession;
-import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
-import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.CapabilitiesBuilder;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-public class DefaultCommitTest {
-
- private NetconfOperationChainedExecution operation;
- private Document requestMessage;
- private NetconfOperationRouter router;
- private DefaultCommitNotificationProducer notifier;
- private NetconfMonitoringService cap;
- private DefaultCommit commit;
-
- @Before
- public void setUp() throws Exception {
- operation = mock(NetconfOperationChainedExecution.class);
- doReturn(XmlUtil.newDocument()).when(operation).execute(any(Document.class));
- router = mock(NetconfOperationRouter.class);
- doReturn(false).when(operation).isExecutionTermination();
- notifier = mock(DefaultCommitNotificationProducer.class);
- doNothing().when(notifier).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
- cap = mock(NetconfMonitoringService.class);
- doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(cap).getCapabilities();
- Document rpcData = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
- doReturn(rpcData).when(router).onNetconfMessage(any(Document.class), any(NetconfServerSession.class));
- commit = new DefaultCommit(notifier, cap, "", router);
- }
-
- @Test
- public void testHandleWithNotification() throws Exception {
- requestMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/commit.xml");
- commit.handle(requestMessage, operation);
- verify(operation, times(1)).execute(requestMessage);
- verify(notifier, times(1)).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
- }
-
- @Test
- public void testHandleWithoutNotification() throws Exception {
- requestMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/commit.xml");
- Element elem = requestMessage.getDocumentElement();
- elem.setAttribute("notify", "false");
- commit.handle(requestMessage, operation);
- verify(operation, times(1)).execute(requestMessage);
- verify(notifier, never()).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
- }
-
- @Test(expected = NetconfDocumentedException.class)
- public void testHandle() throws Exception {
- Document rpcData = XmlFileLoader.xmlFileToDocument("netconfMessages/get.xml");
- doReturn(rpcData).when(router).onNetconfMessage(any(Document.class), any(NetconfServerSession.class));
- requestMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/commit.xml");
- commit.handle(requestMessage, operation);
- }
-}
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
public class DefaultStopExiTest {
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>object-cache-guava</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>mockito-configuration</artifactId>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anySetOf;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
+
import com.google.common.io.ByteStreams;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
+import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
+import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
+import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
import org.opendaylight.controller.config.spi.ModuleFactory;
import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
-import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
-import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
import org.opendaylight.controller.netconf.impl.SessionIdProvider;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
-import org.opendaylight.controller.netconf.notifications.BaseNetconfNotificationListener;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
import org.opendaylight.protocol.framework.NeverReconnectStrategy;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
import org.opendaylight.yangtools.yang.binding.BindingMapping;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.w3c.dom.Element;
public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
new IdentityTestModuleFactory(),
new MultipleDependenciesModuleFactory() };
+ protected ConfigSubsystemFacadeFactory configSubsystemFacadeFactory;
private EventLoopGroup nettyThreadgroup;
private HashedWheelTimer hashedWheelTimer;
final AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
final NetconfMonitoringService netconfMonitoringService = getNetconfMonitoringService(factoriesListener);
- factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
+ configSubsystemFacadeFactory = new ConfigSubsystemFacadeFactory(configRegistryClient, configRegistryClient, getYangStore());
+ factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(configSubsystemFacadeFactory));
factoriesListener.onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(new NetconfMonitoringOperationService(netconfMonitoringService)));
for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories(factoriesListener)) {
}
private Channel startNetconfTcpServer(final AggregatedNetconfOperationServiceFactory listener, final NetconfMonitoringService monitoring) throws Exception {
- final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring, getNotificationProducer());
+ final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring);
final ChannelFuture s;
if(getTcpServerAddress() instanceof LocalAddress) {
return s.channel();
}
- protected DefaultCommitNotificationProducer getNotificationProducer() {
- final DefaultCommitNotificationProducer notificationProducer = mock(DefaultCommitNotificationProducer.class);
- doNothing().when(notificationProducer).close();
- doNothing().when(notificationProducer).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
- return notificationProducer;
- }
-
protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories(final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
return Collections.emptySet();
}
private HardcodedYangStoreService getYangStore() throws IOException {
final Collection<InputStream> yangDependencies = getBasicYangs();
- return new HardcodedYangStoreService(yangDependencies);
+ return new HardcodedYangStoreService(yangDependencies, getBindingRuntimeContext());
}
static Collection<InputStream> getBasicYangs() throws IOException {
}
protected NetconfServerDispatcherImpl createDispatcher(
- final AggregatedNetconfOperationServiceFactory factoriesListener, final NetconfMonitoringService sessionMonitoringService,
- final DefaultCommitNotificationProducer commitNotifier) {
+ final AggregatedNetconfOperationServiceFactory factoriesListener, final NetconfMonitoringService sessionMonitoringService) {
final SessionIdProvider idProvider = new SessionIdProvider();
final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
- hashedWheelTimer, factoriesListener, idProvider, SERVER_CONNECTION_TIMEOUT_MILLIS, commitNotifier, sessionMonitoringService);
+ hashedWheelTimer, factoriesListener, idProvider, SERVER_CONNECTION_TIMEOUT_MILLIS, sessionMonitoringService);
final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
serverNegotiatorFactory);
}
public static final class HardcodedYangStoreService extends YangStoreService {
- public HardcodedYangStoreService(final Collection<? extends InputStream> inputStreams) throws IOException {
+ public HardcodedYangStoreService(final Collection<? extends InputStream> inputStreams, final BindingRuntimeContext bindingRuntimeContext) throws IOException {
super(new SchemaContextProvider() {
@Override
public SchemaContext getSchemaContext() {
return getSchema(inputStreams);
}
- }, new BaseNetconfNotificationListener() {
- @Override
- public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
- // NOOP
- }
});
+
+ refresh(bindingRuntimeContext);
}
private static SchemaContext getSchema(final Collection<? extends InputStream> inputStreams) {
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.opendaylight.controller.config.util.xml.XmlUtil.readXmlToDocument;
import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithName;
import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertElementsCount;
-import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToDocument;
+import com.google.common.collect.HashBiMap;
import com.google.common.collect.Lists;
import java.io.IOException;
-import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.opendaylight.controller.config.api.jmx.notifications.CommitJMXNotification;
+import org.opendaylight.controller.config.api.jmx.notifications.ConfigJMXNotification;
import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
import org.opendaylight.controller.config.persist.api.Persister;
+import org.opendaylight.controller.config.persist.impl.ConfigPersisterNotificationHandler;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
import org.opendaylight.controller.netconf.client.TestingNetconfClient;
-import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
-import org.opendaylight.controller.netconf.persist.impl.ConfigPersisterNotificationHandler;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
import org.w3c.dom.Document;
-import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
public static final int PORT = 12026;
private static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
-
@Override
protected SocketAddress getTcpServerAddress() {
return TCP_ADDRESS;
}
- @Override
- protected DefaultCommitNotificationProducer getNotificationProducer() {
- return new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
- }
-
@Test
public void testNetconfCommitNotifications() throws Exception {
final VerifyingNotificationListener notificationVerifier = createCommitNotificationListener();
try (TestingNetconfClient persisterClient = new TestingNetconfClient("persister", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) {
try (ConfigPersisterNotificationHandler configPersisterNotificationHandler = new ConfigPersisterNotificationHandler(
- platformMBeanServer, mockedAggregator)) {
+ platformMBeanServer, mockedAggregator, configSubsystemFacadeFactory)) {
try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", getClientDispatcher(), getClientConfiguration(TCP_ADDRESS, 4000))) {
- NetconfMessage response = netconfClient.sendMessage(loadGetConfigMessage());
- assertContainsElementWithName(response.getDocument(), "modules");
- assertContainsElementWithName(response.getDocument(), "services");
- response = netconfClient.sendMessage(loadCommitMessage());
- assertContainsElementWithName(response.getDocument(), "ok");
-
- response = netconfClient.sendMessage(loadEditConfigMessage());
+ NetconfMessage response = netconfClient.sendMessage(loadEditConfigMessage());
assertContainsElementWithName(response.getDocument(), "ok");
response = netconfClient.sendMessage(loadCommitMessage());
assertContainsElementWithName(response.getDocument(), "ok");
+
+ response = netconfClient.sendMessage(loadGetConfigMessage());
+ assertContainsElementWithName(response.getDocument(), "modules");
+ assertContainsElementWithName(response.getDocument(), "services");
}
}
}
- notificationVerifier.assertNotificationCount(2);
- notificationVerifier.assertNotificationContent(0, 0, 0, 8);
- notificationVerifier.assertNotificationContent(1, 4, 3, 8);
+ notificationVerifier.assertNotificationCount(1);
- mockedAggregator.assertSnapshotCount(2);
+ mockedAggregator.assertSnapshotCount(1);
// Capabilities are stripped for persister
- mockedAggregator.assertSnapshotContent(0, 0, 0, 1);
- mockedAggregator.assertSnapshotContent(1, 4, 3, 3);
+ mockedAggregator.assertSnapshotContent(0, 4, 3, 3);
+ }
+
+ @Override
+ protected BindingRuntimeContext getBindingRuntimeContext() {
+ final BindingRuntimeContext ret = super.getBindingRuntimeContext();
+ doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
+ doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
+ final HashBiMap<String, String> toBeReturned = HashBiMap.create();
+ toBeReturned.put("two", "Two");
+ toBeReturned.put("one", "One");
+ toBeReturned.put("version1", "Version1");
+ doReturn(toBeReturned).when(ret).getEnumMapping(anyString());
+ return ret;
}
private VerifyingPersister mockAggregator() throws IOException {
private VerifyingNotificationListener createCommitNotificationListener() throws InstanceNotFoundException {
final VerifyingNotificationListener listener = new VerifyingNotificationListener();
- platformMBeanServer.addNotificationListener(DefaultCommitNotificationProducer.OBJECT_NAME, listener, null, null);
+ platformMBeanServer.addNotificationListener(ConfigJMXNotification.OBJECT_NAME, listener, null, null);
return listener;
}
assertEquals(size, notifications.size());
}
- void assertNotificationContent(final int notificationIndex, final int expectedModulesSize, final int expectedServicesSize, final int expectedCapsSize) {
+ void assertNotificationContent(final int notificationIndex) {
final Notification notification = notifications.get(notificationIndex);
assertEquals(CommitJMXNotification.class, notification.getClass());
- final int capsSize = ((CommitJMXNotification) notification).getCapabilities().size();
- assertEquals("Expected capabilities count", expectedCapsSize, capsSize);
- final Element configSnapshot = ((CommitJMXNotification) notification).getConfigSnapshot();
- final int modulesSize = configSnapshot.getElementsByTagName("module").getLength();
- assertEquals("Expected modules count", expectedModulesSize, modulesSize);
- final int servicesSize = configSnapshot.getElementsByTagName("instance").getLength();
- assertEquals("Expected services count", expectedServicesSize, servicesSize);
}
}
throws SAXException, IOException {
final ConfigSnapshotHolder snapshot = snapshots.get(notificationIndex);
final int capsSize = snapshot.getCapabilities().size();
- assertEquals("Expected capabilities count", expectedCapsSize, capsSize);
+ assertEquals("Expected capabilities count should be " + expectedCapsSize + " but was " + snapshot.getCapabilities(), expectedCapsSize, capsSize);
final Document configSnapshot = readXmlToDocument(snapshot.getConfigSnapshot());
assertElementsCount(configSnapshot, "module", expectedModulesSize);
assertElementsCount(configSnapshot, "instance", expectedServicesSize);
import java.util.List;
import java.util.Set;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.client.TestingNetconfClient;
import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
public class NetconfITMonitoringTest extends AbstractNetconfConfigTest {
}
}
-
@Test(timeout = 13 * 10000)
public void testClientHelloWithAuth() throws Exception {
String fileName = "netconfMessages/client_hello_with_auth.xml";
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.auth.AuthProvider;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.RemoteDevice;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
import org.junit.Test;
import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
import org.opendaylight.controller.netconf.client.TestingNetconfClient;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
}
}
- private void assertIsOK(final Document rpcReply) throws NetconfDocumentedException {
+ private void assertIsOK(final Document rpcReply) throws DocumentedException {
assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
}
- private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
+ private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, DocumentedException {
return assertGetConfigWorks(netconfClient, getGetConfig());
}
private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
- throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
+ throws InterruptedException, ExecutionException, TimeoutException, DocumentedException {
final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
assertNotNull(rpcReply);
assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.netconf.it;
-
-import com.google.common.base.Preconditions;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManagerFactory;
-
-public final class SSLUtil {
-
- private SSLUtil() {}
-
- public static SSLContext initializeSecureContext(final String pass, final InputStream ksKeysFile, final InputStream ksTrustFile,
- final String algorithm) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
- UnrecoverableKeyException, KeyManagementException {
-
- Preconditions.checkNotNull(ksTrustFile, "ksTrustFile cannot be null");
- Preconditions.checkNotNull(ksKeysFile, "ksKeysFile cannot be null");
-
- final char[] passphrase = pass.toCharArray();
-
- // First initialize the key and trust material.
- final KeyStore ksKeys = KeyStore.getInstance("JKS");
- ksKeys.load(ksKeysFile, passphrase);
- final KeyStore ksTrust = KeyStore.getInstance("JKS");
- ksTrust.load(ksTrustFile, passphrase);
-
- // KeyManager's decide which key material to use.
- final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
- kmf.init(ksKeys, passphrase);
-
- // TrustManager's decide whether to allow connections.
- final TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
- tmf.init(ksTrust);
-
- final SSLContext sslContext = SSLContext.getInstance("TLS");
-
- // Create/initialize the SSLContext with key material
- sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
- return sslContext;
- }
-
-}
<groupId>${project.groupId}</groupId>
<artifactId>netconf-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
package org.opendaylight.controller.netconf.mapping.api;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.w3c.dom.Document;
/**
* @param requestMessage
* @return
*/
- HandlingPriority canHandle(Document message) throws NetconfDocumentedException;
+ HandlingPriority canHandle(Document message) throws DocumentedException;
/**
* Execute current netconf operation and trigger execution of subsequent
* @param subsequentOperation
* execution of subsequent netconf operation
* @return
- * @throws NetconfDocumentedException
+ * @throws DocumentedException
*/
Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation)
- throws NetconfDocumentedException;
+ throws DocumentedException;
}
*/
package org.opendaylight.controller.netconf.mapping.api;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.w3c.dom.Document;
/**
/**
* Do not execute if this is termination point
*/
- Document execute(Document requestMessage) throws NetconfDocumentedException;
+ Document execute(Document requestMessage) throws DocumentedException;
public static final NetconfOperationChainedExecution EXECUTION_TERMINATION_POINT = new NetconfOperationChainedExecution() {
@Override
}
@Override
- public Document execute(Document requestMessage) throws NetconfDocumentedException {
+ public Document execute(Document requestMessage) throws DocumentedException {
throw new IllegalStateException("This execution represents the termination point in operation execution and cannot be executed itself");
}
};
package org.opendaylight.controller.netconf.mapping.api;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
/**
public class HandlingPriorityTest {
- @Test
- public void testHandlingPriority() throws Exception {
-
-
- assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);
+ @Test public void testHandlingPriority() throws Exception {
+ assertTrue(
+ HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY)
+ == 0);
assertTrue(HandlingPriority.CANNOT_HANDLE.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == -1);
assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.CANNOT_HANDLE) == 1);
- assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_MAX_PRIORITY) == -1);
- assertTrue(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 1);
- assertTrue(HandlingPriority.getHandlingPriority(Integer.MIN_VALUE).compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);
+ assertTrue(
+ HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_MAX_PRIORITY) == -1);
+ assertTrue(
+ HandlingPriority.HANDLE_WITH_MAX_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 1);
+ assertTrue(HandlingPriority.getHandlingPriority(Integer.MIN_VALUE)
+ .compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);
HandlingPriority prio = HandlingPriority.getHandlingPriority(10);
assertTrue(prio.increasePriority(1).compareTo(HandlingPriority.getHandlingPriority(11)) == 0);
assertFalse(HandlingPriority.CANNOT_HANDLE.getPriority().isPresent());
assertFalse(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.equals(new Object()));
- assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY, HandlingPriority.getHandlingPriority(Integer.MAX_VALUE));
- assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.hashCode(), HandlingPriority.getHandlingPriority(Integer.MAX_VALUE).hashCode());
+ assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY,
+ HandlingPriority.getHandlingPriority(Integer.MAX_VALUE));
+ assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.hashCode(),
+ HandlingPriority.getHandlingPriority(Integer.MAX_VALUE).hashCode());
}
}
package org.opendaylight.controller.netconf.monitoring;
import java.util.Collections;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.monitoring.xml.JaxBSerializer;
import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
private Element getPlaceholder(final Document innerResult)
- throws NetconfDocumentedException {
+ throws DocumentedException {
final XmlElement rootElement = XmlElement.fromDomElementWithExpected(
- innerResult.getDocumentElement(), XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.RFC4741_TARGET_NAMESPACE);
+ innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
}
@Override
public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
- throws NetconfDocumentedException {
+ throws DocumentedException {
if (subsequentOperation.isExecutionTermination()){
- throw new NetconfDocumentedException(String.format("Subsequent netconf operation expected by %s", this),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException(String.format("Subsequent netconf operation expected by %s", this),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error);
}
try {
final String errorMessage = "Get operation for netconf-state subtree failed";
LOG.warn(errorMessage, e);
- throw new NetconfDocumentedException(errorMessage, NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error,
- Collections.singletonMap(NetconfDocumentedException.ErrorSeverity.error.toString(), e.getMessage()));
+ throw new DocumentedException(errorMessage, DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error,
+ Collections.singletonMap(DocumentedException.ErrorSeverity.error.toString(), e.getMessage()));
}
}
@Override
protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation)
- throws NetconfDocumentedException {
+ throws DocumentedException {
throw new UnsupportedOperationException("Never gets called");
}
}
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
final GetSchemaEntry entry;
entry = new GetSchemaEntry(xml);
} catch (final IllegalStateException e) {
final Map<String, String> errorInfo = Maps.newHashMap();
errorInfo.put(entry.identifier, e.getMessage());
- LOG.warn("Rpc error: {}", NetconfDocumentedException.ErrorTag.operation_failed, e);
- throw new NetconfDocumentedException(e.getMessage(), NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.operation_failed,
- NetconfDocumentedException.ErrorSeverity.error, errorInfo);
+ LOG.warn("Rpc error: {}", DocumentedException.ErrorTag.operation_failed, e);
+ throw new DocumentedException(e.getMessage(), DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.operation_failed,
+ DocumentedException.ErrorSeverity.error, errorInfo);
}
final Element getSchemaResult;
private final String identifier;
private final Optional<String> version;
- GetSchemaEntry(final XmlElement getSchemaElement) throws NetconfDocumentedException {
+ GetSchemaEntry(final XmlElement getSchemaElement) throws DocumentedException {
getSchemaElement.checkName(GET_SCHEMA);
getSchemaElement.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING);
XmlElement identifierElement = null;
try {
identifierElement = getSchemaElement.getOnlyChildElementWithSameNamespace(IDENTIFIER);
- } catch (final MissingNameSpaceException e) {
+ } catch (final DocumentedException e) {
LOG.trace("Can't get identifier element as only child element with same namespace due to ",e);
- throw NetconfDocumentedException.wrap(e);
+ throw DocumentedException.wrap(e);
}
identifier = identifierElement.getTextContent();
final Optional<XmlElement> versionElement = getSchemaElement
import java.util.Collections;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
import com.google.common.base.Optional;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
public class GetSchemaTest {
" </get-schema>";
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testDefaultGetSchema() throws Exception {
GetSchema schema = new GetSchema(cap);
doThrow(IllegalStateException.class).when(cap).getSchemaForCapability(anyString(), any(Optional.class));
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
+
import java.util.Collections;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SchemasBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.SessionsBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema;
public void testHandleNoSubsequent() throws Exception {
try {
get.handle(null, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
- } catch (final NetconfDocumentedException e) {
- assertNetconfDocumentedEx(e, NetconfDocumentedException.ErrorSeverity.error, NetconfDocumentedException.ErrorTag.operation_failed, NetconfDocumentedException.ErrorType.application);
+ } catch (final DocumentedException e) {
+ assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.error, DocumentedException.ErrorTag.operation_failed, DocumentedException.ErrorType.application);
return;
}
doReturn(incorrectSubsequentResult).when(subsequentOperation).execute(request);
try {
get.handle(request, subsequentOperation);
- } catch (final NetconfDocumentedException e) {
- assertNetconfDocumentedEx(e, NetconfDocumentedException.ErrorSeverity.error, NetconfDocumentedException.ErrorTag.invalid_value, NetconfDocumentedException.ErrorType.application);
+ } catch (final DocumentedException e) {
+ assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.error, DocumentedException.ErrorTag.invalid_value, DocumentedException.ErrorType.application);
return;
}
doThrow(RuntimeException.class).when(subsequentOperation).execute(request);
try {
get.handle(request, subsequentOperation);
- } catch (final NetconfDocumentedException e) {
- assertNetconfDocumentedEx(e, NetconfDocumentedException.ErrorSeverity.error, NetconfDocumentedException.ErrorTag.operation_failed, NetconfDocumentedException.ErrorType.application);
+ } catch (final DocumentedException e) {
+ assertNetconfDocumentedEx(e, DocumentedException.ErrorSeverity.error, DocumentedException.ErrorTag.operation_failed, DocumentedException.ErrorType.application);
assertEquals(1, e.getErrorInfo().size());
return;
}
}
- private void assertNetconfDocumentedEx(final NetconfDocumentedException e, final NetconfDocumentedException.ErrorSeverity severity, final NetconfDocumentedException.ErrorTag errorTag, final NetconfDocumentedException.ErrorType type) {
+ 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());
import java.util.Set;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.DomainName;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
final NetconfMonitoringService service = new NetconfMonitoringService() {
@Override
- public void onSessionUp(final NetconfManagementSession session) {
-
- }
-
- @Override
- public void onSessionDown(final NetconfManagementSession session) {
+ public void onCapabilitiesChanged(Set<Capability> added, Set<Capability> removed) {
}
@Override
- public void onCapabilitiesAdded(final Set<Capability> addedCaps) {
+ public void onSessionUp(final NetconfManagementSession session) {
}
@Override
- public void onCapabilitiesRemoved(final Set<Capability> addedCaps) {
+ public void onSessionDown(final NetconfManagementSession session) {
}
<groupId>openexi</groupId>
<artifactId>nagasena-rta</artifactId>
</dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
- <Export-Package>org.opendaylight.controller.netconf.nettyutil,
- org.opendaylight.controller.netconf.nettyutil.handler,
- org.opendaylight.controller.netconf.nettyutil.handler.exi,
- org.opendaylight.controller.netconf.nettyutil.handler.ssh,
- org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication,
- org.opendaylight.controller.netconf.nettyutil.handler.ssh.client</Export-Package>
+ <Export-Package>org.opendaylight.controller.netconf.nettyutil.*</Export-Package>
</instructions>
</configuration>
</plugin>
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import java.io.IOException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.api.NetconfExiSession;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfSession;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfEXIToMessageDecoder;
import org.opendaylight.controller.netconf.nettyutil.handler.NetconfMessageToEXIEncoder;
import org.opendaylight.controller.netconf.nettyutil.handler.exi.EXIParameters;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.protocol.framework.AbstractProtocolSession;
import org.openexi.proc.common.EXIOptionsException;
import org.openexi.sax.TransmogrifierException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.io.IOException;
import java.util.List;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
package org.opendaylight.controller.netconf.nettyutil.handler.exi;
import com.google.common.base.Preconditions;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.openexi.proc.common.AlignmentType;
import org.openexi.proc.common.EXIOptions;
import org.openexi.proc.common.EXIOptionsException;
import com.google.common.collect.Lists;
import java.util.List;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.openexi.proc.common.EXIOptions;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+
import com.google.common.collect.Lists;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Before;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.openexi.proc.common.EXIOptions;
import org.openexi.proc.common.EXIOptionsException;
import org.openexi.sax.Transmogrifier;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
public class NetconfHelloMessageToXMLEncoderTest {
import java.util.List;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
public class NetconfXMLToHelloMessageDecoderTest {
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.openexi.proc.common.AlignmentType;
import org.openexi.proc.common.EXIOptions;
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>ietf-netconf-notifications</artifactId>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Export-Package>org.opendaylight.controller.netconf.notifications.*</Export-Package>
- </instructions>
- </configuration>
</plugin>
</plugins>
</build>
/**
* Callback used to notify about a change in used capabilities
*/
- void onCapabilityChanged(NetconfCapabilityChange capabilityChange);
+ void onCapabilityChanged(final NetconfCapabilityChange capabilityChange);
// TODO add other base notifications
/**
* Collector of all notifications. Base or generic
*/
-public interface NetconfNotificationCollector {
+public interface NetconfNotificationCollector {
/**
* Add notification publisher for a particular stream
<configuration>
<instructions>
<Bundle-Activator>org.opendaylight.controller.netconf.notifications.impl.osgi.Activator</Bundle-Activator>
+ <Export-Package>org.opendaylight.controller.netconf.notifications.impl.*</Export-Package>
</instructions>
</configuration>
</plugin>
@Override
public synchronized void onNotification(final StreamNameType stream, final NetconfNotification notification) {
LOG.debug("Notification of type {} detected", stream);
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.debug("Notification of type {} detected: {}", stream, notification);
}
return new NotificationRegistration() {
@Override
public void close() {
- synchronized(NetconfNotificationManager.this) {
+ synchronized (NetconfNotificationManager.this) {
streamListeners.remove(listener);
}
}
final StreamNameType streamName = stream.getName();
LOG.debug("Notification publisher registered for stream: {}", streamName);
- if(LOG.isTraceEnabled()) {
+ if (LOG.isTraceEnabled()) {
LOG.trace("Notification publisher registered for stream: {}", stream);
}
- if(streamMetadata.containsKey(streamName)) {
+ if (streamMetadata.containsKey(streamName)) {
LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName, streamMetadata.get(streamName));
} else {
streamMetadata.put(streamName, stream);
streamListener.onStreamRegistered(stream);
}
}
+
private synchronized void notifyStreamRemoved(final StreamNameType stream) {
for (final NetconfNotificationStreamListener streamListener : streamListeners) {
streamListener.onStreamUnregistered(stream);
baseRegistration.close();
}
+ private static NetconfNotification serializeNotification(final NetconfCapabilityChange capabilityChange) {
+ return NotificationsTransformUtil.transform(capabilityChange);
+ }
+
@Override
public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(capabilityChange));
- }
-
- private static NetconfNotification serializeNotification(final NetconfCapabilityChange capabilityChange) {
- return NotificationsTransformUtil.transform(capabilityChange);
+// baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(computeDiff(removed, added)));
}
}
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.List;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfSession;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.SessionAwareNetconfOperation;
import org.opendaylight.controller.netconf.notifications.NotificationListenerRegistration;
import org.opendaylight.controller.netconf.notifications.impl.NetconfNotificationManager;
import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
import org.slf4j.Logger;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
operationElement.checkName(CREATE_SUBSCRIPTION);
operationElement.checkNamespace(CreateSubscriptionInput.QNAME.getNamespace().toString());
// FIXME reimplement using CODEC_REGISTRY and parse everything into generated class instance
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
- private static StreamNameType parseStreamIfPresent(final XmlElement operationElement) throws NetconfDocumentedException {
+ private static StreamNameType parseStreamIfPresent(final XmlElement operationElement) throws DocumentedException {
final Optional<XmlElement> stream = operationElement.getOnlyChildElementWithSameNamespaceOptionally("stream");
return stream.isPresent() ? new StreamNameType(stream.get().getTextContent()) : NetconfNotificationManager.BASE_STREAM_NAME;
}
import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMResult;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.notifications.NetconfNotificationRegistry;
import org.opendaylight.controller.netconf.util.mapping.AbstractNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.NetconfBuilder;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
}
@Override
- public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
final Document partialResponse = subsequentOperation.execute(requestMessage);
final Streams availableStreams = notificationRegistry.getNotificationPublishers();
if(availableStreams.getStream().isEmpty() == false) {
return partialResponse;
}
- static void serializeStreamsSubtree(final Document partialResponse, final Streams availableStreams) throws NetconfDocumentedException {
+ static void serializeStreamsSubtree(final Document partialResponse, final Streams availableStreams) throws DocumentedException {
final Netconf netconfSubtree = new NetconfBuilder().setStreams(availableStreams).build();
final NormalizedNode<?, ?> normalized = toNormalized(netconfSubtree);
}
private static Element getPlaceholder(final Document innerResult)
- throws NetconfDocumentedException {
+ throws DocumentedException {
final XmlElement rootElement = XmlElement.fromDomElementWithExpected(
- innerResult.getDocumentElement(), XmlNetconfConstants.RPC_REPLY_KEY, XmlNetconfConstants.RFC4741_TARGET_NAMESPACE);
+ innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
}
@Override
protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation)
- throws NetconfDocumentedException {
+ throws DocumentedException {
throw new UnsupportedOperationException("Never gets called");
}
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.notifications.NetconfNotification;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.$YangModuleInfoImpl;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Set;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.BasicCapability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.api.util.NetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import org.opendaylight.controller.netconf.notifications.impl.NetconfNotificationManager;
import org.opendaylight.controller.netconf.notifications.impl.ops.CreateSubscription;
import org.opendaylight.controller.netconf.notifications.impl.ops.Get;
-import org.opendaylight.controller.netconf.util.capability.BasicCapability;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class Activator implements BundleActivator {
+ private static final Logger LOG = LoggerFactory.getLogger(Activator.class);
+
private ServiceRegistration<NetconfNotificationCollector> netconfNotificationCollectorServiceRegistration;
private ServiceRegistration<NetconfOperationServiceFactory> operationaServiceRegistration;
private NetconfNotificationManager netconfNotificationManager;
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- listener.onCapabilitiesAdded(capabilities);
+ listener.onCapabilitiesChanged(capabilities, Collections.<Capability>emptySet());
return new AutoCloseable() {
@Override
public void close() {
- listener.onCapabilitiesRemoved(capabilities);
+ listener.onCapabilitiesChanged(Collections.<Capability>emptySet(), capabilities);
}
};
}
private final CreateSubscription createSubscription = new CreateSubscription(netconfSessionIdForReporting, netconfNotificationManager);
-
@Override
public Set<NetconfOperation> getNetconfOperations() {
return Sets.<NetconfOperation>newHashSet(
final Dictionary<String, String> properties = new Hashtable<>();
properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.NETCONF_MONITORING);
operationaServiceRegistration = context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
-
}
@Override
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfSession;
import org.opendaylight.controller.netconf.notifications.NetconfNotificationListener;
import org.opendaylight.controller.netconf.notifications.NetconfNotificationRegistry;
import org.opendaylight.controller.netconf.notifications.NotificationListenerRegistration;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
import org.w3c.dom.Element;
import com.google.common.collect.Lists;
import java.io.IOException;
import org.junit.Test;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.StreamsBuilder;
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.notifications.NetconfNotification;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChangeBuilder;
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <id>config</id>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>yang-jmx-generator-plugin</artifactId>
- <version>${config.version}</version>
- </dependency>
- </dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<!-- compile dependencies -->
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>config-manager-facade-xml</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-api</artifactId>
<groupId>org.opendaylight.controller</groupId>
<artifactId>config-api</artifactId>
</dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
package org.opendaylight.controller.netconf.util;
import com.google.common.base.Preconditions;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
private NetconfUtil() {}
- public static Document checkIsMessageOk(Document response) throws NetconfDocumentedException {
+ public static Document checkIsMessageOk(Document response) throws DocumentedException {
XmlElement element = XmlElement.fromDomDocument(response);
- Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
+ Preconditions.checkState(element.getName().equals(XmlMappingConstants.RPC_REPLY_KEY));
element = element.getOnlyChildElement();
if (element.getName().equals(XmlNetconfConstants.OK)) {
return response;
*/
package org.opendaylight.controller.netconf.util.mapping;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@Override
protected Element handle(Document document, XmlElement operationElement,
- NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
if (!subsequentOperation.isExecutionTermination()){
- throw new NetconfDocumentedException(String.format("No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
- NetconfDocumentedException.ErrorType.application,
- NetconfDocumentedException.ErrorTag.malformed_message,
- NetconfDocumentedException.ErrorSeverity.error);
+ throw new DocumentedException(String.format("No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
+ DocumentedException.ErrorType.application,
+ DocumentedException.ErrorTag.malformed_message,
+ DocumentedException.ErrorSeverity.error);
}
return handleWithNoSubsequentOperations(document, operationElement);
return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
}
- protected abstract Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException;
+ protected abstract Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException;
}
import com.google.common.base.Optional;
import java.util.Map;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- public HandlingPriority canHandle(final Document message) throws NetconfDocumentedException {
+ public HandlingPriority canHandle(final Document message) throws DocumentedException {
OperationNameAndNamespace operationNameAndNamespace = null;
operationNameAndNamespace = new OperationNameAndNamespace(message);
return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace());
private final String operationName, namespace;
private final XmlElement operationElement;
- public OperationNameAndNamespace(final Document message) throws NetconfDocumentedException {
+ public OperationNameAndNamespace(final Document message) throws DocumentedException {
XmlElement requestElement = null;
requestElement = getRequestElementWithCheck(message);
operationElement = requestElement.getOnlyChildElement();
}
}
- protected static XmlElement getRequestElementWithCheck(final Document message) throws NetconfDocumentedException {
+ protected static XmlElement getRequestElementWithCheck(final Document message) throws DocumentedException {
return XmlElement.fromDomElementWithExpected(message.getDocumentElement(), XmlNetconfConstants.RPC_KEY,
XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
}
@Override
public Document handle(final Document requestMessage,
- final NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
XmlElement requestElement = getRequestElementWithCheck(requestMessage);
Map<String, Attr> attributes = requestElement.getAttributes();
Element response = handle(document, operationElement, subsequentOperation);
- Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+ Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
if(XmlElement.fromDomElement(response).hasNamespace()) {
rpcReply.appendChild(response);
}
protected abstract Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation)
- throws NetconfDocumentedException;
+ throws DocumentedException;
@Override
public String toString() {
*/
package org.opendaylight.controller.netconf.util.mapping;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@Override
protected Element handle(Document document, XmlElement operationElement,
- NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
return handleWithNoSubsequentOperations(document, operationElement);
}
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import java.util.Set;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
// accept even if hello has no namespace
return element.getName().equals(HELLO_TAG) &&
(!element.hasNamespace() || element.getNamespace().equals(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
- } catch (MissingNameSpaceException e) {
+ } catch (DocumentedException e) {
// Cannot happen, since we check for hasNamespace
throw new IllegalStateException(e);
}
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
if(xmlElement.getChildElements().size() != 1) {
return false;
}
- return xmlElement.getOnlyChildElement().getName().equals(XmlNetconfConstants.OK);
+ try {
+ return xmlElement.getOnlyChildElement().getName().equals(XmlNetconfConstants.OK);
+ } catch (DocumentedException e) {
+ throw new NetconfDocumentedException(e);
+ }
}
public static boolean isErrorMessage(NetconfMessage message) throws NetconfDocumentedException {
if(xmlElement.getChildElements().size() != 1) {
return false;
}
- return xmlElement.getOnlyChildElement().getName().equals(XmlNetconfConstants.RPC_ERROR);
+ try {
+ return xmlElement.getOnlyChildElement().getName().equals(DocumentedException.RPC_ERROR);
+ } catch (DocumentedException e) {
+ throw new NetconfDocumentedException(e);
+ }
}
public static Collection<String> extractCapabilitiesFromHello(Document doc) throws NetconfDocumentedException {
// Trim possible leading/tailing whitespace
try {
return input.getTextContent().trim();
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
LOG.trace("Error fetching input text content",e);
return null;
}
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfSession;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
private SendErrorExceptionUtil() {}
public static void sendErrorMessage(final NetconfSession session,
- final NetconfDocumentedException sendErrorException) {
+ final DocumentedException sendErrorException) {
LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
final Document errorDocument = createDocument(sendErrorException);
ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument));
f.addListener(new SendErrorVerifyingListener(sendErrorException));
}
- public static void sendErrorMessage(final Channel channel, final NetconfDocumentedException sendErrorException) {
+ public static void sendErrorMessage(final Channel channel, final DocumentedException sendErrorException) {
LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
final Document errorDocument = createDocument(sendErrorException);
ChannelFuture f = channel.writeAndFlush(new NetconfMessage(errorDocument));
f.addListener(new SendErrorVerifyingListener(sendErrorException));
}
- public static void sendErrorMessage(final NetconfSession session, final NetconfDocumentedException sendErrorException,
+ public static void sendErrorMessage(final NetconfSession session, final DocumentedException sendErrorException,
final NetconfMessage incommingMessage) {
final Document errorDocument = createDocument(sendErrorException);
if (LOG.isTraceEnabled()) {
}
private static void tryToCopyAttributes(final Document incommingDocument, final Document errorDocument,
- final NetconfDocumentedException sendErrorException) {
+ final DocumentedException sendErrorException) {
try {
final Element incommingRpc = incommingDocument.getDocumentElement();
Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY), "Missing %s element",
XmlNetconfConstants.RPC_KEY);
final Element rpcReply = errorDocument.getDocumentElement();
- Preconditions.checkState(rpcReply.getTagName().equals(XmlNetconfConstants.RPC_REPLY_KEY), "Missing %s element",
- XmlNetconfConstants.RPC_REPLY_KEY);
+ Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY), "Missing %s element",
+ XmlMappingConstants.RPC_REPLY_KEY);
final NamedNodeMap incomingAttributes = incommingRpc.getAttributes();
for (int i = 0; i < incomingAttributes.getLength(); i++) {
}
}
- private static Document createDocument(final NetconfDocumentedException sendErrorException) {
+ private static Document createDocument(final DocumentedException sendErrorException) {
return sendErrorException.toXMLDocument();
}
* Checks if netconf error was sent successfully.
*/
private static final class SendErrorVerifyingListener implements ChannelFutureListener {
- private final NetconfDocumentedException sendErrorException;
+ private final DocumentedException sendErrorException;
- public SendErrorVerifyingListener(final NetconfDocumentedException sendErrorException) {
+ public SendErrorVerifyingListener(final DocumentedException sendErrorException) {
this.sendErrorException = sendErrorException;
}
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import static org.junit.Assert.fail;
import org.junit.Test;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
public class NetconfUtilTest {
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{
handleWithNoSubsequentOperationsRun = true;
return null;
}
assertEquals(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY, netconfOperation.getHandlingPriority());
}
- @Test(expected = NetconfDocumentedException.class)
+ @Test(expected = DocumentedException.class)
public void testHandle() throws Exception {
NetconfOperationChainedExecution operation = mock(NetconfOperationChainedExecution.class);
doReturn("").when(operation).toString();
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
}
@Override
- protected Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException {
+ protected Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException{
this.handleRun = true;
try {
return XmlUtil.readXmlToElement("<element/>");
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{
return null;
}
import io.netty.util.concurrent.GenericFutureListener;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfSession;
import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
NetconfSession netconfSession;
ChannelFuture channelFuture;
Channel channel;
- private NetconfDocumentedException exception;
+ private DocumentedException exception;
@Before
public void setUp() throws Exception {
doReturn(channelFuture).when(netconfSession).sendMessage(any(NetconfMessage.class));
doReturn(channelFuture).when(channelFuture).addListener(any(GenericFutureListener.class));
doReturn(channelFuture).when(channel).writeAndFlush(any(NetconfMessage.class));
- exception = new NetconfDocumentedException("err");
+ exception = new DocumentedException("err");
}
@Test
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import org.custommonkey.xmlunit.NodeTest;
import org.custommonkey.xmlunit.NodeTestException;
import org.custommonkey.xmlunit.NodeTester;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
--- /dev/null
+package org.opendaylight.controller.netconf.util.xml;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.w3c.dom.Element;
+
+public class XMLNetconfUtilTest {
+
+ @Test
+ public void testXPath() throws Exception {
+ final XPathExpression correctXPath = XMLNetconfUtil.compileXPath("/top/innerText");
+ try {
+ XMLNetconfUtil.compileXPath("!@(*&$!");
+ fail("Incorrect xpath should fail");
+ } catch (IllegalStateException e) {}
+ final Object value = XmlUtil.evaluateXPath(correctXPath, XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
+ assertEquals("value", ((Element) value).getTextContent());
+ }
+
+}
\ No newline at end of file
<modules>
<module>netconf-api</module>
- <module>netconf-cli</module>
<module>netconf-config</module>
<module>netconf-impl</module>
<module>config-netconf-connector</module>
<module>mdsal-netconf-monitoring</module>
<module>netconf-util</module>
<module>netconf-netty-util</module>
- <module>config-persister-impl</module>
<module>netconf-mapping-api</module>
<module>netconf-client</module>
+ <module>netconf-config-dispatcher</module>
<module>netconf-ssh</module>
<module>netconf-tcp</module>
<module>netconf-monitoring</module>
- <module>ietf-netconf</module>
- <module>ietf-netconf-monitoring</module>
- <module>ietf-netconf-notifications</module>
- <module>ietf-netconf-monitoring-extension</module>
<module>netconf-connector-config</module>
<module>netconf-mdsal-config</module>
<module>netconf-auth</module>
- <module>netconf-testtool</module>
<module>netconf-notifications-impl</module>
<module>netconf-notifications-api</module>
+ <module>sal-netconf-connector</module>
+ <module>features</module>
+ <module>models</module>
+ <module>tools</module>
<module>netconf-artifacts</module>
</modules>
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <version>${yangtools.version}</version>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>${yangtools.version}</version>
- </dependency>
- </dependencies>
<executions>
<execution>
+ <id>config</id>
<goals>
<goal>generate-sources</goal>
</goals>
<configuration>
- <yangFilesRootDir>src/main/yang</yangFilesRootDir>
<codeGenerators>
<generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
+ <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
+ <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
+ <additionalConfiguration>
+ <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
+ </additionalConfiguration>
</generator>
<generator>
- <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${project.build.directory}/site/models</outputBaseDir>
+ <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
+ <outputBaseDir>${salGeneratorPath}</outputBaseDir>
</generator>
</codeGenerators>
<inspectDependencies>true</inspectDependencies>
</configuration>
</execution>
</executions>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>yang-jmx-generator-plugin</artifactId>
+ <version>${config.version}</version>
+ </dependency>
+ </dependencies>
</plugin>
</plugins>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-parent</artifactId>
- <version>1.3.0-SNAPSHOT</version>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
</parent>
<artifactId>sal-netconf-connector</artifactId>
<packaging>bundle</packaging>
+ <!-- Preserve version from mdsal -->
+ <version>${mdsal.version}</version>
+
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-api</artifactId>
- <version>${netconf.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-manager</artifactId>
- <version>${netconf.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-manager</artifactId>
- <version>${netconf.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-netconf-connector</artifactId>
- <version>${netconf.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-persister-impl</artifactId>
- <version>${netconf.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>config-util</artifactId>
- <version>${netconf.version}</version>
- <scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-impl</artifactId>
- <version>${netconf.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-mapping-api</artifactId>
- <version>${netconf.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>netconf-util</artifactId>
- <version>${netconf.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>yang-test</artifactId>
- <version>${netconf.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
- <configuration>
- <instructions>
- <Import-Package>*</Import-Package>
- </instructions>
- </configuration>
</plugin>
-
<plugin>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${salGeneratorPath}</outputBaseDir>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
- <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
- <additionalConfiguration>
- <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
- </additionalConfiguration>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>target/site/models</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
</plugin>
</plugins>
</build>
*/
public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
{
- private static final Logger logger = LoggerFactory.getLogger(NetconfConnectorModule.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
private BundleContext bundleContext;
private Optional<NetconfSessionPreferences> userCapabilities;
userCapabilities = getUserCapabilities();
if(getKeepaliveExecutor() == null) {
- logger.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
+ LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
// Instantiate the default executor, now we know its necessary
if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
connectionAttempts = maxConnectionAttempts;
} else {
- logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
+ LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
connectionAttempts = null;
}
*/
package org.opendaylight.controller.sal.connect.api;
+import com.google.common.util.concurrent.ListenableFuture;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import com.google.common.util.concurrent.ListenableFuture;
-
public interface RemoteDeviceCommunicator<M> extends AutoCloseable {
ListenableFuture<RpcResult<M>> sendRequest(M message, QName rpc);
*/
public final class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
- private static final Logger logger = LoggerFactory.getLogger(NetconfDevice.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
/**
* Initial schema context contains schemas for netconf monitoring and netconf notifications
org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
INIT_SCHEMA_CTX = moduleInfoBackedContext.tryToCreateSchemaContext().get();
} catch (final RuntimeException e) {
- logger.error("Unable to prepare schema context for netconf initialization", e);
+ LOG.error("Unable to prepare schema context for netconf initialization", e);
throw new ExceptionInInitializerError(e);
}
}
// 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
- logger.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
+ LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
final NetconfDeviceRpc initRpc = getRpcForInitialization(listener);
final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
- if(shouldListenOnSchemaChange(remoteSessionCapabilities)) {
- registerToBaseNetconfStream(initRpc, listener);
+ if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
+ registerToBaseNetconfStream(initRpc, listener);
}
final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
@Override
public void onFailure(final Throwable t) {
- logger.warn("{}: Unexpected error resolving device sources: {}", id, t);
+ LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
handleSalInitializationFailure(t, listener);
}
};
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 =
+ final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture =
deviceRpc.invokeRpc(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)) {
- logger.info("{}: Schemas change detected, reconnecting", id);
+ LOG.info("{}: Schemas change detected, reconnecting", id);
// 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) {
- logger.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
+ LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
}
});
}
salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
notificationHandler.onRemoteSchemaUp(messageTransformer);
- logger.info("{}: Netconf connector initialized successfully", id);
+ LOG.info("{}: Netconf connector initialized successfully", id);
}
private void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
- logger.error("{}: Initialization in sal failed, disconnecting from device", id, t);
+ LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
listener.close();
onRemoteSessionDown();
resetMessageTransformer();
@Override
public DeviceSources call() throws Exception {
final NetconfStateSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
- logger.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
+ 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()) {
- logger.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
+ LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
id, requiredSourcesNotProvided);
- logger.warn("{}: Attempting to build schema context from required sources", id);
+ 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.
// 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()) {
- logger.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
+ LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
id, providedSourcesNotRequired);
- logger.warn("{}: Adding provided but not required sources as required to prevent failures", id);
- logger.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
+ 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);
}
*/
// FIXME reimplement without recursion
private void setUpSchema(final Collection<SourceIdentifier> requiredSources) {
- logger.trace("{}: Trying to build schema context from {}", id, requiredSources);
+ LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
// If no more sources, fail
if(requiredSources.isEmpty()) {
@Override
public void onSuccess(final SchemaContext result) {
- logger.debug("{}: Schema context built successfully from {}", id, requiredSources);
+ LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
final Collection<QName> filteredQNames = Sets.difference(deviceSources.getProvidedSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
capabilities.addCapabilities(filteredQNames);
capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
// In case source missing, try without it
if (t instanceof MissingSchemaSourceException) {
final SourceIdentifier missingSource = ((MissingSchemaSourceException) t).getSourceId();
- logger.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
+ LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource)), UnavailableCapability.FailureReason.MissingSource);
setUpSchema(stripMissingSource(requiredSources, missingSource));
final SchemaResolutionException resolutionException = (SchemaResolutionException) t;
final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
- logger.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
+ LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
setUpSchema(resolutionException.getResolvedSources());
// unknown error, fail
} else {
});
if (qNames.isEmpty()) {
- logger.debug("Unable to map any source identfiers to a capability reported by device : " + identifiers);
+ LOG.debug("{}: Unable to map any source identfiers to a capability reported by device : {}", id, identifiers);
}
return qNames;
}
*/
private static NetconfStateSchemas create(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
if(remoteSessionCapabilities.isMonitoringSupported() == false) {
- LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas");
+ LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
return EMPTY;
}
import com.google.common.base.Preconditions;
import java.util.LinkedList;
import java.util.List;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.MessageTransformer;
import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
*/
final class NotificationHandler {
- private static final Logger logger = LoggerFactory.getLogger(NotificationHandler.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NotificationHandler.class);
private final RemoteDeviceHandler<?> salFacade;
private final List<NetconfMessage> queue = new LinkedList<>();
private void queueNotification(final NetconfMessage notification) {
Preconditions.checkState(passNotifications == false);
- logger.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
- if(logger.isTraceEnabled()) {
- logger.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
+ LOG.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
+ if(LOG.isTraceEnabled()) {
+ LOG.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
}
queue.add(notification);
}
private synchronized void passNotification(final DOMNotification parsedNotification) {
- logger.debug("{}: Forwarding notification {}", id, parsedNotification);
+ LOG.debug("{}: Forwarding notification {}", id, parsedNotification);
if(filter == null || filter.filterNotification(parsedNotification).isPresent()) {
salFacade.onNotification(parsedNotification);
import java.util.Queue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.RemoteDevice;
import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
- private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
private final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice;
private final Optional<NetconfSessionPreferences> overrideNetconfCapabilities;
public void onSessionUp(final NetconfClientSession session) {
sessionLock.lock();
try {
- logger.debug("{}: Session established", id);
+ LOG.debug("{}: Session established", id);
this.session = session;
NetconfSessionPreferences netconfSessionPreferences =
NetconfSessionPreferences.fromNetconfSession(session);
- logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionPreferences);
+ LOG.trace("{}: Session advertised capabilities: {}", id,
+ netconfSessionPreferences);
if(overrideNetconfCapabilities.isPresent()) {
netconfSessionPreferences = netconfSessionPreferences.addModuleCaps(overrideNetconfCapabilities.get());
- logger.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id, netconfSessionPreferences);
+ LOG.debug(
+ "{}: Session capabilities overridden, capabilities that will be used: {}",
+ id, netconfSessionPreferences);
}
remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
@Override
public void operationComplete(Future<Object> future) throws Exception {
if (!future.isSuccess() && !future.isCancelled()) {
- logger.debug("{}: Connection failed", id, future.cause());
+ LOG.debug("{}: Connection failed", id, future.cause());
NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
}
}
@Override
public void onSessionDown(final NetconfClientSession session, final Exception e) {
- logger.warn("{}: Session went down", id, e);
+ LOG.warn("{}: Session went down", id, e);
tearDown( null );
}
@Override
public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
- logger.warn("{}: Session terminated {}", id, reason);
+ LOG.warn("{}: Session terminated {}", id, reason);
tearDown( reason.getErrorMessage() );
}
requests.poll();
} else {
request = null;
- logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
+ LOG.warn("{}: Ignoring unsolicited message {}", id,
+ msgToS(message));
}
}
finally {
if( request != null ) {
- logger.debug("{}: Message received {}", id, message);
+ LOG.debug("{}: Message received {}", id, message);
- if(logger.isTraceEnabled()) {
- logger.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 );
} catch (final NetconfDocumentedException e) {
- logger.warn( "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
- id, msgToS( request.request ), msgToS( message ), e );
+ LOG.warn(
+ "{}: 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() );
try {
NetconfMessageTransformUtil.checkSuccessReply(message);
} catch(final NetconfDocumentedException e) {
- logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
- msgToS( request.request ), msgToS( message ), 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() );
private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
final NetconfMessage message, final QName rpc) {
- if(logger.isTraceEnabled()) {
- logger.trace("{}: Sending message {}", id, msgToS(message));
+ if(LOG.isTraceEnabled()) {
+ LOG.trace("{}: Sending message {}", id, msgToS(message));
}
if (session == null) {
- logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
+ LOG.warn("{}: Session is disconnected, failing RPC request {}",
+ id, message);
return Futures.immediateFuture( createSessionDownRpcResult() );
}
public void operationComplete(final Future<Void> future) throws Exception {
if( !future.isSuccess() ) {
// We expect that a session down will occur at this point
- logger.debug( "{}: Failed to send request {}", id,
- XmlUtil.toString(req.request.getDocument()), future.cause() );
+ 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,
req.future.setException( future.cause() );
}
else {
- logger.trace( "Finished sending request {}", req.request );
+ LOG.trace("Finished sending request {}", req.request);
}
}
});
}
private void processNotification(final NetconfMessage notification) {
- if(logger.isTraceEnabled()) {
- logger.trace("{}: Notification received: {}", id, notification);
+ if(LOG.isTraceEnabled()) {
+ LOG.trace("{}: Notification received: {}", id, notification);
}
remoteDevice.onNotification(notification);
*/
package org.opendaylight.controller.sal.connect.netconf.listener;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.GuardedBy;
-
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.AbstractFuture;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
final class UncancellableFuture<V> extends AbstractFuture<V> {
@GuardedBy("this")
public final class NetconfDeviceSalFacade implements AutoCloseable, RemoteDeviceHandler<NetconfSessionPreferences> {
- private static final Logger logger= LoggerFactory.getLogger(NetconfDeviceSalFacade.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSalFacade.class);
private final RemoteDeviceId id;
private final NetconfDeviceSalProvider salProvider;
@Override
public synchronized void onDeviceDisconnected() {
- salProvider.getTopologyDatastoreAdapter().updateDeviceData(false, new NetconfDeviceCapabilities());
+ salProvider.getTopologyDatastoreAdapter().updateDeviceData(false,
+ new NetconfDeviceCapabilities());
salProvider.getMountInstance().onTopologyDeviceDisconnected();
}
try {
resource.close();
} catch (final Exception e) {
- logger.warn("{}: Ignoring exception while closing {}", id, resource, e);
+ LOG.warn("{}: Ignoring exception while closing {}", id,
+ resource, e);
}
}
}
final class NetconfDeviceSalProvider implements AutoCloseable, Provider, BindingAwareProvider {
- private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
private final RemoteDeviceId id;
private MountInstance mountInstance;
@Override
public void onSessionInitiated(final Broker.ProviderSession session) {
- logger.debug("{}: (BI)Session with sal established {}", id, session);
+ LOG.debug("{}: (BI)Session with sal established {}", id, session);
final DOMMountPointService mountService = session.getService(DOMMountPointService.class);
if (mountService != null) {
@Override
public void onSessionInitiated(final BindingAwareBroker.ProviderContext session) {
- logger.debug("{}: Session with sal established {}", id, session);
+ LOG.debug("{}: Session with sal established {}", id, session);
final DataBroker dataBroker = session.getSALService(DataBroker.class);
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);
}
synchronized void onTopologyDeviceDisconnected() {
if(topologyRegistration == null) {
- logger.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
+ 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;
}
}
final class NetconfDeviceTopologyAdapter implements AutoCloseable {
- public static final Logger logger = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
public static final Function<Entry<QName, FailureReason>, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = new Function<Entry<QName, FailureReason>, UnavailableCapability>() {
@Override
public UnavailableCapability apply(final Entry<QName, FailureReason> input) {
this.txChain = Preconditions.checkNotNull(dataService).createTransactionChain(new TransactionChainListener() {
@Override
public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction, Throwable cause) {
- logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
+ LOG.error("{}: TransactionChain({}) {} FAILED!", id, chain,
+ transaction.getIdentifier(), cause);
throw new IllegalStateException(id + " TransactionChain(" + chain + ") not committed correctly", cause);
}
@Override
public void onTransactionChainSuccessful(TransactionChain<?, ?> chain) {
- logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
+ LOG.trace("{}: TransactionChain({}) SUCCESSFUL", id, chain);
}
});
initDeviceData();
}
- private void initDeviceData() {
+ private void initDeviceData() {
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
createNetworkTopologyIfNotPresent(writeTx);
nodeBuilder.addAugmentation(NetconfNode.class, netconfNodeBuilder.build());
Node node = nodeBuilder.build();
- logger.trace("{}: Init device state transaction {} putting if absent operational data started.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Init device state transaction {} putting if absent operational data started.",
+ id, writeTx.getIdentifier());
writeTx.put(LogicalDatastoreType.OPERATIONAL, path, node);
- logger.trace("{}: Init device state transaction {} putting operational data ended.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Init device state transaction {} putting operational data ended.",
+ id, writeTx.getIdentifier());
- logger.trace("{}: Init device state transaction {} putting if absent config data started.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Init device state transaction {} putting if absent config data started.",
+ id, writeTx.getIdentifier());
writeTx.put(LogicalDatastoreType.CONFIGURATION, path, getNodeWithId(id));
- logger.trace("{}: Init device state transaction {} putting config data ended.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Init device state transaction {} putting config data ended.",
+ id, writeTx.getIdentifier());
commitTransaction(writeTx, "init");
}
final Node data = buildDataForNetconfNode(up, capabilities);
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- logger.trace("{}: Update device state transaction {} merging operational data started.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Update device state transaction {} merging operational data started.",
+ id, writeTx.getIdentifier());
writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath(), data);
- logger.trace("{}: Update device state transaction {} merging operational data ended.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Update device state transaction {} merging operational data ended.",
+ id, writeTx.getIdentifier());
commitTransaction(writeTx, "update");
}
final Node data = getNodeIdBuilder(id).addAugmentation(NetconfNode.class, netconfNode).build();
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- logger.trace("{}: Setting device state as failed {} putting operational data started.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Setting device state as failed {} putting operational data started.",
+ id, writeTx.getIdentifier());
writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath(), data);
- logger.trace("{}: Setting device state as failed {} putting operational data ended.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Setting device state as failed {} putting operational data ended.",
+ id, writeTx.getIdentifier());
commitTransaction(writeTx, "update-failed-device");
}
public void removeDeviceConfiguration() {
final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- logger.trace("{}: Close device state transaction {} removing all data started.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Close device state transaction {} removing all data started.",
+ id, writeTx.getIdentifier());
writeTx.delete(LogicalDatastoreType.CONFIGURATION, id.getTopologyBindingPath());
writeTx.delete(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath());
- logger.trace("{}: Close device state transaction {} removing all data ended.", id, writeTx.getIdentifier());
+ LOG.trace(
+ "{}: Close device state transaction {} removing all data ended.",
+ id, writeTx.getIdentifier());
commitTransaction(writeTx, "close");
}
private void createNetworkTopologyIfNotPresent(final WriteTransaction writeTx) {
final NetworkTopology networkTopology = new NetworkTopologyBuilder().build();
- logger.trace("{}: Merging {} container to ensure its presence", id, networkTopology.QNAME, writeTx.getIdentifier());
+ LOG.trace("{}: Merging {} container to ensure its presence", id,
+ networkTopology.QNAME, writeTx.getIdentifier());
writeTx.merge(LogicalDatastoreType.CONFIGURATION, networkTopologyPath, networkTopology);
writeTx.merge(LogicalDatastoreType.OPERATIONAL, networkTopologyPath, networkTopology);
final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
- logger.trace("{}: Merging {} container to ensure its presence", id, topology.QNAME, writeTx.getIdentifier());
+ LOG.trace("{}: Merging {} container to ensure its presence", id,
+ topology.QNAME, writeTx.getIdentifier());
writeTx.merge(LogicalDatastoreType.CONFIGURATION, topologyListPath, topology);
writeTx.merge(LogicalDatastoreType.OPERATIONAL, topologyListPath, topology);
}
private void commitTransaction(final WriteTransaction transaction, final String txType) {
- logger.trace("{}: Committing Transaction {}:{}", id, txType, transaction.getIdentifier());
+ LOG.trace("{}: Committing Transaction {}:{}", id, txType,
+ transaction.getIdentifier());
final CheckedFuture<Void, TransactionCommitFailedException> result = transaction.submit();
Futures.addCallback(result, new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
- logger.trace("{}: Transaction({}) {} SUCCESSFUL", id, txType, transaction.getIdentifier());
+ LOG.trace("{}: Transaction({}) {} SUCCESSFUL", id, txType,
+ transaction.getIdentifier());
}
@Override
public void onFailure(final Throwable t) {
- logger.error("{}: Transaction({}) {} FAILED!", id, txType, transaction.getIdentifier(), t);
+ LOG.error("{}: Transaction({}) {} FAILED!", id, txType,
+ transaction.getIdentifier(), t);
throw new IllegalStateException(id + " Transaction(" + txType + ") not committed correctly", t);
}
});
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);
+ }
}
throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-
+import java.util.concurrent.ExecutionException;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import java.util.concurrent.ExecutionException;
-
public class ReadWriteTx implements DOMDataReadWriteTransaction {
private final DOMDataReadTransaction delegateReadTx;
}
});
} catch (final NetconfDocumentedException e) {
- LOG.warn("{}: Failed to lock running. Failed to initialize transaction", e);
+ LOG.warn("{}: Failed to lock running. Failed to initialize transaction", id, e);
finished = true;
throw new RuntimeException(id + ": Failed to lock running. Failed to initialize transaction", e);
}
@Override
protected void handleEditException(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final NetconfDocumentedException e, final String editType) {
- LOG.warn("{}: Error " + editType + " data to (candidate){}, data: {}, canceling", id, path, data, e);
+ LOG.warn("{}: Error {} data to (candidate){}, data: {}, canceling", id, editType, path, data, e);
cancel();
throw new RuntimeException(id + ": Error while " + editType + ": (candidate)" + path, e);
}
invokeBlocking("Edit candidate", new Function<NetconfBaseOps, ListenableFuture<DOMRpcResult>>() {
@Override
public ListenableFuture<DOMRpcResult> apply(final NetconfBaseOps input) {
- return defaultOperation.isPresent()
- ? input.editConfigCandidate(new NetconfRpcFutureCallback("Edit candidate", id), editStructure, defaultOperation.get(),
- rollbackSupport)
- : input.editConfigCandidate(new NetconfRpcFutureCallback("Edit candidate", id), editStructure,
- rollbackSupport);
+ return defaultOperation.isPresent()
+ ? input.editConfigCandidate(new NetconfRpcFutureCallback("Edit candidate", id), editStructure, defaultOperation.get(),
+ rollbackSupport)
+ : input.editConfigCandidate(new NetconfRpcFutureCallback("Edit candidate", id), editStructure,
+ rollbackSupport);
}
});
}
}
});
} catch (final NetconfDocumentedException e) {
- LOG.warn("{}: Failed to initialize netconf transaction (lock running)", e);
+ LOG.warn("{}: Failed to initialize netconf transaction (lock running)", id, e);
finished = true;
throw new RuntimeException(id + ": Failed to initialize netconf transaction (lock running)", e);
}
@Override
protected void handleEditException(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data, final NetconfDocumentedException e, final String editType) {
- LOG.warn("{}: Error " + editType + " data to (running){}, data: {}, canceling", id, path, data, e);
+ LOG.warn("{}: Error {} data to (running){}, data: {}, canceling", id, editType, path, data, e);
cancel();
throw new RuntimeException(id + ": Error while " + editType + ": (running)" + path, e);
}
invokeBlocking("Edit running", new Function<NetconfBaseOps, ListenableFuture<DOMRpcResult>>() {
@Override
public ListenableFuture<DOMRpcResult> apply(final NetconfBaseOps input) {
- return defaultOperation.isPresent()
- ? input.editConfigRunning(new NetconfRpcFutureCallback("Edit running", id), editStructure, defaultOperation.get(),
- rollbackSupport)
- : input.editConfigRunning(new NetconfRpcFutureCallback("Edit running", id), editStructure,
- rollbackSupport);
+ return defaultOperation.isPresent()
+ ? input.editConfigRunning(new NetconfRpcFutureCallback("Edit running", id), editStructure, defaultOperation.get(),
+ rollbackSupport)
+ : input.editConfigRunning(new NetconfRpcFutureCallback("Edit running", id), editStructure,
+ rollbackSupport);
}
});
}
}
});
} catch (final NetconfDocumentedException e) {
- LOG.warn("{}: Failed to unlock running datastore", e);
+ LOG.warn("{}: Failed to unlock running datastore", id, e);
throw new RuntimeException(id + ": Failed to unlock running datastore", e);
}
}
public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
- private static final Logger logger = LoggerFactory.getLogger(NetconfRemoteSchemaYangSourceProvider.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NetconfRemoteSchemaYangSourceProvider.class);
private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
"schemaDownload", SchemaSourceException.class) {
final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> builder = Builders.containerBuilder();
builder.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME))
- .withChild(identifier)
- .withChild(format);
+ .withChild(identifier).withChild(format);
if(revision.isPresent()) {
final QName revisionQName = QName.cachedReference(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version"));
final Optional<String> revision = Optional.fromNullable(formattedRevision);
final NormalizedNode<?, ?> getSchemaRequest = createGetSchemaRequest(moduleName, revision);
- logger.trace("{}: Loading YANG schema source for {}:{}", id, moduleName, revision);
+ LOG.trace("{}: Loading YANG schema source for {}:{}", id, moduleName,
+ revision);
final ListenableFuture<YangTextSchemaSource> transformed = Futures.transform(
rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
// (goal is to limit concurrent schema download, since NetconfDevice listener does not handle concurrent messages properly)
// TODO retest this
try {
- logger.trace("{}: Blocking for {}", id, sourceIdentifier);
+ LOG.trace("{}: Blocking for {}", id, sourceIdentifier);
checked.checkedGet();
} catch (final SchemaSourceException e) {
return Futures.immediateFailedCheckedFuture(e);
Preconditions.checkState(schemaString.isPresent(),
"%s: Unexpected response to get-schema, schema not present in message for: %s", id, sourceIdentifier);
- logger.debug("{}: YANG Schema successfully retrieved for {}:{}", id, moduleName, revision);
+ LOG.debug("{}: YANG Schema successfully retrieved for {}:{}",
+ id, moduleName, revision);
return new NetconfYangTextSchemaSource(id, sourceIdentifier, schemaString);
}
- logger.warn("{}: YANG schema was not successfully retrieved for {}. Errors: {}", id, sourceIdentifier,
- input.getErrors());
+ LOG.warn(
+ "{}: YANG schema was not successfully retrieved for {}. Errors: {}",
+ id, sourceIdentifier, input.getErrors());
throw new IllegalStateException(String.format(
"%s: YANG schema was not successfully retrieved for %s. Errors: %s", id, sourceIdentifier,
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.notifications.NetconfNotification;
import org.opendaylight.controller.netconf.util.OrderedNormalizedNodeWriter;
-import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.MessageTransformer;
import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
import org.opendaylight.controller.sal.connect.util.MessageCounter;
try {
return new AbstractMap.SimpleEntry<>(EVENT_TIME_FORMAT.get().parse(eventTimeElement.getTextContent()), notificationElement);
- } catch (NetconfDocumentedException e) {
+ } catch (DocumentedException e) {
throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
} catch (ParseException e) {
- throw new IllegalArgumentException("Notification event time in wrong format " + EVENT_TIME + " " + message);
+ throw new IllegalArgumentException("Unable to parse event time from " + eventTimeElement, e);
}
}
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
@Override
public void onSuccess(final DOMRpcResult result) {
if(result.getErrors().isEmpty()) {
- LOG.trace("{}: " + type + " invoked successfully", id);
+ LOG.trace("{}: {} invoked successfully", id, type);
} else {
onUnsuccess(result);
}
}
protected void onUnsuccess(final DOMRpcResult result) {
- LOG.warn("{}: " + type + " invoked unsuccessfully: {}", id, result.getErrors());
+ LOG.warn("{}: {} invoked unsuccessfully: {}", id, type, result.getErrors());
}
@Override
public void onFailure(final Throwable t) {
- LOG.warn("{}: " + type + " failed.", id, t);
+ LOG.warn("{}: {} failed.", id, type, t);
}
}
package org.opendaylight.controller.sal.connect.util;
-import java.util.concurrent.atomic.AtomicInteger;
-
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
+import java.util.concurrent.atomic.AtomicInteger;
public class MessageCounter {
final AtomicInteger messageId = new AtomicInteger(0);
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())));
+ 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) {
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.MessageTransformer;
import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
}
}).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
- final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
- = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, new NetconfStateSchemas.NetconfStateSchemasResolver() {
+ final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
@Override
public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
final Module first = Iterables.getFirst(schema.getModules(), null);
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(), schemaFactory, stateSchemasResolver);
final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), true);
// Monitoring supported
import java.util.Collections;
import java.util.Set;
import org.junit.Test;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Before;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.notifications.NetconfNotification;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
import org.w3c.dom.Document;
-/**
- * @author Lukas Sedlak <lsedlak@cisco.com>
- */
public class NetconfToNotificationTest {
NetconfMessageTransformer messageTransformer;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
import org.w3c.dom.Document;
-
-/**
- * Test case for reported bug 1355
- *
- * @author Lukas Sedlak
- * @see <a
- * https://bugs.opendaylight.org/show_bug.cgi?id=1355</a>
- */
public class NetconfToRpcRequestTest {
private final static String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
import com.google.common.base.Strings;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
private NetconfMessage createSuccessResponseMessage( String messageID ) throws ParserConfigurationException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
- Element rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, RPC_REPLY_KEY );
+ 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 );
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
import org.opendaylight.controller.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
import org.opendaylight.controller.sal.connect.netconf.util.NetconfBaseOps;
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
+ <artifactId>netconf-tools</artifactId>
<version>0.4.0-SNAPSHOT</version>
</parent>
<artifactId>netconf-cli</artifactId>
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
import org.opendaylight.controller.netconf.cli.reader.ReadingException;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
<parent>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>netconf-subsystem</artifactId>
+ <artifactId>netconf-tools</artifactId>
<version>0.4.0-SNAPSHOT</version>
</parent>
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
}
@Override
- public void onCapabilitiesAdded(Set<Capability> addedCaps) {
-
- }
-
- @Override
- public void onCapabilitiesRemoved(Set<Capability> removedCaps) {
+ public void onSessionUp(NetconfManagementSession session) {
}
@Override
- public void onSessionUp(NetconfManagementSession session) {
+ public void onSessionDown(NetconfManagementSession session) {
}
@Override
- public void onSessionDown(NetconfManagementSession session) {
+ public void onCapabilitiesChanged(Set<Capability> added, Set<Capability> removed) {
}
}
import net.sourceforge.argparse4j.annotation.Arg;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import java.util.Collections;
import java.util.Date;
import java.util.List;
-import org.opendaylight.controller.netconf.api.Capability;
-import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
+import org.opendaylight.controller.config.facade.xml.util.Util;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.lang.management.ManagementFactory;
import java.net.BindException;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.AbstractMap;
+import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.sshd.server.PasswordAuthenticator;
import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
import org.apache.sshd.server.session.ServerSession;
-import org.opendaylight.controller.netconf.api.Capability;
+import org.opendaylight.controller.config.util.capability.Capability;
import org.opendaylight.controller.netconf.api.monitoring.CapabilityListener;
import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
import org.opendaylight.controller.netconf.impl.SessionIdProvider;
aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(simulatedOperationProvider);
aggregatedNetconfOperationServiceFactory.onAddNetconfOperationServiceFactory(monitoringService);
- final DefaultCommitNotificationProducer commitNotifier = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
-
final Set<String> serverCapabilities = exi
? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES
: Sets.newHashSet(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0, XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
- hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, commitNotifier, monitoringService1, serverCapabilities);
+ hashedWheelTimer, aggregatedNetconfOperationServiceFactory, idProvider, generateConfigsTimeout, monitoringService1, serverCapabilities);
final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
serverNegotiatorFactory);
@Override
public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
- listener.onCapabilitiesAdded(caps);
+ listener.onCapabilitiesChanged(caps, Collections.<Capability>emptySet());
return new AutoCloseable() {
@Override
public void close() throws Exception {}
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
import org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandler;
import org.opendaylight.controller.netconf.test.tool.TestToolUtils;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.api.RemoteDevice;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import java.util.Collections;
import java.util.List;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlElement;
public class DataList {
package org.opendaylight.controller.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.impl.NetconfServerSession;
import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultNetconfOperation;
import org.opendaylight.controller.netconf.util.mapping.AbstractLastNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
long delayAggregator = 0;
for (final Map.Entry<Notification, NetconfMessage> notification : notifications.entrySet()) {
package org.opendaylight.controller.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfigXmlParser;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final XmlElement configElementData = operationElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
containsDelete(configElementData);
package org.opendaylight.controller.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Element element = XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
for(final XmlElement e : storage.getConfigList()) {
package org.opendaylight.controller.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
final Element element = XmlUtil.createElement(document, XmlNetconfConstants.DATA_KEY, Optional.<String>absent());
for(final XmlElement e : storage.getConfigList()) {
package org.opendaylight.controller.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
package org.opendaylight.controller.netconf.test.tool.rpc;
import com.google.common.base.Optional;
-import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.config.util.xml.XmlElement;
+import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
-import org.opendaylight.controller.netconf.util.xml.XmlElement;
-import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>netconf-subsystem</artifactId>
+ <version>0.4.0-SNAPSHOT</version>
+ <relativePath>../</relativePath>
+ </parent>
+ <artifactId>netconf-tools</artifactId>
+
+ <version>0.4.0-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <name>${project.artifactId}</name>
+
+ <modules>
+ <module>netconf-cli</module>
+ <module>netconf-testtool</module>
+ </modules>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
+ </instructions>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-maven-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>maven-sal-api-gen-plugin</artifactId>
+ <version>${yangtools.version}</version>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate-sources</goal>
+ </goals>
+ <configuration>
+ <yangFilesRootDir>src/main/yang</yangFilesRootDir>
+ <codeGenerators>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
+ <outputBaseDir>${salGeneratorPath}</outputBaseDir>
+ </generator>
+ <generator>
+ <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
+ <outputBaseDir>${project.build.directory}/site/models</outputBaseDir>
+ </generator>
+ </codeGenerators>
+ <inspectDependencies>true</inspectDependencies>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <failsOnError>false</failsOnError>
+ <failOnViolation>true</failOnViolation>
+ <configLocation>checkstyle-logging.xml</configLocation>
+ <consoleOutput>true</consoleOutput>
+ <includeTestSourceDirectory>true</includeTestSourceDirectory>
+ <sourceDirectory>${project.basedir}</sourceDirectory>
+ <includes>**\/*.java,**\/*.xml,**\/*.ini,**\/*.sh,**\/*.bat,**\/*.yang</includes>
+ <excludes>**\/target\/,**\/bin\/,**\/target-ide\/,**\/${jmxGeneratorPath}\/,**\/${salGeneratorPath}\/,**\/netconf\/test\/tool\/Main.java, **\/netconf\/test\/tool\/client\/stress\/StressClient.java</excludes>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>checkstyle-logging</artifactId>
+ <version>${yangtools.version}</version>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+</project>