DependencyManagement section of your parent pom -->
<branding.version>1.1.0-SNAPSHOT</branding.version>
<karaf.resources.version>1.5.0-SNAPSHOT</karaf.resources.version>
- <karaf.version>3.0.1</karaf.version>
+ <karaf.version>3.0.3</karaf.version>
<feature.test.version>0.7.0-SNAPSHOT</feature.test.version>
<karaf.empty.version>1.5.0-SNAPSHOT</karaf.empty.version>
<surefire.version>2.16</surefire.version>
DependencyManagement section of your parent pom -->
<branding.version>1.1.0-SNAPSHOT</branding.version>
<karaf.resources.version>1.5.0-SNAPSHOT</karaf.resources.version>
- <karaf.version>3.0.1</karaf.version>
+ <karaf.version>3.0.3</karaf.version>
<karaf.empty.version>1.5.0-SNAPSHOT</karaf.empty.version>
<surefire.version>2.16</surefire.version>
</properties>
<properties>
<branding.version>1.1.0-SNAPSHOT</branding.version>
<karaf.resources.version>1.5.0-SNAPSHOT</karaf.resources.version>
+ <karaf.localFeature>standard</karaf.localFeature>
+ <!-- Karaf Maven plugin 3.023 reinstalls already installed
+ boot features to container, which could be observed
+ in huge logs and seems like loop in build, even if it
+ is not.
+ -->
+ <karaf.maven.version>3.0.1</karaf.maven.version>
</properties>
<dependencyManagement>
<dependencies>
</dependencies>
</dependencyManagement>
<dependencies>
+ <!-- karaf standard features -->
+ <dependency>
+ <groupId>org.apache.karaf.features</groupId>
+ <artifactId>standard</artifactId>
+ <version>${karaf.version}</version>
+ <type>xml</type>
+ <classifier>features</classifier>
+ <scope>runtime</scope>
+ </dependency>
<!-- ODL Branding -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
<plugin>
<groupId>org.apache.karaf.tooling</groupId>
<artifactId>karaf-maven-plugin</artifactId>
- <version>${karaf.version}</version>
+ <version>${karaf.maven.version}</version>
<extensions>true</extensions>
<configuration>
<!-- no startupFeatures -->
<groupId>org.opendaylight.controller</groupId>
<artifactId>karaf-parent</artifactId>
<version>1.5.0-SNAPSHOT</version>
- <relativePath/>
+ <relativePath>../karaf-parent</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.opendaylight.controller</groupId>
# Increase the maximum file descriptors if we can
if [ "$os400" = "false" ] && [ "$cygwin" = "false" ]; then
MAX_FD_LIMIT=`ulimit -H -n`
- if [ "$MAX_FD_LIMIT" != 'unlimited' ]; then
+ if [ "$MAX_FD_LIMIT" != 'unlimited' ]; then
if [ $? -eq 0 ]; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then
# use the system max
fi
if [ "x$JAVA_HOME" = "x" ] && [ "$darwin" = "true" ]; then
- JAVA_HOME="$(/usr/libexec/java_home)"
+ JAVA_HOME="$(/usr/libexec/java_home -v 1.7)"
fi
if [ "x$JAVA" = "x" ] && [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
else
warn "JAVA_HOME not set; results may vary"
JAVA=`type java`
- JAVA=`expr "$JAVA" : '.*is \(.*\)$'`
+ JAVA=`expr "$JAVA" : '.* \(/.*\)$'`
if [ "x$JAVA" = "x" ]; then
die "java command not found"
fi
fi
export JAVA_OPTS
+ if [ "x$EXTRA_JAVA_OPTS" != "x" ]; then
+ JAVA_OPTS="$JAVA_OPTS $EXTRA_JAVA_OPTS"
+ fi
+
# Set Debug options if enabled
if [ "x$KARAF_DEBUG" != "x" ]; then
# Use the defaults if JAVA_DEBUG_OPTS was not set
CLASSPATH="$CLASSPATH:$file"
fi
done
- DEFAULT_JAVA_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"
+
+ DEFAULT_JAVA_DEBUG_PORT="5005"
+ if [ "x$JAVA_DEBUG_PORT" = "x" ]; then
+ JAVA_DEBUG_PORT="$DEFAULT_JAVA_DEBUG_PORT"
+ fi
+ DEFAULT_JAVA_DEBUG_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$JAVA_DEBUG_PORT"
##
## TODO: Move to conf/profiler/yourkit.{sh|cmd}
run() {
- CLASSPATH="${KARAF_HOME}/system/org/apache/karaf/instance/org.apache.karaf.instance.command/3.0.1/org.apache.karaf.instance.command-3.0.1.jar:${KARAF_HOME}/system/org/apache/karaf/instance/org.apache.karaf.instance.core/3.0.1/org.apache.karaf.instance.core-3.0.1.jar:${KARAF_HOME}/system/org/apache/karaf/shell/org.apache.karaf.shell.console/3.0.1/org.apache.karaf.shell.console-3.0.1.jar:${KARAF_HOME}/system/org/apache/karaf/shell/org.apache.karaf.shell.table/3.0.1/org.apache.karaf.shell.table-3.0.1.jar:${KARAF_HOME}/system/org/apache/aries/blueprint/org.apache.aries.blueprint.api/1.0.0/org.apache.aries.blueprint.api-1.0.0.jar:${KARAF_HOME}/system/org/apache/aries/blueprint/org.apache.aries.blueprint.core/1.4.0/org.apache.aries.blueprint.core-1.4.0.jar:${KARAF_HOME}/system/org/apache/aries/blueprint/org.apache.aries.blueprint.cm/1.0.3/org.apache.aries.blueprint.cm-1.0.3.jar:${KARAF_HOME}/system/org/ops4j/pax/logging/pax-logging-api/1.7.2/pax-logging-api-1.7.2.jar:${KARAF_HOME}/system/org/apache/felix/org.apache.felix.framework/4.2.1/org.apache.felix.framework-4.2.1.jar:${KARAF_HOME}/system/jline/jline/2.11/jline-2.11.jar:$CLASSPATH"
+ CLASSPATH="${KARAF_HOME}/system/org/apache/karaf/instance/org.apache.karaf.instance.command/3.0.3/org.apache.karaf.instance.command-3.0.3.jar:${KARAF_HOME}/system/org/apache/karaf/instance/org.apache.karaf.instance.core/3.0.3/org.apache.karaf.instance.core-3.0.3.jar:${KARAF_HOME}/system/org/apache/karaf/shell/org.apache.karaf.shell.console/3.0.3/org.apache.karaf.shell.console-3.0.3.jar:${KARAF_HOME}/system/org/apache/karaf/shell/org.apache.karaf.shell.table/3.0.3/org.apache.karaf.shell.table-3.0.3.jar:${KARAF_HOME}/system/org/apache/aries/blueprint/org.apache.aries.blueprint.api/1.0.1/org.apache.aries.blueprint.api-1.0.1.jar:${KARAF_HOME}/system/org/apache/aries/blueprint/org.apache.aries.blueprint.core/1.4.2/org.apache.aries.blueprint.core-1.4.2.jar:${KARAF_HOME}/system/org/apache/aries/blueprint/org.apache.aries.blueprint.cm/1.0.5/org.apache.aries.blueprint.cm-1.0.5.jar:${KARAF_HOME}/system/org/ops4j/pax/logging/pax-logging-api/1.8.1/pax-logging-api-1.8.1.jar:${KARAF_HOME}/system/org/apache/felix/org.apache.felix.framework/4.2.1/org.apache.felix.framework-4.2.1.jar:${KARAF_HOME}/system/jline/jline/2.12/jline-2.12.jar:$CLASSPATH"
if $cygwin; then
KARAF_HOME=`cygpath --path --windows "$KARAF_HOME"`
}
main "$@"
-
)\r
\r
set DEFAULT_JAVA_OPTS=\r
-set DEFAULT_JAVA_DEBUG_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005\r
+set DEFAULT_JAVA_DEBUG_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005\r
\r
rem Support for loading native libraries\r
set PATH=%PATH%;%KARAF_BASE%\lib;%KARAF_HOME%\lib\r
\r
if "%JAVA_OPTS%" == "" set JAVA_OPTS=%DEFAULT_JAVA_OPTS%\r
\r
+if "%EXTRA_JAVA_OPTS%" == "" goto :KARAF_EXTRA_JAVA_OPTS_END\r
+ set JAVA_OPTS="%JAVA_OPTS% %EXTRA_JAVA_OPTS%"\r
+:KARAF_EXTRA_JAVA_OPTS_END\r
+\r
if "%KARAF_DEBUG%" == "" goto :KARAF_DEBUG_END\r
rem Use the defaults if JAVA_DEBUG_OPTS was not set\r
if "%JAVA_DEBUG_OPTS%" == "" set JAVA_DEBUG_OPTS=%DEFAULT_JAVA_DEBUG_OPTS%\r
\r
- set "JAVA_OPTS=%JAVA_DEBUG_OPTS% %JAVA_OPTS%"\r
+ set JAVA_OPTS="%JAVA_DEBUG_OPTS% %JAVA_OPTS%"\r
call :warn Enabling Java debug options: %JAVA_DEBUG_OPTS%\r
:KARAF_DEBUG_END\r
\r
\r
:CLASSPATH_END\r
\r
-set CLASSPATH=%KARAF_HOME%\system\org\apache\karaf\instance\org.apache.karaf.instance.command\3.0.1\org.apache.karaf.instance.command-3.0.1.jar;%KARAF_HOME%\system\org\apache\karaf\instance\org.apache.karaf.instance.core\3.0.1\org.apache.karaf.instance.core-3.0.1.jar;%KARAF_HOME%\system\org\apache\karaf\shell\org.apache.karaf.shell.console\3.0.1\org.apache.karaf.shell.console-3.0.1.jar;%KARAF_HOME%\system\org\apache\karaf\shell\org.apache.karaf.shell.table\3.0.1\org.apache.karaf.shell.table-3.0.1.jar;%KARAF_HOME%\system\org\apache\aries\blueprint\org.apache.aries.blueprint.api\1.0.0\org.apache.aries.blueprint.api-1.0.0.jar;%KARAF_HOME%\system\org\apache\aries\blueprint\org.apache.aries.blueprint.core\1.4.0\org.apache.aries.blueprint.core-1.4.0.jar;%KARAF_HOME%\system\org\apache\aries\blueprint\org.apache.aries.blueprint.cm\1.0.3\org.apache.aries.blueprint.cm-1.0.3.jar;%KARAF_HOME%\system\org\ops4j\pax\logging\pax-logging-api\1.7.2\pax-logging-api-1.7.2.jar;%KARAF_HOME%\system\org\apache\felix\org.apache.felix.framework\4.2.1\org.apache.felix.framework-4.2.1.jar;%KARAF_HOME%\system\jline\jline\2.11\jline-2.11.jar;%CLASSPATH%\r
+set CLASSPATH=%KARAF_HOME%\system\org\apache\karaf\instance\org.apache.karaf.instance.command\3.0.3\org.apache.karaf.instance.command-3.0.3.jar;%KARAF_HOME%\system\org\apache\karaf\instance\org.apache.karaf.instance.core\3.0.3\org.apache.karaf.instance.core-3.0.3.jar;%KARAF_HOME%\system\org\apache\karaf\shell\org.apache.karaf.shell.console\3.0.3\org.apache.karaf.shell.console-3.0.3.jar;%KARAF_HOME%\system\org\apache\karaf\shell\org.apache.karaf.shell.table\3.0.3\org.apache.karaf.shell.table-3.0.3.jar;%KARAF_HOME%\system\org\apache\aries\blueprint\org.apache.aries.blueprint.api\1.0.1\org.apache.aries.blueprint.api-1.0.1.jar;%KARAF_HOME%\system\org\apache\aries\blueprint\org.apache.aries.blueprint.core\1.4.2\org.apache.aries.blueprint.core-1.4.2.jar;%KARAF_HOME%\system\org\apache\aries\blueprint\org.apache.aries.blueprint.cm\1.0.5\org.apache.aries.blueprint.cm-1.0.5.jar;%KARAF_HOME%\system\org\ops4j\pax\logging\pax-logging-api\1.8.1\pax-logging-api-1.8.1.jar;%KARAF_HOME%\system\org\apache\felix\org.apache.felix.framework\4.2.1\org.apache.felix.framework-4.2.1.jar;%KARAF_HOME%\system\jline\jline\2.12\jline-2.12.jar;%CLASSPATH%\r
\r
:EXECUTE\r
if "%SHIFT%" == "true" SET ARGS=%2 %3 %4 %5 %6 %7 %8\r
:END\r
\r
endlocal\r
-\r
# limitations under the License.
#
-DIRNAME=`dirname $0`
-PROGNAME=`basename $0`
+DIRNAME=`dirname "$0"`
+PROGNAME=`basename "$0"`
#
# Sourcing environment settings for karaf similar to tomcats setenv
# Increase the maximum file descriptors if we can
if [ "$os400" = "false" ] && [ "$cygwin" = "false" ]; then
MAX_FD_LIMIT=`ulimit -H -n`
- if [ "$MAX_FD_LIMIT" != 'unlimited' ]; then
+ if [ "$MAX_FD_LIMIT" != 'unlimited' ]; then
if [ $? -eq 0 ]; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then
# use the system max
fi
if [ "x$JAVA_HOME" = "x" ] && [ "$darwin" = "true" ]; then
- JAVA_HOME="$(/usr/libexec/java_home)"
+ JAVA_HOME="$(/usr/libexec/java_home -v 1.7)"
fi
if [ "x$JAVA" = "x" ] && [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
else
warn "JAVA_HOME not set; results may vary"
JAVA=`type java`
- JAVA=`expr "$JAVA" : '.*is \(.*\)$'`
+ JAVA=`expr "$JAVA" : '.* \(/.*\)$'`
if [ "x$JAVA" = "x" ]; then
die "java command not found"
fi
checkJvmVersion() {
# echo "`$JAVA -version`"
- VERSION=`$JAVA -version 2>&1 | egrep '"([0-9].[0-9]\..*[0-9])"' | awk '{print substr($3,2,length($3)-2)}' | awk '{print substr($1, 3, 3)}' | sed -e 's;\.;;g'`
+ VERSION=`$JAVA -version 2>&1 | egrep '"([0-9].[0-9]\..*[0-9]).*"' | awk '{print substr($3,2,length($3)-2)}' | awk '{print substr($1, 3, 3)}' | sed -e 's;\.;;g'`
# echo $VERSION
if [ "$VERSION" -lt "60" ]; then
echo "JVM must be greater than 1.6"
fi
export JAVA_OPTS
+ if [ "x$EXTRA_JAVA_OPTS" != "x" ]; then
+ JAVA_OPTS="$JAVA_OPTS $EXTRA_JAVA_OPTS"
+ fi
+
# Set Debug options if enabled
if [ "x$KARAF_DEBUG" != "x" ]; then
# Ignore DEBUG in case of stop or client mode
CLASSPATH="$CLASSPATH:$file"
fi
done
- DEFAULT_JAVA_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"
+
+ DEFAULT_JAVA_DEBUG_PORT="5005"
+ if [ "x$JAVA_DEBUG_PORT" = "x" ]; then
+ JAVA_DEBUG_PORT="$DEFAULT_JAVA_DEBUG_PORT"
+ fi
+ DEFAULT_JAVA_DEBUG_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$JAVA_DEBUG_PORT"
##
## TODO: Move to conf/profiler/yourkit.{sh|cmd}
# Determine the JVM vendor
detectJVM
-
+
# Determine the JVM version >= 1.6
checkJvmVersion
\r
set LOCAL_CLASSPATH=%CLASSPATH%\r
set JAVA_MODE=-server\r
-if not exist "%JAVA_HOME%\bin\server\jvm.dll" (\r
- if not exist "%JAVA_HOME%\jre\bin\server\jvm.dll" (\r
- echo WARNING: Running karaf on a Java HotSpot Client VM because server-mode is not available.\r
- echo Install Java Developer Kit to fix this.\r
- echo For more details see http://java.sun.com/products/hotspot/whitepaper.html#client\r
- set JAVA_MODE=-client\r
- )\r
-)\r
-set DEFAULT_JAVA_OPTS=%JAVA_MODE% -Xms%JAVA_MIN_MEM% -Xmx%JAVA_MAX_MEM% -Dderby.system.home="%KARAF_DATA%\derby" -Dderby.storage.fileSyncTransactionLog=true -Dcom.sun.management.jmxremote -XX:+UnlockDiagnosticVMOptions -XX:+UnsyncloadClass\r
-\r
-rem Check some easily accessible MIN/MAX params for JVM mem usage\r
-if not "%JAVA_PERM_MEM%" == "" (\r
- set DEFAULT_JAVA_OPTS=%DEFAULT_JAVA_OPTS% -XX:PermSize=%JAVA_PERM_MEM%\r
-)\r
-if not "%JAVA_MAX_PERM_MEM%" == "" (\r
- set DEFAULT_JAVA_OPTS=%DEFAULT_JAVA_OPTS% -XX:MaxPermSize=%JAVA_MAX_PERM_MEM%\r
-)\r
\r
set CLASSPATH=%LOCAL_CLASSPATH%;%KARAF_BASE%\conf\r
-set DEFAULT_JAVA_DEBUG_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005\r
+set DEFAULT_JAVA_DEBUG_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005\r
\r
if "%LOCAL_CLASSPATH%" == "" goto :KARAF_CLASSPATH_EMPTY\r
set CLASSPATH=%LOCAL_CLASSPATH%;%KARAF_BASE%\conf\r
)\r
if not exist "%JAVA_HOME%" (\r
goto TryRegJDK\r
- )\r
- goto TryJDKEnd\r
+ )\r
+ goto TryJDKEnd\r
:TryRegJDK\r
rem try getting the JAVA_HOME from registry\r
FOR /F "usebackq tokens=3*" %%A IN (`REG QUERY "HKLM\Software\JavaSoft\Java Development Kit" /v CurrentVersion`) DO (\r
if not exist "%JAVA_HOME%" (\r
call :warn Unable to retrieve JAVA_HOME from Registry\r
)\r
- goto TryJDKEnd\r
+ goto TryJDKEnd\r
:TryJDKEnd\r
if not exist "%JAVA_HOME%" (\r
call :warn JAVA_HOME is not valid: "%JAVA_HOME%"\r
set JAVA=%JAVA_HOME%\bin\java\r
:Check_JAVA_END\r
\r
+if not exist "%JAVA_HOME%\bin\server\jvm.dll" (\r
+ if not exist "%JAVA_HOME%\jre\bin\server\jvm.dll" (\r
+ echo WARNING: Running Karaf on a Java HotSpot Client VM because server-mode is not available.\r
+ echo Install Java Developer Kit to fix this.\r
+ echo For more details see http://java.sun.com/products/hotspot/whitepaper.html#client\r
+ set JAVA_MODE=-client\r
+ )\r
+)\r
+set DEFAULT_JAVA_OPTS=%JAVA_MODE% -Xms%JAVA_MIN_MEM% -Xmx%JAVA_MAX_MEM% -Dderby.system.home="%KARAF_DATA%\derby" -Dderby.storage.fileSyncTransactionLog=true -Dcom.sun.management.jmxremote -XX:+UnlockDiagnosticVMOptions -XX:+UnsyncloadClass\r
+\r
+rem Check some easily accessible MIN/MAX params for JVM mem usage\r
+if not "%JAVA_PERM_MEM%" == "" (\r
+ set DEFAULT_JAVA_OPTS=%DEFAULT_JAVA_OPTS% -XX:PermSize=%JAVA_PERM_MEM%\r
+)\r
+if not "%JAVA_MAX_PERM_MEM%" == "" (\r
+ set DEFAULT_JAVA_OPTS=%DEFAULT_JAVA_OPTS% -XX:MaxPermSize=%JAVA_MAX_PERM_MEM%\r
+)\r
+\r
if "%JAVA_OPTS%" == "" set JAVA_OPTS=%DEFAULT_JAVA_OPTS%\r
\r
+if "%EXTRA_JAVA_OPTS%" == "" goto :KARAF_EXTRA_JAVA_OPTS_END\r
+ set JAVA_OPTS=%JAVA_OPTS% %EXTRA_JAVA_OPTS%\r
+:KARAF_EXTRA_JAVA_OPTS_END\r
+\r
if "%KARAF_DEBUG%" == "" goto :KARAF_DEBUG_END\r
if "%1" == "stop" goto :KARAF_DEBUG_END\r
if "%1" == "client" goto :KARAF_DEBUG_END\r
rem Use the defaults if JAVA_DEBUG_OPTS was not set\r
if "%JAVA_DEBUG_OPTS%" == "" set JAVA_DEBUG_OPTS=%DEFAULT_JAVA_DEBUG_OPTS%\r
\r
- set "JAVA_OPTS=%JAVA_DEBUG_OPTS% %JAVA_OPTS%"\r
+ set JAVA_OPTS=%JAVA_DEBUG_OPTS% %JAVA_OPTS%\r
call :warn Enabling Java debug options: %JAVA_DEBUG_OPTS%\r
:KARAF_DEBUG_END\r
\r
\r
:EXECUTE_DEBUG\r
if "%JAVA_DEBUG_OPTS%" == "" set JAVA_DEBUG_OPTS=%DEFAULT_JAVA_DEBUG_OPTS%\r
- set "JAVA_OPTS=%JAVA_DEBUG_OPTS% %JAVA_OPTS%"\r
+ set JAVA_OPTS=%JAVA_DEBUG_OPTS% %JAVA_OPTS%\r
shift\r
goto :RUN_LOOP\r
\r
if not "%PAUSE%" == "" pause\r
\r
:END_NO_PAUSE\r
-\r
#
#
-# The following section shows the possible configuration options for the default
+# The following section shows the possible configuration options for the default
# karaf scripts
#
# export JAVA_HOME # Location of Java installation
# export JAVA_MAX_MEM # Maximum memory for the JVM
# export JAVA_PERM_MEM # Minimum perm memory for the JVM
# export JAVA_MAX_PERM_MEM # Maximum perm memory for the JVM
+# export EXTRA_JAVA_OPTS # Additional JVM options
# export KARAF_HOME # Karaf home folder
# export KARAF_DATA # Karaf data folder
# export KARAF_BASE # Karaf base folder
# export KARAF_ETC # Karaf etc folder
# export KARAF_OPTS # Additional available Karaf options
# export KARAF_DEBUG # Enable debug mode
+# export KARAF_REDIRECT # Enable/set the std/err redirection when using bin/start
if [ "x$JAVA_MAX_PERM_MEM" = "x" ]; then
export JAVA_MAX_PERM_MEM="512m"
fi
if [ "x$JAVA_MAX_MEM" = "x" ]; then
export JAVA_MAX_MEM="2048m"
fi
-
rem SET JAVA_PERM_MEM
rem Maximum perm memory for the JVM
rem SET JAVA_MAX_PERM_MEM
+rem Additional JVM options
+rem SET EXTRA_JAVA_OPTS
rem Karaf home folder
rem SET KARAF_HOME
rem Karaf data folder
# Extra packages to import from the boot class loader
org.osgi.framework.system.packages.extra=org.apache.karaf.branding,sun.reflect,sun.reflect.misc,sun.misc,sun.nio.ch
-# Override the config.properties to remove
-# ${services-${karaf.framework}}
-# This is to work around:
-# https://issues.apache.org/jira/browse/KARAF-3092
-# Which should be fixed in karaf 3.0.2
-# Which is not as of today (2014-08-24) released.
-# Since it is biting folks, we need to fix it here
-# Please remove this when we shift to karaf 3.0.2
-org.osgi.framework.system.capabilities= \
- ${eecap-${java.specification.version}}, \
- service-reference;effective:=active;objectClass=org.osgi.service.packageadmin.PackageAdmin, \
- service-reference;effective:=active;objectClass=org.osgi.service.startlevel.StartLevel, \
- service-reference;effective:=active;objectClass=org.osgi.service.url.URLHandlers
-
# https://bugs.eclipse.org/bugs/show_bug.cgi?id=325578
# Extend the framework to avoid the resources to be presented with
# a URL of type bundleresource: but to be presented as file:
javax.accessibility, \
javax.activation;version="1.1", \
javax.activity, \
- javax.annotation;version="1.1", \
- javax.annotation.processing;version="1.1", \
+ javax.annotation;version="1.0", \
+ javax.annotation.processing;version="1.6", \
javax.crypto, \
javax.crypto.interfaces, \
javax.crypto.spec, \
org.w3c.dom.xpath, \
org.xml.sax, \
org.xml.sax.ext, \
- org.xml.sax.helpers, \
+ org.xml.sax.helpers, \
sun.misc
# Standard package set. Note that:
javax.accessibility, \
javax.activation;version="1.1", \
javax.activity, \
- javax.annotation;version="1.2", \
- javax.annotation.processing;version="1.2", \
+ javax.annotation;version="1.0", \
+ javax.annotation.processing;version="1.6", \
javax.crypto, \
javax.crypto.interfaces, \
javax.crypto.spec, \
org.w3c.dom.xpath, \
org.xml.sax, \
org.xml.sax.ext, \
- org.xml.sax.helpers, \
+ org.xml.sax.helpers, \
sun.misc
jre-1.8= \
javax.accessibility, \
javax.activation;version="1.1", \
javax.activity, \
- javax.annotation;version="1.2", \
- javax.annotation.processing;version="1.2", \
+ javax.annotation;version="1.0", \
+ javax.annotation.processing;version="1.6", \
javax.crypto, \
javax.crypto.interfaces, \
javax.crypto.spec, \
javax.xml.ws.wsaddressing;version="2.2", \
javax.xml.ws.spi.http;version="2.2", \
javax.xml.xpath, \
+ javafx.animation, \
+ javafx.application, \
+ javafx.beans, \
+ javafx.beans.binding, \
+ javafx.beans.property, \
+ javafx.beans.property.adapter, \
+ javafx.beans.value, \
+ javafx.collections, \
+ javafx.concurrent, \
+ javafx.css, \
+ javafx.embed.swing, \
+ javafx.embed.swt, \
+ javafx.event, \
+ javafx.fxml, \
+ javafx.geometry, \
+ javafx.scene, \
+ javafx.scene.canvas, \
+ javafx.scene.chart, \
+ javafx.scene.control, \
+ javafx.scene.control.cell, \
+ javafx.scene.effect, \
+ javafx.scene.image, \
+ javafx.scene.input, \
+ javafx.scene.layout, \
+ javafx.scene.media, \
+ javafx.scene.paint, \
+ javafx.scene.shape, \
+ javafx.scene.text, \
+ javafx.scene.transform, \
+ javafx.scene.web, \
+ javafx.stage, \
+ javafx.util, \
+ javafx.util.converter, \
org.ietf.jgss, \
org.omg.CORBA, \
org.omg.CORBA_2_3, \
org.w3c.dom.xpath, \
org.xml.sax, \
org.xml.sax.ext, \
- org.xml.sax.helpers, \
+ org.xml.sax.helpers, \
sun.misc
<bundle>mvn:org.opendaylight.controller/configuration.implementation/${configuration.implementation.version}</bundle>
</feature>
<feature name="odl-adsal-thirdparty" description="OpenDaylight :: AD-SAL :: Third-Party Depenencies" version="${project.version}">
- <bundle>mvn:org.opendaylight.controller/logging.bridge/${logging.bridge.version}</bundle>
+ <!-- Removed out - causes loop in loggers which polutes logs expotencially
+ <bundle>mvn:org.opendaylight.controller/logging.bridge/${logging.bridge.version}</bundle>
+ -->
</feature>
</features>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
- <version>3.0.0</version>
+ <version>${karaf.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
DependencyManagement section of your parent pom -->
<branding.version>1.1.0-SNAPSHOT</branding.version>
<karaf.resources.version>1.5.0-SNAPSHOT</karaf.resources.version>
- <karaf.version>3.0.1</karaf.version>
+ <karaf.version>3.0.3</karaf.version>
</properties>
<dependencies>
DependencyManagement section of your parent pom -->
<branding.version>1.1.0-SNAPSHOT</branding.version>
<karaf.resources.version>1.5.0-SNAPSHOT</karaf.resources.version>
- <karaf.version>3.0.1</karaf.version>
+ <karaf.version>3.0.3</karaf.version>
<feature.test.version>1.5.0-SNAPSHOT</feature.test.version>
<karaf.empty.version>1.5.0-SNAPSHOT</karaf.empty.version>
<surefire.version>2.16</surefire.version>
<jsr311.api.version>1.1.1</jsr311.api.version>
<jsr311.v2.api.version>2.0</jsr311.v2.api.version>
<karaf.branding.version>1.1.0-SNAPSHOT</karaf.branding.version>
- <karaf.shell.version>3.0.0</karaf.shell.version>
- <karaf.version>3.0.1</karaf.version>
+ <karaf.shell.version>${karaf.version}</karaf.shell.version>
<leveldb.version>0.7</leveldb.version>
<leveldbjni.version>1.8</leveldbjni.version>
<lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
import com.google.common.base.Preconditions;
import java.util.LinkedHashSet;
import java.util.List;
-import java.util.Map;
import javax.xml.bind.JAXBException;
import org.apache.karaf.features.BundleInfo;
import org.apache.karaf.features.Conditional;
import org.apache.karaf.features.ConfigFileInfo;
+import org.apache.karaf.features.ConfigInfo;
import org.apache.karaf.features.Dependency;
import org.apache.karaf.features.Feature;
import org.slf4j.Logger;
/*
* @param f Feature to wrap
*/
- public AbstractFeatureWrapper(Feature f) {
+ public AbstractFeatureWrapper(final Feature f) {
Preconditions.checkNotNull(f,"FeatureWrapper requires non-null Feature in constructor");
this.feature = f;
}
* from the underlying Feature Config files
*/
public LinkedHashSet<FeatureConfigSnapshotHolder> getFeatureConfigSnapshotHolders() throws Exception {
- LinkedHashSet <FeatureConfigSnapshotHolder> snapShotHolders = new LinkedHashSet<FeatureConfigSnapshotHolder>();
- for(ConfigFileInfo c: getConfigurationFiles()) {
+ final LinkedHashSet <FeatureConfigSnapshotHolder> snapShotHolders = new LinkedHashSet<FeatureConfigSnapshotHolder>();
+ for(final ConfigFileInfo c: getConfigurationFiles()) {
try {
snapShotHolders.add(new FeatureConfigSnapshotHolder(c,this));
- } catch (JAXBException e) {
+ } catch (final JAXBException e) {
LOG.debug("{} is not a config subsystem config file",c.getFinalname());
}
}
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
- AbstractFeatureWrapper other = (AbstractFeatureWrapper) obj;
+ final AbstractFeatureWrapper other = (AbstractFeatureWrapper) obj;
if (feature == null) {
if (other.feature != null) {
return false;
* @return
* @see org.apache.karaf.features.Feature#getId()
*/
+ @Override
public String getId() {
return feature.getId();
}
* @return
* @see org.apache.karaf.features.Feature#getName()
*/
+ @Override
public String getName() {
return feature.getName();
}
* @return
* @see org.apache.karaf.features.Feature#getDescription()
*/
+ @Override
public String getDescription() {
return feature.getDescription();
}
* @return
* @see org.apache.karaf.features.Feature#getDetails()
*/
+ @Override
public String getDetails() {
return feature.getDetails();
}
* @return
* @see org.apache.karaf.features.Feature#getVersion()
*/
+ @Override
public String getVersion() {
return feature.getVersion();
}
* @return
* @see org.apache.karaf.features.Feature#hasVersion()
*/
+ @Override
public boolean hasVersion() {
return feature.hasVersion();
}
* @return
* @see org.apache.karaf.features.Feature#getResolver()
*/
+ @Override
public String getResolver() {
return feature.getResolver();
}
* @return
* @see org.apache.karaf.features.Feature#getInstall()
*/
+ @Override
public String getInstall() {
return feature.getInstall();
}
* @return
* @see org.apache.karaf.features.Feature#getDependencies()
*/
+ @Override
public List<Dependency> getDependencies() {
return feature.getDependencies();
}
* @return
* @see org.apache.karaf.features.Feature#getBundles()
*/
+ @Override
public List<BundleInfo> getBundles() {
return feature.getBundles();
}
* @return
* @see org.apache.karaf.features.Feature#getConfigurations()
*/
- public Map<String, Map<String, String>> getConfigurations() {
+ @Override
+ public List<ConfigInfo> getConfigurations() {
return feature.getConfigurations();
}
* @return
* @see org.apache.karaf.features.Feature#getConfigurationFiles()
*/
+ @Override
public List<ConfigFileInfo> getConfigurationFiles() {
return feature.getConfigurationFiles();
}
* @return
* @see org.apache.karaf.features.Feature#getConditional()
*/
+ @Override
public List<? extends Conditional> getConditional() {
return feature.getConditional();
}
* @return
* @see org.apache.karaf.features.Feature#getStartLevel()
*/
+ @Override
public int getStartLevel() {
return feature.getStartLevel();
}
* @return
* @see org.apache.karaf.features.Feature#getRegion()
*/
+ @Override
public String getRegion() {
return feature.getRegion();
}
<artifactId>sal-remoterpc-connector</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft-example</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<!-- OpenFlow stuff -->
<dependency>
assertNotNull("Module has not been created correctly.", messageBusAppImplModuleFactory.createModule("instanceName1", dependencyResolverMock, dynamicMBeanWithInstanceMock, bundleContextMock));
}
-}
+}
\ No newline at end of file
*/
package org.opendaylight.controller.config.yang.messagebus.app.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.mock;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.config.api.DependencyResolver;
+import org.opendaylight.controller.config.api.JmxAttribute;
import org.opendaylight.controller.config.api.ModuleIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.MountPointService;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+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.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
+import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.sal.core.api.Provider;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.osgi.framework.BundleContext;
+import javax.management.ObjectName;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
public class MessageBusAppImplModuleTest {
MessageBusAppImplModule messageBusAppImplModule;
assertEquals("Set and/or get method/s don't work correctly.", bundleContext, messageBusAppImplModule.getBundleContext());
}
- //TODO: create MessageBusAppImplModule.createInstance test
-}
+ @Test
+ public void createInstanceTest() throws Exception{
+ org.opendaylight.controller.sal.binding.api.BindingAwareBroker bindingAwareBrokerMock = mock(org.opendaylight.controller.sal.binding.api.BindingAwareBroker.class);
+ Broker brokerMock = mock(Broker.class);
+ doReturn(brokerMock).when(dependencyResolverMock).resolveInstance(eq(org.opendaylight.controller.sal.core.api.Broker.class), any(ObjectName.class), any(JmxAttribute.class));
+ doReturn(bindingAwareBrokerMock).when(dependencyResolverMock).resolveInstance(eq(org.opendaylight.controller.sal.binding.api.BindingAwareBroker.class), any(ObjectName.class), any(JmxAttribute.class));
+ messageBusAppImplModule.resolveDependencies();
+
+ BindingAwareBroker.ProviderContext providerContext = mock(BindingAwareBroker.ProviderContext.class);
+ doReturn(providerContext).when(bindingAwareBrokerMock).registerProvider(any(BindingAwareProvider.class));
+ Broker.ProviderSession providerSessionMock = mock(Broker.ProviderSession.class);
+ doReturn(providerSessionMock).when(brokerMock).registerProvider(any(Provider.class));
+ DataBroker dataBrokerMock = mock(DataBroker.class);
+ doReturn(dataBrokerMock).when(providerContext).getSALService(eq(DataBroker.class));
+ DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
+ doReturn(domNotificationPublishServiceMock).when(providerSessionMock).getService(DOMNotificationPublishService.class);
+ DOMMountPointService domMountPointServiceMock = mock(DOMMountPointService.class);
+ doReturn(domMountPointServiceMock).when(providerSessionMock).getService(DOMMountPointService.class);
+ MountPointService mountPointServiceMock = mock(MountPointService.class);
+ doReturn(mountPointServiceMock).when(providerContext).getSALService(eq(MountPointService.class));
+ RpcProviderRegistry rpcProviderRegistryMock = mock(RpcProviderRegistry.class);
+ doReturn(rpcProviderRegistryMock).when(providerContext).getSALService(eq(RpcProviderRegistry.class));
+
+ WriteTransaction writeTransactionMock = mock(WriteTransaction.class);
+ doReturn(writeTransactionMock).when(dataBrokerMock).newWriteOnlyTransaction();
+ doNothing().when(writeTransactionMock).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class), eq(true));
+
+ assertNotNull("EventSourceRegistryWrapper has not been created correctly.", messageBusAppImplModule.createInstance());
+ }
+
+}
\ No newline at end of file
--- /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.messagebus.app.impl;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.messagebus.spi.EventSource;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+public class EventSourceRegistrationImplTest {
+
+ EventSourceRegistrationImplLocal eventSourceRegistrationImplLocal;
+ EventSourceTopology eventSourceTopologyMock;
+
+ @BeforeClass
+ public static void initTestClass() throws IllegalAccessException, InstantiationException {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ EventSource eventSourceMock = mock(EventSource.class);
+ eventSourceTopologyMock = mock(EventSourceTopology.class);
+ eventSourceRegistrationImplLocal = new EventSourceRegistrationImplLocal(eventSourceMock, eventSourceTopologyMock);
+ }
+
+ @Test
+ public void removeRegistrationTest() {
+ eventSourceRegistrationImplLocal.removeRegistration();
+ verify(eventSourceTopologyMock, times(1)).unRegister(any(EventSource.class));
+ }
+
+
+ private class EventSourceRegistrationImplLocal extends EventSourceRegistrationImpl{
+
+ /**
+ * @param instance of EventSource that has been registered by {@link EventSourceRegistryImpl#registerEventSource(Node, org.opendaylight.controller.messagebus.spi.EventSource)}
+ * @param eventSourceTopology
+ */
+ public EventSourceRegistrationImplLocal(EventSource instance, EventSourceTopology eventSourceTopology) {
+ super(instance, eventSourceTopology);
+ }
+ }
+
+}
\ No newline at end of file
nodeIdMock = mock(NodeId.class);
doReturn(nodeIdMock).when(dataObjectMock).getId();
- doReturn("0").when(nodeIdMock).getValue();
+ doReturn("nodeIdPattern1").when(nodeIdMock).getValue();
}
@Test
verify(eventSourceServiceMock, times(1)).joinTopic(any(JoinTopicInput.class));
}
-}
+}
\ No newline at end of file
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
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.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
CreateTopicInput createTopicInputMock;
ListenerRegistration listenerRegistrationMock;
NodeKey nodeKey;
+ RpcRegistration<EventAggregatorService> aggregatorRpcReg;
@BeforeClass
public static void initTestClass() throws IllegalAccessException, InstantiationException {
}
private void constructorTestHelper(){
- RpcRegistration<EventAggregatorService> aggregatorRpcReg = mock(RpcRegistration.class);
+ aggregatorRpcReg = mock(RpcRegistration.class);
EventSourceService eventSourceService = mock(EventSourceService.class);
doReturn(aggregatorRpcReg).when(rpcProviderRegistryMock).addRpcImplementation(eq(EventAggregatorService.class), any(EventSourceTopology.class));
doReturn(eventSourceService).when(rpcProviderRegistryMock).getRpcService(EventSourceService.class);
doReturn(checkedFutureMock).when(writeTransactionMock).submit();
}
-//TODO: create test for createTopic
-// public void createTopicTest() throws Exception{
-// createTopicTestHelper();
-// assertNotNull("Topic has not been created correctly.", eventSourceTopology.createTopic(createTopicInputMock));
-// }
+ @Test
+ public void createTopicTest() throws Exception{
+ topicTestHelper();
+ assertNotNull("Topic has not been created correctly.", eventSourceTopology.createTopic(createTopicInputMock));
+ }
private void topicTestHelper() throws Exception{
constructorTestHelper();
assertNotNull("Instance has not been created correctly.", eventSourceTopology.destroyTopic(destroyTopicInput));
}
+ @Test
+ public void closeTest() throws Exception{
+ constructorTestHelper();
+ topicTestHelper();
+ Map<DataChangeListener, ListenerRegistration<DataChangeListener>> localMap = getTopicListenerRegistrations();
+ DataChangeListener dataChangeListenerMock = mock(DataChangeListener.class);
+ ListenerRegistration<DataChangeListener> listenerListenerRegistrationMock = (ListenerRegistration<DataChangeListener>) mock(ListenerRegistration.class);
+ localMap.put(dataChangeListenerMock, listenerListenerRegistrationMock);
+ eventSourceTopology.close();
+ verify(aggregatorRpcReg, times(1)).close();
+ verify(listenerListenerRegistrationMock, times(1)).close();
+ }
+
@Test
public void registerTest() throws Exception {
topicTestHelper();
verify(routedRpcRegistrationMock, times(1)).registerPath(eq(NodeContext.class), any(KeyedInstanceIdentifier.class));
}
-}
+ @Test
+ public void unregisterTest() throws Exception {
+ topicTestHelper();
+ EventSource eventSourceMock = mock(EventSource.class);
+ NodeId nodeId = new NodeId("nodeIdValue1");
+ nodeKey = new NodeKey(nodeId);
+ Map<NodeKey, BindingAwareBroker.RoutedRpcRegistration<EventSourceService>> localMap = getRoutedRpcRegistrations();
+ NodeKey nodeKeyMock = mock(NodeKey.class);
+ doReturn(nodeKeyMock).when(eventSourceMock).getSourceNodeKey();
+ BindingAwareBroker.RoutedRpcRegistration<EventSourceService> routedRpcRegistrationMock = (BindingAwareBroker.RoutedRpcRegistration<EventSourceService>) mock(BindingAwareBroker.RoutedRpcRegistration.class);
+ localMap.put(nodeKeyMock, routedRpcRegistrationMock);
+ eventSourceTopology.unRegister(eventSourceMock);
+ verify(routedRpcRegistrationMock, times(1)).close();
+ }
+
+ @Test
+ public void registerEventSourceTest() throws Exception {
+ topicTestHelper();
+ Node nodeMock = mock(Node.class);
+ EventSource eventSourceMock = mock(EventSource.class);
+ NodeId nodeId = new NodeId("nodeIdValue1");
+ nodeKey = new NodeKey(nodeId);
+ doReturn(nodeKey).when(nodeMock).getKey();
+ doReturn(nodeKey).when(eventSourceMock).getSourceNodeKey();
+ BindingAwareBroker.RoutedRpcRegistration routedRpcRegistrationMock = mock(BindingAwareBroker.RoutedRpcRegistration.class);
+ doReturn(routedRpcRegistrationMock).when(rpcProviderRegistryMock).addRoutedRpcImplementation(EventSourceService.class, eventSourceMock);
+ doNothing().when(routedRpcRegistrationMock).registerPath(eq(NodeContext.class), any(KeyedInstanceIdentifier.class));
+ assertNotNull("Return value has not been created correctly.", eventSourceTopology.registerEventSource(eventSourceMock));
+ }
+
+ private Map getTopicListenerRegistrations() throws Exception{
+ Field nesField = EventSourceTopology.class.getDeclaredField("topicListenerRegistrations");
+ nesField.setAccessible(true);
+ return (Map) nesField.get(eventSourceTopology);
+ }
+
+ private Map getRoutedRpcRegistrations() throws Exception{
+ Field nesField = EventSourceTopology.class.getDeclaredField("routedRpcRegistrations");
+ nesField.setAccessible(true);
+ return (Map) nesField.get(eventSourceTopology);
+ }
+
+}
\ No newline at end of file
netconfEventSourceManager =
NetconfEventSourceManager.create(dataBrokerMock,
- domNotificationPublishServiceMock,
- domMountPointServiceMock,
- mountPointServiceMock,
- eventSourceRegistry,
- namespaceToStreamList);
+ domNotificationPublishServiceMock,
+ domMountPointServiceMock,
+ mountPointServiceMock,
+ eventSourceRegistry,
+ namespaceToStreamList);
}
@Test
Map<InstanceIdentifier, DataObject> mapUpdate = new HashMap<>();
InstanceIdentifier instanceIdentifierMock = mock(InstanceIdentifier.class);
Node dataObjectMock = mock(Node.class);
+
if(create){
mapCreate.put(instanceIdentifierMock, dataObjectMock);
}
if(update){
mapUpdate.put(instanceIdentifierMock, dataObjectMock);
}
+
doReturn(mapCreate).when(asyncDataChangeEventMock).getCreatedData();
doReturn(mapUpdate).when(asyncDataChangeEventMock).getUpdatedData();
NetconfNode netconfNodeMock = mock(NetconfNode.class);
doReturn(esrMock).when(eventSourceRegistry).registerEventSource(any(EventSource.class));
}
-}
+}
\ No newline at end of file
*/
package org.opendaylight.controller.messagebus.app.impl;
-import static org.junit.Assert.assertEquals;
-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 static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import java.lang.reflect.Field;
-import java.net.URI;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.binding.api.BindingService;
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;
+import java.lang.reflect.Field;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+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 static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
public class NetconfEventSourceTest {
NetconfEventSource netconfEventSource;
DOMMountPoint domMountPointMock;
JoinTopicInput joinTopicInputMock;
- AsyncDataChangeEvent asyncDataChangeEventMock;
- Node dataObjectMock;
@Before
public void setUp() throws Exception {
Map<String, String> streamMap = new HashMap<>();
- streamMap.put("string1", "string2");
+ streamMap.put("uriStr1", "string2");
domMountPointMock = mock(DOMMountPoint.class);
DOMNotificationPublishService domNotificationPublishServiceMock = mock(DOMNotificationPublishService.class);
MountPoint mountPointMock = mock(MountPoint.class);
doReturn(rpcConsumerRegistryMock).when(onlyOptionalMock).get();
doReturn(notificationsServiceMock).when(rpcConsumerRegistryMock).getRpcService(NotificationsService.class);
org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node node
- = mock(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class);
+ = mock(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class);
org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId nodeId
- = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId("NodeId1");
+ = new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId("NodeId1");
doReturn(nodeId).when(node).getNodeId();
netconfEventSource = new NetconfEventSource(node, streamMap, domMountPointMock, domNotificationPublishServiceMock, mountPointMock);
}
doReturn(topicId).when(joinTopicInputMock).getTopicId();
NotificationPattern notificationPatternMock = mock(NotificationPattern.class);
doReturn(notificationPatternMock).when(joinTopicInputMock).getNotificationPattern();
- doReturn("regexString1").when(notificationPatternMock).getValue();
+ doReturn("uriStr1").when(notificationPatternMock).getValue();
SchemaContext schemaContextMock = mock(SchemaContext.class);
doReturn(schemaContextMock).when(domMountPointMock).getSchemaContext();
doReturn(domNotificationServiceMock).when(domNotificationServiceOptionalMock).get();
ListenerRegistration listenerRegistrationMock = mock(ListenerRegistration.class);
doReturn(listenerRegistrationMock).when(domNotificationServiceMock).registerNotificationListener(any(NetconfEventSource.class), any(List.class));
+
+ Optional<DOMService> optionalMock = (Optional<DOMService>) mock(Optional.class);
+ doReturn(optionalMock).when(domMountPointMock).getService(DOMRpcService.class);
+ 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));
}
//TODO: create Test for NetConfEventSource#onNotification
return (Set) nesField.get(netconfEventSource);
}
-}
+}
\ No newline at end of file
String bodyString = "TopicDOMNotification [body=" + containerNodeBodyMockToString + "]";
assertEquals("String has not been created correctly.", bodyString, topicDOMNotification.toString());
}
-}
+}
\ No newline at end of file
<module>sal-rest-docgen-maven</module>
<module>sal-akka-raft</module>
+ <module>sal-akka-raft-example</module>
<!--InMemory DOM DataStore-->
<module>sal-inmemory-datastore</module>
--- /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>sal-parent</artifactId>
+ <version>1.2.0-SNAPSHOT</version>
+ </parent>
+ <artifactId>sal-akka-raft-example</artifactId>
+ <packaging>bundle</packaging>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <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>
+ </plugins>
+ </build>
+ <scm>
+ <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
+ <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
+ <tag>HEAD</tag>
+ <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL:Architecture:Clustering</url>
+ </scm>
+</project>
long followerNextIndex = followerLogInformation.getNextIndex();
boolean isFollowerActive = followerLogInformation.isFollowerActive();
boolean sendAppendEntries = false;
- List<ReplicatedLogEntry> entries = Collections.EMPTY_LIST;
+ List<ReplicatedLogEntry> entries = Collections.emptyList();
if (mapFollowerToSnapshot.get(followerId) != null) {
// if install snapshot is in process , then sent next chunk if possible
--- /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.md.sal.binding.impl;
+
+import com.google.common.collect.ImmutableMap;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
+import org.opendaylight.controller.md.sal.dom.api.DOMNotificationListener;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.binding.Notification;
+import org.opendaylight.yangtools.yang.binding.NotificationListener;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.binding.util.NotificationListenerInvoker;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+
+class BindingDOMNotificationListenerAdapter implements DOMNotificationListener {
+
+ private final BindingNormalizedNodeSerializer codec;
+ private final NotificationListener delegate;
+ private final Map<SchemaPath,NotificationListenerInvoker> invokers;
+
+ public BindingDOMNotificationListenerAdapter(final BindingNormalizedNodeSerializer codec, final NotificationListener delegate) {
+ this.codec = codec;
+ this.delegate = delegate;
+ this.invokers = createInvokerMapFor(delegate.getClass());
+ }
+
+ @Override
+ public void onNotification(@Nonnull final DOMNotification notification) {
+ final Notification baNotification = deserialize(notification);
+ final QName notificationQName = notification.getType().getLastComponent();
+ getInvoker(notification.getType()).invokeNotification(delegate, notificationQName, baNotification);
+ }
+
+ private Notification deserialize(final DOMNotification notification) {
+ if(notification instanceof LazySerializedDOMNotification) {
+ return ((LazySerializedDOMNotification) notification).getBindingData();
+ }
+ return codec.fromNormalizedNodeNotification(notification.getType(), notification.getBody());
+ }
+
+ private NotificationListenerInvoker getInvoker(final SchemaPath type) {
+ return invokers.get(type);
+ }
+
+ protected Set<SchemaPath> getSupportedNotifications() {
+ return invokers.keySet();
+ }
+
+ private static Map<SchemaPath, NotificationListenerInvoker> createInvokerMapFor(final Class<? extends NotificationListener> implClz) {
+ final Map<SchemaPath, NotificationListenerInvoker> builder = new HashMap<>();
+ for(final Class<?> iface : implClz.getInterfaces()) {
+ if(NotificationListener.class.isAssignableFrom(iface) && BindingReflections.isBindingClass(iface)) {
+ @SuppressWarnings("unchecked")
+ final Class<? extends NotificationListener> listenerType = (Class<? extends NotificationListener>) iface;
+ final NotificationListenerInvoker invoker = NotificationListenerInvoker.from(listenerType);
+ for(final SchemaPath path : getNotificationTypes(listenerType)) {
+ builder.put(path, invoker);
+ }
+ }
+ }
+ return ImmutableMap.copyOf(builder);
+ }
+
+ private static Set<SchemaPath> getNotificationTypes(final Class<? extends NotificationListener> type) {
+ // TODO: Investigate possibility and performance impact if we cache this or expose
+ // it from NotificationListenerInvoker
+ final Set<SchemaPath> ret = new HashSet<>();
+ for(final Method method : type.getMethods()) {
+ if(BindingReflections.isNotificationCallback(method)) {
+ final Class<?> notification = method.getParameterTypes()[0];
+ final QName name = BindingReflections.findQName(notification);
+ ret.add(SchemaPath.create(true, name));
+ }
+ }
+ return ret;
+ }
+}
\ No newline at end of file
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.controller.md.sal.binding.impl.BindingDOMAdapterBuilder.Factory;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.md.sal.dom.api.DOMService;
import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.yangtools.yang.binding.Notification;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
public class BindingDOMNotificationPublishServiceAdapter implements NotificationPublishService, AutoCloseable {
private final BindingNormalizedNodeSerializer codecRegistry;
private final DOMNotificationPublishService domPublishService;
- public BindingDOMNotificationPublishServiceAdapter(BindingNormalizedNodeSerializer codecRegistry, DOMNotificationPublishService domPublishService) {
+ public BindingDOMNotificationPublishServiceAdapter(final BindingNormalizedNodeSerializer codecRegistry, final DOMNotificationPublishService domPublishService) {
this.codecRegistry = codecRegistry;
this.domPublishService = domPublishService;
}
}
private DOMNotification toDomNotification(final Notification notification) {
- final ContainerNode domNotification = codecRegistry.toNormalizedNodeNotification(notification);
- return new DOMNotificationImpl(domNotification);
+ return LazySerializedDOMNotification.create(codecRegistry, notification);
}
@Override
}
- private static class DOMNotificationImpl implements DOMNotification {
-
- private final SchemaPath type;
- private final ContainerNode body;
-
- public DOMNotificationImpl(final ContainerNode body) {
- this.type = SchemaPath.create(true, body.getIdentifier().getNodeType());
- this.body = body;
- }
-
- @Nonnull
- @Override
- public SchemaPath getType() {
- return this.type;
- }
-
- @Nonnull
- @Override
- public ContainerNode getBody() {
- return this.body;
- }
- }
-
protected static class Builder extends BindingDOMAdapterBuilder<NotificationPublishService> {
@Override
}
@Override
- protected NotificationPublishService createInstance(BindingToNormalizedNodeCodec codec,
- ClassToInstanceMap<DOMService> delegates) {
- BindingNormalizedNodeSerializer codecReg = codec.getCodecRegistry();
- DOMNotificationPublishService domPublish = delegates.getInstance(DOMNotificationPublishService.class);
+ protected NotificationPublishService createInstance(final BindingToNormalizedNodeCodec codec,
+ final ClassToInstanceMap<DOMService> delegates) {
+ final BindingNormalizedNodeSerializer codecReg = codec.getCodecRegistry();
+ final DOMNotificationPublishService domPublish = delegates.getInstance(DOMNotificationPublishService.class);
return new BindingDOMNotificationPublishServiceAdapter(codecReg, domPublish);
}
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
import java.util.Set;
-import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.NotificationService;
import org.opendaylight.controller.md.sal.binding.impl.BindingDOMAdapterBuilder.Factory;
-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.DOMNotificationService;
import org.opendaylight.controller.md.sal.dom.api.DOMService;
import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.Notification;
import org.opendaylight.yangtools.yang.binding.NotificationListener;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
public class BindingDOMNotificationServiceAdapter implements NotificationService, AutoCloseable {
};
private final BindingNormalizedNodeSerializer codec;
private final DOMNotificationService domNotifService;
- private final NotificationInvokerFactory notificationInvokerFactory;
- public BindingDOMNotificationServiceAdapter(BindingNormalizedNodeSerializer codec, DOMNotificationService domNotifService, NotificationInvokerFactory notificationInvokerFactory) {
+ public BindingDOMNotificationServiceAdapter(final BindingNormalizedNodeSerializer codec, final DOMNotificationService domNotifService, final NotificationInvokerFactory notificationInvokerFactory) {
this.codec = codec;
this.domNotifService = domNotifService;
- this.notificationInvokerFactory = notificationInvokerFactory;
}
@Override
- public <T extends NotificationListener> ListenerRegistration<T> registerNotificationListener(T listener) {
- final NotificationInvokerFactory.NotificationInvoker invoker = notificationInvokerFactory.invokerFor(listener);
- final DOMNotificationListener domListener = new NotificationInvokerImpl(invoker);
- final Collection<SchemaPath> schemaPaths = convertNotifTypesToSchemaPath(invoker.getSupportedNotifications());
- final ListenerRegistration<DOMNotificationListener> domRegistration =
- domNotifService.registerNotificationListener(domListener, schemaPaths);
+ public <T extends NotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener) {
+ final BindingDOMNotificationListenerAdapter domListener = new BindingDOMNotificationListenerAdapter(codec, listener);
+ final ListenerRegistration<BindingDOMNotificationListenerAdapter> domRegistration =
+ domNotifService.registerNotificationListener(domListener, domListener.getSupportedNotifications());
return new ListenerRegistrationImpl<>(listener, domRegistration);
}
-
-
- private Collection<SchemaPath> convertNotifTypesToSchemaPath(Set<Class<? extends Notification>> notificationTypes) {
- final List<SchemaPath> schemaPaths = new ArrayList<>();
- for (Class<? extends Notification> notificationType : notificationTypes) {
- schemaPaths.add(SchemaPath.create(true, BindingReflections.findQName(notificationType)));
- }
- return schemaPaths;
- }
-
@Override
public void close() throws Exception {
private static class ListenerRegistrationImpl<T extends NotificationListener> extends AbstractListenerRegistration<T> {
private final ListenerRegistration<?> listenerRegistration;
- public ListenerRegistrationImpl(T listener, ListenerRegistration<?> listenerRegistration) {
+ public ListenerRegistrationImpl(final T listener, final ListenerRegistration<?> listenerRegistration) {
super(listener);
this.listenerRegistration = listenerRegistration;
}
}
}
- private class NotificationInvokerImpl implements DOMNotificationListener {
- private final NotificationInvokerFactory.NotificationInvoker invoker;
-
- public NotificationInvokerImpl(NotificationInvokerFactory.NotificationInvoker invoker) {
- this.invoker = invoker;
- }
-
- @Override
- public void onNotification(@Nonnull DOMNotification notification) {
- final Notification baNotification =
- codec.fromNormalizedNodeNotification(notification.getType(), notification.getBody());
- invoker.getInvocationProxy().onNotification(baNotification);
-
- }
- }
-
private static class Builder extends BindingDOMAdapterBuilder<NotificationService> {
-
@Override
- protected NotificationService createInstance(BindingToNormalizedNodeCodec codec,
- ClassToInstanceMap<DOMService> delegates) {
- DOMNotificationService domNotification = delegates.getInstance(DOMNotificationService.class);
- NotificationInvokerFactory invokerFactory = SingletonHolder.INVOKER_FACTORY;
+ protected NotificationService createInstance(final BindingToNormalizedNodeCodec codec,
+ final ClassToInstanceMap<DOMService> delegates) {
+ final DOMNotificationService domNotification = delegates.getInstance(DOMNotificationService.class);
+ final NotificationInvokerFactory invokerFactory = SingletonHolder.INVOKER_FACTORY;
return new BindingDOMNotificationServiceAdapter(codec.getCodecRegistry(), domNotification, invokerFactory);
}
public Set<? extends Class<? extends DOMService>> getRequiredDelegates() {
return ImmutableSet.of(DOMNotificationService.class);
}
-
-
-
}
}
--- /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.md.sal.binding.impl;
+
+import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.binding.Notification;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+
+/**
+ * Lazy serialized implementation of DOM Notification.
+ *
+ * This implementation performs serialization of data, only if receiver
+ * of notification actually accessed data from notification.
+ *
+ */
+class LazySerializedDOMNotification implements DOMNotification {
+
+ private final BindingNormalizedNodeSerializer codec;
+ private final Notification data;
+ private final SchemaPath type;
+
+ private ContainerNode domBody;
+
+ private LazySerializedDOMNotification(final BindingNormalizedNodeSerializer codec, final Notification data, final SchemaPath type) {
+ super();
+ this.codec = codec;
+ this.data = data;
+ this.type = type;
+ }
+
+ static DOMNotification create(final BindingNormalizedNodeSerializer codec, final Notification data) {
+ final SchemaPath type = SchemaPath.create(true, BindingReflections.findQName(data.getImplementedInterface()));
+ return new LazySerializedDOMNotification(codec, data, type);
+ }
+
+ @Override
+ public SchemaPath getType() {
+ return type;
+ }
+
+ @Override
+ public ContainerNode getBody() {
+ if (domBody == null) {
+ domBody = codec.toNormalizedNodeNotification(data);
+ }
+ return domBody;
+ }
+
+ protected Notification getBindingData() {
+ return data;
+ }
+}
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-akka-raft</artifactId>
- <version>1.2.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft-example</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-akka-raft</artifactId>
- <version>1.2.0-SNAPSHOT</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
final YangInstanceIdentifier path = message.getPath();
try {
- Boolean exists = transaction.exists(path).checkedGet();
- DataExistsReply dataExistsReply = new DataExistsReply(exists);
+ boolean exists = transaction.exists(path).checkedGet();
+ DataExistsReply dataExistsReply = DataExistsReply.create(exists);
getSender().tell(returnSerialized ? dataExistsReply.toSerializable() :
dataExistsReply, getSelf());
} catch (ReadFailedException e) {
getSender().tell(new akka.actor.Status.Failure(e),getSelf());
}
-
}
private static class ShardTransactionCreator implements Creator<ShardTransaction> {
import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
try {
proxyFuture.set(NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.builder().build(),
future.get(), actorContext.getSchemaContext()));
- } catch (InterruptedException | ExecutionException e) {
+ } catch (DataValidationFailedException | InterruptedException | ExecutionException e) {
proxyFuture.setException(e);
}
}
import org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages;
-public class DataExistsReply implements SerializableMessage{
+public class DataExistsReply implements SerializableMessage {
public static final Class<ShardTransactionMessages.DataExistsReply> SERIALIZABLE_CLASS =
ShardTransactionMessages.DataExistsReply.class;
+ private static final DataExistsReply TRUE = new DataExistsReply(true, null);
+ private static final DataExistsReply FALSE = new DataExistsReply(false, null);
+ private static final ShardTransactionMessages.DataExistsReply SERIALIZABLE_TRUE =
+ ShardTransactionMessages.DataExistsReply.newBuilder().setExists(true).build();
+ private static final ShardTransactionMessages.DataExistsReply SERIALIZABLE_FALSE =
+ ShardTransactionMessages.DataExistsReply.newBuilder().setExists(false).build();
+
private final boolean exists;
- public DataExistsReply(final boolean exists) {
+ private DataExistsReply(final boolean exists, final Void dummy) {
this.exists = exists;
}
+ /**
+ * @deprecated Use {@link #create(boolean)} instead.
+ * @param exists
+ */
+ @Deprecated
+ public DataExistsReply(final boolean exists) {
+ this(exists, null);
+ }
+
+ public static DataExistsReply create(final boolean exists) {
+ return exists ? TRUE : FALSE;
+ }
+
public boolean exists() {
return exists;
}
- @Override public Object toSerializable() {
- return ShardTransactionMessages.DataExistsReply.newBuilder()
- .setExists(exists).build();
+ @Override
+ public Object toSerializable() {
+ return exists ? SERIALIZABLE_TRUE : SERIALIZABLE_FALSE;
}
- public static DataExistsReply fromSerializable(final Object serializable){
+ public static DataExistsReply fromSerializable(final Object serializable) {
ShardTransactionMessages.DataExistsReply o = (ShardTransactionMessages.DataExistsReply) serializable;
- return new DataExistsReply(o.getExists());
+ return create(o.getExists());
}
-
}
* 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.cluster.datastore.utils;
import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
-import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
-import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
+import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class NormalizedNodeAggregator {
-
- private static final ExecutorService executorService = MoreExecutors.newDirectExecutorService();
-
private final YangInstanceIdentifier rootIdentifier;
private final List<Optional<NormalizedNode<?, ?>>> nodes;
- private final InMemoryDOMDataStore dataStore;
-
- NormalizedNodeAggregator(YangInstanceIdentifier rootIdentifier, List<Optional<NormalizedNode<?, ?>>> nodes,
- SchemaContext schemaContext){
+ private final DataTree dataTree;
+ private NormalizedNodeAggregator(YangInstanceIdentifier rootIdentifier, List<Optional<NormalizedNode<?, ?>>> nodes,
+ SchemaContext schemaContext) {
this.rootIdentifier = rootIdentifier;
this.nodes = nodes;
- this.dataStore = new InMemoryDOMDataStore("aggregator", executorService);
- this.dataStore.onGlobalContextUpdated(schemaContext);
+ this.dataTree = InMemoryDataTreeFactory.getInstance().create();
+ this.dataTree.setSchemaContext(schemaContext);
}
/**
* @param nodes
* @param schemaContext
* @return
- * @throws ExecutionException
- * @throws InterruptedException
+ * @throws DataValidationFailedException
*/
public static Optional<NormalizedNode<?,?>> aggregate(YangInstanceIdentifier rootIdentifier,
List<Optional<NormalizedNode<?, ?>>> nodes,
- SchemaContext schemaContext)
- throws ExecutionException, InterruptedException {
+ SchemaContext schemaContext) throws DataValidationFailedException {
return new NormalizedNodeAggregator(rootIdentifier, nodes, schemaContext).aggregate();
}
- private Optional<NormalizedNode<?,?>> aggregate() throws ExecutionException, InterruptedException {
+ private Optional<NormalizedNode<?,?>> aggregate() throws DataValidationFailedException {
return combine().getRootNode();
}
- private NormalizedNodeAggregator combine() throws InterruptedException, ExecutionException {
- DOMStoreWriteTransaction domStoreWriteTransaction = dataStore.newWriteOnlyTransaction();
+ private NormalizedNodeAggregator combine() throws DataValidationFailedException {
+ DataTreeModification mod = dataTree.takeSnapshot().newModification();
- for(Optional<NormalizedNode<?,?>> node : nodes) {
- if(node.isPresent()) {
- domStoreWriteTransaction.merge(rootIdentifier, node.get());
+ for (Optional<NormalizedNode<?,?>> node : nodes) {
+ if (node.isPresent()) {
+ mod.merge(rootIdentifier, node.get());
}
}
- DOMStoreThreePhaseCommitCohort ready = domStoreWriteTransaction.ready();
- ready.canCommit().get();
- ready.preCommit().get();
- ready.commit().get();
+
+ dataTree.validate(mod);
+ final DataTreeCandidate candidate = dataTree.prepare(mod);
+ dataTree.commit(candidate);
return this;
}
- private Optional<NormalizedNode<?, ?>> getRootNode() throws InterruptedException, ExecutionException {
- DOMStoreReadTransaction readTransaction = dataStore.newReadOnlyTransaction();
-
- CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read =
- readTransaction.read(rootIdentifier);
-
- return read.get();
+ private Optional<NormalizedNode<?, ?>> getRootNode() {
+ return dataTree.takeSnapshot().readNode(rootIdentifier);
}
-
-
}
}
protected Future<Object> dataExistsSerializedReply(boolean exists) {
- return Futures.successful(new DataExistsReply(exists).toSerializable());
+ return Futures.successful(DataExistsReply.create(exists).toSerializable());
}
protected Future<DataExistsReply> dataExistsReply(boolean exists) {
- return Futures.successful(new DataExistsReply(exists));
+ return Futures.successful(DataExistsReply.create(exists));
}
protected Future<BatchedModificationsReply> batchedModificationsReply(int count) {
return Futures.successful(new BatchedModificationsReply(count));
}
- protected Future<Object> incompleteFuture(){
+ protected Future<Object> incompleteFuture() {
return mock(Future.class);
}
OperationCompleter completer = new OperationCompleter(operationLimiter );
- completer.onComplete(null, new DataExistsReply(true));
+ completer.onComplete(null, DataExistsReply.create(true));
assertEquals("availablePermits", ++availablePermits, operationLimiter.availablePermits());
- completer.onComplete(null, new DataExistsReply(true));
+ completer.onComplete(null, DataExistsReply.create(true));
assertEquals("availablePermits", ++availablePermits, operationLimiter.availablePermits());
completer.onComplete(null, new IllegalArgumentException());
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public class NormalizedNodeAggregatorTest {
@Test
- public void testAggregate() throws InterruptedException, ExecutionException, ReadFailedException {
+ public void testAggregate() throws InterruptedException, ExecutionException, ReadFailedException, DataValidationFailedException {
SchemaContext schemaContext = SchemaContextHelper.full();
NormalizedNode<?, ?> expectedNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
NormalizedNode<?, ?> expectedNode2 = ImmutableNodes.containerNode(CarsModel.CARS_QNAME);
import org.opendaylight.controller.md.sal.dom.spi.AbstractRegistrationTree;
import org.opendaylight.controller.md.sal.dom.spi.RegistrationTreeNode;
import org.opendaylight.controller.md.sal.dom.spi.RegistrationTreeSnapshot;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
/**
* Callback notifying the subclass that the specified registration is being closed and it's user no longer
- * wishes to receive notifications. This notification is invoked while the {@link ListenerRegistration#close()}
+ * wishes to receive notifications. This notification is invoked while the {@link org.opendaylight.yangtools.concepts.ListenerRegistration#close()}
* method is executing. Subclasses can use this callback to properly remove any delayed notifications pending
* towards the registration.
*
}
@Override
- public final <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener) {
+ public final <L extends DOMDataTreeChangeListener> AbstractDOMDataTreeChangeListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener) {
// Take the write lock
takeLock();
try {
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-akka-raft</artifactId>
- <version>1.2.0-SNAPSHOT</version>
</dependency>
<dependency>
}
@Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener) {
- return changePublisher.registerTreeChangeListener(treeId, listener);
+ public synchronized <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener) {
+ /*
+ * Make sure commit is not occurring right now. Listener has to be
+ * registered and its state capture enqueued at a consistent point.
+ */
+ return changePublisher.registerTreeChangeListener(treeId, listener, dataTree.takeSnapshot());
}
@Override
return name + "-" + txCounter.getAndIncrement();
}
- private static void warnDebugContext(AbstractDOMStoreTransaction<?> transaction) {
+ private static void warnDebugContext(final AbstractDOMStoreTransaction<?> transaction) {
final Throwable ctx = transaction.getDebugContext();
if (ctx != null) {
LOG.warn("Transaction {} has been allocated in the following context", transaction.getIdentifier(), ctx);
*/
package org.opendaylight.controller.md.sal.dom.store.impl;
+import com.google.common.base.Optional;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.controller.md.sal.dom.spi.AbstractDOMDataTreeChangeListenerRegistration;
import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTreeChangePublisher;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager;
import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager.Invoker;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.DefaultDataTreeCandidate;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
protected void notifyListeners(final Collection<AbstractDOMDataTreeChangeListenerRegistration<?>> registrations, final YangInstanceIdentifier path, final DataTreeCandidateNode node) {
- final DataTreeCandidate candidate = new DefaultDataTreeCandidate(path, node);
+ final DataTreeCandidate candidate = DataTreeCandidates.newDataTreeCandidate(path, node);
for (AbstractDOMDataTreeChangeListenerRegistration<?> reg : registrations) {
LOG.debug("Enqueueing candidate {} to registration {}", candidate, registrations);
// FIXME: remove the queue for this registration and make sure we clear it
}
+ <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener, final DataTreeSnapshot snapshot) {
+ final AbstractDOMDataTreeChangeListenerRegistration<L> reg = registerTreeChangeListener(treeId, listener);
+
+ final Optional<NormalizedNode<?, ?>> node = snapshot.readNode(treeId);
+ if (node.isPresent()) {
+ final DataTreeCandidate candidate = DataTreeCandidates.fromNormalizedNode(treeId, node.get());
+ notificationManager.submitNotification(reg, candidate);
+ }
+
+ return reg;
+ }
+
synchronized void publishChange(@Nonnull final DataTreeCandidate candidate) {
// Runs synchronized with registrationRemoved()
processCandidateTree(candidate);
*/
package org.opendaylight.controller.md.sal.dom.store.impl;
+import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
* Computes data change events for all affected registered listeners in data
* tree.
*/
-final class ResolveDataChangeEventsTask {
+@Beta
+public final class ResolveDataChangeEventsTask {
private static final Logger LOG = LoggerFactory.getLogger(ResolveDataChangeEventsTask.class);
private final DataTreeCandidate candidate;
private Multimap<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> collectedEvents;
- public ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
+ private ResolveDataChangeEventsTask(final DataTreeCandidate candidate, final ListenerTree listenerTree) {
this.candidate = Preconditions.checkNotNull(candidate);
this.listenerRoot = Preconditions.checkNotNull(listenerTree);
}
<dependency>\r
<groupId>org.apache.karaf.shell</groupId>\r
<artifactId>org.apache.karaf.shell.console</artifactId>\r
- <version>3.0.1</version>\r
+ <version>${karaf.version}</version>\r
</dependency>\r
\r
<dependency>\r
private final ControllerContext salContext;
private static final Splitter SLASH_SPLITTER = Splitter.on("/");
- private static final Splitter AT_SPLITTER = Splitter.on("@");
private static final String MOUNT_ARG = ControllerContext.MOUNT;
public SchemaRetrievalServiceImpl(final ControllerContext controllerContext) {
}
private SchemaContext getMountSchemaContext(final String identifier) {
- final InstanceIdentifierContext mountContext = salContext.toMountPointIdentifier(identifier);
+ final InstanceIdentifierContext<?> mountContext = salContext.toMountPointIdentifier(identifier);
return mountContext.getSchemaContext();
}
package org.opendaylight.controller.sal.rest.impl;
-import com.google.common.base.Optional;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
return uriInfo.getPathParameters(false).getFirst(RestconfConstants.IDENTIFIER);
}
- protected final Optional<InstanceIdentifierContext> getIdentifierWithSchema() {
- return Optional.of(getInstanceIdentifierContext());
- }
-
- protected InstanceIdentifierContext getInstanceIdentifierContext() {
+ protected InstanceIdentifierContext<?> getInstanceIdentifierContext() {
return ControllerContext.getInstance().toInstanceIdentifier(getIdentifier());
}
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
WebApplicationException {
try {
- final InstanceIdentifierContext<?> path = getIdentifierWithSchema().get();
+ final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
if (entityStream.available() < 1) {
return new NormalizedNodeContext(path, null);
}
}
@Override
+ @Deprecated
public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
return restconf.invokeRpc(identifier, noPayload, uriInfo);
}
}
errContBuild.withChild(listErorsBuilder.build());
- final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<DataSchemaNode>(null,
+ final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
(DataSchemaNode) errorsSchemaNode, null, context.getGlobalSchema()), errContBuild.build());
Object responseBody;
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
NormalizedNode<?, ?> data = errorsNode.getData();
- final InstanceIdentifierContext<DataSchemaNode> context = (InstanceIdentifierContext<DataSchemaNode>) errorsNode.getInstanceIdentifierContext();
- final DataSchemaNode schema = context.getSchemaNode();
+ final InstanceIdentifierContext<?> context = errorsNode.getInstanceIdentifierContext();
+ final DataSchemaNode schema = (DataSchemaNode) context.getSchemaNode();
SchemaPath path = context.getSchemaNode().getPath();
final OutputStreamWriter outputWriter = new OutputStreamWriter(outStream, Charsets.UTF_8);
private Object toXMLResponseBody(final NormalizedNodeContext errorsNode, final DataNodeContainer errorsSchemaNode) {
- final InstanceIdentifierContext<DataSchemaNode> pathContext = (InstanceIdentifierContext<DataSchemaNode>) errorsNode.getInstanceIdentifierContext();
+ final InstanceIdentifierContext<?> pathContext = errorsNode.getInstanceIdentifierContext();
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
XMLStreamWriter xmlWriter;
*/
package org.opendaylight.controller.sal.rest.impl;
-import com.google.common.base.Optional;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
WebApplicationException {
try {
- final Optional<InstanceIdentifierContext> path = getIdentifierWithSchema();
+ final InstanceIdentifierContext<?> path = getInstanceIdentifierContext();
if (entityStream.available() < 1) {
// represent empty nopayload input
- return new NormalizedNodeContext(path.get(), null);
+ return new NormalizedNodeContext(path, null);
}
final DocumentBuilder dBuilder;
}
final Document doc = dBuilder.parse(entityStream);
- final NormalizedNode<?, ?> result = parse(path.get(),doc);
- return new NormalizedNodeContext(path.get(),result);
+ final NormalizedNode<?, ?> result = parse(path,doc);
+ return new NormalizedNodeContext(path,result);
} catch (final Exception e) {
LOG.debug("Error parsing xml input", e);
onGlobalContextUpdated(schemas);
}
- public InstanceIdentifierContext toInstanceIdentifier(final String restconfInstance) {
+ public InstanceIdentifierContext<?> toInstanceIdentifier(final String restconfInstance) {
return toIdentifier(restconfInstance, false);
}
return globalSchema;
}
- public InstanceIdentifierContext toMountPointIdentifier(final String restconfInstance) {
+ public InstanceIdentifierContext<?> toMountPointIdentifier(final String restconfInstance) {
return toIdentifier(restconfInstance, true);
}
- private InstanceIdentifierContext toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
+ private InstanceIdentifierContext<?> toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
checkPreconditions();
if(restconfInstance == null) {
final InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
final Module latestModule = globalSchema.findModuleByName(startModule, null);
- final InstanceIdentifierContext iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
+ final InstanceIdentifierContext<?> iiWithSchemaNode = collectPathArguments(builder, pathArgs, latestModule, null,
toMountPointIdentifier);
if (iiWithSchemaNode == null) {
return object == null ? "" : URLEncoder.encode(codec.serialize(object).toString(), ControllerContext.URI_ENCODING_CHAR_SET);
}
- private InstanceIdentifierContext collectPathArguments(final InstanceIdentifierBuilder builder,
+ private InstanceIdentifierContext<?> collectPathArguments(final InstanceIdentifierBuilder builder,
final List<String> strings, final DataNodeContainer parentNode, final DOMMountPoint mountPoint,
final boolean returnJustMountPoint) {
Preconditions.<List<String>> checkNotNull(strings);
if (returnJustMountPoint || strings.size() == 1) {
final YangInstanceIdentifier instance = YangInstanceIdentifier.builder().toInstance();
- return new InstanceIdentifierContext(instance, mountPointSchema, mount,mountPointSchema);
+ return new InstanceIdentifierContext<>(instance, mountPointSchema, mount,mountPointSchema);
}
final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
return createContext(builder.build(), targetNode, mountPoint,mountPoint != null ? mountPoint.getSchemaContext() : globalSchema);
}
- private InstanceIdentifierContext createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
+ private InstanceIdentifierContext<?> createContext(final YangInstanceIdentifier instance, final DataSchemaNode dataSchemaNode,
final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
final YangInstanceIdentifier instanceIdentifier = new DataNormalizer(schemaContext).toNormalized(instance);
- return new InstanceIdentifierContext(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
+ return new InstanceIdentifierContext<>(instanceIdentifier, dataSchemaNode, mountPoint,schemaContext);
}
public static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.ExtendedType;
import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
}
- private static class TypeDef {
- public final TypeDefinition<? extends Object> typedef;
- public final QName qName;
-
- TypeDef(final TypeDefinition<? extends Object> typedef, final QName qName) {
- this.typedef = typedef;
- this.qName = qName;
- }
- }
-
- private final static RestconfImpl INSTANCE = new RestconfImpl();
+ private static final RestconfImpl INSTANCE = new RestconfImpl();
private static final int NOTIFICATION_PORT = 8181;
private static final int CHAR_NOT_FOUND = -1;
- private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
+ private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
- private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+ private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
- private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
+ private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
- private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
+ private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
private BrokerFacade broker;
Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
moduleContainerBuilder.withChild(allModuleMap);
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
null, schemaContext), moduleContainerBuilder.build());
}
throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
}
- final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
+ final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
final Set<Module> modules = controllerContext.getAllModules(mountPoint);
- final SchemaContext schemaContext = mountPoint.getSchemaContext();
final MapNode mountPointModulesMap = makeModuleMapNode(modules);
final Module restconfModule = getRestconfModule();
Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
moduleContainerBuilder.withChild(mountPointModulesMap);
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build());
}
DOMMountPoint mountPoint = null;
final SchemaContext schemaContext;
if (identifier.contains(ControllerContext.MOUNT)) {
- final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
+ final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
mountPoint = mountPointIdentifier.getMountPoint();
module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
schemaContext = mountPoint.getSchemaContext();
restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, moduleSchemaNode, mountPoint,
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
schemaContext), moduleMap);
}
streamsContainerBuilder.withChild(listStreamsBuilder.build());
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, streamsContainerSchemaNode, null,
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
schemaContext), streamsContainerBuilder.build());
}
Set<Module> modules = null;
DOMMountPoint mountPoint = null;
if (identifier.contains(ControllerContext.MOUNT)) {
- final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
+ final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
mountPoint = mountPointIdentifier.getMountPoint();
modules = controllerContext.getAllModules(mountPoint);
final SchemaContext schemaContext;
if (identifier.contains(ControllerContext.MOUNT)) {
// mounted RPC call - look up mount instance.
- final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
+ final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
mountPoint = mountPointId.getMountPoint();
schemaContext = mountPoint.getSchemaContext();
final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
resultNodeSchema = rpcDataSchemaNode.getDataChildByName(result.getResult().getNodeType());
}
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, resultNodeSchema, mountPoint,
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint,
schemaContext), resultData);
}
@Override
public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
- final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
+ final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
final DOMMountPoint mountPoint = iiWithData.getMountPoint();
NormalizedNode<?, ?> data = null;
final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
return new NormalizedNodeContext(iiWithData, data);
}
+ // FIXME: Move this to proper place
+ @SuppressWarnings("unused")
private Integer parseDepthParameter(final UriInfo info) {
final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
@Override
public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
- final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
+ final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
final DOMMountPoint mountPoint = iiWithData.getMountPoint();
NormalizedNode<?, ?> data = null;
final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
return new NormalizedNodeContext(iiWithData, data);
}
- private boolean parsePrettyPrintParameter(final UriInfo info) {
- final String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
- return Boolean.parseBoolean(param);
- }
-
@Override
public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
Preconditions.checkNotNull(identifier);
- final InstanceIdentifierContext<DataSchemaNode> iiWithData =
- (InstanceIdentifierContext<DataSchemaNode>) payload.getInstanceIdentifierContext();
+ final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
validateInput(iiWithData.getSchemaNode(), payload);
validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
* if key values or key count in payload and URI isn't equal
*
*/
- private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext<DataSchemaNode> iiWithData,
+ private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext<?> iiWithData,
final NormalizedNode<?, ?> payload) {
if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
return yangIdent;
}
- final InstanceIdentifierContext parentContext = payload.getInstanceIdentifierContext();
+ final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
if(parentSchemaNode instanceof DataNodeContainer) {
final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
}
final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
- final InstanceIdentifierContext<DataSchemaNode> iiWithData = (InstanceIdentifierContext<DataSchemaNode>) payload.getInstanceIdentifierContext();
+ final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
- final YangInstanceIdentifier resultII;
try {
if (mountPoint != null) {
broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
@Override
public Response deleteConfigurationData(final String identifier) {
- final InstanceIdentifierContext<DataSchemaNode> iiWithData = controllerContext.toInstanceIdentifier(identifier);
+ final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
final DOMMountPoint mountPoint = iiWithData.getMountPoint();
final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
return result;
}
- private boolean endsWithMountPoint(final String identifier) {
- return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
- }
-
- private String addMountPointIdentifier(final String identifier) {
- final boolean endsWith = identifier.endsWith("/");
- if (endsWith) {
- return (identifier + ControllerContext.MOUNT);
- }
-
- return identifier + "/" + ControllerContext.MOUNT;
- }
-
- private TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
- TypeDefinition<?> baseType = type;
- QName qName = nodeQName;
- while (baseType.getBaseType() != null) {
- if (baseType instanceof ExtendedType) {
- qName = baseType.getQName();
- }
- baseType = baseType.getBaseType();
- }
-
- return new TypeDef(baseType, qName);
-
- }
-
- private TypeDef typeDefinition(final DataSchemaNode node) {
- if (node instanceof LeafListSchemaNode) {
- return typeDefinition(((LeafListSchemaNode)node).getType(), node.getQName());
- } else if (node instanceof LeafSchemaNode) {
- return typeDefinition(((LeafSchemaNode)node).getType(), node.getQName());
- } else if (node instanceof AnyXmlSchemaNode) {
- return null;
- } else {
- throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
- }
- }
-
- private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
- final InstanceIdentifierContext iiWithSchemaNode) {
- return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
- }
-
- private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
- final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
- return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
- iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
- iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
- }
-
- private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
- final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
- Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
- final List<PathArgument> result = new ArrayList<PathArgument>();
- final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
- while (iter.hasNext()) {
- final PathArgument pathArgument = iter.next();
- if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
- result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
- }
- result.add(pathArgument);
- }
- return YangInstanceIdentifier.create(result);
- }
-
- private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
- if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
- return true;
- }
- return false;
- }
-
public BigInteger getOperationalReceived() {
// TODO Auto-generated method stub
return null;
+++ /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.sal.restconf.impl.cnsn.to.json.test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.Map;
-import java.util.Set;
-import org.junit.BeforeClass;
-import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.controller.sal.restconf.impl.test.structures.Cont;
-import org.opendaylight.controller.sal.restconf.impl.test.structures.Lf;
-import org.opendaylight.controller.sal.restconf.impl.test.structures.LfLst;
-import org.opendaylight.controller.sal.restconf.impl.test.structures.Lst;
-import org.opendaylight.controller.sal.restconf.impl.test.structures.LstItem;
-
-public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
-
- @BeforeClass
- public static void initialize() {
- dataLoad("/cnsn-to-json/simple-yang-types", 1, "simple-yang-types", "cont1");
- }
-
- private void verifyJsonOutputForEmptyData(final String jsonOutput) {
- assertNotNull(jsonOutput);
- final StringReader strReader = new StringReader(jsonOutput);
- final JsonReader jReader = new JsonReader(strReader);
-
- String exception = null;
- Cont dataFromJson = null;
- try {
- dataFromJson = jsonReadCont1(jReader);
- } catch (final IOException e) {
- exception = e.getMessage();
- }
-
- assertNotNull("Data structures from json are missing.", dataFromJson);
- checkDataFromJsonEmpty(dataFromJson);
-
- assertNull("Error during reading Json output: " + exception, exception);
- }
-
- private void verifyJsonOutput(final String jsonOutput) {
- assertNotNull(jsonOutput);
- final StringReader strReader = new StringReader(jsonOutput);
- final JsonReader jReader = new JsonReader(strReader);
-
- String exception = null;
- Cont dataFromJson = null;
- try {
- dataFromJson = jsonReadCont1(jReader);
- } catch (final IOException e) {
- exception = e.getMessage();
- }
-
- assertNotNull("Data structures from json are missing.", dataFromJson);
- checkDataFromJson(dataFromJson);
-
- assertNull("Error during reading Json output: " + exception, exception);
- }
-
- private Cont jsonReadCont1(final JsonReader jReader) throws IOException {
- jReader.beginObject();
- assertNotNull("cont1 is missing.", jReader.hasNext());
-
- Cont dataFromJson = new Cont(jReader.nextName());
- dataFromJson = jsonReadCont1Elements(jReader, dataFromJson);
-
- assertFalse("cont shouldn't have other element.", jReader.hasNext());
- jReader.endObject();
- return dataFromJson;
-
- }
-
- private Cont jsonReadCont1Elements(final JsonReader jReader, final Cont redData) throws IOException {
- jReader.beginObject();
- while (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- if (keyName.equals("lf11")) {
- redData.addLf(new Lf(keyName, nextValue(jReader)));
- } else if (keyName.equals("lflst11")) {
- LfLst lfLst = new LfLst(keyName);
- lfLst = jsonReadLflstValues(jReader, lfLst);
- redData.addLfLst(lfLst);
- } else if (keyName.equals("lflst12")) {
- final LfLst lfLst = new LfLst(keyName);
- jsonReadLflstValues(jReader, lfLst);
- redData.addLfLst(lfLst);
- } else if (keyName.equals("lst11")) {
- Lst lst = new Lst(keyName);
- lst = jsonReadLst11(jReader, lst);
- redData.addLst(lst);
- } else {
- assertTrue("Key " + keyName + " doesn't exists in yang file.", false);
- }
- }
- jReader.endObject();
- return redData;
-
- }
-
- private Lst jsonReadLst11(final JsonReader jReader, final Lst lst) throws IOException {
- jReader.beginArray();
-
- while (jReader.hasNext()) {
- final LstItem lstItem = jsonReadLst11Elements(jReader);
- lst.addLstItem(lstItem);
- }
- jReader.endArray();
- return lst;
- }
-
- private LstItem jsonReadLst11Elements(final JsonReader jReader) throws IOException {
- final LstItem lstItem = new LstItem();
- jReader.beginObject();
- while (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- if (keyName.equals("lf111")) {
- lstItem.addLf(new Lf(keyName, nextValue(jReader)));
- } else if (keyName.equals("lf112")) {
- lstItem.addLf(new Lf(keyName, nextValue(jReader)));
- } else if (keyName.equals("cont111")) {
- Cont cont = new Cont(keyName);
- cont = jsonReadCont111(jReader, cont);
- lstItem.addCont(cont);
- } else if (keyName.equals("lst111")) {
- Lst lst = new Lst(keyName);
- lst = jsonReadLst111(jReader, lst);
- lstItem.addLst(lst);
- } else if (keyName.equals("lst112")) {
- Lst lst = new Lst(keyName);
- lst = jsonReadLst112(jReader, lst);
- lstItem.addLst(lst);
- } else {
- assertTrue("Key " + keyName + " doesn't exists in yang file.", false);
- }
- }
- jReader.endObject();
- return lstItem;
- }
-
- private Lst jsonReadLst112(final JsonReader jReader, final Lst lst) throws IOException {
- jReader.beginArray();
- while (jReader.hasNext()) {
- final LstItem lstItem = jsonReadLst112Elements(jReader);
- lst.addLstItem(lstItem);
- }
- jReader.endArray();
- return lst;
- }
-
- private LstItem jsonReadLst112Elements(final JsonReader jReader) throws IOException {
- final LstItem lstItem = new LstItem();
- jReader.beginObject();
- if (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- if (keyName.equals("lf1121")) {
- lstItem.addLf(new Lf(keyName, nextValue(jReader)));
- }
- }
- jReader.endObject();
- return lstItem;
-
- }
-
- private Lst jsonReadLst111(final JsonReader jReader, final Lst lst) throws IOException {
- jReader.beginArray();
- while (jReader.hasNext()) {
- final LstItem lstItem = jsonReadLst111Elements(jReader);
- lst.addLstItem(lstItem);
- }
- jReader.endArray();
- return lst;
- }
-
- private LstItem jsonReadLst111Elements(final JsonReader jReader) throws IOException {
- final LstItem lstItem = new LstItem();
- jReader.beginObject();
- if (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- if (keyName.equals("lf1111")) {
- lstItem.addLf(new Lf(keyName, nextValue(jReader)));
- }
- }
- jReader.endObject();
- return lstItem;
- }
-
- private Object nextValue(final JsonReader jReader) throws IOException {
- if (jReader.peek().equals(JsonToken.NULL)) {
- jReader.nextNull();
- return null;
- } else if (jReader.peek().equals(JsonToken.NUMBER)) {
- return jReader.nextInt();
- } else {
- return jReader.nextString();
- }
- }
-
- private Cont jsonReadCont111(final JsonReader jReader, Cont cont) throws IOException {
- jReader.beginObject();
- cont = jsonReadCont111Elements(jReader, cont);
- jReader.endObject();
- return cont;
- }
-
- private Cont jsonReadCont111Elements(final JsonReader jReader, final Cont cont) throws IOException {
- while (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- if (keyName.equals("lf1111")) {
- cont.addLf(new Lf(keyName, nextValue(jReader)));
- } else if (keyName.equals("lflst1111")) {
- LfLst lfLst = new LfLst(keyName);
- lfLst = jsonReadLflstValues(jReader, lfLst);
- cont.addLfLst(lfLst);
- } else if (keyName.equals("lst1111")) {
- Lst lst = new Lst(keyName);
- lst = jsonReadLst1111(jReader, lst);
- cont.addLst(lst);
- } else {
- assertTrue("Key " + keyName + " doesn't exists in yang file.", false);
- }
- }
- return cont;
-
- }
-
- private Lst jsonReadLst1111(final JsonReader jReader, final Lst lst) throws IOException {
- jReader.beginArray();
- while (jReader.hasNext()) {
- final LstItem lstItem = jsonReadLst1111Elements(jReader);
- lst.addLstItem(lstItem);
- }
- jReader.endArray();
- return lst;
- }
-
- private LstItem jsonReadLst1111Elements(final JsonReader jReader) throws IOException {
- jReader.beginObject();
- final LstItem lstItem = new LstItem();
- while (jReader.hasNext()) {
- final String keyName = jReader.nextName();
- if (keyName.equals("lf1111A") || keyName.equals("lf1111B")) {
- lstItem.addLf(new Lf(keyName, nextValue(jReader)));
- }
- }
- jReader.endObject();
- return lstItem;
- }
-
- private LfLst jsonReadLflstValues(final JsonReader jReader, final LfLst lfLst) throws IOException {
- jReader.beginArray();
- while (jReader.hasNext()) {
- lfLst.addLf(new Lf(nextValue(jReader)));
- }
- jReader.endArray();
- return lfLst;
- }
-
- private void checkDataFromJsonEmpty(final Cont dataFromJson) {
- assertTrue(dataFromJson.getLfs().isEmpty());
- assertTrue(dataFromJson.getLfLsts().isEmpty());
- assertTrue(dataFromJson.getConts().isEmpty());
-
- final Map<String, Lst> lsts = dataFromJson.getLsts();
- assertEquals(1, lsts.size());
- final Lst lst11 = lsts.get("lst11");
- assertNotNull(lst11);
- final Set<LstItem> lstItems = lst11.getLstItems();
- assertNotNull(lstItems);
-
- LstItem lst11_1 = null;
- LstItem lst11_2 = null;
- LstItem lst11_3 = null;
- for (final LstItem lstItem : lstItems) {
- if (lstItem.getLfs().get("lf111").getValue().equals(1)) {
- lst11_1 = lstItem;
- } else if (lstItem.getLfs().get("lf111").getValue().equals(2)) {
- lst11_2 = lstItem;
- } else if (lstItem.getLfs().get("lf111").getValue().equals(3)) {
- lst11_3 = lstItem;
- }
- }
-
- assertNotNull(lst11_1);
- assertNotNull(lst11_2);
- assertNotNull(lst11_3);
-
- // lst11_1
- assertTrue(lst11_1.getLfLsts().isEmpty());
- assertEquals(1, lst11_1.getLfs().size());
- assertEquals(1, lst11_1.getConts().size());
- assertEquals(1, lst11_1.getLsts().size());
- assertEquals(lst11_1.getLsts().get("lst111"), new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35))
- .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem()).addLstItem(new LstItem()));
- assertEquals(lst11_1.getConts().get("cont111"), new Cont("cont111"));
- // : lst11_1
-
- // lst11_2
- assertTrue(lst11_2.getLfLsts().isEmpty());
- assertEquals(1, lst11_2.getLfs().size());
- assertEquals(1, lst11_2.getConts().size());
- assertEquals(1, lst11_2.getLsts().size());
-
- final Cont lst11_2_cont111 = lst11_2.getConts().get("cont111");
-
- // -cont111
- assertNotNull(lst11_2_cont111);
- assertTrue(lst11_2_cont111.getLfs().isEmpty());
- assertEquals(1, lst11_2_cont111.getLfLsts().size());
- assertEquals(1, lst11_2_cont111.getLsts().size());
- assertTrue(lst11_2_cont111.getConts().isEmpty());
-
- assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096), lst11_2_cont111.getLfLsts().get("lflst1111"));
- assertEquals(
- new Lst("lst1111").addLstItem(new LstItem().addLf("lf1111B", 4)).addLstItem(
- new LstItem().addLf("lf1111A", "lf1111A str12")), lst11_2_cont111.getLsts().get("lst1111"));
- // :-cont111
- assertEquals(lst11_2.getLsts().get("lst112"), new Lst("lst112").addLstItem(new LstItem()));
- // : lst11_2
-
- // lst11_3
- assertEquals(1, lst11_3.getLfs().size());
- assertTrue(lst11_3.getLfLsts().isEmpty());
- assertTrue(lst11_3.getLsts().isEmpty());
- assertTrue(lst11_3.getLsts().isEmpty());
-
- // -cont111
- final Cont lst11_3_cont111 = lst11_3.getConts().get("cont111");
- assertEquals(0, lst11_3_cont111.getLfs().size());
- assertEquals(0, lst11_3_cont111.getLfLsts().size());
- assertEquals(1, lst11_3_cont111.getLsts().size());
- assertTrue(lst11_3_cont111.getConts().isEmpty());
-
- assertEquals(new Lst("lst1111").addLstItem(new LstItem()).addLstItem(new LstItem()), lst11_3_cont111.getLsts()
- .get("lst1111"));
- // :-cont111
- // : lst11_3
-
- }
-
- private void checkDataFromJson(final Cont dataFromJson) {
- assertNotNull(dataFromJson.getLfs().get("lf11"));
- assertEquals(dataFromJson.getLfs().get("lf11"), new Lf("lf11", "lf"));
-
- LfLst lflst11 = null;
- LfLst lflst12 = null;
-
- lflst11 = dataFromJson.getLfLsts().get("lflst11");
- lflst12 = dataFromJson.getLfLsts().get("lflst12");
-
- assertNotNull(lflst11);
- assertNotNull(lflst12);
-
- assertEquals(3, lflst11.getLfs().size());
- assertTrue(lflst11.getLfs().contains(new Lf(55)));
- assertTrue(lflst11.getLfs().contains(new Lf(56)));
- assertTrue(lflst11.getLfs().contains(new Lf(57)));
-
- assertEquals(3, lflst12.getLfs().size());
- assertTrue(lflst12.getLfs().contains(new Lf("lflst12 str1")));
- assertTrue(lflst12.getLfs().contains(new Lf("lflst12 str2")));
- assertTrue(lflst12.getLfs().contains(new Lf("lflst12 str3")));
-
- assertEquals(1, dataFromJson.getLsts().size());
- final Lst lst11 = dataFromJson.getLsts().get("lst11");
- assertNotNull(lst11);
- assertEquals(2, lst11.getLstItems().size());
-
- LstItem lst11_1 = null;
- LstItem lst11_2 = null;
- for (final LstItem lstItem : lst11.getLstItems()) {
- final Lf lf = lstItem.getLfs().get("lf111");
- if (lf != null && lf.getValue().equals(140)) {
- lst11_1 = lstItem;
- } else if (lf != null && lf.getValue().equals(141)) {
- lst11_2 = lstItem;
- }
- }
-
- checkLst11_1(lst11_1);
- checkLst11_2(lst11_2);
- }
-
- private void checkLst11_2(final LstItem lst11_2) {
- assertNotNull(lst11_2);
- assertEquals(2, lst11_2.getLfs().size());
- assertEquals(1, lst11_2.getConts().size());
- assertEquals(2, lst11_2.getLsts().size());
-
- assertEquals(lst11_2.getLfs().get("lf112"), new Lf("lf112", "lf112 str2"));
-
- final Cont lst11_2_cont = lst11_2.getConts().get("cont111");
- assertEquals(0, lst11_2_cont.getConts().size());
- assertEquals(1, lst11_2_cont.getLfLsts().size());
- assertEquals(1, lst11_2_cont.getLfs().size());
- assertEquals(1, lst11_2_cont.getLsts().size());
-
- // cont111 check
- assertEquals(new Lf("lf1111", "lf1111 str2"), lst11_2_cont.getLfs().get("lf1111"));
- assertEquals(new LfLst("lflst1111").addLf(new Lf(2049)).addLf(new Lf(1025)).addLf(new Lf(4097)), lst11_2_cont
- .getLfLsts().get("lflst1111"));
-
- assertNotNull(lst11_2_cont.getLsts().get("lst1111"));
- checkLst1111(lst11_2_cont.getLsts().get("lst1111").getLstItems(), new Lf("lf1111A", "lf1111A str21"), new Lf(
- "lf1111B", 5), new Lf("lf1111A", "lf1111A str22"), new Lf("lf1111B", 8));
-
- checkLst11x(lst11_2.getLsts().get("lst111"), new LstItem().addLf(new Lf("lf1111", 55)),
- new LstItem().addLf(new Lf("lf1111", 56)));
- checkLst11x(lst11_2.getLsts().get("lst112"), new LstItem().addLf(new Lf("lf1121", "lf1121 str22")),
- new LstItem().addLf(new Lf("lf1121", "lf1121 str21")));
- }
-
- private void checkLst11_1(final LstItem lst11_1) {
- assertNotNull(lst11_1);
-
- assertEquals(2, lst11_1.getLfs().size());
- assertEquals(1, lst11_1.getConts().size());
- assertEquals(2, lst11_1.getLsts().size());
-
- assertEquals(lst11_1.getLfs().get("lf112"), new Lf("lf112", "lf112 str"));
-
- final Cont lst11_1_cont = lst11_1.getConts().get("cont111");
- assertEquals(0, lst11_1_cont.getConts().size());
- assertEquals(1, lst11_1_cont.getLfLsts().size());
- assertEquals(1, lst11_1_cont.getLfs().size());
- assertEquals(1, lst11_1_cont.getLsts().size());
-
- // cont111 check
- assertEquals(new Lf("lf1111", "lf1111 str"), lst11_1_cont.getLfs().get("lf1111"));
- assertEquals(new LfLst("lflst1111").addLf(new Lf(2048)).addLf(new Lf(1024)).addLf(new Lf(4096)), lst11_1_cont
- .getLfLsts().get("lflst1111"));
-
- assertNotNull(lst11_1_cont.getLsts().get("lst1111"));
- checkLst1111(lst11_1_cont.getLsts().get("lst1111").getLstItems(), new Lf("lf1111A", "lf1111A str11"), new Lf(
- "lf1111B", 4), new Lf("lf1111A", "lf1111A str12"), new Lf("lf1111B", 7));
-
- checkLst11x(lst11_1.getLsts().get("lst111"), new LstItem().addLf(new Lf("lf1111", 65)));
- checkLst11x(lst11_1.getLsts().get("lst112"), new LstItem().addLf(new Lf("lf1121", "lf1121 str11")));
- }
-
- private void checkLst11x(final Lst lst, final LstItem... lstItems) {
- assertNotNull(lst);
-
- final Lst requiredLst = new Lst(lst.getName());
- for (final LstItem lstItem : lstItems) {
- requiredLst.addLstItem(lstItem);
- }
-
- assertEquals(requiredLst, lst);
-
- }
-
- private void checkLst1111(final Set<LstItem> lstItems, final Lf lf11, final Lf lf12, final Lf lf21, final Lf lf22) {
- LstItem lst11_1_cont_lst1111_1 = null;
- LstItem lst11_1_cont_lst1111_2 = null;
- for (final LstItem lstItem : lstItems) {
- if (new LstItem().addLf(lf11).addLf(lf12).equals(lstItem)) {
- lst11_1_cont_lst1111_1 = lstItem;
- } else if (new LstItem().addLf(lf21).addLf(lf22).equals(lstItem)) {
- lst11_1_cont_lst1111_2 = lstItem;
- }
- }
-
- assertNotNull(lst11_1_cont_lst1111_1);
- assertNotNull(lst11_1_cont_lst1111_2);
- }
-
-}
+++ /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.sal.restconf.impl.cnsn.to.json.test;
-
-import java.util.List;
-import java.util.Set;
-import org.junit.BeforeClass;
-import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.Status;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UsesNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CnSnToJsonIncorrectTopLevelTest extends YangAndXmlAndDataSchemaLoader {
-
- private static final Logger LOG = LoggerFactory.getLogger(CnSnToJsonIncorrectTopLevelTest.class);
-
- @BeforeClass
- public static void initialize() {
- dataLoad("/cnsn-to-json/simple-data-types");
- }
-
- private class IncorrectDataSchema implements DataSchemaNode, DataNodeContainer {
-
- @Override
- public String getDescription() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public SchemaPath getPath() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public QName getQName() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getReference() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Status getStatus() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public List<UnknownSchemaNode> getUnknownSchemaNodes() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Set<DataSchemaNode> getChildNodes() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public DataSchemaNode getDataChildByName(final QName arg0) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public DataSchemaNode getDataChildByName(final String arg0) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Set<GroupingDefinition> getGroupings() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Set<TypeDefinition<?>> getTypeDefinitions() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Set<UsesNode> getUses() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public ConstraintDefinition getConstraints() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean isAddedByUses() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isAugmenting() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isConfiguration() {
- // TODO Auto-generated method stub
- return false;
- }
-
- }
-
-}
+++ /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.sal.restconf.impl.cnsn.to.json.test;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import org.junit.BeforeClass;
-import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
-
-/**
- *
- * All tests are commented now because leafref isn't supported now
- *
- */
-
-public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
-
- @BeforeClass
- public static void initialization() {
- dataLoad("/cnsn-to-json/leafref", 2, "main-module", "cont");
- }
-
- private void validateJson(final String regex, final String value) {
- assertNotNull(value);
- final Pattern ptrn = Pattern.compile(regex, Pattern.DOTALL);
- final Matcher mtch = ptrn.matcher(value);
- assertTrue(mtch.matches());
- }
-
-}
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLoader {
- private static final Logger LOG = LoggerFactory.getLogger(CnSnToJsonNotExistingLeafTypeTest.class);
-
@BeforeClass
public static void initialize() {
dataLoad("/cnsn-to-json/simple-data-types");
}
+ @SuppressWarnings("unused")
private DataSchemaNode prepareDataSchemaNode() {
final ContainerSchemaNodeBuilder contBuild = new ContainerSchemaNodeBuilder("module", 1, TestUtils.buildQName("cont",
"simple:uri", "2012-12-17"), SchemaPath.create(true, QName.create("dummy")));
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.CheckedFuture;
import java.io.FileNotFoundException;
testNodeContainer.withChild(leafKey2.build());
}
- final NormalizedNodeContext testCompositeContext = new NormalizedNodeContext(new InstanceIdentifierContext(
+ final NormalizedNodeContext testCompositeContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(
null, testNodeSchemaNode, null, schemaContextTestModule), testNodeContainer.build());
restconfImpl.updateConfigurationData(toUri(uriKey1, uriKey2), testCompositeContext);
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
+
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
SchemaPath type = SchemaPath.create(true, qname);
- YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).toInstance();
+ YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).build();
@Mock
DOMDataReadOnlyTransaction rTransaction;
brokerFacade.readOperationalData(instanceID);
}
- @SuppressWarnings("unchecked")
@Test
public void testInvokeRpc() throws Exception {
final DOMRpcResult expResult = mock(DOMRpcResult.class);
@Ignore
@Test
public void testCommitConfigurationDataPut() {
+ @SuppressWarnings("unchecked")
final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
when(wTransaction.submit()).thenReturn(expFuture);
@Test
public void testCommitConfigurationDataPost() {
+ @SuppressWarnings("unchecked")
final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
final NormalizedNode<?, ?> dummyNode2 = createDummyNode("dummy:namespace2", "2014-07-01", "dummy local name2");
@Test
public void testCommitConfigurationDataDelete() {
+ @SuppressWarnings("unchecked")
final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
when(wTransaction.submit()).thenReturn(expFuture);
- final NormalizedNode<?, ?> dummyNode2 = createDummyNode("dummy:namespace2", "2014-07-01", "dummy local name2");
-
-
final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = brokerFacade
.commitConfigurationDataDelete(instanceID);
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
+
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
contNode.withChild(lfNode);
container.withChild(contNode.build());
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode, null, schema), container.build());
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
}
@Test
final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
Builders.containerBuilder(rpcInputSchemaNode);
- final NormalizedNodeContext payload = new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode,
+ final NormalizedNodeContext payload = new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
null, schemaContext), containerBuilder.build());
final BrokerFacade brokerFacade = mock(BrokerFacade.class);
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import com.google.common.util.concurrent.CheckedFuture;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
return resourceConfig;
}
+ @SuppressWarnings("unchecked")
@Test
public void deleteConfigStatusCodes() throws UnsupportedEncodingException {
final String uri = "/config/test-interface:interfaces";
@BeforeClass
public static void init() throws FileNotFoundException {
- SchemaContext schemaContextTestModule = TestUtils.loadSchemaContext("/common/augment/yang");
+ final SchemaContext schemaContextTestModule = TestUtils.loadSchemaContext("/common/augment/yang");
controllerContext.setSchemas(schemaContextTestModule);
}
@Test
public void augmentedNodesInUri() {
- InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier("main:cont/augment-main-a:cont1");
+ InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier("main:cont/augment-main-a:cont1");
assertEquals("ns:augment:main:a", iiWithData.getSchemaNode().getQName().getNamespace().toString());
iiWithData = controllerContext.toInstanceIdentifier("main:cont/augment-main-b:cont1");
assertEquals("ns:augment:main:b", iiWithData.getSchemaNode().getQName().getNamespace().toString());
try {
controllerContext.toInstanceIdentifier("main:cont/cont1");
fail("Expected exception");
- } catch (RestconfDocumentedException e) {
+ } catch (final RestconfDocumentedException e) {
assertTrue(e.getErrors().get(0).getErrorMessage().contains("is added as augment from more than one module"));
}
}
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
private static RestconfImpl restconfImpl;
private static SchemaContext schemaContextYangsIetf;
private static SchemaContext schemaContextTestModule;
+ @SuppressWarnings("rawtypes")
private static NormalizedNode answerFromGet;
private static SchemaContext schemaContextModules;
/**
* MountPoint test. URI represents mount point.
*/
+ @SuppressWarnings("unchecked")
@Test
public void getDataWithUrlMountPoint() throws UnsupportedEncodingException, URISyntaxException, ParseException {
when(brokerFacade.readConfigurationData(any(DOMMountPoint.class), any(YangInstanceIdentifier.class))).thenReturn(
* Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
* requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
* InstanceIdentifier parameter in method
- * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, YangInstanceIdentifier)} which is called in
+ * {@link BrokerFacade#readConfigurationData(DOMMountPoint, YangInstanceIdentifier)} which is called in
* method {@link RestconfImpl#readConfigurationData}
*
* @throws ParseException
}
- private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
- throws FileNotFoundException {
- final SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
- mockedControllerContext.setGlobalSchema(schemaContext);
- // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
- }
-
private int get(final String uri, final String mediaType) {
return target(uri).request(mediaType).get().getStatus();
}
type string;
}
*/
+ @SuppressWarnings("rawtypes")
private NormalizedNode prepareCnDataForMountPointTest(final boolean wrapToCont) throws URISyntaxException, ParseException {
final String testModuleDate = "2014-01-09";
final ContainerNode contChild = Builders
}
+ @SuppressWarnings("unchecked")
private void mockReadOperationalDataMethod() {
when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
}
+ @SuppressWarnings("unchecked")
private void mockReadConfigurationDataMethod() {
when(brokerFacade.readConfigurationData(any(YangInstanceIdentifier.class))).thenReturn(answerFromGet);
}
+ @SuppressWarnings("rawtypes")
private NormalizedNode prepareCnDataForSlashesBehindMountPointTest() throws ParseException {
return ImmutableMapEntryNodeBuilder
.create()
getDataWithInvalidDepthParameterTest(mockInfo);
}
+ @SuppressWarnings({"rawtypes", "unchecked"})
private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
try {
final QName qNameDepth1Cont = QName.create("urn:nested:module", "2014-06-3", "depth1-cont");
}
}
+ @SuppressWarnings("unused")
private void verifyXMLResponse(final Response response, final NodeData nodeData) {
final Document doc = response.readEntity(Document.class);
// Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
}
}
- private NodeData expectContainer(final String name, final NodeData... childData) {
- return new NodeData(name, Lists.newArrayList(childData));
- }
-
- private NodeData expectEmptyContainer(final String name) {
- return new NodeData(name, null);
- }
-
- private NodeData expectLeaf(final String name, final Object value) {
- return new NodeData(name, value);
- }
-
- private QName toNestedQName(final String localName) {
- return QName.create("urn:nested:module", "2014-06-3", localName);
- }
-
- private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
- return new NodeData(key, Lists.newArrayList(childData));
- }
-
- private NodeData toSimpleNodeData(final QName key, final Object value) {
- return new NodeData(key, value);
- }
-
}
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.CheckedFuture;
restconfImpl.setControllerContext(context);
}
+ @SuppressWarnings("unchecked")
@Test
@Ignore /// xmlData* need netconf-yang
public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
}
+ @SuppressWarnings("unchecked")
@Test
@Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
.thenReturn(mock(CheckedFuture.class));
final ArgumentCaptor<YangInstanceIdentifier> instanceIdCaptor = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
+ @SuppressWarnings("rawtypes")
final ArgumentCaptor<NormalizedNode> compNodeCaptor = ArgumentCaptor.forClass(NormalizedNode.class);
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import java.io.FileNotFoundException;
@Test
public void putConfigStatusCodesEmptyBody() throws UnsupportedEncodingException {
final String uri = "/config/ietf-interfaces:interfaces/interface/eth0";
+ @SuppressWarnings("unused")
final Response resp = target(uri).request(MediaType.APPLICATION_JSON).put(
Entity.entity("", MediaType.APPLICATION_JSON));
assertEquals(400, put(uri, MediaType.APPLICATION_JSON, ""));
public void testRpcResultCommitedToStatusCodesWithMountPoint() throws UnsupportedEncodingException,
FileNotFoundException, URISyntaxException {
+ @SuppressWarnings("unchecked")
final CheckedFuture<Void, TransactionCommitFailedException> dummyFuture = mock(CheckedFuture.class);
when(
@Test
public void putDataMountPointIntoHighestElement() throws UnsupportedEncodingException, URISyntaxException {
+ @SuppressWarnings("unchecked")
final CheckedFuture<Void, TransactionCommitFailedException> dummyFuture = mock(CheckedFuture.class);
when(
brokerFacade.commitConfigurationDataPut(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
@BeforeClass
public static void init() throws FileNotFoundException {
- Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
+ final Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
assertNotNull(allModules);
- SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
+ final SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
controllerContext = spy(ControllerContext.getInstance());
controllerContext.setSchemas(schemaContext);
restconfImpl.setControllerContext(controllerContext);
}
+ @SuppressWarnings("unchecked")
@Test
public void testExample() throws FileNotFoundException, ParseException {
+ @SuppressWarnings("rawtypes")
+ final
NormalizedNode normalizedNodeData = TestUtils.prepareNormalizedNodeWithIetfInterfacesInterfacesData();
- BrokerFacade brokerFacade = mock(BrokerFacade.class);
+ final BrokerFacade brokerFacade = mock(BrokerFacade.class);
when(brokerFacade.readOperationalData(any(YangInstanceIdentifier.class))).thenReturn(normalizedNodeData);
assertEquals(normalizedNodeData,
brokerFacade.readOperationalData(null));
package org.opendaylight.controller.sal.restconf.impl.test;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+
import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URISyntaxException;
import java.sql.Date;
import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
-import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
-import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
- private final static YangContextParser parser = new YangParserImpl();
+ private final static YangContextParser PARSER = new YangParserImpl();
private static Set<Module> loadModules(final String resourceDirectory) throws FileNotFoundException {
final File testDir = new File(resourceDirectory);
testFiles.add(new File(testDir, fileName));
}
}
- return parser.parseYangModels(testFiles);
+ return PARSER.parseYangModels(testFiles);
}
public static Set<Module> loadModulesFrom(final String yangPath) {
}
public static SchemaContext loadSchemaContext(final Set<Module> modules) {
- return parser.resolveSchemaContext(modules);
+ return PARSER.resolveSchemaContext(modules);
}
public static SchemaContext loadSchemaContext(final String resourceDirectory) throws FileNotFoundException {
- return parser.resolveSchemaContext(loadModulesFrom(resourceDirectory));
+ return PARSER.resolveSchemaContext(loadModulesFrom(resourceDirectory));
}
public static Module findModule(final Set<Module> modules, final String moduleName) {
return buildQName(name, "", null);
}
- private static void prepareMocksForRestconf(final Set<Module> modules, final RestconfImpl restconf) {
- final ControllerContext controllerContext = ControllerContext.getInstance();
- final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
-
- controllerContext.setSchemas(TestUtils.loadSchemaContext(modules));
-
- when(mockedBrokerFacade.commitConfigurationDataPut(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
- .thenReturn(mock(CheckedFuture.class));
-
- restconf.setControllerContext(controllerContext);
- restconf.setBroker(mockedBrokerFacade);
- }
-
public static String loadTextFile(final String filePath) throws IOException {
final FileReader fileReader = new FileReader(filePath);
final BufferedReader bufReader = new BufferedReader(fileReader);
public static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
final String namespace, final String revision, final String... keysAndValues) throws ParseException {
- final java.util.Date date = new SimpleDateFormat("yyyy-MM-dd").parse(revision);
if (keysAndValues.length % 2 != 0) {
new IllegalArgumentException("number of keys argument have to be divisible by 2 (map)");
}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil.getRevisionFormat;
+
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.Date;
+ scopeValue);
final UriInfo mockedUriInfo = mock(UriInfo.class);
+ @SuppressWarnings("unchecked")
final MultivaluedMap<String, String> mockedMultivaluedMap = mock(MultivaluedMap.class);
when(mockedMultivaluedMap.getFirst(eq("datastore"))).thenReturn(datastoreValue);
when(mockedMultivaluedMap.getFirst(eq("scope"))).thenReturn(scopeValue);
.withValue(scope)).build();
container.withChild(scopeNode);
- return new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode, null, schema), container.build());
+ return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
}
}
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
@Test
public void testToInstanceIdentifierList() throws FileNotFoundException {
- InstanceIdentifierContext instanceIdentifier = controllerContext
+ InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:userWithoutClass/foo");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "userWithoutClass");
@Test
public void testToInstanceIdentifierContainer() throws FileNotFoundException {
- final InstanceIdentifierContext instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:users");
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext.toInstanceIdentifier("simple-nodes:users");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "users");
assertTrue(instanceIdentifier.getSchemaNode() instanceof ContainerSchemaNode);
assertEquals(2, ((ContainerSchemaNode) instanceIdentifier.getSchemaNode()).getChildNodes().size());
@Test
@Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
public void testToInstanceIdentifierChoice() throws FileNotFoundException {
- final InstanceIdentifierContext instanceIdentifier = controllerContext
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:food/nonalcoholic");
assertEquals(instanceIdentifier.getSchemaNode().getQName().getLocalName(), "nonalcoholic");
}
@Test
public void testMountPointWithExternModul() throws FileNotFoundException {
initMountService(true);
- final InstanceIdentifierContext instanceIdentifier = controllerContext
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class/student/name");
assertEquals(
"[(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)class, (urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student, (urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)student[{(urn:ietf:params:xml:ns:yang:test-interface2?revision=2014-08-01)name=name}]]",
@Test
public void testMountPointWithoutExternModul() throws FileNotFoundException {
initMountService(true);
- final InstanceIdentifierContext instanceIdentifier = controllerContext
+ final InstanceIdentifierContext<?> instanceIdentifier = controllerContext
.toInstanceIdentifier("simple-nodes:users/yang-ext:mount/");
assertTrue(Iterables.isEmpty(instanceIdentifier.getInstanceIdentifier().getPathArguments()));
}
+++ /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.sal.restconf.impl.test.structures;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-public class CompareLf {
-
- @Test
- public void test() {
- Lf lf1 = new Lf("name", "value");
- Lf lf2 = new Lf("name", "value");
- Lf lf3 = new Lf("name1", "value");
- Lf lf4 = new Lf("name", "value1");
-
- assertTrue(lf1.equals(lf2));
- assertFalse(lf1.equals(lf3));
- assertFalse(lf1.equals(lf4));
- }
-
-}
+++ /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.sal.restconf.impl.test.structures;
-
-public class Cont extends LstItem {
- String name = null;
-
- public Cont(String name) {
- super();
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!this.getClass().equals(obj.getClass())) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- Cont cont = (Cont) obj;
- if (this.name == null) {
- if (cont.name != null) {
- return false;
- }
- } else if (!this.name.equals(cont.name)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
- return result;
- }
-
- @Override
- public String toString() {
- return name;
- }
-
-}
+++ /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.sal.restconf.impl.test.structures;
-
-public class Lf extends YangElement {
- private Object value;
- private int numOfEqualItems = 0;
-
- public Lf(String name, Object value) {
- super(name);
- this.value = value;
- }
-
- public Lf(Object value) {
- super("");
- this.value = value;
- }
-
- public Object getValue() {
- return value;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!this.getClass().equals(obj.getClass())) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- Lf lf = (Lf) obj;
- if (this.value == null) {
- if (lf.value != null) {
- return false;
- }
- } else if (!this.value.equals(lf.value)) {
- return false;
- }
- if (this.numOfEqualItems != lf.numOfEqualItems) {
- return false;
- }
- return true;
- }
-
- public void incNumOfEqualItems() {
- this.numOfEqualItems++;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((value == null) ? 0 : value.hashCode());
- result = prime * result + numOfEqualItems;
- return result;
- }
-
- @Override
- public String toString() {
- return super.toString() + ":" + value;
- }
-
-}
+++ /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.sal.restconf.impl.test.structures;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class LfLst extends YangElement {
- Set<Lf> lfs;
-
- public LfLst(String name) {
- super(name);
- lfs = new HashSet<>();
- }
-
- public LfLst addLf(Object value) {
- return addLf(new Lf(value));
- }
-
- public LfLst addLf(Lf lf) {
- while (this.lfs.contains(lf)) {
- lf.incNumOfEqualItems();
- }
- this.lfs.add(lf);
- return this;
- }
-
- public Set<Lf> getLfs() {
- return lfs;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!this.getClass().equals(obj.getClass())) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- LfLst lfLst = (LfLst) obj;
- if (this.lfs == null) {
- if (lfLst.lfs != null) {
- return false;
- }
- } else if (!this.lfs.equals(lfLst.lfs)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((lfs == null) ? 0 : lfs.hashCode());
- return result;
- }
-
- @Override
- public String toString() {
-
- return super.toString();
- }
-
-}
+++ /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.sal.restconf.impl.test.structures;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class Lst extends YangElement {
- private final Set<LstItem> lstItems;
-
- public Lst(final String name) {
- super(name);
- lstItems = new HashSet<>();
- }
-
- public Lst addLstItem(final LstItem lstItem) {
- lstItem.setLstName(name);
- while (this.lstItems.contains(lstItem)) {
- lstItem.incNumOfEqualItems();
- }
- this.lstItems.add(lstItem);
- return this;
- }
-
- public Set<LstItem> getLstItems() {
- return lstItems;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (!this.getClass().equals(obj.getClass())) {
- return false;
- }
- if (!super.equals(obj)) {
- return false;
- }
- Lst lst = (Lst) obj;
- if (this.lstItems == null) {
- if (lst.lstItems != null) {
- return false;
- }
- } else if (!this.lstItems.equals(lst.lstItems)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((lstItems == null) ? 0 : lstItems.hashCode());
- return result;
- }
-}
+++ /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.sal.restconf.impl.test.structures;
-
-import static org.junit.Assert.assertFalse;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class LstItem {
- String lstName;
- Map<String, Lf> lfs;
- Map<String, LfLst> lfLsts;
- Map<String, Lst> lsts;
- Map<String, Cont> conts;
- private int numOfEqualItems = 0;
-
- public LstItem() {
- lfs = new HashMap<>();
- conts = new HashMap<>();
- lfLsts = new HashMap<>();
- lsts = new HashMap<>();
- }
-
- public Map<String, Lst> getLsts() {
- return lsts;
- }
-
- public Map<String, Cont> getConts() {
- return conts;
- }
-
- public Map<String, LfLst> getLfLsts() {
- return lfLsts;
- }
-
- public Map<String, Lf> getLfs() {
- return lfs;
- }
-
- public String getLstName() {
- return lstName;
- }
-
- public LstItem addLf(Lf lf) {
- lfs.put(lf.getName(), lf);
- return this;
- }
-
- public LstItem addLf(String name, Object value) {
- lfs.put(name, new Lf(name, value));
- return this;
- }
-
- public void addLfLst(LfLst lfLst) {
- assertFalse("Found multiple leaf list elements for " + lfLst.getName(), lfLsts.containsKey(lfLst.getName()));
- lfLsts.put(lfLst.getName(), lfLst);
- }
-
- public void addLst(Lst lst) {
- assertFalse("Found multiple list elements for " + lst.getName(), lsts.containsKey(lst.getName()));
- lsts.put(lst.getName(), lst);
- }
-
- public void addCont(Cont cont) {
- conts.put(cont.getName(), cont);
- }
-
- public void incNumOfEqualItems() {
- this.numOfEqualItems++;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!this.getClass().equals(obj.getClass())) {
- return false;
- }
- LstItem lstItem = (LstItem) obj;
- if (this.conts == null) {
- if (lstItem.conts != null) {
- return false;
- }
- } else if (!this.conts.equals(lstItem.conts)) {
- return false;
- }
- if (this.lfs == null) {
- if (lstItem.lfs != null) {
- return false;
- }
- } else if (!this.lfs.equals(lstItem.lfs)) {
- return false;
- }
- if (this.lfLsts == null) {
- if (lstItem.lfLsts != null) {
- return false;
- }
- } else if (!this.lfLsts.equals(lstItem.lfLsts)) {
- return false;
- }
- if (this.lsts == null) {
- if (lstItem.lsts != null) {
- return false;
- }
- } else if (!this.lsts.equals(lstItem.lsts)) {
- return false;
- }
- if (this.numOfEqualItems != lstItem.numOfEqualItems) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((lfs == null) ? 0 : lfs.hashCode());
- result = prime * result + ((lfLsts == null) ? 0 : lfLsts.hashCode());
- result = prime * result + ((lsts == null) ? 0 : lsts.hashCode());
- result = prime * result + ((conts == null) ? 0 : conts.hashCode());
- result = prime * result + numOfEqualItems;
- return result;
- }
-
- @Override
- public String toString() {
- return "lst item of " + lstName;
- }
-
- public void setLstName(String name) {
- this.lstName = name;
- }
-
-}
+++ /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.sal.restconf.impl.test.structures;
-
-public class YangElement {
- protected String name;
-
- protected YangElement(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!this.getClass().equals(obj.getClass())) {
- return false;
- }
- YangElement yangElement = (YangElement) obj;
- if (this.name == null) {
- if (yangElement.name != null) {
- return false;
- }
- } else if (!this.name.equals(yangElement.name)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- @Override
- public String toString() {
- return name;
- }
-
-}
+++ /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.sal.restconf.impl.xml.to.cnsn.test;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class XmlLeafrefToCnSnTest {
- private static final Logger LOG = LoggerFactory.getLogger(XmlLeafrefToCnSnTest.class);
-
-}
package org.opendaylight.controller.netconf.cli.reader.custom;
import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
-
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.netconf.cli.reader.ReadingException;
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.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
filterPartsQNames.add(qName);
}
- List<NormalizedNode<?, ?>> previous = readInnerNode(rawValue);
+ List<? extends NormalizedNode<?, ?>> previous = readInnerNode(rawValue);
for (final QName qName : Lists.reverse(filterPartsQNames).subList(1, filterPartsQNames.size())) {
previous = Collections.<NormalizedNode<?, ?>>singletonList(
);
}
- final DataContainerChild<?, ?> newNode = previous == null ? null
- : ImmutableContainerNodeBuilder.create()
- .withNodeIdentifier(new NodeIdentifier(schemaNode.getQName()))
- .withValue((Collection) previous).build();
+ if (previous == null) {
+ return Collections.singletonList(null);
+ }
+
+ final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = ImmutableContainerNodeBuilder.create();
+ builder.withNodeIdentifier(new NodeIdentifier(schemaNode.getQName()));
+ builder.withValue((Collection<DataContainerChild<?, ?>>) previous);
- return Collections.<NormalizedNode<?, ?>> singletonList(newNode);
+ return Collections.<NormalizedNode<?, ?>> singletonList(builder.build());
}
private List<NormalizedNode<?, ?>> readInnerNode(final String pathString) throws ReadingException {
this.timer = timer;
}
+ protected Timer getTimer() {
+ return timer;
+ }
+
@Override
public Future<NetconfClientSession> createClient(final NetconfClientConfiguration clientConfiguration) {
switch (clientConfiguration.getProtocol()) {
public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfMessage, NetconfClientSession, NetconfClientSessionListener> {
- public static final Set<String> CLIENT_CAPABILITIES = ImmutableSet.of(
+ public static final Set<String> EXI_CLIENT_CAPABILITIES = ImmutableSet.of(
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1,
XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0);
+ public static final Set<String> LEGACY_EXI_CLIENT_CAPABILITIES = ImmutableSet.of(
+ XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
+ XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0);
+
+ public static final Set<String> DEFAULT_CLIENT_CAPABILITIES = ImmutableSet.of(
+ XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
+ XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
+
+ public static final Set<String> LEGACY_FRAMING_CLIENT_CAPABILITIES = ImmutableSet.of(
+ XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0);
+
private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiatorFactory.class);
private static final String START_EXI_MESSAGE_ID = "default-start-exi";
private static final EXIOptions DEFAULT_OPTIONS;
DEFAULT_OPTIONS = opts;
}
+ private final Set<String> clientCapabilities;
+
public NetconfClientSessionNegotiatorFactory(final Timer timer,
final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
final long connectionTimeoutMillis) {
this(timer, additionalHeader, connectionTimeoutMillis, DEFAULT_OPTIONS);
}
+ public NetconfClientSessionNegotiatorFactory(final Timer timer,
+ final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
+ final long connectionTimeoutMillis, final Set<String> capabilities) {
+ this(timer, additionalHeader, connectionTimeoutMillis, DEFAULT_OPTIONS, capabilities);
+
+ }
+
public NetconfClientSessionNegotiatorFactory(final Timer timer,
final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
final long connectionTimeoutMillis, final EXIOptions exiOptions) {
+ this(timer, additionalHeader, connectionTimeoutMillis, exiOptions, EXI_CLIENT_CAPABILITIES);
+ }
+
+ public NetconfClientSessionNegotiatorFactory(final Timer timer,
+ final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
+ final long connectionTimeoutMillis, final EXIOptions exiOptions, final Set<String> capabilities) {
this.timer = Preconditions.checkNotNull(timer);
this.additionalHeader = additionalHeader;
this.connectionTimeoutMillis = connectionTimeoutMillis;
this.options = exiOptions;
+ this.clientCapabilities = capabilities;
}
@Override
NetconfMessage startExiMessage = NetconfStartExiMessage.create(options, START_EXI_MESSAGE_ID);
NetconfHelloMessage helloMessage = null;
try {
- helloMessage = NetconfHelloMessage.createClientHello(CLIENT_CAPABILITIES, additionalHeader);
+ helloMessage = NetconfHelloMessage.createClientHello(clientCapabilities, additionalHeader);
} catch (NetconfDocumentedException e) {
- LOG.error("Unable to create client hello message with capabilities {} and additional handler {}",CLIENT_CAPABILITIES,additionalHeader);
+ LOG.error("Unable to create client hello message with capabilities {} and additional handler {}", clientCapabilities,additionalHeader);
throw new IllegalStateException(e);
}
--- /dev/null
+<modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+<module>
+<type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">prefix:threadfactory-naming</type>
+<name>name{MSG_ID}</name>
+<name-prefix xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">remote-connector-processing-executor</name-prefix>
+</module>
+</modules>
\ No newline at end of file
<groupId>org.opendaylight.controller</groupId>
<artifactId>netconf-connector-config</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-netconf-connector</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>logback-config</artifactId>
<shadedClassifierName>executable</shadedClassifierName>
</configuration>
</execution>
+
+ <execution>
+ <id>stress-client</id>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <shadedArtifactId>stress-client</shadedArtifactId>
+ <filters>
+ <filter>
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ <transformers>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass>org.opendaylight.controller.netconf.test.tool.client.stress.StressClient</mainClass>
+ </transformer>
+ </transformers>
+ <shadedArtifactAttached>true</shadedArtifactAttached>
+ <shadedClassifierName>executable</shadedClassifierName>
+ </configuration>
+ </execution>
</executions>
</plugin>
</plugins>
--- /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.test.tool.client.stress;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+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.slf4j.LoggerFactory;
+
+class AsyncExecutionStrategy implements ExecutionStrategy {
+ private static final Logger LOG = LoggerFactory.getLogger(AsyncExecutionStrategy.class);
+
+ private final Parameters params;
+ private final List<NetconfMessage> preparedMessages;
+ private final NetconfDeviceCommunicator sessionListener;
+ private final List<Integer> editBatches;
+
+ public AsyncExecutionStrategy(final Parameters params, final List<NetconfMessage> editConfigMsgs, final NetconfDeviceCommunicator sessionListener) {
+ this.params = params;
+ this.preparedMessages = editConfigMsgs;
+ this.sessionListener = sessionListener;
+ this.editBatches = countEditBatchSizes(params);
+ }
+
+ private static List<Integer> countEditBatchSizes(final Parameters params) {
+ final List<Integer> editBatches = Lists.newArrayList();
+ if (params.editBatchSize != params.editCount) {
+ final int fullBatches = params.editCount / params.editBatchSize;
+ for (int i = 0; i < fullBatches; i++) {
+ editBatches.add(params.editBatchSize);
+ }
+
+ if (params.editCount % params.editBatchSize != 0) {
+ editBatches.add(params.editCount % params.editBatchSize);
+ }
+ } else {
+ editBatches.add(params.editBatchSize);
+ }
+ return editBatches;
+ }
+
+ @Override
+ public void invoke() {
+ final AtomicInteger responseCounter = new AtomicInteger(0);
+ final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
+
+ int batchI = 0;
+ for (final Integer editBatch : editBatches) {
+ for (int i = 0; i < editBatch; i++) {
+ final int msgId = i + (batchI * params.editBatchSize);
+ final NetconfMessage msg = preparedMessages.get(msgId);
+ LOG.debug("Sending message {}", msgId);
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("Sending message {}", XmlUtil.toString(msg.getDocument()));
+ }
+ final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture =
+ sessionListener.sendRequest(msg, StressClient.EDIT_QNAME);
+ futures.add(netconfMessageFuture);
+ }
+ batchI++;
+ LOG.info("Batch {} with size {} sent. Committing", batchI, editBatch);
+ futures.add(sessionListener.sendRequest(StressClient.COMMIT_MSG, StressClient.COMMIT_QNAME));
+ }
+
+ LOG.info("All batches sent. Waiting for responses");
+ // Wait for every future
+ for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
+ try {
+ final RpcResult<NetconfMessage> netconfMessageRpcResult = future.get(params.msgTimeout, TimeUnit.SECONDS);
+ if(netconfMessageRpcResult.isSuccessful()) {
+ responseCounter.incrementAndGet();
+ LOG.debug("Received response {}", responseCounter.get());
+ } else {
+ LOG.warn("Request failed {}", netconfMessageRpcResult);
+ }
+ } catch (final InterruptedException e) {
+ throw new RuntimeException(e);
+ } catch (final ExecutionException | TimeoutException e) {
+ throw new RuntimeException("Request not finished", e);
+ }
+ }
+
+ Preconditions.checkState(responseCounter.get() == params.editCount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size());
+ }
+}
--- /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.test.tool.client.stress;
+
+import io.netty.channel.EventLoopGroup;
+import io.netty.util.Timer;
+import java.util.Set;
+import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
+import org.opendaylight.controller.netconf.client.NetconfClientSessionNegotiatorFactory;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
+
+public class ConfigurableClientDispatcher extends NetconfClientDispatcherImpl {
+
+ private final Set<String> capabilities;
+
+ private ConfigurableClientDispatcher(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final Timer timer, final Set<String> capabilities) {
+ super(bossGroup, workerGroup, timer);
+ this.capabilities = capabilities;
+ }
+
+ /**
+ * EXI + chunked framing
+ */
+ public static ConfigurableClientDispatcher createChunkedExi(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final Timer timer) {
+ return new ConfigurableClientDispatcher(bossGroup, workerGroup, timer, NetconfClientSessionNegotiatorFactory.EXI_CLIENT_CAPABILITIES);
+ }
+
+ /**
+ * EXI + ]]>]]> framing
+ */
+ public static ConfigurableClientDispatcher createLegacyExi(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final Timer timer) {
+ return new ConfigurableClientDispatcher(bossGroup, workerGroup, timer, NetconfClientSessionNegotiatorFactory.LEGACY_EXI_CLIENT_CAPABILITIES);
+ }
+
+ /**
+ * Chunked framing
+ */
+ public static ConfigurableClientDispatcher createChunked(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final Timer timer) {
+ return new ConfigurableClientDispatcher(bossGroup, workerGroup, timer, NetconfClientSessionNegotiatorFactory.DEFAULT_CLIENT_CAPABILITIES);
+ }
+
+ /**
+ * ]]>]]> framing
+ */
+ public static ConfigurableClientDispatcher createLegacy(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final Timer timer) {
+ return new ConfigurableClientDispatcher(bossGroup, workerGroup, timer, NetconfClientSessionNegotiatorFactory.LEGACY_FRAMING_CLIENT_CAPABILITIES);
+ }
+
+ @Override
+ protected NetconfClientSessionNegotiatorFactory getNegotiatorFactory(final NetconfClientConfiguration cfg) {
+ return new NetconfClientSessionNegotiatorFactory(getTimer(), cfg.getAdditionalHeader(), cfg.getConnectionTimeoutMillis(), capabilities);
+ }
+}
--- /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.test.tool.client.stress;
+
+/**
+ * Created by mmarsale on 18.4.2015.
+ */
+public interface ExecutionStrategy {
+ void invoke();
+}
--- /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.test.tool.client.stress;
+
+import com.google.common.base.Preconditions;
+import java.io.File;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import net.sourceforge.argparse4j.ArgumentParsers;
+import net.sourceforge.argparse4j.annotation.Arg;
+import net.sourceforge.argparse4j.inf.ArgumentParser;
+
+public class Parameters {
+
+ @Arg(dest = "ip")
+ public String ip;
+
+ @Arg(dest = "port")
+ public int port;
+
+ @Arg(dest = "edit-count")
+ public int editCount;
+
+ @Arg(dest = "edit-content")
+ public File editContent;
+
+ @Arg(dest = "edit-batch-size")
+ public int editBatchSize;
+
+ @Arg(dest = "debug")
+ public boolean debug;
+
+ @Arg(dest = "legacy-framing")
+ public boolean legacyFraming;
+
+ @Arg(dest = "exi")
+ public boolean exi;
+
+ @Arg(dest = "async")
+ public boolean async;
+
+ @Arg(dest = "ssh")
+ public boolean ssh;
+
+ @Arg(dest = "msg-timeout")
+ public long msgTimeout;
+
+ static ArgumentParser getParser() {
+ final ArgumentParser parser = ArgumentParsers.newArgumentParser("netconf stress client");
+
+ parser.description("Netconf stress client");
+
+ parser.addArgument("--ip")
+ .type(String.class)
+ .setDefault("127.0.0.1")
+ .type(String.class)
+ .help("Netconf server IP")
+ .dest("ip");
+
+ parser.addArgument("--port")
+ .type(Integer.class)
+ .setDefault(2830)
+ .type(Integer.class)
+ .help("Netconf server port")
+ .dest("port");
+
+ parser.addArgument("--edits")
+ .type(Integer.class)
+ .setDefault(50000)
+ .type(Integer.class)
+ .help("Netconf edit rpcs to be sent")
+ .dest("edit-count");
+
+ parser.addArgument("--edit-content")
+ .type(File.class)
+ .setDefault(new File("edit.txt"))
+ .type(File.class)
+ .dest("edit-content");
+
+ parser.addArgument("--edit-batch-size")
+ .type(Integer.class)
+ .required(false)
+ .setDefault(-1)
+ .type(Integer.class)
+ .dest("edit-batch-size");
+
+ parser.addArgument("--debug")
+ .type(Boolean.class)
+ .setDefault(false)
+ .help("Whether to use debug log level instead of INFO")
+ .dest("debug");
+
+ parser.addArgument("--legacy-framing")
+ .type(Boolean.class)
+ .setDefault(false)
+ .dest("legacy-framing");
+
+ parser.addArgument("--exi")
+ .type(Boolean.class)
+ .setDefault(false)
+ .dest("exi");
+
+ parser.addArgument("--async-requests")
+ .type(Boolean.class)
+ .setDefault(true)
+ .dest("async");
+
+ parser.addArgument("--msg-timeout")
+ .type(Integer.class)
+ .setDefault(60)
+ .dest("msg-timeout");
+
+ parser.addArgument("--ssh")
+ .type(Boolean.class)
+ .setDefault(false)
+ .dest("ssh");
+
+ // TODO add get-config option instead of edit + commit
+ // TODO different edit config content
+
+ return parser;
+ }
+
+ void validate() {
+ Preconditions.checkArgument(port > 0, "Port =< 0");
+ Preconditions.checkArgument(editCount > 0, "Edit count =< 0");
+ if (editBatchSize == -1) {
+ editBatchSize = editCount;
+ } else {
+ Preconditions.checkArgument(editBatchSize <= editCount, "Edit count =< 0");
+ }
+
+ Preconditions.checkArgument(editContent.exists(), "Edit content file missing");
+ Preconditions.checkArgument(editContent.isDirectory() == false, "Edit content file is a dir");
+ Preconditions.checkArgument(editContent.canRead(), "Edit content file is unreadable");
+ // TODO validate
+ }
+
+ public InetSocketAddress getInetAddress() {
+ try {
+ return new InetSocketAddress(InetAddress.getByName(ip), port);
+ } catch (final UnknownHostException e) {
+ throw new IllegalArgumentException("Unknown ip", 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.netconf.test.tool.client.stress;
+
+import ch.qos.logback.classic.Level;
+import com.google.common.base.Charsets;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.Lists;
+import com.google.common.io.Files;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.util.HashedWheelTimer;
+import io.netty.util.Timer;
+import io.netty.util.concurrent.GlobalEventExecutor;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import net.sourceforge.argparse4j.inf.ArgumentParser;
+import net.sourceforge.argparse4j.inf.ArgumentParserException;
+import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
+import org.opendaylight.controller.netconf.client.NetconfClientSession;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
+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.opendaylight.controller.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.protocol.framework.NeverReconnectStrategy;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.CommitInput;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.EditConfigInput;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
+
+public final class StressClient {
+
+ private static final Logger LOG = LoggerFactory.getLogger(StressClient.class);
+
+ static final QName COMMIT_QNAME = QName.create(CommitInput.QNAME, "commit");
+ public static final NetconfMessage COMMIT_MSG;
+
+ static {
+ try {
+ COMMIT_MSG = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"commit-batch\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
+ " <commit/>\n" +
+ "</rpc>"));
+ } catch (SAXException | IOException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+ static final QName EDIT_QNAME = QName.create(EditConfigInput.QNAME, "edit-config");
+ static final org.w3c.dom.Document editBlueprint;
+
+ static {
+ try {
+ editBlueprint = XmlUtil.readXmlToDocument(
+ "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
+ " <edit-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
+ " <target>\n" +
+ " <candidate/>\n" +
+ " </target>\n" +
+ " <config/>\n" +
+ " </edit-config>\n" +
+ "</rpc>");
+ } catch (SAXException | IOException e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+ private static final String MSG_ID_PLACEHOLDER = "{MSG_ID}";
+ private static final String MSG_ID_PLACEHOLDER_REGEX = "\\{MSG_ID\\}";
+
+ public static void main(final String[] args) {
+ final Parameters params = parseArgs(args, Parameters.getParser());
+ params.validate();
+
+ // TODO remove
+ try {
+ Thread.sleep(10000);
+ } catch (final InterruptedException e) {
+// e.printStackTrace();
+ }
+
+ final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ root.setLevel(params.debug ? Level.DEBUG : Level.INFO);
+
+ LOG.info("Preparing messages");
+ // Prepare all msgs up front
+ final List<NetconfMessage> preparedMessages = Lists.newArrayListWithCapacity(params.editCount);
+
+ final String editContentString;
+ boolean needsModification = false;
+ try {
+ editContentString = Files.toString(params.editContent, Charsets.UTF_8);
+ if(editContentString.contains(MSG_ID_PLACEHOLDER)) {
+ needsModification = true;
+ };
+ } catch (IOException e) {
+ throw new IllegalArgumentException("Cannot read content of " + params.editContent);
+ }
+
+ for (int i = 0; i < params.editCount; i++) {
+ final Document msg = XmlUtil.createDocumentCopy(editBlueprint);
+ msg.getDocumentElement().setAttribute("message-id", Integer.toString(i));
+ final NetconfMessage netconfMessage = new NetconfMessage(msg);
+
+ final Element editContentElement;
+ try {
+ // Insert message id where needed
+ final String specificEditContent = needsModification ?
+ editContentString.replaceAll(MSG_ID_PLACEHOLDER_REGEX, Integer.toString(i)) :
+ editContentString;
+
+ editContentElement = XmlUtil.readXmlToElement(specificEditContent);
+ final Node config = ((Element) msg.getDocumentElement().getElementsByTagName("edit-config").item(0)).
+ getElementsByTagName("config").item(0);
+ config.appendChild(msg.importNode(editContentElement, true));
+ } catch (final IOException | SAXException e) {
+ throw new IllegalArgumentException("Edit content file is unreadable", e);
+ }
+
+ preparedMessages.add(netconfMessage);
+
+ }
+
+
+ final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
+ final Timer timer = new HashedWheelTimer();
+
+ final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup, timer);
+
+ final NetconfDeviceCommunicator sessionListener = getSessionListener(params.getInetAddress());
+
+ final NetconfClientConfiguration cfg = getNetconfClientConfiguration(params, sessionListener);
+
+ LOG.info("Connecting to netconf server {}:{}", params.ip, params.port);
+ final NetconfClientSession netconfClientSession;
+ try {
+ netconfClientSession = netconfClientDispatcher.createClient(cfg).get();
+ } catch (final InterruptedException e) {
+ throw new RuntimeException(e);
+ } catch (final ExecutionException e) {
+ throw new RuntimeException("Unable to connect", e);
+ }
+
+ LOG.info("Starting stress test");
+ final Stopwatch started = Stopwatch.createStarted();
+ getExecutionStrategy(params, preparedMessages, sessionListener).invoke();
+ started.stop();
+
+ LOG.info("FINISHED. Execution time: {}", started);
+ LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
+
+ // Cleanup
+ netconfClientSession.close();
+ timer.stop();
+ try {
+ nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ LOG.warn("Unable to close executor properly", e);
+ }
+ }
+
+ private static ExecutionStrategy getExecutionStrategy(final Parameters params, final List<NetconfMessage> preparedMessages, final NetconfDeviceCommunicator sessionListener) {
+ if(params.async) {
+ return new AsyncExecutionStrategy(params, preparedMessages, sessionListener);
+ } else {
+ return new SyncExecutionStrategy(params, preparedMessages, sessionListener);
+ }
+ }
+
+ private static NetconfClientDispatcherImpl configureClientDispatcher(final Parameters params, final NioEventLoopGroup nioGroup, final Timer timer) {
+ final NetconfClientDispatcherImpl netconfClientDispatcher;
+ if(params.exi) {
+ if(params.legacyFraming) {
+ netconfClientDispatcher= ConfigurableClientDispatcher.createLegacyExi(nioGroup, nioGroup, timer);
+ } else {
+ netconfClientDispatcher = ConfigurableClientDispatcher.createChunkedExi(nioGroup, nioGroup, timer);
+ }
+ } else {
+ if(params.legacyFraming) {
+ netconfClientDispatcher = ConfigurableClientDispatcher.createLegacy(nioGroup, nioGroup, timer);
+ } else {
+ netconfClientDispatcher = ConfigurableClientDispatcher.createChunked(nioGroup, nioGroup, timer);
+ }
+ }
+ return netconfClientDispatcher;
+ }
+
+ private static NetconfClientConfiguration getNetconfClientConfiguration(final Parameters params, final NetconfDeviceCommunicator sessionListener) {
+ final NetconfClientConfigurationBuilder netconfClientConfigurationBuilder = NetconfClientConfigurationBuilder.create();
+ netconfClientConfigurationBuilder.withSessionListener(sessionListener);
+ netconfClientConfigurationBuilder.withAddress(params.getInetAddress());
+ netconfClientConfigurationBuilder.withProtocol(params.ssh ? NetconfClientConfiguration.NetconfClientProtocol.SSH : NetconfClientConfiguration.NetconfClientProtocol.TCP);
+ netconfClientConfigurationBuilder.withConnectionTimeoutMillis(20000L);
+ netconfClientConfigurationBuilder.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
+ return netconfClientConfigurationBuilder.build();
+ }
+
+ static NetconfDeviceCommunicator getSessionListener(final InetSocketAddress inetAddress) {
+ final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> loggingRemoteDevice = new LoggingRemoteDevice();
+ return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test", inetAddress), loggingRemoteDevice);
+ }
+
+ private static Parameters parseArgs(final String[] args, final ArgumentParser parser) {
+ final Parameters opt = new Parameters();
+ try {
+ parser.parseArgs(args, opt);
+ return opt;
+ } catch (final ArgumentParserException e) {
+ parser.handleError(e);
+ }
+
+ System.exit(1);
+ return null;
+ }
+
+
+ private static class LoggingRemoteDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
+ @Override
+ public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities, final NetconfDeviceCommunicator netconfDeviceCommunicator) {
+ LOG.info("Session established");
+ }
+
+ @Override
+ public void onRemoteSessionDown() {
+ LOG.info("Session down");
+ }
+
+ @Override
+ public void onRemoteSessionFailed(final Throwable throwable) {
+ LOG.info("Session failed");
+ }
+
+ @Override
+ public void onNotification(final NetconfMessage notification) {
+ LOG.info("Notification received: {}", notification.toString());
+ }
+ }
+
+}
--- /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.test.tool.client.stress;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+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.slf4j.LoggerFactory;
+
+// TODO reuse code from org.opendaylight.controller.netconf.test.tool.client.stress.AsyncExecutionStrategy
+class SyncExecutionStrategy implements ExecutionStrategy {
+ private static final Logger LOG = LoggerFactory.getLogger(SyncExecutionStrategy.class);
+
+ private final Parameters params;
+ private final List<NetconfMessage> preparedMessages;
+ private final NetconfDeviceCommunicator sessionListener;
+ private final List<Integer> editBatches;
+
+ public SyncExecutionStrategy(final Parameters params, final List<NetconfMessage> preparedMessages, final NetconfDeviceCommunicator sessionListener) {
+ this.params = params;
+ this.preparedMessages = preparedMessages;
+ this.sessionListener = sessionListener;
+ editBatches = countEditBatchSizes(params);
+ }
+
+ private static List<Integer> countEditBatchSizes(final Parameters params) {
+ final List<Integer> editBatches = Lists.newArrayList();
+ if (params.editBatchSize != params.editCount) {
+ final int fullBatches = params.editCount / params.editBatchSize;
+ for (int i = 0; i < fullBatches; i++) {
+ editBatches.add(params.editBatchSize);
+ }
+
+ if (params.editCount % params.editBatchSize != 0) {
+ editBatches.add(params.editCount % params.editBatchSize);
+ }
+ } else {
+ editBatches.add(params.editBatchSize);
+ }
+ return editBatches;
+ }
+
+ public void invoke() {
+ final AtomicInteger responseCounter = new AtomicInteger(0);
+
+ int batchI = 0;
+ for (final Integer editBatch : editBatches) {
+ for (int i = 0; i < editBatch; i++) {
+ final int msgId = i + (batchI * params.editBatchSize);
+ final NetconfMessage msg = preparedMessages.get(msgId);
+ LOG.debug("Sending message {}", msgId);
+ if(LOG.isDebugEnabled()) {
+ LOG.debug("Sending message {}", XmlUtil.toString(msg.getDocument()));
+ }
+ final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture =
+ sessionListener.sendRequest(msg, StressClient.EDIT_QNAME);
+ // Wait for response
+ waitForResponse(responseCounter, netconfMessageFuture);
+
+ }
+ batchI++;
+ LOG.info("Batch {} with size {} sent. Committing", batchI, editBatch);
+
+ // Commit batch sync
+ waitForResponse(responseCounter,
+ sessionListener.sendRequest(StressClient.COMMIT_MSG, StressClient.COMMIT_QNAME));
+ }
+
+ Preconditions.checkState(responseCounter.get() == params.editCount + editBatches.size(), "Not all responses were received, only %s from %s", responseCounter.get(), params.editCount + editBatches.size());
+ }
+
+ private void waitForResponse(AtomicInteger responseCounter, final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture) {
+ try {
+ final RpcResult<NetconfMessage> netconfMessageRpcResult =
+ netconfMessageFuture.get(params.msgTimeout, TimeUnit.SECONDS);
+ if (netconfMessageRpcResult.isSuccessful()) {
+ responseCounter.incrementAndGet();
+ LOG.debug("Received response {}", responseCounter.get());
+ } else {
+ LOG.warn("Request failed {}", netconfMessageRpcResult);
+ }
+
+ } catch (final InterruptedException e) {
+ throw new RuntimeException(e);
+ } catch (final ExecutionException | TimeoutException e) {
+ throw new RuntimeException("Request not finished", e);
+ }
+ }
+}
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
+ // Performance improvement for messages with size <10k according to
+ // https://xerces.apache.org/xerces2-j/faq-performance.html
+ factory.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
} catch (ParserConfigurationException e) {
throw new ExceptionInInitializerError(e);
}
<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</excludes>
+ <excludes>**\/target\/,**\/bin\/,**\/target-ide\/,**\/${jmxGeneratorPath}\/,**\/${salGeneratorPath}\/,**\/netconf\/test\/tool\/Main.java, **\/netconf\/test\/tool\/client\/stress\/StressClient.java</excludes>
</configuration>
<dependencies>
<dependency>